Imported Upstream version 2.7
[ossec-hids.git] / src / shared / privsep_op.c
1 /*      $OSSEC, privsep_op.h, v0.2, 2004/08/05, Daniel B. Cid$      */
2
3 /* Copyright (C) 2009 Trend Micro Inc.
4  * All right reserved.
5  *
6  * This program is a free software; you can redistribute it
7  * and/or modify it under the terms of the GNU General Public
8  * License (version 2) as published by the FSF - Free Software
9  * Foundation
10  */
11
12 /* Part of the OSSEC HIDS
13  * Available at http://www.ossec.net
14  */
15
16 /* Functions for privilege separation.
17  */
18
19 #ifndef WIN32
20
21 #include <stdio.h>
22 #include <pwd.h>
23 #include <grp.h>
24 #include <sys/types.h>
25 #include <unistd.h>
26
27 #include "headers/os_err.h"
28
29 int Privsep_GetUser(char * name)
30 {
31     int os_uid = -1;
32
33     struct passwd *pw;
34     pw = getpwnam(name);
35     if(pw == NULL)
36         return(OS_INVALID);
37
38     os_uid = (int)pw->pw_uid;
39     endpwent();
40
41     return(os_uid);
42 }
43
44 int Privsep_GetGroup(char * name)
45 {
46     int os_gid = -1;
47
48     struct group *grp;
49     grp = getgrnam(name);
50     if(grp == NULL)
51         return(OS_INVALID);
52
53     os_gid = (int)grp->gr_gid;
54     endgrent();
55
56     return(os_gid);
57 }
58
59 int Privsep_SetUser(uid_t uid)
60 {
61     if(setuid(uid) < 0)
62         return(OS_INVALID);
63
64     #ifndef HPUX
65     if(seteuid(uid) < 0)
66         return(OS_INVALID);
67     #endif
68
69     return(OS_SUCCESS);
70 }
71
72 int Privsep_SetGroup(gid_t gid)
73 {
74     if (setgroups(1, &gid) == -1)
75         return(OS_INVALID);
76
77     #ifndef HPUX
78     if(setegid(gid) < 0)
79         return(OS_INVALID);
80     #endif
81
82     if(setgid(gid) < 0)
83         return(OS_INVALID);
84
85     return(OS_SUCCESS);
86 }
87
88 int Privsep_Chroot(char * path)
89 {
90     if(chdir(path) < 0)
91         return(OS_INVALID);
92
93     if(chroot(path) < 0)
94         return(OS_INVALID);
95
96     chdir("/");
97
98     return(OS_SUCCESS);
99 }
100
101 #endif
102 /* EOF */