0

I can't understand what's happening with buf1 and pass in main(). I understand that after buffer overflow in gets(buf1):

  1. Firstly (by input more then 15 characters), we are actually changing calling frame for calling function main()
  2. Secondly (if keep input more then 19 characters), then we will start change return address of calling function main().

But why after 16 character in gets (buf1) (123456789012345**6**) we get pass equal 54 (which is ASCII code for 6). We do not overflow pass variable so why we get this pass = 54?

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

int CommandInjection(char *varCommand)
{
    char cat[] = "cat ";
    char *command;
    size_t commandLength;

    commandLength = strlen(cat) + strlen(varCommand) + 1;
    command = (char *) malloc(commandLength);
    strncpy(command, cat, commandLength);
    strncat(command, varCommand, (commandLength - strlen(cat)) );

    system(command); //The function system is executed with the input entered by the user. The input can be dangerous.

    return (0);
}

int main(void)
{
    char buf1[15];
    char varCommand[30];
    bool pass = 0;

    printf("\nEnter the password: \n(If you enter more than 15 characters you can break the security)\n");
    gets(buf1); //Function that does not make bound checking

    if(strcmp(buf1, "thepassword"))
    {
        printf ("\nWrong Password\n PASS=%d", pass);
        if(pass==true)
            printf ("\nHowever, there was memory corruption and you can enter to other part of the  program\n pass=%d", pass);
    }
    else
    {
        printf ("\nCorrect Password\n");
        pass = true;
    }

    if(pass == true)
    {
        // Don't must enter here if the password is wrong
        printf ("\nEnter the file name (for example: text.txt; ls -l)\n");
        gets(varCommand); //There is no input validation  
        CommandInjection(varCommand);
    }

    return 0;
}
Marcus Rossel
  • 3,196
  • 1
  • 26
  • 41
  • 1
    don't use `gets()`. use `fgets()` instead – Arun A S Mar 29 '15 at 10:23
  • buf1 is 15 bytes long, if you try to put 16 characters in it you'll get: buf1=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]. The 16th. character is an overflow into the pass parameter, that's why you're getting 16(ASCII 54) there. Did I understand you correctly? – Ishay Peled Mar 29 '15 at 10:44
  • In fact `char buf1[15]`; can only accept a **14-char** password, plus the string terminator. After that you are getting Undefined Behaviour, so anything can happen. Focus on making sure the code works robustly, not on the side-effects of failure. `pass` remained `0` when I entered too many characters. – Weather Vane Mar 29 '15 at 10:47
  • @IshayPeled, yes, you have understood me right. – Nikita Nikita Mar 29 '15 at 15:24
  • @Weather, but I want understand this because I want understand how overflow work on stack, from security point of view. – Nikita Nikita Mar 29 '15 at 15:28

0 Answers0