Chinaunix首页 | 论坛 | 博客
  • 博客访问: 402150
  • 博文数量: 78
  • 博客积分: 3642
  • 博客等级: 中校
  • 技术积分: 695
  • 用 户 组: 普通用户
  • 注册时间: 2006-10-23 15:33
文章分类

全部博文(78)

文章存档

2007年(53)

2006年(25)

分类: C/C++

2006-10-25 15:48:36

//drop privileges

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <pwd.h>

int main(int argc,char **argv)
{
    pid_t pid;
    int status;
    struct passwd *pw;

    pw = getpwnam("nobody");

    if(geteuid() != 0)
    {
         printf("You must be root!\n");
         exit(1);
    }
    if(pw == NULL)
    {
        printf("Can't find user nobody\n");
        exit(1);
    }
        
    if(setgid(pw->pw_gid) == -1 || setuid(pw->pw_uid) == -1)
    {
        printf("Unable to switch user %s(%d,%d)\n",pw->pw_name,pw->pw_uid, pw->pw_gid);
        exit(1);
    }

    if(setreuid(-1, 0) == 0)
    {
          printf("Unable to completely drop privileges\n");
          exit(1);
    }

    if(geteuid() == 0)
    {
        printf("Running as root is NOT recommended");
    }

    pid = fork();

    if(pid < 0)
    {
        return -1;
    }
    else if(pid == 0)
    {
        execl("/bin/sh", "sh", "-c","ls", NULL);
        fprintf(stderr,"Something is wrong!\n");
    }

    waitpid(-1,&status,0);
    if(WIFEXITED(status) == 0)
    {
        printf("Exit abnormity\n");
        return -1;
    }
    
    printf("Exit status:%d\n",WEXITSTATUS(status) );

    return 0;
}

阅读(2014) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~