【发布时间】:2015-12-15 11:19:46
【问题描述】:
我想从 C++ 代码更改我的默认网关。我正在使用 Eclipse 作为 IDE。以下是我的代码。
//change_gw.cpp
#include <iostream>
#include <unistd.h>
using namespace std;
//To execute terminal commands
std::string exec(char* cmd) {
FILE* pipe = popen(cmd, "r");
if (!pipe) return "ERROR";
char buffer[128];
std::string result = "";
while(!feof(pipe)) {
if(fgets(buffer, 128, pipe) != NULL)
result += buffer;
}
pclose(pipe);
return result;
}
int main() {
int euid = geteuid();
int uid = getuid();
cout<<"euid is "<<euid<<endl;
cout<<"uid is "<<uid<<endl;
int result = setreuid(euid,-1); //change the uid to euid (0 - root)
if(result != 0) {
cout<<strerror(errno)<<endl;
return -1;
}
string result = exec("sudo route del default");
if (result == "ERROR") {
cout<<"del route failed"<<endl;
return -1;
}
result = exec("sudo route add default gw ip dev iface");
if (result == "ERROR") {
cout<<"add route failed"<<endl;
return -1;
}
cout<<"route changed succefully"<<endl;
setreuid(uid,-1); //revert the changes to uid
return 0;
}
我已经成功编译了这段代码并获得了可执行文件。编译是从 eclipse 环境中完成的。我从终端手动对可执行文件进行了以下更改。
chown root:root change_gw //change the owner to root
chmod u+s change_gw //set user id
现在,当我从 eclipse 环境运行可执行文件时,我得到以下输出。
euid = 0
uid = 1002
route changed successfully
虽然上面的代码运行良好,但我想知道我正在做的天气是正确且有效的。而且由于编译是在 Eclipse 环境中完成的,因此可执行文件的用户每次都从 root 更改为本地用户,我每次都需要更改 setuserid 标志。我怎么能避免每次都做这个改变?
【问题讨论】:
-
stackoverflow.com/questions/22733967/… 解释了如何在不通过命令的情况下修改路由表。
-
您希望任何人都能够添加此路线吗?如果没有,只需将用户保留为本地用户,然后他们必须输入密码才能更改路由表。如果您确实希望程序设置为 setuid,则需要搜索如果您不想成为一个巨大的安全漏洞而必须采取的预防措施。
-
最终评论 - exec 不将单个字符串作为参数。您必须准备一个(可修改的)字符串数组作为 argv。