开发者

linux how to patch this code

开发者 https://www.devze.com 2023-02-19 05:49 出处:网络
#include <WhatHere?> #include <WhatHere?> #include <WhatHere?> int main(int argc, char **argv) {
#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 t开发者_StackOverflow社区he 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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消