Add one-line GPL boilerplate to numerous (but not all yet) source files.
[oweals/busybox.git] / loginutils / login.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
4  */
5
6 #include <fcntl.h>
7 #include <signal.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <syslog.h>
12 #include <termios.h>
13 #include <unistd.h>
14 #include <utmp.h>
15 #include <sys/resource.h>
16 #include <sys/stat.h>
17 #include <sys/types.h>
18 #include <ctype.h>
19 #include <time.h>
20
21 #include "busybox.h"
22 #ifdef CONFIG_SELINUX
23 #include <selinux/selinux.h>  /* for is_selinux_enabled()  */
24 #include <selinux/get_context_list.h> /* for get_default_context() */
25 #include <selinux/flask.h> /* for security class definitions  */
26 #include <errno.h>
27 #endif
28
29 #ifdef CONFIG_FEATURE_UTMP
30 // import from utmp.c
31 static void checkutmp(int picky);
32 static void setutmp(const char *name, const char *line);
33 /* Stuff global to this file */
34 static struct utmp utent;
35 #endif
36
37 // login defines
38 #define TIMEOUT       60
39 #define EMPTY_USERNAME_COUNT    10
40 #define USERNAME_SIZE 32
41
42
43 static int check_nologin ( int amroot );
44
45 #if defined CONFIG_FEATURE_SECURETTY
46 static int check_tty ( const char *tty );
47
48 #else
49 static inline int check_tty ( const char *tty )  { return 1; }
50
51 #endif
52
53 static int is_my_tty ( const char *tty );
54 static int login_prompt ( char *buf_name );
55 static void motd ( void );
56
57
58 static void alarm_handler ( int sig ATTRIBUTE_UNUSED)
59 {
60         fprintf (stderr, "\nLogin timed out after %d seconds.\n", TIMEOUT );
61         exit ( EXIT_SUCCESS );
62 }
63
64
65 int login_main(int argc, char **argv)
66 {
67         char tty[BUFSIZ];
68         char full_tty[200];
69         char fromhost[512];
70         char username[USERNAME_SIZE];
71         const char *tmp;
72         int amroot;
73         int flag;
74         int failed;
75         int count=0;
76         struct passwd *pw, pw_copy;
77 #ifdef CONFIG_WHEEL_GROUP
78         struct group *grp;
79 #endif
80         int opt_preserve = 0;
81         int opt_fflag = 0;
82         char *opt_host = 0;
83         int alarmstarted = 0;
84 #ifdef CONFIG_SELINUX
85         security_context_t user_sid = NULL;
86 #endif
87
88         username[0]=0;
89         amroot = ( getuid ( ) == 0 );
90         signal ( SIGALRM, alarm_handler );
91         alarm ( TIMEOUT );
92         alarmstarted = 1;
93
94         while (( flag = getopt(argc, argv, "f:h:p")) != EOF ) {
95                 switch ( flag ) {
96                 case 'p':
97                         opt_preserve = 1;
98                         break;
99                 case 'f':
100                         /*
101                          * username must be a separate token
102                          * (-f root, *NOT* -froot). --marekm
103                          */
104                         if ( optarg != argv[optind-1] )
105                                 bb_show_usage( );
106
107                         if ( !amroot )          /* Auth bypass only if real UID is zero */
108                                 bb_error_msg_and_die ( "-f permission denied" );
109
110                         safe_strncpy(username, optarg, USERNAME_SIZE);
111                         opt_fflag = 1;
112                         break;
113                 case 'h':
114                         opt_host = optarg;
115                         break;
116                 default:
117                         bb_show_usage( );
118                 }
119         }
120
121         if (optind < argc)             // user from command line (getty)
122                 safe_strncpy(username, argv[optind], USERNAME_SIZE);
123
124         if ( !isatty ( 0 ) || !isatty ( 1 ) || !isatty ( 2 ))
125                 return EXIT_FAILURE;            /* Must be a terminal */
126
127 #ifdef CONFIG_FEATURE_UTMP
128         checkutmp ( !amroot );
129 #endif
130
131         tmp = ttyname ( 0 );
132         if ( tmp && ( strncmp ( tmp, "/dev/", 5 ) == 0 ))
133                 safe_strncpy ( tty, tmp + 5, sizeof( tty ));
134         else if ( tmp && *tmp == '/' )
135                 safe_strncpy ( tty, tmp, sizeof( tty ));
136         else
137                 safe_strncpy ( tty, "UNKNOWN", sizeof( tty ));
138
139 #ifdef CONFIG_FEATURE_UTMP
140         if ( amroot )
141                 memset ( utent.ut_host, 0, sizeof utent.ut_host );
142 #endif
143
144         if ( opt_host ) {
145 #ifdef CONFIG_FEATURE_UTMP
146                 safe_strncpy ( utent.ut_host, opt_host, sizeof( utent. ut_host ));
147 #endif
148                 snprintf ( fromhost, sizeof( fromhost ) - 1, " on `%.100s' from `%.200s'", tty, opt_host );
149         }
150         else
151                 snprintf ( fromhost, sizeof( fromhost ) - 1, " on `%.100s'", tty );
152
153         bb_setpgrp;
154
155         openlog ( "login", LOG_PID | LOG_CONS | LOG_NOWAIT, LOG_AUTH );
156
157         while ( 1 ) {
158                 failed = 0;
159
160                 if ( !username[0] )
161                         if(!login_prompt ( username ))
162                                 return EXIT_FAILURE;
163
164                 if ( !alarmstarted && ( TIMEOUT > 0 )) {
165                         alarm ( TIMEOUT );
166                         alarmstarted = 1;
167                 }
168
169                 if (!( pw = getpwnam ( username ))) {
170                         pw_copy.pw_name   = "UNKNOWN";
171                         pw_copy.pw_passwd = "!";
172                         opt_fflag = 0;
173                         failed = 1;
174                 } else
175                         pw_copy = *pw;
176
177                 pw = &pw_copy;
178
179                 if (( pw-> pw_passwd [0] == '!' ) || ( pw-> pw_passwd[0] == '*' ))
180                         failed = 1;
181
182                 if ( opt_fflag ) {
183                         opt_fflag = 0;
184                         goto auth_ok;
185                 }
186
187                 if (!failed && ( pw-> pw_uid == 0 ) && ( !check_tty ( tty )))
188                         failed = 1;
189
190                 /* Don't check the password if password entry is empty (!) */
191                 if ( !pw-> pw_passwd[0] )
192                         goto auth_ok;
193
194                 /* authorization takes place here */
195                 if ( correct_password ( pw ))
196                         goto auth_ok;
197
198                 failed = 1;
199
200 auth_ok:
201                 if ( !failed)
202                         break;
203
204                 bb_do_delay(FAIL_DELAY);
205                 puts("Login incorrect");
206                 username[0] = 0;
207                 if ( ++count == 3 ) {
208                         syslog ( LOG_WARNING, "invalid password for `%s'%s\n", pw->pw_name, fromhost);
209                         return EXIT_FAILURE;
210         }
211         }
212
213         alarm ( 0 );
214         if ( check_nologin ( pw-> pw_uid == 0 ))
215                 return EXIT_FAILURE;
216
217 #ifdef CONFIG_FEATURE_UTMP
218         setutmp ( username, tty );
219 #endif
220
221         if ( *tty != '/' )
222                 snprintf ( full_tty, sizeof( full_tty ) - 1, "/dev/%s", tty);
223         else
224                 safe_strncpy ( full_tty, tty, sizeof( full_tty ) - 1 );
225
226 #ifdef CONFIG_SELINUX
227         if (is_selinux_enabled())
228         {
229                 security_context_t old_tty_sid, new_tty_sid;
230
231                 if (get_default_context(username, NULL, &user_sid))
232                 {
233                         fprintf(stderr, "Unable to get SID for %s\n", username);
234                         exit(1);
235                 }
236                 if (getfilecon(full_tty, &old_tty_sid) < 0)
237                 {
238                         fprintf(stderr, "getfilecon(%.100s) failed: %.100s\n", full_tty, strerror(errno));
239                         return EXIT_FAILURE;
240                 }
241                 if (security_compute_relabel(user_sid, old_tty_sid, SECCLASS_CHR_FILE, &new_tty_sid) != 0)
242                 {
243                         fprintf(stderr, "security_change_sid(%.100s) failed: %.100s\n", full_tty, strerror(errno));
244                         return EXIT_FAILURE;
245                 }
246                 if(setfilecon(full_tty, new_tty_sid) != 0)
247                 {
248                         fprintf(stderr, "chsid(%.100s, %s) failed: %.100s\n", full_tty, new_tty_sid, strerror(errno));
249                         return EXIT_FAILURE;
250                 }
251         }
252 #endif
253         if ( !is_my_tty ( full_tty ))
254                 syslog ( LOG_ERR, "unable to determine TTY name, got %s\n", full_tty );
255
256         /* Try these, but don't complain if they fail
257          * (for example when the root fs is read only) */
258         chown ( full_tty, pw-> pw_uid, pw-> pw_gid );
259         chmod ( full_tty, 0600 );
260
261         change_identity ( pw );
262         tmp = pw-> pw_shell;
263         if(!tmp || !*tmp)
264                 tmp = DEFAULT_SHELL;
265         setup_environment ( tmp, 1, !opt_preserve, pw );
266
267         motd ( );
268         signal ( SIGALRM, SIG_DFL );    /* default alarm signal */
269
270         if ( pw-> pw_uid == 0 )
271                 syslog ( LOG_INFO, "root login %s\n", fromhost );
272 #ifdef CONFIG_SELINUX
273         /* well, a simple setexeccon() here would do the job as well,
274          * but let's play the game for now */
275         set_current_security_context(user_sid);
276 #endif
277         run_shell ( tmp, 1, 0, 0);      /* exec the shell finally. */
278
279         return EXIT_FAILURE;
280 }
281
282
283
284 static int login_prompt ( char *buf_name )
285 {
286         char buf [1024];
287         char *sp, *ep;
288         int i;
289
290         for(i=0; i<EMPTY_USERNAME_COUNT; i++) {
291                 print_login_prompt();
292
293                 if ( !fgets ( buf, sizeof( buf ) - 1, stdin ))
294                         return 0;
295
296                 if ( !strchr ( buf, '\n' ))
297                         return 0;
298
299                 for ( sp = buf; isspace ( *sp ); sp++ ) { }
300                 for ( ep = sp; isgraph ( *ep ); ep++ ) { }
301
302                 *ep = 0;
303                 safe_strncpy(buf_name, sp, USERNAME_SIZE);
304                 if(buf_name[0])
305                         return 1;
306         }
307         return 0;
308 }
309
310
311 static int check_nologin ( int amroot )
312 {
313         if ( access ( bb_path_nologin_file, F_OK ) == 0 ) {
314                 FILE *fp;
315                 int c;
316
317                 if (( fp = fopen ( bb_path_nologin_file, "r" ))) {
318                         while (( c = getc ( fp )) != EOF )
319                                 putchar (( c == '\n' ) ? '\r' : c );
320
321                         fflush ( stdout );
322                         fclose ( fp );
323                 } else {
324                         puts ( "\r\nSystem closed for routine maintenance.\r" );
325                 }
326                 if ( !amroot )
327                         return 1;
328
329                 puts ( "\r\n[Disconnect bypassed -- root login allowed.]\r" );
330         }
331         return 0;
332 }
333
334 #ifdef CONFIG_FEATURE_SECURETTY
335
336 static int check_tty ( const char *tty )
337 {
338         FILE *fp;
339         int i;
340         char buf[BUFSIZ];
341
342         if (( fp = fopen ( bb_path_securetty_file, "r" ))) {
343                 while ( fgets ( buf, sizeof( buf ) - 1, fp )) {
344                         for ( i = strlen( buf ) - 1; i >= 0; --i ) {
345                                 if ( !isspace ( buf[i] ))
346                                         break;
347                         }
348                         buf[++i] = '\0';
349                         if (( buf [0] == '\0' ) || ( buf [0] == '#' ))
350                                 continue;
351
352                         if ( strcmp ( buf, tty ) == 0 ) {
353                                 fclose ( fp );
354                                 return 1;
355                         }
356                 }
357                 fclose(fp);
358                 return 0;
359         }
360         /* A missing securetty file is not an error. */
361         return 1;
362 }
363
364 #endif
365
366 /* returns 1 if true */
367 static int is_my_tty ( const char *tty )
368 {
369         struct stat by_name, by_fd;
370
371         if ( stat ( tty, &by_name ) || fstat ( 0, &by_fd ))
372                 return 0;
373
374         if ( by_name. st_rdev != by_fd. st_rdev )
375                 return 0;
376         else
377                 return 1;
378 }
379
380
381 static void motd (void)
382 {
383         FILE *fp;
384         int c;
385
386         if (( fp = fopen ( bb_path_motd_file, "r" ))) {
387                 while (( c = getc ( fp )) != EOF )
388                         putchar ( c );
389                 fclose ( fp );
390         }
391 }
392
393
394 #ifdef CONFIG_FEATURE_UTMP
395 // vv  Taken from tinylogin utmp.c  vv
396
397 #define NO_UTENT \
398         "No utmp entry.  You must exec \"login\" from the lowest level \"sh\""
399 #define NO_TTY \
400         "Unable to determine your tty name."
401
402 /*
403  * checkutmp - see if utmp file is correct for this process
404  *
405  *      System V is very picky about the contents of the utmp file
406  *      and requires that a slot for the current process exist.
407  *      The utmp file is scanned for an entry with the same process
408  *      ID.  If no entry exists the process exits with a message.
409  *
410  *      The "picky" flag is for network and other logins that may
411  *      use special flags.  It allows the pid checks to be overridden.
412  *      This means that getty should never invoke login with any
413  *      command line flags.
414  */
415
416 static void checkutmp(int picky)
417 {
418         char *line;
419         struct utmp *ut;
420         pid_t pid = getpid();
421
422         setutent();
423
424         /* First, try to find a valid utmp entry for this process.  */
425         while ((ut = getutent()))
426                 if (ut->ut_pid == pid && ut->ut_line[0] && ut->ut_id[0] &&
427                         (ut->ut_type == LOGIN_PROCESS || ut->ut_type == USER_PROCESS))
428                         break;
429
430         /* If there is one, just use it, otherwise create a new one.  */
431         if (ut) {
432                 utent = *ut;
433         } else {
434                 time_t t_tmp;
435                 
436                 if (picky) {
437                         puts(NO_UTENT);
438                         exit(1);
439                 }
440                 line = ttyname(0);
441                 if (!line) {
442                         puts(NO_TTY);
443                         exit(1);
444                 }
445                 if (strncmp(line, "/dev/", 5) == 0)
446                         line += 5;
447                 memset((void *) &utent, 0, sizeof utent);
448                 utent.ut_type = LOGIN_PROCESS;
449                 utent.ut_pid = pid;
450                 strncpy(utent.ut_line, line, sizeof utent.ut_line);
451                 /* XXX - assumes /dev/tty?? */
452                 strncpy(utent.ut_id, utent.ut_line + 3, sizeof utent.ut_id);
453                 strncpy(utent.ut_user, "LOGIN", sizeof utent.ut_user);
454                 t_tmp = (time_t)utent.ut_time;
455                 time(&t_tmp);
456         }
457 }
458
459 /*
460  * setutmp - put a USER_PROCESS entry in the utmp file
461  *
462  *      setutmp changes the type of the current utmp entry to
463  *      USER_PROCESS.  the wtmp file will be updated as well.
464  */
465
466 static void setutmp(const char *name, const char *line ATTRIBUTE_UNUSED)
467 {
468         time_t t_tmp = (time_t)utent.ut_time;
469
470         utent.ut_type = USER_PROCESS;
471         strncpy(utent.ut_user, name, sizeof utent.ut_user);
472         time(&t_tmp);
473         /* other fields already filled in by checkutmp above */
474         setutent();
475         pututline(&utent);
476         endutent();
477 #ifdef CONFIG_FEATURE_WTMP
478         if (access(bb_path_wtmp_file, R_OK|W_OK) == -1) {
479                 close(creat(bb_path_wtmp_file, 0664));
480         }
481         updwtmp(bb_path_wtmp_file, &utent);
482 #endif
483 }
484 #endif /* CONFIG_FEATURE_UTMP */