linux how to patch this code

狂风中的少年 提交于 2019-12-25 04:15:20

问题


#include <WhatHere?>
#include <WhatHere?>
#include <WhatHere?>
int main(int argc, char **argv) {
    char command[50] = "echo ";
    strcat(command,argv[1]); // concatenate the input so that the final command is "echo <input>"
    system(command); // call the system() function to print the input
    return 0; // denote that the program has finished executing successfully
}

Can we get a remote access by running this code ? I know it is possible but please help me patch it up.


回答1:


Assuming that you're worried about the potential buffer overflow, you could fix it like this:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main (int argc, char **argv) {
    char *command;
    if (argc != 2) {
        fprintf (stderr, "Wrong number of arguments\n");
        return 1;
    }
    if ((command = malloc (strlen (argv[1]) + 6)) == NULL) {
        fprintf (stderr, "Could not allocate memory\n");
        return 1;
    }
    strcpy (command, "echo ");
    strcat(command,argv[1]);
    system(command);
    free (command);
    return 0;
}

This makes enough room for "echo " (5), argv[1] (string length) and the null terminator (1).

It's still potentially dangerous allowing user-specified stuff to be run but at least you won't get buffer overflows any more.




回答2:


Paxdiablo gave a good solution to your buffer overflow problem, but that's really the least of your problems here. Your big issue is that you are blindly using input from the user without inspecting it first.

For example, running your program like:

./your_app "\"goodbye data\" && rm -rf /"

would end in disaster, even if you program had no buffer overflow problems. An attacker could just as easily pass in an entire shell script that did all sorts of nasty things, all they would have to do is re-write it to fit in a single line.

You need to inspect incoming user input before you pass it to system() and make sure that it looks like what you are expecting. Better yet, avoid using system() with user input entirely and instead use safer methods to do what you need (in your example, you can replace your call to system("echo ...") with printf()). If you absolutely must pass user input to system(), consider running your app in a restricted environment like a chroot jail to at least make it more difficult to do anything nasty.



来源:https://stackoverflow.com/questions/5419139/linux-how-to-patch-this-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!