Posts Tagged ‘strxcat’

strxcat

Monday, October 20th, 2014

A faster and perhaps more secure way to concatenate strings in C

by mar10, mar10 a krutt punto org

strlcat is part of many BSD systems and also used in many important software projects.

strlcat concatenates two c strings. The C library contains a function that does a similar task: strncat. However, it only considers the length of the source operand. strlcat requires the size of the destination operand, in that way it is possible to detect buffer overflows.

What is wrong with strlcat?

  • strlcat has been used in the wrong way, i.e. there are cases where this function was not really necessary, even so, it was used.
  • strlcat does not cover you in the case of string truncation. In some cases that can result in a very serious problem for your code (i.e. for you!).

Many examples of the use of strlcat are available in top software projects, i.e. The BSD Operating System (FreeBSD, OpenBSD, NetBSD, …).

However, sometimes coders forget to validate the return value of strlcat:

Inside the file tor-gencert.c, part of the TOR project, you can find something like this:

static int
generate_certificate(void)
{
  char buf[8192];
  ...
  ...
  strlcat(buf,
          "-----END ID SIGNATURE-----\n"
          "dir-key-certification\n", sizeof(buf));
  ...
  ...
}

They never evaluate the return value of strlcat. It seems that buf is large enough to store the RSA certificate that is created by this function. However, less experienced coders may go wrong with this bad coding example. How do the tor developers deal with a truncation error made by the strlcat function?

A possible solution: strxcat

Well in the example shown above, perhaps the use of strlcat was not adequate. We propose a new str*cat function that does not truncate. We found that our function performs better than the original strlcat version written by Mr. Todd C. Miller.

See our code here.

SHA1: 569e42d167165a68a3d9defa1ef8d7a5c84d9e79 strxcat.c

Our code is released under the 3-clause BSD license, however it can be re-licensed under the GPL v3 and the LGPL v3.

References

License

Copyright (C) 2014 mar10

Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.

A copy of the license can be found here.