7d28bf4b871d981b38b6f97dd2b452055e84405e
[util-vserver.git] / src / vsh.c
1 /*
2  * Marc E. Fiuczynski <mef@cs.princeton.edu>
3  *
4  * Copyright (c) 2004 The Trustees of Princeton University (Trustees).
5  *
6  * vsh is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2, or (at your option)
9  * any later version.
10  *
11  * vsh is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
14  * License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with Poptop; see the file COPYING.  If not, write to the Free
18  * Software Foundation, 59 Temple Place - Suite 330, Boston, MA
19  * 02111-1307, USA.
20  */
21
22 #ifdef HAVE_CONFIG_H
23 #  include <config.h>
24 #endif
25 #include "compat.h"
26
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <stdlib.h>
31 #include <errno.h>
32 #include <pwd.h>
33 #include <unistd.h>
34 #include <syscall.h>
35 #include <sys/syscall.h>
36 #include <asm/unistd.h>
37 #include <sys/mount.h>
38 #include <sys/types.h>
39 #include <sys/stat.h>
40 #include <sys/resource.h>
41 #include <fcntl.h>
42 #include <ctype.h>
43 #include <stdarg.h>
44
45 //--------------------------------------------------------------------
46 #include "vserver.h"
47 #include "planetlab.h"
48
49 #undef CONFIG_VSERVER_LEGACY
50
51 /* Null byte made explicit */
52 #define NULLBYTE_SIZE                    1
53
54 /* Base for all vserver roots for chroot */
55 #define VSERVER_ROOT_BASE       "/vservers"
56
57 static int
58 _PERROR(const char *format, char *file, int line, int _errno, ...)
59 {
60         va_list ap;
61
62         va_start(ap, _errno);
63         fprintf(stderr, "%s:%d: ", file, line);
64         vfprintf(stderr, format, ap);
65         if (_errno)
66                 fprintf(stderr, ": %s (%d)", strerror(_errno), _errno);
67         fputs("\n", stderr);
68         fflush(stderr);
69
70         return _errno;
71 }
72
73 #define PERROR(format, args...) _PERROR(format, __FILE__, __LINE__, errno, ## args)
74
75 /* Change to root:root (before entering new context) */
76 static int setuidgid_root()
77 {
78         if (setgid(0) < 0) {
79                 PERROR("setgid(0)");
80                 return -1;
81         }
82         if (setuid(0) < 0) {
83                 PERROR("setuid(0)");
84                 return -1;
85         }
86         return 0;
87 }
88
89 static void compute_new_root(char *base, char **root, uid_t uid)
90 {
91         int             root_len;
92         struct passwd   *pwd;
93
94         if ((pwd = getpwuid(uid)) == NULL) {
95                 PERROR("getpwuid(%d)", uid);
96                 exit(1);
97         }
98
99         root_len = 
100                 strlen(base) + strlen("/") +
101                 strlen(pwd->pw_name)      + NULLBYTE_SIZE;
102         (*root) = (char *)malloc(root_len);
103         if ((*root) == NULL) {
104                 PERROR("malloc(%d)", root_len);
105                 exit(1);
106         }
107     
108         sprintf((*root), "%s/%s", base, pwd->pw_name);
109         (*root)[root_len - 1] = '\0';
110 }
111
112 /* Example: sandbox_root = /vservers/bnc, relpath = /proc/1 */
113 static int sandbox_file_exists(char *sandbox_root, char *relpath)
114 {
115         struct stat stat_buf;
116         char   *file;
117         int    len, exists = 0;
118
119         len = strlen(sandbox_root) + strlen(relpath) + NULLBYTE_SIZE;
120         if ((file = (char *)malloc(len)) == NULL) {
121                 PERROR("malloc(%d)", len);
122                 exit(1);
123         }
124         sprintf(file, "%s%s", sandbox_root, relpath);
125         file[len - 1] = '\0';
126         if (stat(file, &stat_buf) == 0) {
127                 exists = 1;
128         }
129
130
131         free(file);
132         return exists;
133 }
134
135 static int proc_mounted(char *sandbox_root)
136 {
137         return sandbox_file_exists(sandbox_root, "/proc/1");
138 }
139
140 static int devpts_mounted(char *sandbox_root)
141 {
142         return sandbox_file_exists(sandbox_root, "/dev/pts/0");
143 }
144
145 static void mount_proc(char *sandbox_root)
146 {
147         char        *source = "/proc";
148         char        *target;
149         int         len;
150
151         len = strlen(sandbox_root) + strlen("/") + strlen("proc") + NULLBYTE_SIZE;
152         if ((target = (char *)malloc(len)) == NULL) {
153                 PERROR("malloc(%d)", len);
154                 exit(1);
155         }
156
157         sprintf(target, "%s/proc", sandbox_root);
158         target[len - 1] = '\0';
159         if (!proc_mounted(sandbox_root))
160                 mount(source, target, "proc", MS_BIND | MS_RDONLY, NULL);
161
162         free(target);
163 }
164
165 static void mount_devpts(char *sandbox_root)
166 {
167         char        *source = "/dev/pts";
168         char        *target;
169         int         len;
170     
171         len = strlen(sandbox_root) + strlen("/") + strlen("dev/pts") + NULLBYTE_SIZE;
172         if ((target = (char *)malloc(len)) == NULL) {
173                 PERROR("malloc(%d)", len);
174                 exit(1);
175         }
176
177         sprintf(target, "%s/dev/pts", sandbox_root);
178         target[len - 1] = '\0';
179         if (!devpts_mounted(sandbox_root))
180                 mount(source, target, "devpts", 0, NULL);
181
182         free(target);
183 }
184
185 static int sandbox_chroot(uid_t uid)
186 {
187         char *sandbox_root = NULL;
188
189         compute_new_root(VSERVER_ROOT_BASE,&sandbox_root, uid);
190         mount_proc(sandbox_root);
191         mount_devpts(sandbox_root);
192         if (chroot(sandbox_root) < 0) {
193                 PERROR("chroot(%s)", sandbox_root);
194                 exit(1);
195         }
196         if (chdir("/") < 0) {
197                 PERROR("chdir(/)");
198                 exit(1);
199         }
200         return 0;
201 }
202
203 #define WHITESPACE(buffer,index,len)     \
204   while(isspace((int)buffer[index])) \
205         if (index < len) index++; else goto out;
206
207 struct resources {
208         char *name;
209         unsigned long long *limit;
210 };
211
212 #define VSERVERCONF "/etc/vservers/"
213 static void get_limits(char *context, struct resources *list){
214         FILE *fb;
215         size_t len = strlen(VSERVERCONF) + strlen(context) + strlen(".conf") + NULLBYTE_SIZE;
216         char *conf = (char *)malloc(len);       
217         struct resources *r;
218
219         sprintf(conf, "%s%s.conf", VSERVERCONF, context);
220
221         /* open the conf file for reading */
222         fb = fopen(conf,"r");
223         if (fb != NULL) {
224                 size_t index;
225                 char *buffer = malloc(1000);
226                 char *p;
227
228                 /* the conf file exist */ 
229                 while((p=fgets(buffer,1000-1,fb))!=NULL) {
230                         index = 0;
231                         len = strnlen(buffer,1000);
232                         WHITESPACE(buffer,index,len);
233                         if (buffer[index] == '#') 
234                                 continue;
235
236                         for (r=list; r->name; r++)
237                                 if ((p=strstr(&buffer[index],r->name))!=NULL) {
238                                         /* adjust index into buffer */
239                                         index+= (p-&buffer[index])+strlen(r->name);
240
241                                         /* skip over whitespace */
242                                         WHITESPACE(buffer,index,len);
243
244                                         /* expecting to see = sign */
245                                         if (buffer[index++]!='=') goto out;
246
247                                         /* skip over whitespace */
248                                         WHITESPACE(buffer,index,len);
249
250                                         /* expecting to see a digit for number */
251                                         if (!isdigit((int)buffer[index])) goto out;
252
253                                         *r->limit = atoi(&buffer[index]);
254                                         break;
255                                 }
256                 }
257         out:
258                 free(buffer);
259         } else {
260                 fprintf(stderr,"cannot open %s\n",conf);
261         }
262         free(conf);
263 }
264
265
266 static int sandbox_processes(xid_t ctx, char *context)
267 {
268 #ifdef CONFIG_VSERVER_LEGACY
269         int     flags;
270
271         flags = 0;
272         flags |= 1; /* VX_INFO_LOCK -- cannot request a new vx_id */
273         /* flags |= 4; VX_INFO_NPROC -- limit number of procs in a context */
274
275         (void) vc_new_s_context(ctx, 0, flags);
276
277         /* use legacy dirty hack for capremove */
278         if (vc_new_s_context(VC_SAMECTX, vc_get_insecurebcaps(), flags) == VC_NOCTX) {
279                 PERROR("vc_new_s_context(%u, 0x%16ullx, 0x%08x)",
280                        VC_SAMECTX, vc_get_insecurebcaps(), flags);
281                 exit(1);
282         }
283 #else
284         int  ctx_is_new;
285         unsigned long long cpu = VC_LIM_KEEP;
286         unsigned long long mem = VC_LIM_KEEP;
287         unsigned long long task = VC_LIM_KEEP;
288         unsigned long long cpuguaranteed = 0;
289         struct resources list[] = 
290                 {{"MEMLIMIT", &mem},
291                  {"CPULIMIT", &cpu},
292                  {"CPUGUARANTEED", &cpuguaranteed},
293                  {"TASKLIMIT", &task},
294                  {0,0}};
295
296         get_limits(context,list);
297
298         /* check whether the slice has been disabled */
299         if (!cpu)
300           {
301             fprintf(stderr, "*** this slice has been suspended ***\n");
302             exit(0);
303           }
304
305         (void) (sandbox_chroot(ctx));
306
307         if ((ctx_is_new = pl_chcontext(ctx, 0, ~vc_get_insecurebcaps())) < 0)
308           {
309             PERROR("pl_chcontext(%u)", ctx);
310             exit(1);
311           }
312         if (ctx_is_new)
313           {
314             /* set resources */
315             struct vc_rlimit limits;
316
317             limits.min = VC_LIM_KEEP;
318             limits.soft = VC_LIM_KEEP;
319             limits.hard = mem;
320             if (vc_set_rlimit(ctx, RLIMIT_RSS, &limits))
321               {
322                 PERROR("pl_setrlimit(%u, RLIMIT_RSS)", ctx);
323                 exit(1);
324               }
325             limits.hard = task;
326             if (vc_set_rlimit(ctx, RLIMIT_NPROC, &limits))
327               {
328                 PERROR("pl_setrlimit(%u, RLIMIT_NPROC)", ctx);
329                 exit(1);
330               }
331             cpuguaranteed &= VS_SCHED_CPU_GUARANTEED;
332             if (pl_setsched(ctx, cpu, cpuguaranteed) < 0)
333               {
334                 PERROR("pl_setsched(&u)", ctx);
335                 exit(1);
336               }
337             pl_setup_done(ctx);
338           }
339 #endif
340         return 0;
341 }
342
343
344 void runas_slice_user(char *username)
345 {
346         struct passwd pwdd, *pwd = &pwdd, *result;
347         char          *pwdBuffer;
348         char          *home_env, *logname_env, *mail_env, *shell_env, *user_env;
349         int           home_len, logname_len, mail_len, shell_len, user_len;
350         long          pwdBuffer_len;
351         static char   *envp[10];
352
353
354         pwdBuffer_len = sysconf(_SC_GETPW_R_SIZE_MAX);
355         if (pwdBuffer_len == -1) {
356                 PERROR("sysconf(_SC_GETPW_R_SIZE_MAX)");
357                 exit(1);
358         }
359
360         pwdBuffer = (char*)malloc(pwdBuffer_len);
361         if (pwdBuffer == NULL) {
362                 PERROR("malloc(%d)", pwdBuffer_len);
363                 exit(1);
364         }
365
366         errno = 0;
367         if ((getpwnam_r(username,pwd,pwdBuffer,pwdBuffer_len, &result) != 0) || (errno != 0)) {
368                 PERROR("getpwnam_r(%s)", username);
369                 exit(1);
370         }
371
372         if (setgid(pwd->pw_gid) < 0) {
373                 PERROR("setgid(%d)", pwd->pw_gid);
374                 exit(1);
375         }
376
377         if (setuid(pwd->pw_uid) < 0) {
378                 PERROR("setuid(%d)", pwd->pw_uid);
379                 exit(1);
380         }
381
382         if (chdir(pwd->pw_dir) < 0) {
383                 PERROR("chdir(%s)", pwd->pw_dir);
384                 exit(1);
385         }
386
387         home_len    = strlen("HOME=") + strlen(pwd->pw_dir) + NULLBYTE_SIZE;
388         logname_len = strlen("LOGNAME=") + strlen(username) + NULLBYTE_SIZE;
389         mail_len    = strlen("MAIL=/var/spool/mail/") + strlen(username) 
390                 + NULLBYTE_SIZE;
391         shell_len   = strlen("SHELL=") + strlen(pwd->pw_shell) + NULLBYTE_SIZE;
392         user_len    = strlen("USER=") + strlen(username) + NULLBYTE_SIZE;
393
394         home_env    = (char *)malloc(home_len);
395         logname_env = (char *)malloc(logname_len);
396         mail_env    = (char *)malloc(mail_len);
397         shell_env   = (char *)malloc(shell_len);
398         user_env    = (char *)malloc(user_len);
399
400         if ((home_env    == NULL)  || 
401             (logname_env == NULL)  ||
402             (mail_env    == NULL)  ||
403             (shell_env   == NULL)  ||
404             (user_env    == NULL)) {
405                 PERROR("malloc");
406                 exit(1);
407         }
408
409         sprintf(home_env, "HOME=%s", pwd->pw_dir);
410         sprintf(logname_env, "LOGNAME=%s", username);
411         sprintf(mail_env, "MAIL=/var/spool/mail/%s", username);
412         sprintf(shell_env, "SHELL=%s", pwd->pw_shell);
413         sprintf(user_env, "USER=%s", username);
414     
415         home_env[home_len - 1]       = '\0';
416         logname_env[logname_len - 1] = '\0';
417         mail_env[mail_len - 1]       = '\0';
418         shell_env[shell_len - 1]     = '\0';
419         user_env[user_len - 1]       = '\0';
420
421         envp[0] = home_env;
422         envp[1] = logname_env;
423         envp[2] = mail_env;
424         envp[3] = shell_env;
425         envp[4] = user_env;
426         envp[5] = 0;
427
428         if ((putenv(home_env)    < 0) ||
429             (putenv(logname_env) < 0) ||
430             (putenv(mail_env)    < 0) ||
431             (putenv(shell_env)   < 0) ||
432             (putenv(user_env)    < 0)) {
433                 PERROR("vserver: putenv error ");
434                 exit(1);
435         }
436 }
437
438 void slice_enter(char *context)
439 {
440         struct passwd pwdd, *pwd = &pwdd, *result;
441         char          *pwdBuffer;
442         long          pwdBuffer_len;
443         uid_t uid;
444
445         pwdBuffer_len = sysconf(_SC_GETPW_R_SIZE_MAX);
446         if (pwdBuffer_len == -1) {
447                 PERROR("sysconf(_SC_GETPW_R_SIZE_MAX)");
448                 exit(1);
449         }
450
451         pwdBuffer = (char*)malloc(pwdBuffer_len);
452         if (pwdBuffer == NULL) {
453                 PERROR("malloc(%d)", pwdBuffer_len);
454                 exit(1);
455         }
456
457         errno = 0;
458         if ((getpwnam_r(context,pwd,pwdBuffer,pwdBuffer_len, &result) != 0) || (errno != 0)) {
459                 PERROR("getpwnam_r(%s)", context);
460                 exit(2);
461         }
462         uid = pwd->pw_uid;
463
464         if (setuidgid_root() < 0) { /* For chroot, new_s_context */
465                 fprintf(stderr, "vsh: Could not become root, check that SUID flag is set on binary\n");
466                 exit(2);
467         }
468
469 #ifdef CONFIG_VSERVER_LEGACY
470         (void) (sandbox_chroot(uid));
471 #endif
472
473         if (sandbox_processes((xid_t) uid, context) < 0) {
474                 fprintf(stderr, "vsh: Could not change context to %d\n", uid);
475                 exit(2);
476         }
477 }
478
479 //--------------------------------------------------------------------
480
481 #define DEFAULT_SHELL "/bin/sh"
482
483 /* Exit statuses for programs like 'env' that exec other programs.
484    EXIT_FAILURE might not be 1, so use EXIT_FAIL in such programs.  */
485 enum
486 {
487   EXIT_CANNOT_INVOKE = 126,
488   EXIT_ENOENT = 127
489 };
490
491 int main(int argc, char **argv)
492 {
493     struct passwd   pwdd, *pwd = &pwdd, *result;
494     char            *context, *username, *shell, *pwdBuffer;
495     long            pwdBuffer_len;
496     uid_t           uid;
497     int             index, i;
498
499     if (argv[0][0]=='-') 
500       index = 1;
501     else
502       index = 0;
503
504     uid = getuid();
505     if ((pwd = getpwuid(uid)) == NULL) {
506       PERROR("getpwuid(%d)", uid);
507       exit(1);
508     }
509
510     context = (char*)strdup(pwd->pw_name);
511     if (!context) {
512       PERROR("strdup");
513       exit(2);
514     }
515
516     /* enter vserver "context" */
517     slice_enter(context);
518
519     /* Now run as username in this context. Note that for PlanetLab's
520        vserver configuration the context name also happens to be the
521        "default" username within the vserver context.
522     */
523     username = context;
524     runas_slice_user(username);
525
526     /* With the uid/gid appropriately set. Let's figure out what the
527      * shell in the vserver's /etc/passwd is for the given username.
528      */
529
530     pwdBuffer_len = sysconf(_SC_GETPW_R_SIZE_MAX);
531     if (pwdBuffer_len == -1) {
532             PERROR("sysconf(_SC_GETPW_R_SIZE_MAX");
533             exit(1);
534     }
535     pwdBuffer = (char*)malloc(pwdBuffer_len);
536     if (pwdBuffer == NULL) {
537             PERROR("malloc(%d)", pwdBuffer_len);
538             exit(1);
539     }
540
541     errno = 0;
542     if ((getpwnam_r(username,pwd,pwdBuffer,pwdBuffer_len, &result) != 0) || (errno != 0)) {
543         PERROR("getpwnam_r(%s)", username);
544         exit(1);
545     }
546
547     /* Make sure pw->pw_shell is non-NULL.*/
548     if (pwd->pw_shell == NULL || pwd->pw_shell[0] == '\0') {
549       pwd->pw_shell = (char *) DEFAULT_SHELL;
550     }
551
552     shell = (char *)strdup(pwd->pw_shell);
553     if (!shell) {
554       PERROR("strdup");
555       exit(2);
556     }
557
558     /* Check whether 'su' or 'sshd' invoked us as a login shell or
559        not; did this above when testing argv[0]=='-'.
560     */
561     argv[0] = shell;
562     if (index == 1) {
563       char **args;
564       args = (char**)malloc(sizeof(char*)*(argc+2));
565       if (!args) {
566         PERROR("malloc(%d)", sizeof(char*)*(argc+2));
567         exit(1);
568       }
569       args[0] = argv[0];
570       args[1] = "-l";
571       for(i=1;i<argc+1;i++) {
572         args[i+1] = argv[i];
573       }
574       argv = args;
575     }
576     (void) execvp(shell,argv);
577     {
578       int exit_status = (errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE);
579       exit (exit_status);
580     }
581
582     return 0; /* shutup compiler */
583 }