</>EmbeddedInterview

What happens when a user logs in on a Linux terminal?

MediumEmbedded Linux & Boot

Short answer: init starts getty on each terminal; getty opens the TTY, prints the login prompt and reads the user name, then execs login. login checks the password (via PAM against /etc/shadow), sets up the session, changes to the user's UID/GID with setgid()/setuid(), and execs the user's shell from /etc/passwd. Over SSH, sshd does the same job instead of getty/login.

Step by step on a serial console

  1. init starts getty (agetty, or BusyBox getty) for ttyS0/ttyAMA0, as configured in /etc/inittab or a systemd serial-getty@.service.
  2. getty opens the terminal device, sets the baud rate and line settings (termios), makes it the controlling terminal of a new session (setsid()), prints /etc/issue and login:, reads the name.
  3. getty execs login username (the same process, PID unchanged).
  4. login reads the password with echo disabled, verifies it through PAM (which hashes the input and compares with /etc/shadow), checks account expiry and /etc/nologin.
  5. login records the session (utmp/wtmp, lastlog), sets the TTY owner to the user, then drops privileges: initgroups(), setgid(), setuid(). This order matters: after setuid() to a normal user it can no longer change groups.
  6. It sets HOME, SHELL, USER, PATH, changes to the home directory and execs the shell with a leading - in argv[0] (e.g. -bash), which tells the shell it is a login shell and should read /etc/profile and ~/.profile.

Where the kernel is involved

  • The TTY layer and line discipline handle echo, line editing (canonical mode), and turning Ctrl-C into SIGINT for the foreground process group.
  • setuid()/setgid() are system calls; the kernel checks that only a privileged process (root, or with CAP_SETUID) may change to an arbitrary UID.
  • Sessions and process groups (setsid, tcsetpgrp) let the shell do job control.
  • When you log out, the shell exits, init sees its child died and starts a fresh getty.

Embedded note: many products disable login on the serial console in production, or use autologin during development. Leaving a root shell on the debug UART of a shipped device is a classic security finding.