Often Misused: Authentication (getlogin) Abstract The getlogin() function is easy to spoof. Do not rely on the name it returns. Explanation The getlogin() function is supposed to return a string containing the name of the user currently logged in at the terminal, but an attacker can cause getlogin() to return the name of any user who is logged in to the machine. Do not rely on the name returned by getlogin() when making security decisions. Example 1: The following code relies on getlogin() to determine whether or not a user is trusted. It is easily subverted. pwd = getpwnam(getlogin()); if (isTrustedGroup(pwd->pw_gid)) { allow(); } else { deny(); } Recommendations You should rely on a user's ID, not the username, for identification. The previous example can be rewritten as: pwd = getpwuid(getuid()); if (isTrustedGroup(pwd->pw_gid)) { allow(); } else { deny(); } If multiple users are allowed to share the same user ID (a dubious proposition from a security standpoint), a bit more care is required. The following example checks to see whether the username returned by getlogin() matches the username associated with the user ID; the check ensures that if two users share the same ID, one user cannot act on behalf of the other. pwd = getpwuid(getuid()); pwdName = pwd->pw_name; /* Bail out if the name associated with the uid does not match the name associated with the terminal. */ if (strncmp(pwdName, getlogin(), MAX_NAM_LEN)) { printf("shared uid not supported\n"); deny(); return; } if (isTrustedGroup(pwd->pw_gid)) { allow(); } else { deny(); } Note: If the process is not being run from a terminal, getlogin() returns NULL. |