[英]linux how to patch this code
#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
}
我们可以通过运行此代码获得远程访问吗? 我知道有可能,但请帮助我进行修补。
假设您担心潜在的缓冲区溢出,可以像这样修复它:
#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;
}
这为"echo "
(5), argv[1]
(字符串长度)和空终止符(1) argv[1]
足够的空间。
允许运行用户指定的内容仍然很危险,但是至少您不会再有缓冲区溢出了。
Paxdiablo为您的缓冲区溢出问题提供了一个很好的解决方案,但这实际上是您遇到的最少问题。 您的大问题是,您在不首先检查用户输入的情况下就盲目使用用户输入。
例如,运行程序如下:
./your_app "\"goodbye data\" && rm -rf /"
即使您的程序没有缓冲区溢出问题,也将以灾难告终。 攻击者可以很容易地传入执行各种令人讨厌的事情的整个shell脚本,他们所要做的就是将其重新编写以适合一行。
您需要检查传入的用户输入,然后再将其传递给system()
并确保它看起来像您期望的那样。 更好的是,避免完全将system()
与用户输入一起使用,而应使用更安全的方法来完成您需要的操作(在您的示例中,可以将对system("echo ...")
调用替换为printf()
)。 如果您绝对必须将用户输入传递给system()
,请考虑在受限的环境(例如chroot
监狱system()
运行您的应用程序,以至少使做讨厌的事情变得更加困难。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.