Repository navigation
Rework the partially overlapping handling - #5427
bernd-edlinger wants to merge 1 commit into
Conversation
d8a8a27 to
20846cc
Compare
|
Could you add a test for this, and test both positive and negative cases? |
There was a problem hiding this comment.
Two things [for now?]. Shouldn't it be cmpl instead of inl? Secondly I'd like to suggest to flip the terms of the expression, i.e. compare in and out + ctx->buf_len first. It's more readable and takes less computations.
On related note. Looking few lines down we see i = ctx->buf_len. Since we cache the value, we can as well start earlier...
There was a problem hiding this comment.
The code below assumes inl is in bytes, and out is != NULL.
So if EVP_CIPH_FLAG_LENGTH_BITS is set, the cipher does
very likey not support bit lengths, nor AAD.
There was a problem hiding this comment.
The code below assumes inl is in bytes
In such case wouldn't it be appropriate to add a commentary that says "past this point inl is bytes"?
There was a problem hiding this comment.
Yes, good point. I will update the comment accordingly.
There was a problem hiding this comment.
One thing where I am not sure is, if the buffer size of the output should be
assumed to be inl + (bl - 1) or if it should be (inl + ctx->buf_len)/bl * bl
thus if the caller can be expected to know the internal state of the incomplete
buffer.
There was a problem hiding this comment.
Yeah, I'm pondering over this too...
There was a problem hiding this comment.
At least the documentation says clearly inl + (bl - 1)
There was a problem hiding this comment.
You can move it even higher...
There was a problem hiding this comment.
Not quite. It happens at line 356. Current numbering, not original.
There was a problem hiding this comment.
This is somewhat confusing comment... What is it that is suggested to omit? I'd argue that following should always work:
unsigned char *inp = buf, *out = buf;
for (i = 0; i < sizeof(buf); i++) {
EVP_EncryptUpdate(ctx, out, &outl, inp++, 1);
out += outl;
}
In other words "pure" in-place. Note that currently it's effectively handled by (PTRDIFF_T)in != (PTRDIFF_T)(out + i) rather than by is_any_overlapping...
There was a problem hiding this comment.
I don't understand why this is not written as
EVP_EncryptUpdate(ctx, out, &outl, inp, sizeof(buf));
There was a problem hiding this comment.
Because question is not what it is right thing to do in the snippet, but what should work no matter what. If you need something that helps imagining, consider *inp = readioport(); prior call to EVP_EncryptUpdate.
There was a problem hiding this comment.
But in that use case, why should you write char-after-char in the same buffer space where the cipher text is
constructed?
Why not do simply char ch = readioport(); EVP_EncryptUpdate(ctx, out, &outl, &ch, 1); ?
There was a problem hiding this comment.
The real question here is, if I read the documentation of EVP_EncryptUpdate:
EVP_EncryptUpdate() encrypts B<inl> bytes from the buffer B<in> and
writes the encrypted version to B<out>. This function can be called
multiple times to encrypt successive blocks of data. The amount
of data written depends on the block alignment of the encrypted data:
as a result the amount of data written may be anything from zero bytes
to (inl + cipher_block_size - 1) so B<out> should contain sufficient
room. The actual number of bytes written is placed in B<outl>. It also
checks if B<in> and B<out> are partially overlapping, and if they are
0 is returned to indicate failure.
I don't see how partially overlapping can be understood to allow the
aliasing that happens in this loop:
unsigned char *inp = buf, *out = buf;
for (i = 0; i < sizeof(buf); i++) {
EVP_EncryptUpdate(ctx, out, &outl, inp++, 1);
out += outl;
}
How can one consider EVP_EncryptUpdate(ctx, out, &outl, out+1, 1); a partial overlapping buffer?
but not EVP_EncryptUpdate(ctx, out, &outl, out, 1); in the second iteration of the loop, (when ctx->buf_len == 1) ?
There was a problem hiding this comment.
Why not do simply
I'm perfectly aware of what one can do [better], but thing is that you can't assume that you'll be in position to pose this question to each user. Instead you have to assume that caller is not as rational as you :-) In other words it doesn't matter how irrational suggested snippet is, it should just work...
There was a problem hiding this comment.
Keep in mind difference between partially and fully overlapping. Fully overlapping, or in other words in-place processing, should work. [I have to step out now, i.e. more detailed remark will be provided later.]
There was a problem hiding this comment.
How can one consider EVP_EncryptUpdate(ctx, out, &outl, out+1, 1); a partial overlapping buffer? but not EVP_EncryptUpdate(ctx, out, &outl, out, 1); in the second iteration of the loop, (when ctx->buf_len == 1) ?
Well, there is no good formal answer to this question. But I'd say that this is the case when intention counts. And above mentioned second iteration of the loop is arguably indication of legitimate intention. I.e. if you see that end of [tp to be] written data aligns perfectly with input, you know you are looking at in-place processing.
[BTW, one can probably argue that first case should work too. Well, as long as caller always passes one byte at a time (or small enough) and advances input pointer, so that complete blocks are written one by one and never overstep the input. But I'd say that we are free to make the choice to claim this case unsupported.]
There was a problem hiding this comment.
All depends on the definition of partially overlapping.
Our doc fails to define it because it should be self-evident.
My definition would be:
[a..b] and [c..d] are partially overlapping IF the intersection
of both intervals is not empty, and there exists at least one
element in [a..b] that is not in [c..d] or vice-versa.
But the current behaviour of EVP_EncryptUpdate with regard to partially
overlapping in and out buffers is in fact totally different from
what the doc says. No matter what I write in this comment.
I do just not like to encourage people to use this kind of programming style.
Which is very hard to explain and it is fragile, because if you
load just one byte in the internal buffer before the loop starts,
the loop will fail immediately.
There was a problem hiding this comment.
I'm still unclear on what is it that one shouldn't rely on...
There was a problem hiding this comment.
In this case IMHO in and out should not alias at all.
But the doc does not say that either....
There was a problem hiding this comment.
Well, I'd argue that this note is more contradicting than documentation. Indeed, documentation says that function will return error, while this note can be interpreted as "some black magic is happens here, but it will disappear". While what's going on in reality is that checks are effectively hardened, so that documentation becomes so to say more right, and there is no sign of it disappearing in the future. As we are not going to support partially overlapping buffers (which are different from fully overlapping buffers), because we simply can't do that, because lower level subroutines don't leave that kind of guarantee. In fact one could always argue, i.e. before documentation was modified to mention partially overlapping buffers, that this was natural limitation and caller could never count on sensible/predictable outcome with [partially] overlapping buffers.
EDIT: "caller could never count on [partially] overlapping buffers."
There was a problem hiding this comment.
Yes, in the end the documentation and the implementation should match.
What is going on in the check down below is an implementation detail,
and that should not be relied upon by the caller.
There was a problem hiding this comment.
I'm not exactly happy that there are actual subroutine calls. As low-level gets faster, overhead becomes more significant (on short inputs), and it's only appropriate working toward reducing it. For reference, as soon as subroutine is non-static, compiler will refuse to inline it if you compile with -fPIC, and we do so by default.
There was a problem hiding this comment.
I could make the three is_xxx static, and move them plus this ugly PTRDIFF_T into the
header file.
Do you know why we can not just use uintptr_t ?
There was a problem hiding this comment.
Do you know why we can not just use uintptr_t ?
This is a little bit wrong question. It's not about present can or cannot, but rather about past choices, from time when there were compilers in support matrix that didn't have it. However! Even today it's not that obvious that it would be appropriate to use it, because it's claimed optional by standard. Well, one can as well choose to take the same path as with other *_t types, i.e. provide own typedefs in case they are missing. See e_os2.h to get the idea. And it looks like one is likely to do something like that... If we choose to take this path that is...
There was a problem hiding this comment.
On a side note I kind of liked original better, i.e. straight comparison of one pointer plus offset with another pointer. It was more readable, as here you have to work unnecessary hard to confirm that it's correct. Once again, side[!] note :-)
There was a problem hiding this comment.
You can move it even higher... But let's say it's a side note...
There was a problem hiding this comment.
Sadly I must say, that we have zero test coverage for EVP_CIPH_FLAG_LENGTH_BITS.
There was a problem hiding this comment.
I apologize, but I still find this confusing/contradicting. It gives an impression that there is something specific legacy application may rely on, something that works and is currently supported [and something we consider stopping supporting]. But simple fact of life is that partially overlapping buffers were never supported. Yes, something might have worked, but it was never actually supported. To draw an analogy, you can call memcpy with partially overlapping buffers, and it will do something. And this something might even work out for you that time. But does it make it supported for legacy applications? No. Well, one can argue that memcpy is off the hook, because there is disclaimer in its manual page. But does lack of disclaimer in earlier OpenSSL documentation put an obligation on us to actually support it? I'd say no, not really(*). As it is naturally assumed limitation. It's just that originally there was no check and application code was held fully responsible for possible mishaps, and now there is. One can argue that current check is buggy as it doesn't catch all corner cases, but you can't really say that its hardening would conflict with legacy applications, as they were never to actually rely on its lack to start with. In other words if anything, this note should simply state that check can be hardened in the future. [Though it kind of calls for following question. If we recognize that check is not 100%, then why isn't it fixed now. One can argue that it's a trade-off decision, to catch most obvious cases, but fast. As previous check.]
(*) BTW, if answer was yes, then solution would have be different and more convoluted.
[Just in case for bypasser's reference, fully overlapping buffers are considered different from partially overlapping buffers, and are supported. Well, one can argue that there is ambiguity, because output from block cipher is padded, and padded output won't be fully overlapping with input. Yes, but padding is performed in separate finalization call, when application input is fully consumed.]
There was a problem hiding this comment.
Well, I am actually not sure if there is any real application doing that.
There are however are some tests doing exactly that.
If it would be my decision, I would drop the admittedly hard to explain
is_pointer_offset_by_bias-thing completely and simplify this check to:
if (is_any_overlapping(out, inl + (bl - 1), in, inl)) {
... and adjust the test accordingly.
If that would be acceptable the comment could be dropped as well.
There was a problem hiding this comment.
As mentioned earlier, I'm not really happy about is_pointer_offset_by_bias (it's unnecessary hard to audit), but in combination with second check it becomes extra tricky. I mean first it's 'in, out' and then 'out, in', br-r-r-r... As for whether or not it should be inl + bl - 1 or something else. I'd say that formally speaking "something else"... You've mentioned floor_to_blocksize(inl + i) earlier... [Just in case, note there is block_mask that can be used with "floor".]
There was a problem hiding this comment.
Even though it's not critical, I'd say it would be appropriate to cache block_size value.
There was a problem hiding this comment.
Wouldn't it be more appropriate to check for specific error? As opposite to ignoring any that is.
There was a problem hiding this comment.
And in case test fails [i.e. EVP_CipherUpdate returning success], wouldn't it be appropriate to set t->err to something specific and terminate test? I mean as it stands now, failure at this point would hopefully map to VALUE_MISMATCH, but isn't it's not actually given that it does for every given test.
There was a problem hiding this comment.
Yeah, this is a kind of borderline test here, and it does indeed succeed if the
cipher block size == 1.
In a way the in and out buffers are fully overlapping (in == out)
yet we get an EVP_R_PARTIALLY_OVERLAPPING (which is in a way
questionable in this case)
I could change in and out to be off by 1, and then it would always
fail, simply because the buffer is partially overlapping.
|
Well, it seems that we, me and @bernd-edlinger, effectively reached impasse, as I for one don't approve the omission of specific corner case of |
|
If we support overlapped buffers (i.e. any level of in place) we should support any level of overlap. |
|
By the documentation we support overlapping as long as it is not partially overlapping. |
4446355 to
200daba
Compare
|
Travis failure is unrelated. |
There was a problem hiding this comment.
I think the mask is not right, leaves one bit too much in the last byte,
consider bit_len == 1 then this does last_byte &= 0x7F >> 1
There was a problem hiding this comment.
If you don't specify direction, it will exercise vector both ways.
There was a problem hiding this comment.
Ah, I did not know.
But I wanted to follow the example of the other
CFB-128 tests below.
There was a problem hiding this comment.
While this line looks dandy I'd still argue that is_partially_overlapping is unnecessary complex. If I may make suggestion, why not this:
bl = ctx->cipher->block_size;
i = ctx->buf_len;
assert(bl > 1 || i == 0);
if ((PTRDIFF_T)(out + i) != (PTRDIRR_T)in /* in-place? */
&& is_overlapping(out, (i + cmpl) & -bl, in, cmpl)) {
bad ...
}
where is_overlapping is
int is_overlapping(PTRDIFF_T ptr1, PTRDIFF_T len1, PTRDIFF_T ptr,2 PTRDIFF_T len2)
{
PTRDIFF_T diff = ptr2 - ptr1;
return len2 > 0 & (diff < len1 | (diff > (0 - len2);
}
Note that either length of 0 counts as no overlap. Then note that checks for overlapping and in-place are effectively separated. This is to emphasize the difference, and it also improves readability because is_overlapping is exactly what intuition tells you. no "secret society knowledge" is required.
There was a problem hiding this comment.
It depends again on the definition of "partially overlapping".
As I understood the term initially, it would always imply "in!=out && ..."
But to me the exception "out+i != in && ..." is still somehow artificially.
It is only one possible overlapping that works, and the user must have
knowledge of the internal state if the cipher context.
Now I understood we trust our users to know such things.
And we want to support all or nothing with regard to overlapping.
So I try to support another use case where encrypt in-place but
with some separation between the in and out blocks.
I think of encrypting a small header followed by a big payload,
and again a small trailer.
I realized, that if there is just two cipher blocks room, you need only
one big block that can hold the complete encrypted data.
One can place the payload at the end of the output block,
in a differently partially overlapping way.
There was a problem hiding this comment.
As I understood the term initially, it would always imply "in!=out && ..."
Correct. And suggestion is to explicitly rip out the first term of condition and "re-brand" it as "in-place or non-overlapping".
But to me the exception "out+i != in && ..." is still somehow artificially.
Yeah, it's somewhat counter-intuitive, but it's correct.
It is only one possible overlapping that works,
Keep in mind that it's counter-intuitive only for block-oriented modes, such as CBC, ECB. Things like CTR, XTS, etc. behave totally intuitive. [Recall that [then] i is always zero, as hinted by assert.]
and the user must have knowledge of the internal state if the cipher context.
Yes, but all user has to do is to use ctx consistently.
So I try to support another use case where encrypt in-place but
with some separation between the in and out blocks.
I'd say don't, it's not worth the complexity.
There was a problem hiding this comment.
It's not much complexity, test cases are there for it,
and it used to work in 1.0.1
There was a problem hiding this comment.
It's not much complexity
Things add up, and each step can be viewed as "that's not much of additional complexity", but then some day you step back and drop your arms...
it used to work in 1.0.1
But that was incidental, since there were no checks.
There was a problem hiding this comment.
That's what I wrote on the project list
https://mta.openssl.org/pipermail/openssl-project/2018-March/000346.html
where I wrote this:
"I think for instance of WRAP mode, where the primitive basically
supports arbitrary overlapping (uses memmove) but we can no longer
use that feature because of the partially overlapping check in the
EVP cipher handling.
And the other use case, which I think is worth to mention is
unsigned char *inp = buf + sizeof(buf) - 1, *out = buf;
for (i = 0; i<sizeof(buf)-X; i++) {
*inp = getc();
EVP_EncryptUpdate(ctx, out, &outl, inp, 1);
out += outl;
}"
So I thought everybody should be informed, at least no one objected.
There was a problem hiding this comment.
As for second use case. I don't quite follow. It works with what I suggest, i.e. wouldn't need special treatment. [We assume that sizeof(buf) is multiple of block size. And it has to be, because of possible padding.] As for WRAP. I admit I have to look closer... But note that it has CUSTOM_CIPHER flag and it's underlying primitive that is responsible for overlap check.
There was a problem hiding this comment.
Yes, and after I noticed that the current check uses the wrong return value
in the partially overlapping code, I saw that modes/wrap128.c always
does "memmove(out, in + 8, inlen)" so that check can be removed.
There was a problem hiding this comment.
Just to be clear, I don't feel that "So I try to support another use case where encrypt in-place but with some separation between the in and out blocks" was verbalized in the message clearly enough. And secondly I'd rather insist on explicit feedback than view lack of one as consent.
There was a problem hiding this comment.
For the second use case, a better pseudo code would be:
unsigned char *inp = buf + sizeof(buf) - X, *out = buf;
EVP_EncryptUpdate(ctx, out, &outl, &head, sizeof(head));
out += outl;
EVP_EncryptUpdate(ctx, out, &outl, in, X);
out += outl;
EVP_EncryptUpdate(ctx, out, &outl, &tail, sizeof(tail));
out += outl;
with X > 75% sizeof(buf)
sizeof(head), sizeof(tail) not necessary multiple of block size
There was a problem hiding this comment.
On side note, [i.e. no action is actually expected,] it wouldn't be inappropriate to coalesce OPENSSL_cleanse chains like this by
struct { unsigned char tmp[8], icv[8], etc.; } scratch;
...
memcpy(scratch.tmp, ...
...
OPENSSL_cleanse(&scratch, sizeof(scratch));
|
Where are we on this? @mattcaswell marked it 1.1.1, I take that as priority marker. |
|
From my side, this is still good. (I think I would not merge the cleanse calls in 3des code, not |
bf25d68 to
933098b
Compare
|
This is not strictly 1.1.1 (the PR would be backported to 1.1.0) so I am removing that milestone. |
The problem here is that in the default case of EVP_EncryptUpdate the in and out buffers can have different sizes: Suppose we have a block_size=16 and already buf_len=15. EVP_EncryptUpdate is called with in==out and inl==2. In this case, is_partially_overlapping(in+15, in, 2) returns false, because the intervals are not overlapping at all. But ctx->cipher->do_cipher(ctx, out, ctx->buf, bl) clobbers the second byte before it is used. Make partially overlapping more permissive, i.e. allow essentially all kinds of overlapping that "work" Fix error handling in aes_ocb_cipher Avoid undefined behavior in des_ede3_unwrap Add a sentence about in-place encryption to the doc Add a statement about the output buffer size for WRAP mode ciphers Add a definition for partially overlapping Add test cases for invalid overlapping Add test cases for overlapping encryption Add AES-xxx-CFB1/8 test vectors from NIST SP800-38A Reuse the second DES-EDE3-CFB1 as BitLen test
933098b to
6a3e769
Compare
The problem here is that in the default case of EVP_EncryptUpdate
the in and out buffers can have different sizes:
Suppose we have a block_size=16 and already buf_len=15.
EVP_EncryptUpdate is called with in==out and inl==2.
In this case, is_partially_overlapping(in+15, in, 2)
returns false, because the intervals are not overlapping at all.
But ctx->cipher->do_cipher(ctx, out, ctx->buf, bl) clobbers the
second byte before it is used.