68c2aa9392e275d58611584754c765df0036670e
[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 #ifdef __linux__
48 # include <sys/statfs.h>
49 # include <sys/mount.h>
50 # include <linux/fs.h>
51 # include <linux/magic.h>
52 # include <linux/major.h>
53 # ifndef TMPFS_MAGIC
54 # define TMPFS_MAGIC 0x01021994
55 # endif
56 # ifndef MNT_DETACH
57 # define MNT_DETACH 2
58 # endif
59 # define dovoid(f) if ((f)){}
60 #endif
61
62 #define BS CTRL('h')
63 #define NL CTRL('j')
64 #define CR CTRL('m')
65
66 #ifdef WITH_SELINUX
67 # include <selinux/selinux.h>
68 # include <selinux/get_context_list.h>
69 #endif
70
71 #include "consoles.h"
72 #define CONMAX 16
73
74 #define CHECK_DES 1
75 #define CHECK_MD5 1
76
77 #define F_PASSWD "/etc/passwd"
78 #define F_SHADOW "/etc/shadow"
79 #define BINSH "/bin/sh"
80 #define STATICSH "/bin/sash"
81
82 char *Version = "@(#)sulogin 2.85-3 23-Apr-2003 miquels@cistron.nl";
83
84 static int timeout;
85 static int profile;
86 static volatile uint32_t openfd; /* Remember higher file descriptors */
87 static volatile uint32_t *usemask;
88
89 static sighandler_t saved_sigint = SIG_DFL;
90 static sighandler_t saved_sigtstp = SIG_DFL;
91 static sighandler_t saved_sigquit = SIG_DFL;
92 static sighandler_t saved_sighup = SIG_DFL;
93
94 static volatile sig_atomic_t alarm_rised;
95 static volatile sig_atomic_t sigchild;
96
97 #ifndef IUCLC
98 # define IUCLC 0
99 #endif
100
101 /*
102 * Fix the tty modes and set reasonable defaults.
103 */
104 static
105 void tcinit(struct console *con)
106 {
107 int serial, flags;
108 struct termios *tio = &con->tio;
109 int fd = con->fd;
110
111 /* Expected error */
112 serial = errno = 0;
113
114 /* Get line attributes */
115 if (tcgetattr(fd, tio) < 0) {
116 con->flags |= CON_NOTTY;
117 return;
118 }
119
120 /* Handle serial lines here */
121 if (ioctl (fd, TIOCMGET, (char*)&serial) == 0) {
122 speed_t ispeed, ospeed;
123 struct winsize ws;
124
125 /* this is a modem line */
126 con->flags |= CON_SERIAL;
127
128 /* Flush input and output queues on modem lines */
129 (void) tcflush(fd, TCIOFLUSH);
130
131 ispeed = cfgetispeed(tio);
132 ospeed = cfgetospeed(tio);
133
134 if (!ispeed) ispeed = TTYDEF_SPEED;
135 if (!ospeed) ospeed = TTYDEF_SPEED;
136
137 tio->c_iflag = tio->c_lflag = tio->c_oflag = 0;
138 tio->c_cflag = CREAD | CS8 | HUPCL | (tio->c_cflag & CLOCAL);
139
140 cfsetispeed(tio, ispeed);
141 cfsetospeed(tio, ospeed);
142
143 tio->c_line = 0;
144 tio->c_cc[VTIME] = 0;
145 tio->c_cc[VMIN] = 1;
146
147 if (ioctl(fd, TIOCGWINSZ, &ws) == 0) {
148 int set = 0;
149 if (ws.ws_row == 0) {
150 ws.ws_row = 24;
151 set++;
152 }
153 if (ws.ws_col == 0) {
154 ws.ws_col = 80;
155 set++;
156 }
157 (void)ioctl(fd, TIOCSWINSZ, &ws);
158 }
159
160 goto setattr;
161 }
162 #if defined(SANE_TIO) && (SANE_TIO == 1)
163 /*
164 * Use defaults of <sys/ttydefaults.h> for base settings
165 * of a local terminal line like a virtual console.
166 */
167 tio->c_iflag |= TTYDEF_IFLAG;
168 tio->c_oflag |= TTYDEF_OFLAG;
169 tio->c_lflag |= TTYDEF_LFLAG;
170 # ifdef CBAUD
171 tio->c_lflag &= ~CBAUD;
172 # endif
173 tio->c_cflag |= (B38400 | TTYDEF_CFLAG);
174
175 /* Sane setting, allow eight bit characters, no carriage return delay
176 * the same result as `stty sane cr0 pass8'
177 */
178 tio->c_iflag |= (BRKINT | ICRNL | IMAXBEL);
179 tio->c_iflag &= ~(IGNBRK | INLCR | IGNCR | IXOFF | IUCLC | IXANY | INPCK | ISTRIP);
180 tio->c_oflag |= (OPOST | ONLCR | NL0 | CR0 | TAB0 | BS0 | VT0 | FF0);
181 tio->c_oflag &= ~(OLCUC | OCRNL | ONOCR | ONLRET | OFILL | OFDEL |\
182 NLDLY|CRDLY|TABDLY|BSDLY|VTDLY|FFDLY);
183 tio->c_lflag |= (ISIG | ICANON | IEXTEN | ECHO|ECHOE|ECHOK|ECHOKE);
184 tio->c_lflag &= ~(ECHONL|ECHOCTL|ECHOPRT | NOFLSH | XCASE | TOSTOP);
185 tio->c_cflag |= (CREAD | CS8 | HUPCL);
186 tio->c_cflag &= ~(PARODD | PARENB);
187
188 /*
189 * VTIME and VMIN can overlap with VEOF and VEOL since they are
190 * only used for non-canonical mode. We just set the at the
191 * beginning, so nothing bad should happen.
192 */
193 tio->c_cc[VTIME] = 0;
194 tio->c_cc[VMIN] = CMIN;
195 tio->c_cc[VINTR] = CINTR;
196 tio->c_cc[VQUIT] = CQUIT;
197 tio->c_cc[VERASE] = CERASE; /* ASCII DEL (0177) */
198 tio->c_cc[VKILL] = CKILL;
199 tio->c_cc[VEOF] = CEOF;
200 # ifdef VSWTC
201 tio->c_cc[VSWTC] = _POSIX_VDISABLE;
202 # else
203 tio->c_cc[VSWTCH] = _POSIX_VDISABLE;
204 # endif
205 tio->c_cc[VSTART] = CSTART;
206 tio->c_cc[VSTOP] = CSTOP;
207 tio->c_cc[VSUSP] = CSUSP;
208 tio->c_cc[VEOL] = _POSIX_VDISABLE;
209 tio->c_cc[VREPRINT] = CREPRINT;
210 tio->c_cc[VDISCARD] = CDISCARD;
211 tio->c_cc[VWERASE] = CWERASE;
212 tio->c_cc[VLNEXT] = CLNEXT;
213 tio->c_cc[VEOL2] = _POSIX_VDISABLE;
214 #endif
215 setattr:
216 /* Set line attributes */
217 tcsetattr(fd, TCSANOW, tio);
218
219 /* Enable blocking mode for read and write */
220 if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
221 (void)fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
222 }
223
224
225 /*
226 * Finalize the tty modes on modem lines.
227 */
228 static
229 void tcfinal(struct console *con)
230 {
231 int serial;
232 struct termios *tio = &con->tio;
233 int fd = con->fd;
234
235 /* Expected error */
236 serial = errno = 0;
237
238 if ((con->flags & CON_SERIAL) == 0) {
239 #ifdef __linux__
240 setenv("TERM", "linux", 1);
241 #else
242 setenv("TERM", "vt100", 1);
243 #endif
244 return;
245 }
246 if (con->flags & CON_NOTTY)
247 return;
248 setenv("TERM", "vt100", 1);
249
250 tio->c_iflag |= (IXON | IXOFF);
251 tio->c_lflag |= (ICANON | ISIG | ECHO|ECHOE|ECHOK|ECHOKE);
252 tio->c_oflag |= OPOST;
253
254 tio->c_cc[VINTR] = CINTR;
255 tio->c_cc[VQUIT] = CQUIT;
256 tio->c_cc[VERASE] = con->cp.erase;
257 tio->c_cc[VKILL] = con->cp.kill;
258 tio->c_cc[VEOF] = CEOF;
259 #ifdef VSWTC
260 tio->c_cc[VSWTC] = _POSIX_VDISABLE;
261 #else
262 tio->c_cc[VSWTCH] = _POSIX_VDISABLE;
263 #endif
264 tio->c_cc[VSTART] = CSTART;
265 tio->c_cc[VSTOP] = CSTOP;
266 tio->c_cc[VSUSP] = CSUSP;
267 tio->c_cc[VEOL] = _POSIX_VDISABLE;
268
269 if (con->cp.eol == CR) {
270 tio->c_iflag |= ICRNL;
271 tio->c_iflag &= ~(INLCR|IGNCR);
272 tio->c_oflag |= ONLCR;
273 tio->c_oflag &= ~(OCRNL|ONLRET);
274 }
275
276 switch (con->cp.parity) {
277 default:
278 case 0:
279 tio->c_cflag &= ~(PARODD | PARENB);
280 tio->c_iflag &= ~(INPCK | ISTRIP);
281 break;
282 case 1: /* odd parity */
283 tio->c_cflag |= PARODD;
284 /* fall through */
285 case 2: /* even parity */
286 tio->c_cflag |= PARENB;
287 tio->c_iflag |= (INPCK | ISTRIP);
288 /* fall through */
289 case (1 | 2): /* no parity bit */
290 tio->c_cflag &= ~CSIZE;
291 tio->c_cflag |= CS7;
292 break;
293 }
294
295 /* Set line attributes */
296 (void)tcsetattr(fd, TCSANOW, tio);
297 }
298
299 /*
300 * Called at timeout.
301 */
302 static
303 # ifdef __GNUC__
304 __attribute__((__noinline__))
305 void alrm_handler(int sig __attribute__((unused)))
306 # else
307 void alrm_handler(int sig)
308 # endif
309 {
310 alarm_rised++;
311 }
312
313 /*
314 * Called at timeout.
315 */
316 static
317 # ifdef __GNUC__
318 __attribute__((__noinline__))
319 void chld_handler(int sig __attribute__((unused)))
320 # else
321 void chld_handler(int sig)
322 # endif
323 {
324 sigchild++;
325 }
326
327 /*
328 * See if an encrypted password is valid. The encrypted
329 * password is checked for traditional-style DES and
330 * FreeBSD-style MD5 encryption.
331 */
332 static
333 int valid(const char *pass)
334 {
335 const char *s;
336 char id[5];
337 size_t len;
338 off_t off;
339
340 if (pass[0] == 0) return 1;
341 #if CHECK_MD5
342 if (pass[0] != '$') goto check_des;
343
344 /*
345 * up to 4 bytes for the signature e.g. $1$
346 */
347 for(s = pass+1; *s && *s != '$'; s++)
348 ;
349 if (*s++ != '$') return 0;
350 if ((off = (off_t)(s-pass)) > 4 || off < 3) return 0;
351
352 memset(id, '\0', sizeof(id));
353 strncpy(id, pass, off);
354
355 /*
356 * up to 16 bytes for the salt
357 */
358 for(; *s && *s != '$'; s++)
359 ;
360 if (*s++ != '$') return 0;
361 if ((off_t)(s-pass) > 16) return 0;
362 len = strlen(s);
363
364 /*
365 * the MD5 hash (128 bits or 16 bytes) encoded in base64 = 22 bytes
366 */
367 if ((strcmp(id, "$1$") == 0) && (len < 22 || len > 24)) return 0;
368
369 /*
370 * the SHA-256 hash 43 bytes
371 */
372 if ((strcmp(id, "$5$") == 0) && (len < 42 || len > 44)) return 0;
373
374 /*
375 * the SHA-512 hash 86 bytes
376 */
377 if ((strcmp(id, "$6$") == 0) && (len < 85 || len > 87)) return 0;
378
379 /*
380 * e.g. Blowfish hash
381 */
382 return 1;
383 check_des:
384 #endif
385 #if CHECK_DES
386 if (strlen(pass) != 13) return 0;
387 for (s = pass; *s; s++) {
388 if ((*s < '0' || *s > '9') &&
389 (*s < 'a' || *s > 'z') &&
390 (*s < 'A' || *s > 'Z') &&
391 *s != '.' && *s != '/') return 0;
392 }
393 #endif
394 return 1;
395 }
396
397 /*
398 * Set a variable if the value is not NULL.
399 */
400 static
401 void set(char **var, char *val)
402 {
403 if (val) *var = val;
404 }
405
406 /*
407 * Get the root password entry.
408 */
409 static
410 struct passwd *getrootpwent(int try_manually)
411 {
412 static struct passwd pwd;
413 struct passwd *pw;
414 struct spwd *spw;
415 FILE *fp;
416 static char line[256];
417 static char sline[256];
418 char *p;
419
420 /*
421 * First, we try to get the password the standard
422 * way using normal library calls.
423 */
424 if ((pw = getpwnam("root")) &&
425 !strcmp(pw->pw_passwd, "x") &&
426 (spw = getspnam("root")))
427 pw->pw_passwd = spw->sp_pwdp;
428 if (pw || !try_manually) return pw;
429
430 /*
431 * If we come here, we could not retrieve the root
432 * password through library calls and we try to
433 * read the password and shadow files manually.
434 */
435 pwd.pw_name = "root";
436 pwd.pw_passwd = "";
437 pwd.pw_gecos = "Super User";
438 pwd.pw_dir = "/";
439 pwd.pw_shell = "";
440 pwd.pw_uid = 0;
441 pwd.pw_gid = 0;
442
443 if ((fp = fopen(F_PASSWD, "r")) == NULL) {
444 perror(F_PASSWD);
445 return &pwd;
446 }
447
448 /*
449 * Find root in the password file.
450 */
451 while((p = fgets(line, 256, fp)) != NULL) {
452 if (strncmp(line, "root:", 5) != 0)
453 continue;
454 p += 5;
455 set(&pwd.pw_passwd, strsep(&p, ":"));
456 (void)strsep(&p, ":");
457 (void)strsep(&p, ":");
458 set(&pwd.pw_gecos, strsep(&p, ":"));
459 set(&pwd.pw_dir, strsep(&p, ":"));
460 set(&pwd.pw_shell, strsep(&p, "\n"));
461 p = line;
462 break;
463 }
464 fclose(fp);
465
466 /*
467 * If the encrypted password is valid
468 * or not found, return.
469 */
470 if (p == NULL) {
471 fprintf(stderr, "sulogin: %s: no entry for root\n\r", F_PASSWD);
472 return &pwd;
473 }
474 if (valid(pwd.pw_passwd)) return &pwd;
475
476 /*
477 * The password is invalid. If there is a
478 * shadow password, try it.
479 */
480 strcpy(pwd.pw_passwd, "");
481 if ((fp = fopen(F_SHADOW, "r")) == NULL) {
482 fprintf(stderr, "sulogin: %s: root password garbled\n\r", F_PASSWD);
483 return &pwd;
484 }
485 while((p = fgets(sline, 256, fp)) != NULL) {
486 if (strncmp(sline, "root:", 5) != 0)
487 continue;
488 p += 5;
489 set(&pwd.pw_passwd, strsep(&p, ":"));
490 break;
491 }
492 fclose(fp);
493
494 /*
495 * If the password is still invalid,
496 * NULL it, and return.
497 */
498 if (p == NULL) {
499 fprintf(stderr, "sulogin: %s: no entry for root\n\r", F_SHADOW);
500 strcpy(pwd.pw_passwd, "");
501 }
502 if (!valid(pwd.pw_passwd)) {
503 fprintf(stderr, "sulogin: %s: root password garbled\n\r", F_SHADOW);
504 strcpy(pwd.pw_passwd, ""); }
505 return &pwd;
506 }
507
508 /*
509 * Ask by prompt for the password.
510 */
511 static
512 void doprompt(const char *crypted, struct console *con)
513 {
514 struct termios tty;
515
516 if (con->flags & CON_SERIAL) {
517 tty = con->tio;
518 /*
519 * For prompting: map NL in output to CR-NL
520 * otherwise we may see stairs in the output.
521 */
522 tty.c_oflag |= (ONLCR | OPOST);
523 (void) tcsetattr(con->fd, TCSADRAIN, &tty);
524 }
525 if (con->file == (FILE*)0) {
526 if ((con->file = fdopen(con->fd, "r+")) == (FILE*)0)
527 goto err;
528 }
529 #if defined(USE_ONELINE)
530 if (crypted[0])
531 fprintf(con->file, "Give root password for login: ");
532 else
533 fprintf(con->file, "Press enter for login: ");
534 #else
535 if (crypted[0])
536 fprintf(con->file, "Give root password for maintenance\n\r");
537 else
538 fprintf(con->file, "Press enter for maintenance");
539 fprintf(con->file, "(or type Control-D to continue): ");
540 #endif
541 fflush(con->file);
542 err:
543 if (con->flags & CON_SERIAL)
544 (void) tcsetattr(con->fd, TCSADRAIN, &con->tio);
545 }
546
547 /*
548 * Make sure to have an own session and controlling terminal
549 */
550 static
551 void setup(struct console *con)
552 {
553 pid_t pid, pgrp, ppgrp, ttypgrp;
554 int fd;
555
556 if (con->flags & CON_NOTTY)
557 return;
558 fd = con->fd;
559
560 /*
561 * Only go through this trouble if the new
562 * tty doesn't fall in this process group.
563 */
564 pid = getpid();
565 pgrp = getpgid(0);
566 ppgrp = getpgid(getppid());
567 ttypgrp = tcgetpgrp(fd);
568
569 if (pgrp != ttypgrp && ppgrp != ttypgrp) {
570 if (pid != getsid(0)) {
571 if (pid == getpgid(0))
572 setpgid(0, getpgid(getppid()));
573 setsid();
574 }
575
576 signal(SIGHUP, SIG_IGN);
577 if (ttypgrp > 0)
578 ioctl(0, TIOCNOTTY, (char *)1);
579 signal(SIGHUP, saved_sighup);
580 if (fd > 0) close(0);
581 if (fd > 1) close(1);
582 if (fd > 2) close(2);
583
584 ioctl(fd, TIOCSCTTY, (char *)1);
585 tcsetpgrp(fd, ppgrp);
586 }
587 dup2(fd, 0);
588 dup2(fd, 1);
589 dup2(fd, 2);
590 con->fd = 0;
591
592 for (fd = 3; fd < 32; fd++) {
593 if (openfd & (1<<fd)) {
594 close(fd);
595 openfd &= ~(1<<fd);
596 }
597 }
598 }
599
600 /*
601 * Fetch the password. Note that there is no
602 * default timeout as we normally skip this during boot.
603 */
604 static
605 char *getpasswd(struct console *con)
606 {
607 static char pass[128], *ptr;
608 struct sigaction sa;
609 struct chardata *cp;
610 struct termios tty;
611 char *ret = pass;
612 unsigned char tc;
613 char c, ascval;
614 int eightbit;
615 int fd;
616
617 if (con->flags & CON_NOTTY)
618 goto out;
619 fd = con->fd;
620 cp = &con->cp;
621
622 tty = con->tio;
623 tty.c_iflag &= ~(IUCLC|IXON|IXOFF|IXANY);
624 tty.c_lflag &= ~(ECHO|ECHOE|ECHOK|ECHONL|TOSTOP|ISIG);
625 tc = (tcsetattr(fd, TCSAFLUSH, &tty) == 0);
626
627 sa.sa_handler = alrm_handler;
628 sa.sa_flags = 0;
629 sigaction(SIGALRM, &sa, NULL);
630 if (timeout) alarm(timeout);
631
632 ptr = &pass[0];
633 cp->eol = *ptr = '\0';
634
635 eightbit = ((con->flags & CON_SERIAL) == 0 || (tty.c_cflag & (PARODD|PARENB)) == 0);
636 while (cp->eol == '\0') {
637 if (read(fd, &c, 1) < 1) {
638 if (errno == EINTR || errno == EAGAIN) {
639 usleep(1000);
640 continue;
641 }
642 ret = (char*)0;
643 switch (errno) {
644 case 0:
645 case EIO:
646 case ESRCH:
647 case EINVAL:
648 case ENOENT:
649 break;
650 default:
651 fprintf(stderr, "sulogin: read(%s): %m\n\r", con->tty);
652 break;
653 }
654 goto quit;
655 }
656
657 if (eightbit)
658 ascval = c;
659 else if (c != (ascval = (c & 0177))) {
660 uint32_t bits, mask;
661 for (bits = 1, mask = 1; mask & 0177; mask <<= 1) {
662 if (mask & ascval)
663 bits++;
664 }
665 cp->parity |= ((bits & 1) ? 1 : 2);
666 }
667
668 switch (ascval) {
669 case 0:
670 *ptr = '\0';
671 goto quit;
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, doshell = 0;
962
963 doprompt(passwd, con);
964 if ((answer = getpasswd(con)) == NULL)
965 break;
966
967 if (passwd[0] == '\0')
968 doshell++;
969 else {
970 char *cryptbuf;
971 cryptbuf = crypt(answer, passwd);
972 if (cryptbuf == NULL)
973 fprintf(stderr, "sulogin: crypt failed: %m\n\r");
974 else if (strcmp(cryptbuf, pwd->pw_passwd) == 0)
975 doshell++;
976 }
977
978 if (doshell) {
979 *usemask |= (1<<con->id);
980 sushell(pwd);
981 *usemask &= ~(1<<con->id);
982 failed++;
983 }
984
985 signal(SIGQUIT, SIG_IGN);
986 signal(SIGTSTP, SIG_IGN);
987 signal(SIGINT, SIG_IGN);
988
989 if (failed) {
990 fprintf(stderr, "sulogin: can not execute su shell.\n\r");
991 break;
992 }
993 fprintf(stderr, "Login incorrect.\n\r");
994 sleep(3);
995 }
996 if (alarm_rised) {
997 tcfinal(con);
998 fprintf(stderr, "Timed out.\n\r");
999 }
1000 /*
1001 * User may pressed Control-D.
1002 */
1003 exit(0);
1004 case -1:
1005 fprintf(stderr, "sulogin: can not fork: %m\n\r");
1006 /* fall through */
1007 default:
1008 break;
1009 }
1010 } while ((con = con->next) && (con->id < CONMAX));
1011
1012 while ((pid = wait(&status))) {
1013 if (errno == ECHILD)
1014 break;
1015 if (pid < 0)
1016 continue;
1017 for (con = consoles; con && con->id < CONMAX; con = con->next) {
1018 if (con->pid == pid) {
1019 *usemask &= ~(1<<con->id);
1020 continue;
1021 }
1022 if (kill(con->pid, 0) < 0) {
1023 *usemask &= ~(1<<con->id);
1024 continue;
1025 }
1026 if (*usemask & (1<<con->id))
1027 continue;
1028 kill(con->pid, SIGHUP);
1029 usleep(5000);
1030 kill(con->pid, SIGKILL);
1031 }
1032 }
1033 signal(SIGCHLD, SIG_DFL);
1034
1035 return 0;
1036 }