如何在linux上从c++程序将权限级别提升到root

How to elevate privilege level to root from c++ program on linux

本文关键字:root 权限 linux 上从 程序 c++      更新时间:2023-10-16

我想从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标志。我怎么能避免每次都做这种改变呢?

不需要setreuid()调用。可执行文件上的suid位就足够了,并且可以做完全相同的事情。这个setreuid()调用在这里什么都不做。

如果需要执行setgid()setuid(),则可能需要也可能不需要执行。