- don't free user-supplied string (via -e)
[oweals/busybox.git] / libbb / update_passwd.c
index 8914b8b45b8bf5c457e00bfff2a639ba40be3478..88bc28ca93a01a75ed5b63f6c5d67a31f8fdcd85 100644 (file)
 
 #include "libbb.h"
 
-int update_passwd(const char *filename, const char *username,
+#if ENABLE_SELINUX
+static void check_selinux_update_passwd(const char *username)
+{
+       security_context_t context;
+       char *seuser;
+
+       if (getuid() != (uid_t)0 || is_selinux_enabled() == 0)
+               return;         /* No need to check */
+
+       if (getprevcon_raw(&context) < 0)
+               bb_perror_msg_and_die("getprevcon failed");
+       seuser = strtok(context, ":");
+       if (!seuser)
+               bb_error_msg_and_die("invalid context '%s'", context);
+       if (strcmp(seuser, username) != 0) {
+               if (checkPasswdAccess(PASSWD__PASSWD) != 0)
+                       bb_error_msg_and_die("SELinux: access denied");
+       }
+       if (ENABLE_FEATURE_CLEAN_UP)
+               freecon(context);
+}
+#else
+#define check_selinux_update_passwd(username) ((void)0)
+#endif
+
+int FAST_FUNC update_passwd(const char *filename, const char *username,
                        const char *new_pw)
 {
        struct stat sb;
@@ -27,6 +52,12 @@ int update_passwd(const char *filename, const char *username,
        int cnt = 0;
        int ret = -1; /* failure */
 
+       filename = xmalloc_follow_symlinks(filename);
+       if (filename == NULL)
+               return -1;
+
+       check_selinux_update_passwd(username);
+
        /* New passwd file, "/etc/passwd+" for now */
        fnamesfx = xasprintf("%s+", filename);
        sfx_char = &fnamesfx[strlen(fnamesfx)-1];
@@ -38,6 +69,8 @@ int update_passwd(const char *filename, const char *username,
                goto free_mem;
        old_fd = fileno(old_fp);
 
+       selinux_preserve_fcontext(old_fd);
+
        /* Try to create "/etc/passwd+". Wait if it exists. */
        i = 30;
        do {
@@ -114,6 +147,7 @@ int update_passwd(const char *filename, const char *username,
 
  free_mem:
        free(fnamesfx);
-       free((char*)username);
+       free((char *)filename);
+       free((char *)username);
        return ret;
 }