1 #include <sys/types.h>
2 #include <pwd.h>
3 #include <grp.h>
4 #include "sancp.h"
5 
SChangeUserGroup(void)6 void SChangeUserGroup(void){
7 	struct passwd *pw;
8 	struct group *gr;
9 
10 	extern gvars gVars;
11 
12 	gVars.uid=getuid();
13 	gVars.gid=getgid();
14 
15 	if(gVars.username!=NULL){
16 
17 		if((gVars.uid = atoi(gVars.username)) == 0)
18 		{
19 			pw = getpwnam(gVars.username);
20 			if(pw == NULL){
21 				syslog(LOG_ERR,"User \"%s\" unknown\n", gVars.username);
22 				exit(0);
23 
24 			}
25 	      		gVars.uid = pw->pw_uid;
26 		}
27 		else
28 		{
29 			pw = getpwuid(gVars.uid);
30 			if(pw == NULL){
31 				syslog(LOG_ERR,"Can not obtain username for uid: %lu\n", (u_long) gVars.uid);
32 		    	 	exit(0);
33 			}
34 		}
35 		gVars.gid = pw->pw_gid;
36 	}
37 
38 	if(gVars.groupname != NULL){
39 
40         	if((gVars.gid = atoi(gVars.groupname)) == 0)
41 	        {
42 	            gr = getgrnam(gVars.groupname);
43 
44 	            if(gr == NULL)
45 		    {
46 	                 syslog(LOG_ERR,"Group \"%s\" unknown\n", gVars.groupname);
47 		    	 exit(0);
48 		    }
49 
50 	            gVars.gid = gr->gr_gid;
51 		}
52 	}
53 	if(gVars.groupname != NULL)
54 	{
55 		if(setgid(gVars.gid) < 0){
56 			syslog(LOG_ERR,"Can not set gid: %lu\n", (u_long) gVars.gid);
57 			exit(0);
58 		}
59 	}
60 
61 	if(gVars.username != NULL)
62 	{
63 		if(gVars.groupname == NULL)
64 		{
65 			if(setgid(gVars.gid) < 0){
66 				syslog(LOG_ERR,"Can not set gid: %lu\n", (u_long) gVars.gid);
67 				exit(0);
68 
69 			}
70 		}
71 		if(getuid() == 0 && initgroups(gVars.username, gVars.gid) < 0){
72 			syslog(LOG_ERR,"Can not initgroups(%s,%lu)", gVars.username, (u_long) gVars.gid);
73 			exit(0);
74 		}
75 		endgrent();
76 		endpwent();
77  		if(setuid(gVars.uid) < 0){
78 			syslog(LOG_ERR,"Can not set uid: %lu\n", (u_long) gVars.uid);
79 		    	 exit(0);
80 		}
81 	}
82 }
83 
84