c++ - 无法提升程序权限
问题描述
我正在从具有 sudo 访问权限的用户运行 C++ 程序。二进制是用./binName
命令启动的。
从它我可以执行sudo ls
功能popen
- 这工作正常。所以我虽然我可以用open
函数打开一些特权文件,但它返回 -1 并带有 errno= 13:Permission denied。
所以然后我虽然我需要强制设置我的euid,seteuid
但它返回-1,errno = 13:权限被拒绝
当我启动sudo ./binName
所有工作正常的程序时,我可以打开任何具有open
功能的文件。我做错了什么?
#include <stdio.h>
#include <vector>
#include <cstdint>
#include <cstring>
#include <string>
#include <fcntl.h>
#include <unistd.h>
#define Log(fmt, ...) printf("%s | " fmt, __FUNCTION__, ##__VA_ARGS__)
bool OpenPath(const std::string& path) {
if (path.empty()) return false;
const int f = open(path.c_str(), O_RDWR);
if (f == -1){
Log("[!] Unable to open %s, errno= %d:%s\n", path.c_str(), errno, strerror(errno));
return false;
}
close(f);
return true;
}
bool ReadFromStream(const char *command, std::vector<uint8_t> &output)
{
FILE *fp = popen(command, "r");
if (!fp)
{
Log("[!] Error: Unable to popen\n");
return false;
}
char str[512];
while (!feof(fp))
{
if (fgets(str, sizeof(str), fp))
{
const int size = strlen(str);
output.insert(output.end(), str, str + size);
}
}
pclose(fp);
return !output.empty();
}
bool HasRights() {
const __uid_t uid = getuid();
const __uid_t gid = geteuid();
bool elevated = uid == 0 || uid != gid;
Log("uid= %d, gid= %d, elevated= %d\n", uid, gid, elevated);
if (elevated && OpenPath("/usr/bin/ls")) // it's just a test path
return true;
std::vector<uint8_t> buffer;
if (ReadFromStream("sudo -n ls", buffer)) {
const std::string str(buffer.begin(), buffer.end());
if (str != "sudo: a password is required")
{
if (seteuid(0) == -1) {
Log("[!] Unable seteuid, errno= %d:%s\n", errno, strerror(errno));
}
return OpenPath("/usr/bin/ls"); // it's just a test path
}
}
return false;
}
int main(int argc, char **argv)
const auto hasRights = HasRights();
Log("hasRights= %d\n", hasRights);
return 0;
}
没有 sudo 权限的输出= ./binName
HasRights | uid= 1000, gid= 1000, elevated= 0
HasRights | [!] Unable seteuid, errno= 1:Operation not permitted
OpenPath | [!] Unable to open /usr/bin/ls, errno= 13:Permission denied
test | hasRights= 0
具有 sudo 权限的输出= sudo ./binName
HasRights | uid= 0, gid= 0, elevated= 1
test | hasRights= 1
sudo 超时时的输出= ./binName
HasRights | uid= 1000, gid= 1000, elevated= 0
sudo: a password is required
test | hasRights= 0