BUG OF THE MONTH | Unchecked input data

V1010 CWE-20 Unchecked tainted data is used in index: ‘strlen(command_buf)’.

static const char *basic_gets(int *cnt)
  int c = getchar();
  if (c < 0) {
    if (fgets(command_buf, sizeof(command_buf) - 1, stdin) 
          != command_buf) {
    command_buf[strlen(command_buf)-1] = '\0'; /* remove endline */

The analyzer warns about suspicious access to the command_buf array by an index. It is considered suspicious because unchecked external data is used as an index. Data is external as it was received through the fgets function from the stdin. Data is unchecked as there was no check before using. The expression fgets(command_buf, ….) != command_buf doesn’t count as in this case we check only the fact of receiving data, not its content.

The problem of this code is that under certain circumstances there will be a recording ‘\0’ outside the array, which will lead to the undefined behavior. For this, it is enough to just enter a zero-length string (a zero-length string in terms of the C language, i.e. the one in which the first character will be ‘\0’).

Let’s get a rough estimate of what will happen when feeding a zero-length string to the function:

  • fgets(command_buf, ….) -> command_buf;
  • fgets(….) != command_buf -> false (then-branch of the if statement is ignored);
  • strlen(command_buf) -> 0;
  • command_buf[strlen(command_buf) – 1] -> command_buf[-1].


What is interesting here is that this analyzer warning can be pretty “grasped between fingers”. In order to reproduce the problem, you need to:

  • get program execution to this function;
  • adjust the input so that the call of getchar() returned a negative value;
  • pass a string with a terminal null to the fgets function in the beginning and a function must successfully read the string.

Digging in sources for a while, I have formed a specific sequence of the problem reproducing:

  • Run fs_cli.exe in a batch-mode (fs_cli.exe -b). I’d like to note that to perform further steps, you need to make sure the connection to the fs_cli.exe server has been successful. For this purpose it is enough, for example, to locally run FreeSwitchConsole.exe as administrator.
  • After that we need to perform the input so that the call of getchar() returned a negative value.
  • Now let’s enter a string with a terminal null in the beginning (for example, ‘\0Oooops’).
  • ….

You can find a video of reproducing the problem below:

Please click here to see more bugs from this project.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.