]> git.ipfire.org Git - thirdparty/util-linux.git/blob - login-utils/sulogin.c
login-utils: verify writing to streams was successful
[thirdparty/util-linux.git] / login-utils / sulogin.c
1 /*
2 * sulogin
3 *
4 * This program gives Linux machines a reasonable secure way to boot single
5 * user. It forces the user to supply the root password before a shell is
6 * started. If there is a shadow password file and the encrypted root password
7 * is "x" the shadow password will be used.
8 *
9 * Copyright (C) 1998-2003 Miquel van Smoorenburg.
10 * Copyright (C) 2012 Karel Zak <kzak@redhat.com>
11 *
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
16 *
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 */
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <stdio.h>
29 #include <string.h>
30 #include <stdlib.h>
31 #include <unistd.h>
32 #include <fcntl.h>
33 #include <signal.h>
34 #include <pwd.h>
35 #include <shadow.h>
36 #include <termios.h>
37 #include <errno.h>
38 #include <getopt.h>
39 #include <sys/ioctl.h>
40 #ifdef HAVE_CRYPT_H
41 # include <crypt.h>
42 #endif
43
44 #ifdef HAVE_LIBSELINUX
45 # include <selinux/selinux.h>
46 # include <selinux/get_context_list.h>
47 #endif
48
49 #include "c.h"
50 #include "closestream.h"
51 #include "nls.h"
52 #include "pathnames.h"
53 #include "strutils.h"
54 #include "ttyutils.h"
55
56 static unsigned int timeout;
57 static int profile;
58
59 struct sigaction saved_sigint;
60 struct sigaction saved_sigtstp;
61 struct sigaction saved_sigquit;
62
63 /*
64 * Called at timeout.
65 */
66 static void alrm_handler(int sig __attribute__((unused)))
67 {
68 return;
69 }
70
71 static void mask_signal(int signal, void (*handler)(int),
72 struct sigaction *origaction)
73 {
74 struct sigaction newaction;
75
76 newaction.sa_handler = handler;
77 sigemptyset(&newaction.sa_mask);
78 newaction.sa_flags = 0;
79
80 sigaction(signal, NULL, origaction);
81 sigaction(signal, &newaction, NULL);
82 }
83
84 static void unmask_signal(int signal, struct sigaction *sa)
85 {
86 sigaction(signal, sa, NULL);
87 }
88
89 /*
90 * See if an encrypted password is valid. The encrypted password is checked for
91 * traditional-style DES and FreeBSD-style MD5 encryption.
92 */
93 static int valid(const char *pass)
94 {
95 const char *s;
96 char id[5];
97 size_t len;
98 off_t off;
99
100 if (pass[0] == 0)
101 return 1;
102 if (pass[0] != '$')
103 goto check_des;
104
105 /*
106 * up to 4 bytes for the signature e.g. $1$
107 */
108 for (s = pass+1; *s && *s != '$'; s++);
109
110 if (*s++ != '$')
111 return 0;
112
113 if ((off = (off_t)(s-pass)) > 4 || off < 3)
114 return 0;
115
116 memset(id, '\0', sizeof(id));
117 strncpy(id, pass, off);
118
119 /*
120 * up to 16 bytes for the salt
121 */
122 for (; *s && *s != '$'; s++);
123
124 if (*s++ != '$')
125 return 0;
126
127 if ((off_t)(s-pass) > 16)
128 return 0;
129
130 len = strlen(s);
131
132 /*
133 * the MD5 hash (128 bits or 16 bytes) encoded in base64 = 22 bytes
134 */
135 if ((strcmp(id, "$1$") == 0) && (len < 22 || len > 24))
136 return 0;
137
138 /*
139 * the SHA-256 hash 43 bytes
140 */
141 if ((strcmp(id, "$5$") == 0) && (len < 42 || len > 44))
142 return 0;
143
144 /*
145 * the SHA-512 hash 86 bytes
146 */
147 if ((strcmp(id, "$6$") == 0) && (len < 85 || len > 87))
148 return 0;
149
150 /*
151 * e.g. Blowfish hash
152 */
153 return 1;
154 check_des:
155 if (strlen(pass) != 13)
156 return 0;
157
158 for (s = pass; *s; s++) {
159 if ((*s < '0' || *s > '9') &&
160 (*s < 'a' || *s > 'z') &&
161 (*s < 'A' || *s > 'Z') &&
162 *s != '.' && *s != '/')
163 return 0;
164 }
165 return 1;
166 }
167
168 /*
169 * Set a variable if the value is not NULL.
170 */
171 static inline void set(char **var, char *val)
172 {
173 if (val)
174 *var = val;
175 }
176
177 /*
178 * Get the root password entry.
179 */
180 static struct passwd *getrootpwent(int try_manually)
181 {
182 static struct passwd pwd;
183 struct passwd *pw;
184 struct spwd *spw;
185 FILE *fp;
186 static char line[256];
187 static char sline[256];
188 char *p;
189
190 /*
191 * First, we try to get the password the standard way using normal
192 * library calls.
193 */
194 if ((pw = getpwnam("root")) &&
195 !strcmp(pw->pw_passwd, "x") &&
196 (spw = getspnam("root")))
197 pw->pw_passwd = spw->sp_pwdp;
198
199 if (pw || !try_manually)
200 return pw;
201
202 /*
203 * If we come here, we could not retrieve the root password through
204 * library calls and we try to read the password and shadow files
205 * manually.
206 */
207 pwd.pw_name = "root";
208 pwd.pw_passwd = "";
209 pwd.pw_gecos = "Super User";
210 pwd.pw_dir = "/";
211 pwd.pw_shell = "";
212 pwd.pw_uid = 0;
213 pwd.pw_gid = 0;
214
215 if ((fp = fopen(_PATH_PASSWD, "r")) == NULL) {
216 warn(_("%s: open failed"), _PATH_PASSWD);
217 return &pwd;
218 }
219
220 /*
221 * Find root in the password file.
222 */
223 while ((p = fgets(line, 256, fp)) != NULL) {
224 if (strncmp(line, "root:", 5) != 0)
225 continue;
226 p += 5;
227 set(&pwd.pw_passwd, strsep(&p, ":"));
228 strsep(&p, ":");
229 strsep(&p, ":");
230 set(&pwd.pw_gecos, strsep(&p, ":"));
231 set(&pwd.pw_dir, strsep(&p, ":"));
232 set(&pwd.pw_shell, strsep(&p, "\n"));
233 p = line;
234 break;
235 }
236
237 fclose(fp);
238
239 /*
240 * If the encrypted password is valid or not found, return.
241 */
242 if (p == NULL) {
243 warnx(_("%s: no entry for root\n"), _PATH_PASSWD);
244 return &pwd;
245 }
246 if (valid(pwd.pw_passwd))
247 return &pwd;
248
249 /*
250 * The password is invalid. If there is a shadow password, try it.
251 */
252 strcpy(pwd.pw_passwd, "");
253 if ((fp = fopen(_PATH_SHADOW_PASSWD, "r")) == NULL) {
254 warn(_("%s: open failed"), _PATH_PASSWD);
255 return &pwd;
256 }
257 while ((p = fgets(sline, 256, fp)) != NULL) {
258 if (strncmp(sline, "root:", 5) != 0)
259 continue;
260 p += 5;
261 set(&pwd.pw_passwd, strsep(&p, ":"));
262 break;
263 }
264 fclose(fp);
265
266 /*
267 * If the password is still invalid, NULL it, and return.
268 */
269 if (p == NULL) {
270 warnx(_("%s: no entry for root"), _PATH_SHADOW_PASSWD);
271 strcpy(pwd.pw_passwd, "");
272 }
273 if (!valid(pwd.pw_passwd)) {
274 warnx(_("%s: root password garbled"), _PATH_SHADOW_PASSWD);
275 strcpy(pwd.pw_passwd, "");
276 }
277 return &pwd;
278 }
279
280 /*
281 * Ask for the password. Note that there is no default timeout as we normally
282 * skip this during boot.
283 */
284 static char *getpasswd(char *crypted)
285 {
286 struct sigaction sa;
287 struct termios old, tty;
288 static char pass[128];
289 char *ret = pass;
290 size_t i;
291
292 if (crypted[0])
293 printf(_("Give root password for maintenance\n"));
294 else
295 printf(_("Press enter for maintenance"));
296 printf(_("(or type Control-D to continue): "));
297 fflush(stdout);
298
299 tcgetattr(0, &old);
300 tcgetattr(0, &tty);
301 tty.c_iflag &= ~(IUCLC|IXON|IXOFF|IXANY);
302 tty.c_lflag &= ~(ECHO|ECHOE|ECHOK|ECHONL|TOSTOP);
303 tcsetattr(0, TCSANOW, &tty);
304
305 pass[sizeof(pass) - 1] = 0;
306
307 sa.sa_handler = alrm_handler;
308 sa.sa_flags = 0;
309 sigaction(SIGALRM, &sa, NULL);
310 if (timeout)
311 alarm(timeout);
312
313 if (read(0, pass, sizeof(pass) - 1) <= 0)
314 ret = NULL;
315 else {
316 for (i = 0; i < sizeof(pass) && pass[i]; i++)
317 if (pass[i] == '\r' || pass[i] == '\n') {
318 pass[i] = 0;
319 break;
320 }
321 }
322 alarm(0);
323 tcsetattr(0, TCSANOW, &old);
324 printf("\n");
325
326 return ret;
327 }
328
329 /*
330 * Password was OK, execute a shell.
331 */
332 static void sushell(struct passwd *pwd)
333 {
334 char shell[PATH_MAX];
335 char home[PATH_MAX];
336 char *p;
337 char *sushell;
338
339 /*
340 * Set directory and shell.
341 */
342 if (chdir(pwd->pw_dir) != 0) {
343 warn(_("%s: change directory failed"), pwd->pw_dir);
344 printf(_("Logging in with home = \"/\".\n"));
345
346 if (chdir("/") != 0)
347 warn(_("change directory to system root failed"));
348 }
349
350 if ((p = getenv("SUSHELL")) != NULL)
351 sushell = p;
352 else if ((p = getenv("sushell")) != NULL)
353 sushell = p;
354 else {
355 if (pwd->pw_shell[0])
356 sushell = pwd->pw_shell;
357 else
358 sushell = "/bin/sh";
359 }
360 if ((p = strrchr(sushell, '/')) == NULL)
361 p = sushell;
362 else
363 p++;
364
365 snprintf(shell, sizeof(shell), profile ? "-%s" : "%s", p);
366
367 /*
368 * Set some important environment variables.
369 */
370 if (getcwd(home, sizeof(home)) != NULL)
371 setenv("HOME", home, 1);
372
373 setenv("LOGNAME", "root", 1);
374 setenv("USER", "root", 1);
375 if (!profile)
376 setenv("SHLVL","0",1);
377
378 /*
379 * Try to execute a shell.
380 */
381 setenv("SHELL", sushell, 1);
382 unmask_signal(SIGINT, &saved_sigint);
383 unmask_signal(SIGTSTP, &saved_sigtstp);
384 unmask_signal(SIGQUIT, &saved_sigquit);
385
386 #ifdef HAVE_LIBSELINUX
387 if (is_selinux_enabled() > 0) {
388 security_context_t scon=NULL;
389 char *seuser=NULL;
390 char *level=NULL;
391 if (getseuserbyname("root", &seuser, &level) == 0) {
392 if (get_default_context_with_level(seuser, level, 0, &scon) == 0) {
393 if (setexeccon(scon) != 0)
394 warnx(_("setexeccon failed"));
395 freecon(scon);
396 }
397 }
398 free(seuser);
399 free(level);
400 }
401 #endif
402 execl(sushell, shell, NULL);
403 warn(_("%s: exec failed"), sushell);
404
405 setenv("SHELL", "/bin/sh", 1);
406 execl("/bin/sh", profile ? "-sh" : "sh", NULL);
407 warn(_("%s: exec failed"), "/bin/sh");
408 }
409
410 static void fixtty(void)
411 {
412 struct termios tp;
413 int x = 0, fl = 0;
414
415 /* Skip serial console */
416 if (ioctl(STDIN_FILENO, TIOCMGET, (char *) &x) == 0)
417 return;
418
419 #if defined(IUTF8) && defined(KDGKBMODE)
420 /* Detect mode of current keyboard setup, e.g. for UTF-8 */
421 if (ioctl(STDIN_FILENO, KDGKBMODE, &x) == 0 && x == K_UNICODE) {
422 setlocale(LC_CTYPE, "C.UTF-8");
423 fl |= UL_TTY_UTF8;
424 }
425 #else
426 setlocale(LC_CTYPE, "POSIX");
427 #endif
428 memset(&tp, 0, sizeof(struct termios));
429 if (tcgetattr(STDIN_FILENO, &tp) < 0) {
430 warn(_("tcgetattr failed"));
431 return;
432 }
433
434 reset_virtual_console(&tp, fl);
435
436 if (tcsetattr(0, TCSADRAIN, &tp))
437 warn(_("tcsetattr failed"));
438 }
439
440 static void usage(FILE *out)
441 {
442 fputs(USAGE_HEADER, out);
443 fprintf(out, _(
444 " %s [options] [tty device]\n"), program_invocation_short_name);
445
446 fputs(USAGE_OPTIONS, out);
447 fputs(_(" -p, --login-shell start a login shell\n"
448 " -t, --timeout <seconds> max time to wait for a password (default: no limit)\n"
449 " -e, --force examine password files directly if getpwnam(3) fails\n"),
450 out);
451
452 fputs(USAGE_SEPARATOR, out);
453 fputs(USAGE_HELP, out);
454 fputs(USAGE_VERSION, out);
455 fprintf(out, USAGE_MAN_TAIL("sulogin(8)"));
456 }
457
458 int main(int argc, char **argv)
459 {
460 char *tty = NULL;
461 char *p;
462 struct passwd *pwd;
463 int c, fd = -1;
464 int opt_e = 0;
465 pid_t pid, pgrp, ppgrp, ttypgrp;
466 struct sigaction saved_sighup;
467
468 static const struct option longopts[] = {
469 { "login-shell", 0, 0, 'p' },
470 { "timeout", 1, 0, 't' },
471 { "force", 0, 0, 'e' },
472 { "help", 0, 0, 'h' },
473 { "version", 0, 0, 'V' },
474 { NULL, 0, 0, 0 }
475 };
476
477 setlocale(LC_ALL, "");
478 bindtextdomain(PACKAGE, LOCALEDIR);
479 textdomain(PACKAGE);
480 atexit(close_stdout);
481
482 /*
483 * See if we have a timeout flag.
484 */
485 while ((c = getopt_long(argc, argv, "ehpt:V", longopts, NULL)) != -1) {
486 switch(c) {
487 case 't':
488 timeout = strtoul_or_err(optarg, _("failed to parse timeout"));
489 break;
490 case 'p':
491 profile = 1;
492 break;
493 case 'e':
494 opt_e = 1;
495 break;
496 case 'V':
497 printf(UTIL_LINUX_VERSION);
498 return EXIT_SUCCESS;
499 case 'h':
500 usage(stdout);
501 return EXIT_SUCCESS;
502 default:
503 usage(stderr);
504 /* Do not exit! */
505 break;
506 }
507 }
508
509 if (geteuid() != 0)
510 errx(EXIT_FAILURE, _("only root can run this program."));
511
512 /*
513 * See if we need to open an other tty device.
514 */
515 mask_signal(SIGQUIT, SIG_IGN, &saved_sigquit);
516 mask_signal(SIGTSTP, SIG_IGN, &saved_sigtstp);
517 mask_signal(SIGINT, SIG_IGN, &saved_sigint);
518 if (optind < argc)
519 tty = argv[optind];
520
521 if (tty || (tty = getenv("CONSOLE"))) {
522
523 if ((fd = open(tty, O_RDWR)) < 0) {
524 warn(_("%s: open failed"), tty);
525 fd = dup(0);
526 }
527
528 if (!isatty(fd)) {
529 warn(_("%s: not a tty"), tty);
530 close(fd);
531 } else {
532
533 /*
534 * Only go through this trouble if the new tty doesn't
535 * fall in this process group.
536 */
537 pid = getpid();
538 pgrp = getpgid(0);
539 ppgrp = getpgid(getppid());
540 ttypgrp = tcgetpgrp(fd);
541
542 if (pgrp != ttypgrp && ppgrp != ttypgrp) {
543 if (pid != getsid(0)) {
544 if (pid == getpgid(0))
545 setpgid(0, getpgid(getppid()));
546 setsid();
547 }
548
549 sigaction(SIGHUP, NULL, &saved_sighup);
550 if (ttypgrp > 0)
551 ioctl(0, TIOCNOTTY, (char *)1);
552 sigaction(SIGHUP, &saved_sighup, NULL);
553 close(0);
554 close(1);
555 close(2);
556 if (fd > 2)
557 close(fd);
558 if ((fd = open(tty, O_RDWR|O_NOCTTY)) < 0)
559 warn(_("%s: open failed"), tty);
560 else {
561 ioctl(0, TIOCSCTTY, (char *)1);
562 tcsetpgrp(fd, ppgrp);
563 dup2(fd, 0);
564 dup2(fd, 1);
565 dup2(fd, 2);
566 if (fd > 2)
567 close(fd);
568 }
569 } else
570 if (fd > 2)
571 close(fd);
572 }
573 } else if (getpid() == 1) {
574 /* We are init. We hence need to set a session anyway */
575 setsid();
576 if (ioctl(0, TIOCSCTTY, (char *)1))
577 warn(_("TIOCSCTTY: ioctl failed"));
578 }
579
580 fixtty();
581
582 /*
583 * Get the root password.
584 */
585 if ((pwd = getrootpwent(opt_e)) == NULL) {
586 warnx(_("cannot open password database."));
587 sleep(2);
588 }
589
590 /*
591 * Ask for the password.
592 */
593 while (pwd) {
594 if ((p = getpasswd(pwd->pw_passwd)) == NULL)
595 break;
596 if (pwd->pw_passwd[0] == 0 ||
597 strcmp(crypt(p, pwd->pw_passwd), pwd->pw_passwd) == 0)
598 sushell(pwd);
599 mask_signal(SIGQUIT, SIG_IGN, &saved_sigquit);
600 mask_signal(SIGTSTP, SIG_IGN, &saved_sigtstp);
601 mask_signal(SIGINT, SIG_IGN, &saved_sigint);
602 fprintf(stderr, _("Login incorrect\n\n"));
603 }
604
605 /*
606 * User pressed Control-D.
607 */
608 return EXIT_SUCCESS;
609 }