b1bd75aac907fdbf09d5cc06cbdf8f1348a605da
[sysvinit.git] / src / sulogin.c
1 /*
2 * sulogin This program gives Linux machines a reasonable
3 * secure way to boot single user. It forces the
4 * user to supply the root password before a
5 * shell is started.
6 *
7 * If there is a shadow password file and the
8 * encrypted root password is "x" the shadow
9 * password will be used.
10 *
11 * Version: @(#)sulogin 2.85-3 23-Apr-2003 miquels@cistron.nl
12 *
13 * Copyright (C) 1998-2003 Miquel van Smoorenburg.
14 *
15 * This program is free software; you can redistribute it and/or modify
16 * it under the terms of the GNU General Public License as published by
17 * the Free Software Foundation; either version 2 of the License, or
18 * (at your option) any later version.
19 *
20 * This program is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * You should have received a copy of the GNU General Public License
26 * along with this program; if not, write to the Free Software
27 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
28 *
29 */
30
31 #include <sys/mman.h>
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <sys/wait.h>
35 #include <stdio.h>
36 #include <string.h>
37 #include <stdlib.h>
38 #include <unistd.h>
39 #include <fcntl.h>
40 #include <signal.h>
41 #include <pwd.h>
42 #include <shadow.h>
43 #include <termios.h>
44 #include <sys/ttydefaults.h>
45 #include <errno.h>
46 #include <sys/ioctl.h>
47 #if defined(__GLIBC__)
48 # include <crypt.h>
49 # define dovoid(f) if ((f)){}
50 #endif
51 #ifdef __linux__
52 # include <sys/statfs.h>
53 # include <sys/mount.h>
54 # include <linux/fs.h>
55 # include <linux/magic.h>
56 # include <linux/major.h>
57 # ifndef TMPFS_MAGIC
58 # define TMPFS_MAGIC 0x01021994
59 # endif
60 # ifndef MNT_DETACH
61 # define MNT_DETACH 2
62 # endif
63 #endif
64
65 #define BS CTRL('h')
66 #define NL CTRL('j')
67 #define CR CTRL('m')
68
69 #ifdef WITH_SELINUX
70 # include <selinux/selinux.h>
71 # include <selinux/get_context_list.h>
72 #endif
73
74 #include "consoles.h"
75 #define CONMAX 16
76
77 #define CHECK_DES 1
78 #define CHECK_MD5 1
79
80 #define F_PASSWD "/etc/passwd"
81 #define F_SHADOW "/etc/shadow"
82 #define BINSH "/bin/sh"
83 #define STATICSH "/bin/sash"
84
85 char *Version = "@(#)sulogin 2.85-3 23-Apr-2003 miquels@cistron.nl";
86
87 static int timeout;
88 static int profile;
89 static volatile uint32_t openfd; /* Remember higher file descriptors */
90 static volatile uint32_t *usemask;
91
92 static sighandler_t saved_sigint = SIG_DFL;
93 static sighandler_t saved_sigtstp = SIG_DFL;
94 static sighandler_t saved_sigquit = SIG_DFL;
95 static sighandler_t saved_sighup = SIG_DFL;
96
97 static volatile sig_atomic_t alarm_rised;
98 static volatile sig_atomic_t sigchild;
99
100 #ifndef IUCLC
101 # define IUCLC 0
102 #endif
103
104 /*
105 * Fix the tty modes and set reasonable defaults.
106 */
107 static
108 void tcinit(struct console *con)
109 {
110 int serial, flags;
111 struct termios *tio = &con->tio;
112 int fd = con->fd;
113
114 /* Expected error */
115 serial = errno = 0;
116
117 /* Get line attributes */
118 if (tcgetattr(fd, tio) < 0) {
119 con->flags |= CON_NOTTY;
120 return;
121 }
122
123 /* Handle serial lines here */
124 if (ioctl (fd, TIOCMGET, (char*)&serial) == 0) {
125 speed_t ispeed, ospeed;
126 struct winsize ws;
127
128 /* this is a modem line */
129 con->flags |= CON_SERIAL;
130
131 /* Flush input and output queues on modem lines */
132 (void) tcflush(fd, TCIOFLUSH);
133
134 ispeed = cfgetispeed(tio);
135 ospeed = cfgetospeed(tio);
136
137 if (!ispeed) ispeed = TTYDEF_SPEED;
138 if (!ospeed) ospeed = TTYDEF_SPEED;
139
140 tio->c_iflag = tio->c_lflag = tio->c_oflag = 0;
141 tio->c_cflag = CREAD | CS8 | HUPCL | (tio->c_cflag & CLOCAL);
142
143 cfsetispeed(tio, ispeed);
144 cfsetospeed(tio, ospeed);
145
146 tio->c_line = 0;
147 tio->c_cc[VTIME] = 0;
148 tio->c_cc[VMIN] = 1;
149
150 if (ioctl(fd, TIOCGWINSZ, &ws) == 0) {
151 int set = 0;
152 if (ws.ws_row == 0) {
153 ws.ws_row = 24;
154 set++;
155 }
156 if (ws.ws_col == 0) {
157 ws.ws_col = 80;
158 set++;
159 }
160 (void)ioctl(fd, TIOCSWINSZ, &ws);
161 }
162
163 goto setattr;
164 }
165 #if defined(SANE_TIO) && (SANE_TIO == 1)
166 /*
167 * Use defaults of <sys/ttydefaults.h> for base settings
168 * of a local terminal line like a virtual console.
169 */
170 tio->c_iflag |= TTYDEF_IFLAG;
171 tio->c_oflag |= TTYDEF_OFLAG;
172 tio->c_lflag |= TTYDEF_LFLAG;
173 # ifdef CBAUD
174 tio->c_lflag &= ~CBAUD;
175 # endif
176 tio->c_cflag |= (B38400 | TTYDEF_CFLAG);
177
178 /* Sane setting, allow eight bit characters, no carriage return delay
179 * the same result as `stty sane cr0 pass8'
180 */
181 tio->c_iflag |= (BRKINT | ICRNL | IMAXBEL);
182 tio->c_iflag &= ~(IGNBRK | INLCR | IGNCR | IXOFF | IUCLC | IXANY | INPCK | ISTRIP);
183 tio->c_oflag |= (OPOST | ONLCR | NL0 | CR0 | TAB0 | BS0 | VT0 | FF0);
184 tio->c_oflag &= ~(OLCUC | OCRNL | ONOCR | ONLRET | OFILL | OFDEL |\
185 NLDLY|CRDLY|TABDLY|BSDLY|VTDLY|FFDLY);
186 tio->c_lflag |= (ISIG | ICANON | IEXTEN | ECHO|ECHOE|ECHOK|ECHOKE);
187 tio->c_lflag &= ~(ECHONL|ECHOCTL|ECHOPRT | NOFLSH | XCASE | TOSTOP);
188 tio->c_cflag |= (CREAD | CS8 | HUPCL);
189 tio->c_cflag &= ~(PARODD | PARENB);
190
191 /*
192 * VTIME and VMIN can overlap with VEOF and VEOL since they are
193 * only used for non-canonical mode. We just set the at the
194 * beginning, so nothing bad should happen.
195 */
196 tio->c_cc[VTIME] = 0;
197 tio->c_cc[VMIN] = CMIN;
198 tio->c_cc[VINTR] = CINTR;
199 tio->c_cc[VQUIT] = CQUIT;
200 tio->c_cc[VERASE] = CERASE; /* ASCII DEL (0177) */
201 tio->c_cc[VKILL] = CKILL;
202 tio->c_cc[VEOF] = CEOF;
203 # ifdef VSWTC
204 tio->c_cc[VSWTC] = _POSIX_VDISABLE;
205 # else
206 tio->c_cc[VSWTCH] = _POSIX_VDISABLE;
207 # endif
208 tio->c_cc[VSTART] = CSTART;
209 tio->c_cc[VSTOP] = CSTOP;
210 tio->c_cc[VSUSP] = CSUSP;
211 tio->c_cc[VEOL] = _POSIX_VDISABLE;
212 tio->c_cc[VREPRINT] = CREPRINT;
213 tio->c_cc[VDISCARD] = CDISCARD;
214 tio->c_cc[VWERASE] = CWERASE;
215 tio->c_cc[VLNEXT] = CLNEXT;
216 tio->c_cc[VEOL2] = _POSIX_VDISABLE;
217 #endif
218 setattr:
219 /* Set line attributes */
220 tcsetattr(fd, TCSANOW, tio);
221
222 /* Enable blocking mode for read and write */
223 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
224 (void)fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
225 }
226
227
228 /*
229 * Finalize the tty modes on modem lines.
230 */
231 static
232 void tcfinal(struct console *con)
233 {
234 int serial;
235 struct termios *tio = &con->tio;
236 int fd = con->fd;
237
238 /* Expected error */
239 serial = errno = 0;
240
241 if ((con->flags & CON_SERIAL) == 0) {
242 #ifdef __linux__
243 setenv("TERM", "linux", 1);
244 #else
245 setenv("TERM", "vt100", 1);
246 #endif
247 return;
248 }
249 if (con->flags & CON_NOTTY)
250 return;
251 setenv("TERM", "vt100", 1);
252
253 tio->c_iflag |= (IXON | IXOFF);
254 tio->c_lflag |= (ICANON | ISIG | ECHO|ECHOE|ECHOK|ECHOKE);
255 tio->c_oflag |= OPOST;
256
257 tio->c_cc[VINTR] = CINTR;
258 tio->c_cc[VQUIT] = CQUIT;
259 tio->c_cc[VERASE] = con->cp.erase;
260 tio->c_cc[VKILL] = con->cp.kill;
261 tio->c_cc[VEOF] = CEOF;
262 #ifdef VSWTC
263 tio->c_cc[VSWTC] = _POSIX_VDISABLE;
264 #else
265 tio->c_cc[VSWTCH] = _POSIX_VDISABLE;
266 #endif
267 tio->c_cc[VSTART] = CSTART;
268 tio->c_cc[VSTOP] = CSTOP;
269 tio->c_cc[VSUSP] = CSUSP;
270 tio->c_cc[VEOL] = _POSIX_VDISABLE;
271
272 if (con->cp.eol == CR) {
273 tio->c_iflag |= ICRNL;
274 tio->c_iflag &= ~(INLCR|IGNCR);
275 tio->c_oflag |= ONLCR;
276 tio->c_oflag &= ~(OCRNL|ONLRET);
277 }
278
279 switch (con->cp.parity) {
280 default:
281 case 0:
282 tio->c_cflag &= ~(PARODD | PARENB);
283 tio->c_iflag &= ~(INPCK | ISTRIP);
284 break;
285 case 1: /* odd parity */
286 tio->c_cflag |= PARODD;
287 /* fall through */
288 case 2: /* even parity */
289 tio->c_cflag |= PARENB;
290 tio->c_iflag |= (INPCK | ISTRIP);
291 /* fall through */
292 case (1 | 2): /* no parity bit */
293 tio->c_cflag &= ~CSIZE;
294 tio->c_cflag |= CS7;
295 break;
296 }
297
298 /* Set line attributes */
299 (void)tcsetattr(fd, TCSANOW, tio);
300 }
301
302 /*
303 * Called at timeout.
304 */
305 static
306 # ifdef __GNUC__
307 __attribute__((__noinline__))
308 void alrm_handler(int sig __attribute__((unused)))
309 # else
310 void alrm_handler(int sig)
311 # endif
312 {
313 alarm_rised++;
314 }
315
316 /*
317 * Called at timeout.
318 */
319 static
320 # ifdef __GNUC__
321 __attribute__((__noinline__))
322 void chld_handler(int sig __attribute__((unused)))
323 # else
324 void chld_handler(int sig)
325 # endif
326 {
327 sigchild++;
328 }
329
330 /*
331 * See if an encrypted password is valid. The encrypted
332 * password is checked for traditional-style DES and
333 * FreeBSD-style MD5 encryption.
334 */
335 static
336 int valid(const char *pass)
337 {
338 const char *s;
339 char id[5];
340 size_t len;
341 off_t off;
342
343 if (pass[0] == 0) return 1;
344 #if CHECK_MD5
345 if (pass[0] != '$') goto check_des;
346
347 /*
348 * up to 4 bytes for the signature e.g. $1$
349 */
350 for(s = pass+1; *s && *s != '$'; s++)
351 ;
352 if (*s++ != '$') return 0;
353 if ((off = (off_t)(s-pass)) > 4 || off < 3) return 0;
354
355 memset(id, '\0', sizeof(id));
356 strncpy(id, pass, off);
357
358 /*
359 * up to 16 bytes for the salt
360 */
361 for(; *s && *s != '$'; s++)
362 ;
363 if (*s++ != '$') return 0;
364 if ((off_t)(s-pass) > 16) return 0;
365 len = strlen(s);
366
367 /*
368 * the MD5 hash (128 bits or 16 bytes) encoded in base64 = 22 bytes
369 */
370 if ((strcmp(id, "$1$") == 0) && (len < 22 || len > 24)) return 0;
371
372 /*
373 * the SHA-256 hash 43 bytes
374 */
375 if ((strcmp(id, "$5$") == 0) && (len < 42 || len > 44)) return 0;
376
377 /*
378 * the SHA-512 hash 86 bytes
379 */
380 if ((strcmp(id, "$6$") == 0) && (len < 85 || len > 87)) return 0;
381
382 /*
383 * e.g. Blowfish hash
384 */
385 return 1;
386 check_des:
387 #endif
388 #if CHECK_DES
389 if (strlen(pass) != 13) return 0;
390 for (s = pass; *s; s++) {
391 if ((*s < '0' || *s > '9') &&
392 (*s < 'a' || *s > 'z') &&
393 (*s < 'A' || *s > 'Z') &&
394 *s != '.' && *s != '/') return 0;
395 }
396 #endif
397 return 1;
398 }
399
400 /*
401 * Set a variable if the value is not NULL.
402 */
403 static
404 void set(char **var, char *val)
405 {
406 if (val) *var = val;
407 }
408
409 /*
410 * Get the root password entry.
411 */
412 static
413 struct passwd *getrootpwent(int try_manually)
414 {
415 static struct passwd pwd;
416 struct passwd *pw;
417 struct spwd *spw;
418 FILE *fp;
419 static char line[256];
420 static char sline[256];
421 char *p;
422
423 /*
424 * First, we try to get the password the standard
425 * way using normal library calls.
426 */
427 if ((pw = getpwnam("root")) &&
428 !strcmp(pw->pw_passwd, "x") &&
429 (spw = getspnam("root")))
430 pw->pw_passwd = spw->sp_pwdp;
431 if (pw || !try_manually) return pw;
432
433 /*
434 * If we come here, we could not retrieve the root
435 * password through library calls and we try to
436 * read the password and shadow files manually.
437 */
438 pwd.pw_name = "root";
439 pwd.pw_passwd = "";
440 pwd.pw_gecos = "Super User";
441 pwd.pw_dir = "/";
442 pwd.pw_shell = "";
443 pwd.pw_uid = 0;
444 pwd.pw_gid = 0;
445
446 if ((fp = fopen(F_PASSWD, "r")) == NULL) {
447 perror(F_PASSWD);
448 return &pwd;
449 }
450
451 /*
452 * Find root in the password file.
453 */
454 while((p = fgets(line, 256, fp)) != NULL) {
455 if (strncmp(line, "root:", 5) != 0)
456 continue;
457 p += 5;
458 set(&pwd.pw_passwd, strsep(&p, ":"));
459 (void)strsep(&p, ":");
460 (void)strsep(&p, ":");
461 set(&pwd.pw_gecos, strsep(&p, ":"));
462 set(&pwd.pw_dir, strsep(&p, ":"));
463 set(&pwd.pw_shell, strsep(&p, "\n"));
464 p = line;
465 break;
466 }
467 fclose(fp);
468
469 /*
470 * If the encrypted password is valid
471 * or not found, return.
472 */
473 if (p == NULL) {
474 fprintf(stderr, "sulogin: %s: no entry for root\n\r", F_PASSWD);
475 return &pwd;
476 }
477 if (valid(pwd.pw_passwd)) return &pwd;
478
479 /*
480 * The password is invalid. If there is a
481 * shadow password, try it.
482 */
483 strcpy(pwd.pw_passwd, "");
484 if ((fp = fopen(F_SHADOW, "r")) == NULL) {
485 fprintf(stderr, "sulogin: %s: root password garbled\n\r", F_PASSWD);
486 return &pwd;
487 }
488 while((p = fgets(sline, 256, fp)) != NULL) {
489 if (strncmp(sline, "root:", 5) != 0)
490 continue;
491 p += 5;
492 set(&pwd.pw_passwd, strsep(&p, ":"));
493 break;
494 }
495 fclose(fp);
496
497 /*
498 * If the password is still invalid,
499 * NULL it, and return.
500 */
501 if (p == NULL) {
502 fprintf(stderr, "sulogin: %s: no entry for root\n\r", F_SHADOW);
503 strcpy(pwd.pw_passwd, "");
504 }
505 if (!valid(pwd.pw_passwd)) {
506 fprintf(stderr, "sulogin: %s: root password garbled\n\r", F_SHADOW);
507 strcpy(pwd.pw_passwd, ""); }
508 return &pwd;
509 }
510
511 /*
512 * Ask by prompt for the password.
513 */
514 static
515 void doprompt(const char *crypted, struct console *con)
516 {
517 struct termios tty;
518
519 if (con->flags & CON_SERIAL) {
520 tty = con->tio;
521 /*
522 * For prompting: map NL in output to CR-NL
523 * otherwise we may see stairs in the output.
524 */
525 tty.c_oflag |= (ONLCR | OPOST);
526 (void) tcsetattr(con->fd, TCSADRAIN, &tty);
527 }
528 if (con->file == (FILE*)0) {
529 if ((con->file = fdopen(con->fd, "r+")) == (FILE*)0)
530 goto err;
531 }
532 #if defined(USE_ONELINE)
533 if (crypted[0])
534 fprintf(con->file, "Give root password for login: ");
535 else
536 fprintf(con->file, "Press enter for login: ");
537 #else
538 if (crypted[0])
539 fprintf(con->file, "Give root password for maintenance\n\r");
540 else
541 fprintf(con->file, "Press enter for maintenance");
542 fprintf(con->file, "(or type Control-D to continue): ");
543 #endif
544 fflush(con->file);
545 err:
546 if (con->flags & CON_SERIAL)
547 (void) tcsetattr(con->fd, TCSADRAIN, &con->tio);
548 }
549
550 /*
551 * Make sure to have an own session and controlling terminal
552 */
553 static
554 void setup(struct console *con)
555 {
556 pid_t pid, pgrp, ppgrp, ttypgrp;
557 int fd;
558
559 if (con->flags & CON_NOTTY)
560 return;
561 fd = con->fd;
562
563 /*
564 * Only go through this trouble if the new
565 * tty doesn't fall in this process group.
566 */
567 pid = getpid();
568 pgrp = getpgid(0);
569 ppgrp = getpgid(getppid());
570 ttypgrp = tcgetpgrp(fd);
571
572 if (pgrp != ttypgrp && ppgrp != ttypgrp) {
573 if (pid != getsid(0)) {
574 if (pid == getpgid(0))
575 setpgid(0, getpgid(getppid()));
576 setsid();
577 }
578
579 signal(SIGHUP, SIG_IGN);
580 if (ttypgrp > 0)
581 ioctl(0, TIOCNOTTY, (char *)1);
582 signal(SIGHUP, saved_sighup);
583 if (fd > 0) close(0);
584 if (fd > 1) close(1);
585 if (fd > 2) close(2);
586
587 ioctl(fd, TIOCSCTTY, (char *)1);
588 tcsetpgrp(fd, ppgrp);
589 }
590 dup2(fd, 0);
591 dup2(fd, 1);
592 dup2(fd, 2);
593 con->fd = 0;
594
595 for (fd = 3; fd < 32; fd++) {
596 if (openfd & (1<<fd)) {
597 close(fd);
598 openfd &= ~(1<<fd);
599 }
600 }
601 }
602
603 /*
604 * Fetch the password. Note that there is no
605 * default timeout as we normally skip this during boot.
606 */
607 static
608 char *getpasswd(struct console *con)
609 {
610 static char pass[128], *ptr;
611 struct sigaction sa;
612 struct chardata *cp;
613 struct termios tty;
614 char *ret = pass;
615 unsigned char tc;
616 char ascval;
617 int eightbit;
618 int c, fd;
619
620 if (con->flags & CON_NOTTY)
621 goto out;
622 fd = con->fd;
623 cp = &con->cp;
624
625 tty = con->tio;
626 tty.c_iflag &= ~(IUCLC|IXON|IXOFF|IXANY);
627 tty.c_lflag &= ~(ECHO|ECHOE|ECHOK|ECHONL|TOSTOP|ISIG);
628 tc = (tcsetattr(fd, TCSAFLUSH, &tty) == 0);
629
630 sa.sa_handler = alrm_handler;
631 sa.sa_flags = 0;
632 sigaction(SIGALRM, &sa, NULL);
633 if (timeout) alarm(timeout);
634
635 ptr = &pass[0];
636 cp->eol = *ptr = '\0';
637
638 eightbit = ((con->flags & CON_SERIAL) == 0 || (tty.c_cflag & (PARODD|PARENB)) == 0);
639 while (cp->eol == 0) {
640 if (read(fd, &c, 1) < 1) {
641 if (errno == EINTR || errno == EAGAIN) {
642 usleep(1000);
643 continue;
644 }
645 ret = (char*)0;
646 switch (errno) {
647 case 0:
648 case EIO:
649 case ESRCH:
650 case EINVAL:
651 case ENOENT:
652 break;
653 default:
654 fprintf(stderr, "sulogin: read(%s): %m\n\r", con->tty);
655 break;
656 }
657 goto quit;
658 }
659
660 if (eightbit)
661 ascval = c;
662 else if (c != (ascval = (c & 0177))) {
663 uint32_t bits, mask;
664 for (bits = 1, mask = 1; mask & 0177; mask <<= 1) {
665 if (mask & ascval)
666 bits++;
667 }
668 cp->parity |= ((bits & 1) ? 1 : 2);
669 }
670
671 switch (ascval) {
672 case CR:
673 case NL:
674 *ptr = '\0';
675 cp->eol = ascval;
676 break;
677 case BS:
678 case CERASE:
679 cp->erase = ascval;
680 if (ptr > &pass[0])
681 ptr--;
682 break;
683 case CKILL:
684 cp->kill = ascval;
685 while (ptr > &pass[0])
686 ptr--;
687 break;
688 case CEOF:
689 goto quit;
690 default:
691 if ((size_t)(ptr - &pass[0]) >= (sizeof(pass) -1 )) {
692 fprintf(stderr, "sulogin: input overrun at %s\n\r", con->tty);
693 ret = (char*)0;
694 goto quit;
695 }
696 *ptr++ = ascval;
697 break;
698 }
699 }
700 quit:
701 alarm(0);
702 if (tc)
703 (void)tcsetattr(fd, TCSAFLUSH, &con->tio);
704 if (ret && *ret != '\0')
705 tcfinal(con);
706 printf("\r\n");
707 out:
708 return ret;
709 }
710
711 /*
712 * Password was OK, execute a shell.
713 */
714 static
715 void sushell(struct passwd *pwd)
716 {
717 char shell[128];
718 char home[128];
719 char *p;
720 char *sushell;
721
722 /*
723 * Set directory and shell.
724 */
725 if (chdir(pwd->pw_dir) < 0) {
726 if (chdir("/") < 0)
727 fprintf(stderr, "sulogin: change of working directory failed: %m\n\r");
728 }
729 if ((p = getenv("SUSHELL")) != NULL)
730 sushell = p;
731 else if ((p = getenv("sushell")) != NULL)
732 sushell = p;
733 else {
734 if (pwd->pw_shell[0])
735 sushell = pwd->pw_shell;
736 else
737 sushell = BINSH;
738 }
739 if ((p = strrchr(sushell, '/')) == NULL)
740 p = sushell;
741 else
742 p++;
743 snprintf(shell, sizeof(shell), profile ? "-%s" : "%s", p);
744
745 /*
746 * Set some important environment variables.
747 */
748 if (getcwd(home, sizeof(home)) == (char*)0)
749 strcpy(home, "/");
750 setenv("HOME", home, 1);
751 setenv("LOGNAME", "root", 1);
752 setenv("USER", "root", 1);
753 if (!profile)
754 setenv("SHLVL","0",1);
755
756 /*
757 * Try to execute a shell.
758 */
759 setenv("SHELL", sushell, 1);
760 signal(SIGINT, saved_sigint);
761 signal(SIGTSTP, saved_sigtstp);
762 signal(SIGQUIT, saved_sigquit);
763 signal(SIGHUP, SIG_DFL);
764 #ifdef WITH_SELINUX
765 if (is_selinux_enabled() > 0) {
766 security_context_t scon=NULL;
767 char *seuser=NULL;
768 char *level=NULL;
769 if (getseuserbyname("root", &seuser, &level) == 0)
770 if (get_default_context_with_level(seuser, level, 0, &scon) == 0) {
771 if (setexeccon(scon) != 0)
772 fprintf(stderr, "sulogin: setexeccon failed\n\r");
773 freecon(scon);
774 }
775 free(seuser);
776 free(level);
777 }
778 #endif
779 execl(sushell, shell, NULL);
780 perror(sushell);
781
782 setenv("SHELL", BINSH, 1);
783 execl(BINSH, profile ? "-sh" : "sh", NULL);
784 perror(BINSH);
785
786 /* Fall back to staticly linked shell if both the users shell
787 and /bin/sh failed to execute. */
788 setenv("SHELL", STATICSH, 1);
789 execl(STATICSH, STATICSH, NULL);
790 perror(STATICSH);
791 }
792
793 #ifdef __linux__
794 /*
795 * Make C library standard calls like ttyname(3) work.
796 */
797 static uint32_t mounts;
798 #define MNT_PROCFS 0x0001
799 #define MNT_DEVTMPFS 0x0002
800
801 static __attribute__((__noinline__))
802 void putmounts(void)
803 {
804 if (mounts & MNT_DEVTMPFS)
805 umount2("/dev", MNT_DETACH);
806 if (mounts & MNT_PROCFS)
807 umount2("/proc", MNT_DETACH);
808 }
809
810 static __attribute__((__constructor__))
811 void getmounts(void)
812 {
813 struct statfs st;
814 if (statfs("/proc", &st) == 0 && st.f_type != PROC_SUPER_MAGIC) {
815 if (mount("proc", "/proc", "proc", MS_RELATIME, NULL) == 0)
816 mounts |= MNT_PROCFS;
817 }
818 if (statfs("/dev", &st) == 0 && st.f_type != TMPFS_MAGIC) {
819 if (mount("devtmpfs", "/dev", "devtmpfs", MS_RELATIME, "mode=0755,nr_inodes=0") == 0) {
820 mounts |= MNT_DEVTMPFS;
821 (void)mknod("/dev/console", S_IFCHR|S_IRUSR|S_IWUSR, makedev(TTYAUX_MAJOR, 1));
822 if (symlink("/proc/self/fd", "/dev/fd") == 0) {
823 dovoid(symlink("fd/0", "/dev/stdin"));
824 dovoid(symlink("fd/1", "/dev/stdout"));
825 dovoid(symlink("fd/2", "/dev/stderr"));
826 }
827 }
828 }
829 if (mounts) atexit(putmounts);
830 }
831 #endif
832
833 static
834 void usage(void)
835 {
836 fprintf(stderr, "Usage: sulogin [-e] [-p] [-t timeout] [tty device]\n\r");
837 }
838
839 int main(int argc, char **argv)
840 {
841 char *tty = NULL;
842 struct passwd *pwd;
843 int c, status = 0;
844 int reconnect = 0;
845 int opt_e = 0;
846 struct console *con;
847 pid_t pid;
848
849 /*
850 * We are init. We hence need to set uo a session.
851 */
852 if ((pid = getpid()) == 1) {
853 setsid();
854 (void)ioctl(0, TIOCSCTTY, (char *)1);
855 }
856
857 /*
858 * See if we have a timeout flag.
859 */
860 opterr = 0;
861 while((c = getopt(argc, argv, "ept:")) != EOF) switch(c) {
862 case 't':
863 timeout = atoi(optarg);
864 break;
865 case 'p':
866 profile = 1;
867 break;
868 case 'e':
869 opt_e = 1;
870 break;
871 default:
872 usage();
873 /* Do not exit! */
874 break;
875 }
876
877 if (geteuid() != 0) {
878 fprintf(stderr, "sulogin: only root can run sulogin.\n\r");
879 exit(1);
880 }
881
882 saved_sigint = signal(SIGINT, SIG_IGN);
883 saved_sigquit = signal(SIGQUIT, SIG_IGN);
884 saved_sigtstp = signal(SIGTSTP, SIG_IGN);
885 saved_sighup = signal(SIGHUP, SIG_IGN);
886
887 /*
888 * See if we need to open an other tty device.
889 */
890 if (optind < argc)
891 tty = argv[optind];
892 if (!tty || *tty == '\0')
893 tty = getenv("CONSOLE");
894
895 /*
896 * Detect possible consoles, use stdin as fallback.
897 * If an optional tty is given, reconnect it to stdin.
898 */
899 reconnect = detect_consoles(tty, 0);
900
901 /*
902 * Should not happen
903 */
904 if (!consoles) {
905 if (!errno)
906 errno = ENOMEM;
907 fprintf(stderr, "sulogin: cannot open console: %m\n\r");
908 exit(1);
909 }
910
911 /*
912 * If previous stdin was not the speified tty and therefore reconnected
913 * to the specified tty also reconnect stdout and stderr.
914 */
915 if (reconnect) {
916 if (isatty(1) == 0)
917 dup2(0, 1);
918 if (isatty(2) == 0)
919 dup2(0, 2);
920 }
921
922 /*
923 * Get the root password.
924 */
925 if ((pwd = getrootpwent(opt_e)) == NULL) {
926 fprintf(stderr, "sulogin: cannot open password database!\n\r");
927 sleep(2);
928 }
929
930 /*
931 * Prompt for input on the consoles
932 */
933 for (con = consoles; con && con->id < CONMAX; con = con->next) {
934 if (con->fd >= 0) {
935 openfd |= (1<<con->fd);
936 tcinit(con);
937 continue;
938 }
939 if ((con->fd = open(con->tty, O_RDWR | O_NOCTTY | O_NONBLOCK)) < 0)
940 continue;
941 openfd |= (1<<con->fd);
942 tcinit(con);
943 }
944 con = consoles;
945 usemask = (uint32_t*)mmap(NULL, sizeof(uint32_t), PROT_READ|PROT_WRITE, MAP_ANONYMOUS|MAP_SHARED, -1, 0);
946
947 if (con->next == (struct console*)0)
948 goto nofork;
949
950 signal(SIGCHLD, chld_handler);
951 do {
952 switch ((con->pid = fork())) {
953 case 0:
954 signal(SIGCHLD, SIG_DFL);
955 /* fall through */
956 nofork:
957 setup(con);
958 while (1) {
959 char *passwd = pwd->pw_passwd;
960 char *answer;
961 int failed = 0;
962
963 doprompt(passwd, con);
964 if ((answer = getpasswd(con)) == NULL)
965 break;
966
967 if (passwd[0] == '\0' ||
968 strcmp(crypt(answer, passwd), passwd) == 0) {
969 *usemask |= (1<<con->id);
970 sushell(pwd);
971 *usemask &= ~(1<<con->id);
972 failed++;
973 }
974 signal(SIGQUIT, SIG_IGN);
975 signal(SIGTSTP, SIG_IGN);
976 signal(SIGINT, SIG_IGN);
977
978 if (failed) {
979 fprintf(stderr, "sulogin: can not execute su shell.\n\r");
980 break;
981 }
982 fprintf(stderr, "Login incorrect.\n\r");
983 sleep(3);
984 }
985 if (alarm_rised) {
986 tcfinal(con);
987 printf("Timed out.\n\r");
988 }
989 /*
990 * User may pressed Control-D.
991 */
992 exit(0);
993 case -1:
994 fprintf(stderr, "sulogin: can not fork: %m\n\r");
995 /* fall through */
996 default:
997 break;
998 }
999 } while ((con = con->next) && (con->id < CONMAX));
1000
1001 while ((pid = wait(&status))) {
1002 if (errno == ECHILD)
1003 break;
1004 if (pid < 0)
1005 continue;
1006 for (con = consoles; con && con->id < CONMAX; con = con->next) {
1007 if (con->pid == pid) {
1008 *usemask &= ~(1<<con->id);
1009 continue;
1010 }
1011 if (kill(con->pid, 0) < 0) {
1012 *usemask &= ~(1<<con->id);
1013 continue;
1014 }
1015 if (*usemask & (1<<con->id))
1016 continue;
1017 kill(con->pid, SIGHUP);
1018 usleep(5000);
1019 kill(con->pid, SIGKILL);
1020 }
1021 }
1022 signal(SIGCHLD, SIG_DFL);
1023
1024 return 0;
1025 }