Usage of Secure C (memcpy_s, strcpy_s etc) functions on OpenSSL

Phillip Susi phill at
Fri Dec 6 18:50:37 UTC 2019

Michael Wojcik writes:

> No, for a number of reasons:
> - The buffer may be dynamically allocated, in which case sizeof buffer
> is very much the wrong thing.

Obviously then you would use whatever variable you have the buffer size
in rather than sizeof.  The point is that you just tell strncpy 1 less
and make sure the buffer starts off zeroed ( so use calloc ) and then
you don't have to worry about strncpy not null terminating if it was too long.

> - A trailing nul byte is not always desirable (not everything is a string), and not all of the Appendix K
> functions will append one. Neither will strncpy, if the limit is
> reached; strncpy has broken semantics.

I fail to see where there is any issue to discuss when you aren't using
null terminated strings.  If you are just using memcpy, then you know
exactly how many bytes you want to copy and that is exactly how many
gets copied.  How can you screw that up that needs a _s version to
protect you from?

> - The buffer size (less 1) is the wrong value to pass when using strncat with a destination that does not start
> with a nul character. Developers also frequently miss the fact that strncat can append length+1 bytes to
> the buffer. (strncat's semantics are dangerously non-obvious.)

Obviously for strncat you need to subtract strlen() first.

> - Non-trivial programs *will still have to handle truncation properly*. It's rarely the case for a non-trivial
> program that "silently truncate the data" is a good way to handle it. A well-behaved program will treat
> truncation as an error or a special case that needs further handling, or at least needs to be flagged to the
> user or some other diagnostic sink. The C90 length-checked functions don't communicate truncation to
> the caller; the Annex K ones only return "a non-zero value" if a constraint is violated, so there's no
> standardization as to how a particular constraint violation is communicated.

Makes sense in theory.. I've just never seen a program bother in
practice.  This may be one of those differences between acadamia and the
real world.

> Also, sizeof is an operator, not a function. There's no reason to parenthesize its argument unless the
> argument is a type name, in which case it's parenthesized as a special syntactic case.

I'm aware, but virtually all C code I've seen since I learned it in the
'90s has used the parethesis.  On the very rare occasion I see someone
not do it, it feels weird.

More information about the openssl-users mailing list