0
我想從C++代碼更改我的默認網關。我使用eclipse作爲IDE。以下是我的代碼。如何從Linux上的C++程序提升特權級別到根目錄
//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;
}
我已經成功地編譯了這段代碼並獲得了可執行文件。編輯是從日食環境中完成的。我從終端手動對可執行文件進行了以下更改。
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環境下完成的,可執行文件的用戶每次都會從根變爲本地用戶,我需要每次更改setuserid標誌。我怎樣才能避免每次都做這個改變?
http://stackoverflow.com/questions/22733967/linux-how-to-set-default-route-from-c解釋如何修改路由表,而無需通過命令。 –
你想讓任何人能夠添加此路線嗎?如果沒有,只需將用戶作爲本地用戶,然後他們將不得不輸入他們的密碼來更改路由表。如果您希望將程序設置爲setuid,那麼您需要搜索必須採取的預防措施,才能避免出現嚴重的安全漏洞。 –
最終評論 - exec不會將單個字符串作爲參數。你必須準備一個(可修改的)字符串數組作爲argv。 –