muquit / mailsend

A program to send mail via SMTP from command line
Other
297 stars 68 forks source link

A potential Format String bug found in smtp.c #162

Open x14ngch3n opened 1 year ago

x14ngch3n commented 1 year ago

Hi, I'm currently trying to use the static analysis tool Infer to find uncatched API-misuse bugs in OpenWrt packages, and I find a potential Format String bug in your project, version 1.19.

The bug located in smtp.c. Firstly, the program read bytes from fp to buf using fread() in line 638, and buf is later used as the parameter of showVerbose() in line 650, as shown in the following code:

while (fgets(buf,bufsz,fp))
{
    write_to_socket(buf);
    if (g_show_attachment_in_log)
    {
        showVerbose("[C] %s",buf); 
    }
}
(void) fclose(fp);

(void) snprintf(buf,bufsz,"\r\n\r\n");
msock_puts(buf);
showVerbose(buf);

Inside showVerbose(), it directly calls vprintf() twice time with the controlled buffer, which violates CWE134 and can cause undefined behavior.

I also attached the analysis trace given by Infer FYI:

"trace": [
  {
    "file": "smtp.c",
    "line": 638,
    "col": 12,
    "feature": [ "Input", "fgets" ]
  },
  {
    "file": "smtp.c",
    "line": 650,
    "col": 5,
    "feature": [ "Call", "showVerbose" ]
  },
  {
    "file": "utils.c",
    "line": 182,
    "col": 13,
    "feature": [ "FormatString", "vfprintf", [ "Var" ] ]
  },
  {
    "file": "utils.c",
    "line": 197,
    "col": 13,
    "feature": [ "FormatString", "vfprintf", [ "Var" ] ]
   }
],
muquit commented 1 year ago

Fortunately format string is not externally controlled, but should be fixed. Could you test the following code and tell me the infer command you used? It should have the same issue. I could not reproduce it on Ubuntu 20.0.4 File: test.c

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>

void showVerbose(char *format,...)
{
    va_list
        args;

    va_start(args,format);
    vfprintf(stdout,format,args);
    (void) fflush(stdout);
    va_end(args);

    va_start(args,format);
    vfprintf(stdout,format,args);
    (void) fflush(stdout);
    va_end(args);
}

int main(int argc, char *argv[])
{
    char
        buf[1024];

    (void) strncpy(buf,"this is a test\n",sizeof(buf)-1);
    showVerbose(buf);
    return(0);
}
infer --version
Infer version v1.1.0
Copyright 2009 - present Facebook. All Rights Reserved.
infer run -- gcc -g -Wall test.c
Capturing in make/cc mode...
Found 1 source file to analyze in /home/muquit/junk/infer-out
1/1 [################################################################################] 100% 56.294ms

  No issues found

Thanks.

x14ngch3n commented 1 year ago

Actually I'm using a signature-based vulnerability detection tool called Tracer which is built upon Infer. And I don't find that bug with Infer either.