bmsd/bms.c

changeset 746
44d929ff268e
parent 745
3addb8cfcc3e
child 747
b6fbe6821468
equal deleted inserted replaced
745:3addb8cfcc3e 746:44d929ff268e
69 my_shutdown = TRUE; 69 my_shutdown = TRUE;
70 } 70 }
71 71
72 72
73 73
74 int server(void) { 74 /**
75 uid_t myuid; 75 * @brief Drop privileges in a safe way.
76 * @return 0 on success and -1 on failure.
77 */
78 int drop_root_privileges(uid_t pw_uid, gid_t pw_gid, char *pw_dir)
79 {
80 // no need to "drop" the privileges that you don't have in the first place!
81 if (getuid() == pw_uid && getgid() == pw_gid) {
82 syslog(LOG_NOTICE, "No need to drop privileges");
83 } else {
84 if (setgid(pw_gid) != 0) {
85 syslog(LOG_NOTICE, "setgid: %s", strerror(errno));
86 return -1;
87 }
88 if (setuid(pw_uid) != 0) {
89 syslog(LOG_NOTICE, "setgid: %s", strerror(errno));
90 return -1;
91 }
92 }
93
94 /* Change to the home directory */
95 if (chdir(pw_dir) != 0) {
96 syslog(LOG_NOTICE, "chdir(%s): %s", pw_dir, strerror(errno));
97 return -1;
98 }
99
100 /* check if we successfully dropped the root privileges */
101 if (setuid(0) == 0 || seteuid(0) == 0) {
102 syslog(LOG_NOTICE, "could not drop root privileges!");
103 return -1;
104 }
105
106 syslog(LOG_NOTICE, "Privileges dropped to %d:%d", pw_uid, pw_gid);
107 return 0;
108 }
109
110
111
112 int server(void)
113 {
76 struct passwd *mypwd; 114 struct passwd *mypwd;
77 int rc = 0; 115 int rc = 0;
78 char *tmppath = NULL; 116 char *tmppath = NULL;
79 117
80 myuid = getuid(); 118 mypwd = getpwnam("brewery");
81 mypwd = getpwuid(myuid);
82 if (mypwd == NULL) { 119 if (mypwd == NULL) {
83 fprintf(stderr, "[main] Could not find passwd entry\n"); 120 fprintf(stderr, "[main] Could not find passwd entry\n");
84 return 1; 121 return 1;
85 } 122 }
86 123
87 Private_Path = xstrcpy(mypwd->pw_dir); 124 Private_Path = xstrcpy(mypwd->pw_dir);
88 Private_Path = xstrcat(Private_Path, (char *)"/.bms"); 125 Private_Path = xstrcat(Private_Path, (char *)"/.bms");
126
127 if (drop_root_privileges(mypwd->pw_uid, mypwd->pw_gid, mypwd->pw_dir) < 0) {
128 syslog(LOG_NOTICE, "Can't drop privileges");
129 return 1;
130 }
89 131
90 if (lockprog((char *)"bmsd")) { 132 if (lockprog((char *)"bmsd")) {
91 syslog(LOG_NOTICE, "Can't lock"); 133 syslog(LOG_NOTICE, "Can't lock");
92 return 1; 134 return 1;
93 } 135 }

mercurial