2f7b9b21216314d69ba189b4e3508bb645345033
[platform/upstream/busybox.git] / loginutils / login.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
4  */
5
6 //usage:#define login_trivial_usage
7 //usage:       "[-p] [-h HOST] [[-f] USER]"
8 //usage:#define login_full_usage "\n\n"
9 //usage:       "Begin a new session on the system\n"
10 //usage:     "\n        -f      Don't authenticate (user already authenticated)"
11 //usage:     "\n        -h      Name of the remote host"
12 //usage:     "\n        -p      Preserve environment"
13
14 #include "libbb.h"
15 #include <syslog.h>
16 #include <sys/resource.h>
17
18 #if ENABLE_SELINUX
19 # include <selinux/selinux.h>  /* for is_selinux_enabled()  */
20 # include <selinux/get_context_list.h> /* for get_default_context() */
21 # include <selinux/flask.h> /* for security class definitions  */
22 #endif
23
24 #if ENABLE_PAM
25 /* PAM may include <locale.h>. We may need to undefine bbox's stub define: */
26 # undef setlocale
27 /* For some obscure reason, PAM is not in pam/xxx, but in security/xxx.
28  * Apparently they like to confuse people. */
29 # include <security/pam_appl.h>
30 # include <security/pam_misc.h>
31 static const struct pam_conv conv = {
32         misc_conv,
33         NULL
34 };
35 #endif
36
37 enum {
38         TIMEOUT = 60,
39         EMPTY_USERNAME_COUNT = 10,
40         USERNAME_SIZE = 32,
41         TTYNAME_SIZE = 32,
42 };
43
44 static char* short_tty;
45
46 #if ENABLE_FEATURE_NOLOGIN
47 static void die_if_nologin(void)
48 {
49         FILE *fp;
50         int c;
51         int empty = 1;
52
53         fp = fopen_for_read("/etc/nologin");
54         if (!fp) /* assuming it does not exist */
55                 return;
56
57         while ((c = getc(fp)) != EOF) {
58                 if (c == '\n')
59                         bb_putchar('\r');
60                 bb_putchar(c);
61                 empty = 0;
62         }
63         if (empty)
64                 puts("\r\nSystem closed for routine maintenance\r");
65
66         fclose(fp);
67         fflush_all();
68         /* Users say that they do need this prior to exit: */
69         tcdrain(STDOUT_FILENO);
70         exit(EXIT_FAILURE);
71 }
72 #else
73 # define die_if_nologin() ((void)0)
74 #endif
75
76 #if ENABLE_FEATURE_SECURETTY && !ENABLE_PAM
77 static int check_securetty(void)
78 {
79         char *buf = (char*)"/etc/securetty"; /* any non-NULL is ok */
80         parser_t *parser = config_open2("/etc/securetty", fopen_for_read);
81         while (config_read(parser, &buf, 1, 1, "# \t", PARSE_NORMAL)) {
82                 if (strcmp(buf, short_tty) == 0)
83                         break;
84                 buf = NULL;
85         }
86         config_close(parser);
87         /* buf != NULL here if config file was not found, empty
88          * or line was found which equals short_tty */
89         return buf != NULL;
90 }
91 #else
92 static ALWAYS_INLINE int check_securetty(void) { return 1; }
93 #endif
94
95 #if ENABLE_SELINUX
96 static void initselinux(char *username, char *full_tty,
97                                                 security_context_t *user_sid)
98 {
99         security_context_t old_tty_sid, new_tty_sid;
100
101         if (!is_selinux_enabled())
102                 return;
103
104         if (get_default_context(username, NULL, user_sid)) {
105                 bb_error_msg_and_die("can't get SID for %s", username);
106         }
107         if (getfilecon(full_tty, &old_tty_sid) < 0) {
108                 bb_perror_msg_and_die("getfilecon(%s) failed", full_tty);
109         }
110         if (security_compute_relabel(*user_sid, old_tty_sid,
111                                 SECCLASS_CHR_FILE, &new_tty_sid) != 0) {
112                 bb_perror_msg_and_die("security_change_sid(%s) failed", full_tty);
113         }
114         if (setfilecon(full_tty, new_tty_sid) != 0) {
115                 bb_perror_msg_and_die("chsid(%s, %s) failed", full_tty, new_tty_sid);
116         }
117 }
118 #endif
119
120 #if ENABLE_LOGIN_SCRIPTS
121 static void run_login_script(struct passwd *pw, char *full_tty)
122 {
123         char *t_argv[2];
124
125         t_argv[0] = getenv("LOGIN_PRE_SUID_SCRIPT");
126         if (t_argv[0]) {
127                 t_argv[1] = NULL;
128                 xsetenv("LOGIN_TTY", full_tty);
129                 xsetenv("LOGIN_USER", pw->pw_name);
130                 xsetenv("LOGIN_UID", utoa(pw->pw_uid));
131                 xsetenv("LOGIN_GID", utoa(pw->pw_gid));
132                 xsetenv("LOGIN_SHELL", pw->pw_shell);
133                 spawn_and_wait(t_argv); /* NOMMU-friendly */
134                 unsetenv("LOGIN_TTY");
135                 unsetenv("LOGIN_USER");
136                 unsetenv("LOGIN_UID");
137                 unsetenv("LOGIN_GID");
138                 unsetenv("LOGIN_SHELL");
139         }
140 }
141 #else
142 void run_login_script(struct passwd *pw, char *full_tty);
143 #endif
144
145 static void get_username_or_die(char *buf, int size_buf)
146 {
147         int c, cntdown;
148
149         cntdown = EMPTY_USERNAME_COUNT;
150  prompt:
151         print_login_prompt();
152         /* skip whitespace */
153         do {
154                 c = getchar();
155                 if (c == EOF)
156                         exit(EXIT_FAILURE);
157                 if (c == '\n') {
158                         if (!--cntdown)
159                                 exit(EXIT_FAILURE);
160                         goto prompt;
161                 }
162         } while (isspace(c)); /* maybe isblank? */
163
164         *buf++ = c;
165         if (!fgets(buf, size_buf-2, stdin))
166                 exit(EXIT_FAILURE);
167         if (!strchr(buf, '\n'))
168                 exit(EXIT_FAILURE);
169         while ((unsigned char)*buf > ' ')
170                 buf++;
171         *buf = '\0';
172 }
173
174 static void motd(void)
175 {
176         int fd;
177
178         fd = open(bb_path_motd_file, O_RDONLY);
179         if (fd >= 0) {
180                 fflush_all();
181                 bb_copyfd_eof(fd, STDOUT_FILENO);
182                 close(fd);
183         }
184 }
185
186 static void alarm_handler(int sig UNUSED_PARAM)
187 {
188         /* This is the escape hatch!  Poor serial line users and the like
189          * arrive here when their connection is broken.
190          * We don't want to block here */
191         ndelay_on(1);
192         printf("\r\nLogin timed out after %d seconds\r\n", TIMEOUT);
193         fflush_all();
194         /* unix API is brain damaged regarding O_NONBLOCK,
195          * we should undo it, or else we can affect other processes */
196         ndelay_off(1);
197         _exit(EXIT_SUCCESS);
198 }
199
200 int login_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
201 int login_main(int argc UNUSED_PARAM, char **argv)
202 {
203         enum {
204                 LOGIN_OPT_f = (1<<0),
205                 LOGIN_OPT_h = (1<<1),
206                 LOGIN_OPT_p = (1<<2),
207         };
208         char *fromhost;
209         char username[USERNAME_SIZE];
210         int run_by_root;
211         unsigned opt;
212         int count = 0;
213         struct passwd *pw;
214         char *opt_host = NULL;
215         char *opt_user = opt_user; /* for compiler */
216         char *full_tty;
217         IF_SELINUX(security_context_t user_sid = NULL;)
218 #if ENABLE_PAM
219         int pamret;
220         pam_handle_t *pamh;
221         const char *pamuser;
222         const char *failed_msg;
223         struct passwd pwdstruct;
224         char pwdbuf[256];
225         char **pamenv;
226 #endif
227
228         username[0] = '\0';
229         signal(SIGALRM, alarm_handler);
230         alarm(TIMEOUT);
231
232         /* More of suid paranoia if called by non-root: */
233         /* Clear dangerous stuff, set PATH */
234         run_by_root = !sanitize_env_if_suid();
235
236         /* Mandatory paranoia for suid applet:
237          * ensure that fd# 0,1,2 are opened (at least to /dev/null)
238          * and any extra open fd's are closed.
239          * (The name of the function is misleading. Not daemonizing here.) */
240         bb_daemonize_or_rexec(DAEMON_ONLY_SANITIZE | DAEMON_CLOSE_EXTRA_FDS, NULL);
241
242         opt = getopt32(argv, "f:h:p", &opt_user, &opt_host);
243         if (opt & LOGIN_OPT_f) {
244                 if (!run_by_root)
245                         bb_error_msg_and_die("-f is for root only");
246                 safe_strncpy(username, opt_user, sizeof(username));
247         }
248         argv += optind;
249         if (argv[0]) /* user from command line (getty) */
250                 safe_strncpy(username, argv[0], sizeof(username));
251
252         /* Let's find out and memorize our tty */
253         if (!isatty(STDIN_FILENO) || !isatty(STDOUT_FILENO) || !isatty(STDERR_FILENO))
254                 return EXIT_FAILURE;  /* Must be a terminal */
255         full_tty = xmalloc_ttyname(STDIN_FILENO);
256         if (!full_tty)
257                 full_tty = xstrdup("UNKNOWN");
258         short_tty = skip_dev_pfx(full_tty);
259
260         if (opt_host) {
261                 fromhost = xasprintf(" on '%s' from '%s'", short_tty, opt_host);
262         } else {
263                 fromhost = xasprintf(" on '%s'", short_tty);
264         }
265
266         /* Was breaking "login <username>" from shell command line: */
267         /*bb_setpgrp();*/
268
269         openlog(applet_name, LOG_PID | LOG_CONS, LOG_AUTH);
270
271         while (1) {
272                 /* flush away any type-ahead (as getty does) */
273                 tcflush(0, TCIFLUSH);
274
275                 if (!username[0])
276                         get_username_or_die(username, sizeof(username));
277
278 #if ENABLE_PAM
279                 pamret = pam_start("login", username, &conv, &pamh);
280                 if (pamret != PAM_SUCCESS) {
281                         failed_msg = "start";
282                         goto pam_auth_failed;
283                 }
284                 /* set TTY (so things like securetty work) */
285                 pamret = pam_set_item(pamh, PAM_TTY, short_tty);
286                 if (pamret != PAM_SUCCESS) {
287                         failed_msg = "set_item(TTY)";
288                         goto pam_auth_failed;
289                 }
290                 /* set RHOST */
291                 if (opt_host) {
292                         pamret = pam_set_item(pamh, PAM_RHOST, opt_host);
293                         if (pamret != PAM_SUCCESS) {
294                                 failed_msg = "set_item(RHOST)";
295                                 goto pam_auth_failed;
296                         }
297                 }
298                 pamret = pam_authenticate(pamh, 0);
299                 if (pamret != PAM_SUCCESS) {
300                         failed_msg = "authenticate";
301                         goto pam_auth_failed;
302                         /* TODO: or just "goto auth_failed"
303                          * since user seems to enter wrong password
304                          * (in this case pamret == 7)
305                          */
306                 }
307                 /* check that the account is healthy */
308                 pamret = pam_acct_mgmt(pamh, 0);
309                 if (pamret != PAM_SUCCESS) {
310                         failed_msg = "acct_mgmt";
311                         goto pam_auth_failed;
312                 }
313                 /* read user back */
314                 pamuser = NULL;
315                 /* gcc: "dereferencing type-punned pointer breaks aliasing rules..."
316                  * thus we cast to (void*) */
317                 if (pam_get_item(pamh, PAM_USER, (void*)&pamuser) != PAM_SUCCESS) {
318                         failed_msg = "get_item(USER)";
319                         goto pam_auth_failed;
320                 }
321                 if (!pamuser || !pamuser[0])
322                         goto auth_failed;
323                 safe_strncpy(username, pamuser, sizeof(username));
324                 /* Don't use "pw = getpwnam(username);",
325                  * PAM is said to be capable of destroying static storage
326                  * used by getpwnam(). We are using safe(r) function */
327                 pw = NULL;
328                 getpwnam_r(username, &pwdstruct, pwdbuf, sizeof(pwdbuf), &pw);
329                 if (!pw)
330                         goto auth_failed;
331                 pamret = pam_open_session(pamh, 0);
332                 if (pamret != PAM_SUCCESS) {
333                         failed_msg = "open_session";
334                         goto pam_auth_failed;
335                 }
336                 pamret = pam_setcred(pamh, PAM_ESTABLISH_CRED);
337                 if (pamret != PAM_SUCCESS) {
338                         failed_msg = "setcred";
339                         goto pam_auth_failed;
340                 }
341                 break; /* success, continue login process */
342
343  pam_auth_failed:
344                 /* syslog, because we don't want potential attacker
345                  * to know _why_ login failed */
346                 syslog(LOG_WARNING, "pam_%s call failed: %s (%d)", failed_msg,
347                                         pam_strerror(pamh, pamret), pamret);
348                 safe_strncpy(username, "UNKNOWN", sizeof(username));
349 #else /* not PAM */
350                 pw = getpwnam(username);
351                 if (!pw) {
352                         strcpy(username, "UNKNOWN");
353                         goto fake_it;
354                 }
355
356                 if (pw->pw_passwd[0] == '!' || pw->pw_passwd[0] == '*')
357                         goto auth_failed;
358
359                 if (opt & LOGIN_OPT_f)
360                         break; /* -f USER: success without asking passwd */
361
362                 if (pw->pw_uid == 0 && !check_securetty())
363                         goto auth_failed;
364
365                 /* Don't check the password if password entry is empty (!) */
366                 if (!pw->pw_passwd[0])
367                         break;
368  fake_it:
369                 /* authorization takes place here */
370                 if (correct_password(pw))
371                         break;
372 #endif /* ENABLE_PAM */
373  auth_failed:
374                 opt &= ~LOGIN_OPT_f;
375                 bb_do_delay(LOGIN_FAIL_DELAY);
376                 /* TODO: doesn't sound like correct English phrase to me */
377                 puts("Login incorrect");
378                 if (++count == 3) {
379                         syslog(LOG_WARNING, "invalid password for '%s'%s",
380                                                 username, fromhost);
381
382                         if (ENABLE_FEATURE_CLEAN_UP)
383                                 free(fromhost);
384
385                         return EXIT_FAILURE;
386                 }
387                 username[0] = '\0';
388         } /* while (1) */
389
390         alarm(0);
391         /* We can ignore /etc/nologin if we are logging in as root,
392          * it doesn't matter whether we are run by root or not */
393         if (pw->pw_uid != 0)
394                 die_if_nologin();
395
396         IF_SELINUX(initselinux(username, full_tty, &user_sid));
397
398         /* Try these, but don't complain if they fail.
399          * _f_chown is safe wrt race t=ttyname(0);...;chown(t); */
400         fchown(0, pw->pw_uid, pw->pw_gid);
401         fchmod(0, 0600);
402
403         update_utmp(getpid(), USER_PROCESS, short_tty, username, run_by_root ? opt_host : NULL);
404
405         /* We trust environment only if we run by root */
406         if (ENABLE_LOGIN_SCRIPTS && run_by_root)
407                 run_login_script(pw, full_tty);
408
409         change_identity(pw);
410         setup_environment(pw->pw_shell,
411                         (!(opt & LOGIN_OPT_p) * SETUP_ENV_CLEARENV) + SETUP_ENV_CHANGEENV,
412                         pw);
413
414 #if ENABLE_PAM
415         /* Modules such as pam_env will setup the PAM environment,
416          * which should be copied into the new environment. */
417         pamenv = pam_getenvlist(pamh);
418         if (pamenv) while (*pamenv) {
419                 putenv(*pamenv);
420                 pamenv++;
421         }
422 #endif
423
424         motd();
425
426         if (pw->pw_uid == 0)
427                 syslog(LOG_INFO, "root login%s", fromhost);
428
429         if (ENABLE_FEATURE_CLEAN_UP)
430                 free(fromhost);
431
432         /* well, a simple setexeccon() here would do the job as well,
433          * but let's play the game for now */
434         IF_SELINUX(set_current_security_context(user_sid);)
435
436         // util-linux login also does:
437         // /* start new session */
438         // setsid();
439         // /* TIOCSCTTY: steal tty from other process group */
440         // if (ioctl(0, TIOCSCTTY, 1)) error_msg...
441         // BBox login used to do this (see above):
442         // bb_setpgrp();
443         // If this stuff is really needed, add it and explain why!
444
445         /* Set signals to defaults */
446         /* Non-ignored signals revert to SIG_DFL on exec anyway */
447         /*signal(SIGALRM, SIG_DFL);*/
448
449         /* Is this correct? This way user can ctrl-c out of /etc/profile,
450          * potentially creating security breach (tested with bash 3.0).
451          * But without this, bash 3.0 will not enable ctrl-c either.
452          * Maybe bash is buggy?
453          * Need to find out what standards say about /bin/login -
454          * should we leave SIGINT etc enabled or disabled? */
455         signal(SIGINT, SIG_DFL);
456
457         /* Exec login shell with no additional parameters */
458         run_shell(pw->pw_shell, 1, NULL, NULL);
459
460         /* return EXIT_FAILURE; - not reached */
461 }