[Pkg-shadow-devel] [Git][debian/adduser][zg/debian-bug-486877-yesno] 22 commits: add AdduserYesNo.pm

Marc Haber (@zugschlus) gitlab at salsa.debian.org
Mon Nov 30 06:37:23 GMT 2026



Marc Haber pushed to branch zg/debian-bug-486877-yesno at Debian / adduser


Commits:
5e09e1d8 by Marc Haber at 2026-11-30T07:24:01+01:00
add AdduserYesNo.pm

Git-Dch: ignore

- - - - -
539feeed by Marc Haber at 2026-11-30T07:24:01+01:00
accept more international yes/no input

Closes: #486877

- - - - -
32110b3e by Marc Haber at 2026-11-30T07:24:01+01:00
fix: systemcall_useradd, don't fall through at end

Git-Dch: ignore

- - - - -
7f8b2e20 by Marc Haber at 2026-11-30T07:24:01+01:00
AdduserStateFile: Remove stale get_user_data

Git-Dch: ignore

- - - - -
fbe15499 by Marc Haber at 2026-11-30T07:24:01+01:00
AdduserStateFile: _write_state: do atomic write

Git-Dch: ignore

- - - - -
4a65a5b8 by Marc Haber at 2026-11-30T07:24:01+01:00
adduser: expand BEGIN to cover the new modules

Git-Dch: ignore

- - - - -
6cc0501d by Marc Haber at 2026-11-30T07:24:01+01:00
deluser: fix reference to wrong config{"remove"}

Git-Dch: ignore

- - - - -
6b243904 by Marc Haber at 2026-11-30T07:24:01+01:00
fix wrong parenthesis in mtx call

Git-Dch: ignore
this was a systematic error, fixed in other places by rewrites

- - - - -
83e5f72e by Marc Haber at 2026-11-30T07:24:01+01:00
add whitesapce

Git-Dch: ignore

- - - - -
82e27bbf by Marc Haber at 2026-11-30T07:24:02+01:00
fix wrong log_trace that just logged "-"

Git-Dch: ignore

- - - - -
38d88de2 by Marc Haber at 2026-11-30T07:24:02+01:00
fix wrong usage of ==, it's eq for strings

Git-Dch: ignore

- - - - -
4dd5c0b1 by Marc Haber at 2026-11-30T07:24:02+01:00
rewrite unlock_user

Git-Dch: ignore

- - - - -
9453cc9b by Marc Haber at 2026-11-30T07:24:02+01:00
deluser: saniize shell path (avoiding a taint error)

Git-Dch: ignore

- - - - -
fb7b03bb by Marc Haber at 2026-11-30T07:24:02+01:00
add user_pids and kill_user_processes

Git-Dch: ignore

- - - - -
762cd609 by Marc Haber at 2026-11-30T07:24:02+01:00
deluser: rework user deletion (moe care deleting files, kill processes)

Git-Dch: ignore

- - - - -
c22fe658 by Marc Haber at 2026-11-30T07:24:02+01:00
update debian/copyright

- - - - -
59c0135c by Marc Haber at 2026-11-30T07:24:02+01:00
lib_test: add cleanup functions

Git-Dch: ignore

- - - - -
626d26ad by Marc Haber at 2026-11-30T07:24:02+01:00
fix wrong assertions in lib_test.pm

Git-Dch: ignore

- - - - -
ce80f408 by Marc Haber at 2026-11-30T07:24:02+01:00
use cleanup functions in testsuite/*

Git-Dch: ignore

- - - - -
3a8e9ca3 by Marc Haber at 2026-11-30T07:24:02+01:00
testsuite/test11.pl: check for correct error message

Git-Dch: ignore

- - - - -
ddd7bfe1 by Marc Haber at 2026-11-30T07:24:02+01:00
testsuite/test09.pl: it's != for a number, not ne

Git-Dch: ignore

- - - - -
03dd5256 by Marc Haber at 2026-11-30T07:24:02+01:00
testsuite/test08: fix wrong test assertion

Git-Dch: ignore

- - - - -


17 changed files:

- AdduserCommon.pm
- AdduserStatefile.pm
- + AdduserYesNo.pm
- adduser
- debian/copyright
- debian/rules
- deluser
- doc/deluser.8
- testsuite/lib_test.pm
- testsuite/test03.pl
- testsuite/test04.pl
- testsuite/test05.pl
- testsuite/test06.pl
- testsuite/test07.pl
- testsuite/test08.pl
- testsuite/test09.pl
- testsuite/test11.pl


Changes:

=====================================
AdduserCommon.pm
=====================================
@@ -677,6 +677,7 @@ sub systemcall_useradd {
         log_fatal( mtx("`%s' exited from signal %d. Exiting."), $command, $ret&127 );
         exit( RET_SYSTEMCALL_SIGNAL );
     }
+    return 0;
 }
 
 sub systemcall {


=====================================
AdduserStatefile.pm
=====================================
@@ -28,6 +28,8 @@ use vars qw(@EXPORT);
 
 use strict;
 use warnings;
+use Fcntl qw(O_WRONLY O_CREAT O_EXCL);
+use IO::Handle;     # flush, sync
 
 our $STATE_DIR = '/var/lib/adduser';
 our $STATE_FILE = "$STATE_DIR/state";
@@ -120,22 +122,6 @@ sub get_state_value {
     return defined $key ? $data->{$username}{$key} : $data->{$username};
 }
 
-# get_user_data($username)
-#
-# Retrieve all key-value pairs for a given username.
-# This is a convenience wrapper around get_value($username, undef).
-#
-# Parameters:
-#   $username - The username to look up
-#
-# Returns:
-#   A hash reference containing all key-value pairs for the user,
-#   or an empty hash reference if the user doesn't exist
-sub get_state_user_data {
-    my ($username) = @_;
-    return get_value($username, undef);
-}
-
 # delete_user($username)
 #
 # Remove all data for a user from the state file.
@@ -316,38 +302,50 @@ sub _read_state {
 sub _write_state {
     my ($data_ref, $globals_ref) = @_;
 
-    # Use a process-specific temporary file name
-    my $temp_file = "$STATE_FILE.tmp.$$";
-
-    open(my $fh, '>', $temp_file) or die "Cannot write to $temp_file: $!";
-
+    # Build the complete content first, so that nothing is written
+    # unless it is all there.
+    my $out = '';
     if (%$globals_ref) {
-        my @pairs;
-        foreach my $key (sort keys %$globals_ref) {
-            push @pairs, "$key=$globals_ref->{$key}";
-        }
-        print $fh "$GLOBAL_RECORD:", join(':', @pairs), "\n";
+        $out .= "$GLOBAL_RECORD:"
+              . join(':', map { "$_=$globals_ref->{$_}" } sort keys %$globals_ref)
+              . "\n";
     }
-
-    # Write each user's data, sorted for consistency
+    # Each user's data, sorted for consistent, diff-friendly output
     foreach my $username (sort keys %$data_ref) {
-        my @pairs;
-
-        # Build key=value pairs, sorted by key
-        foreach my $key (sort keys %{$data_ref->{$username}}) {
-            push @pairs, "$key=$data_ref->{$username}{$key}";
-        }
-
-        # Write the line: username:key1=value1:key2=value2:...
-        print $fh "$username:", join(':', @pairs), "\n";
+        my $rec = $data_ref->{$username};
+        $out .= "$username:"
+              . join(':', map { "$_=$rec->{$_}" } sort keys %$rec)
+              . "\n";
     }
 
-    close($fh);
+    # Use a process-specific temporary file name
+    my $temp_file = "$STATE_FILE.tmp.$$";
+    unlink($temp_file);     # leftover of a crashed process with a recycled pid
+    sysopen(my $fh, $temp_file, O_WRONLY|O_CREAT|O_EXCL, 0644)
+        or die "Cannot create $temp_file: $!";
+
+    # Every step must succeed, or the old state file stays in place.
+    # One statement per step: Perl's taint flag is scoped to the statement,
+    # so tainted data in $out must not share a statement with chmod().
+    my $ok = print {$fh} $out;
+    $ok &&= $fh->flush;
+    $ok &&= $fh->sync;
+    $ok &&= chmod(0644, $fh);
+    $ok &&= close($fh);
+    unless ($ok) {
+        my $err = "$!";
+        close($fh);
+        unlink($temp_file);
+        die "Cannot write $temp_file: $err";
+    }
 
     # Atomically replace the old state file with the new one
     # This happens while still holding the lock, so no race condition
-    rename($temp_file, $STATE_FILE) or die "Cannot rename $temp_file: $!";
-    chmod(0644, $STATE_FILE);
+    rename($temp_file, $STATE_FILE) or do {
+        my $err = "$!";
+        unlink($temp_file);
+        die "Cannot rename $temp_file to $STATE_FILE: $err";
+    };
 }
 
 # Module must return true


=====================================
AdduserYesNo.pm
=====================================
@@ -0,0 +1,234 @@
+package Debian::AdduserYesNo 3.160;
+use utf8;
+use 5.36.0;
+use feature 'fc';
+
+# AdduserYesNo.pm: Ask a yes/no question and understand the answer in any
+# language
+#
+# This module provides ask_i18n_yesno(), which prints a question followed by
+# a "[yes/no]" prompt (with the labels taken from the gettext catalog, so
+# they appear in the user's language) and reads one line from standard input.
+# The answer is matched case-insensitively (using Unicode case folding)
+# against a built-in table of affirmative and negative words and
+# abbreviations in many languages, so a user can type "ja", "oui", "sí" or
+# "はい" regardless of the language the program is running in, and the
+# English "yes"/"no" always work as a fallback. A word that appears with
+# both meanings in different languages is treated as ambiguous and is
+# rejected rather than guessed at, and an unrecognized or ambiguous answer
+# makes the function explain the problem and ask again. The function
+# returns (1, undef) for yes, (0, undef) for no, and (undef, $reason) if
+# input ended or failed, where $reason is 'eof' or 'input-error', so the
+# caller can tell a refusal from an unanswered question.
+#
+# Copyright (C) 2026 Marc Haber
+#
+# License: GPL-2+
+
+use Debian::AdduserCommon 3.160;
+use Debian::AdduserLogging 3.160;
+
+use parent qw(Exporter);
+use vars qw(@EXPORT $VAR1);
+
+
+ at EXPORT = (
+    'ask_i18n_yesno',
+);
+
+# Accepted answers.
+#
+# Each entry consists of a token and its meaning:
+#   1 = yes
+#   0 = no
+#
+# Add or remove entries freely. Tokens that occur in both
+# categories are automatically treated as ambiguous.
+
+my @yesno_tokens = (
+    # English (also universal fallback)
+    [ 'yes',       1 ],
+    [ 'y',         1 ],
+    [ 'no',        0 ],
+    [ 'n',         0 ],
+
+    # German
+    [ 'ja',        1 ],
+    [ 'j',         1 ],
+    [ 'nein',      0 ],
+
+    # French
+    [ 'oui',       1 ],
+    [ 'o',         1 ],
+    [ 'non',       0 ],
+
+    # Spanish
+    [ 'sí',        1 ],
+    [ 'si',        1 ],
+
+    # Italian
+    [ 'sì',        1 ],
+
+    # Portuguese
+    [ 'sim',       1 ],
+    [ 'não',       0 ],
+    [ 'nao',       0 ],
+
+    # Dutch
+    [ 'nee',       0 ],
+
+    # Swedish
+    [ 'nej',       0 ],
+
+    # Norwegian
+    [ 'nei',       0 ],
+
+    # Danish
+    # Shares ja and nej with Swedish.
+
+    # Finnish
+    [ 'kyllä',     1 ],
+    [ 'kylla',     1 ],
+    [ 'ei',        0 ],
+    [ 'e',         0 ],  # ambiguous with Turkish
+
+    # Polish
+    [ 'tak',       1 ],
+    [ 'nie',       0 ],
+
+    # Czech
+    [ 'ano',       1 ],
+    [ 'a',         1 ],
+    [ 'ne',        0 ],
+
+    # Slovak
+    [ 'áno',       1 ],
+    [ 'nie',       0 ],
+
+    # Hungarian
+    [ 'igen',      1 ],
+    [ 'i',         1 ],
+    [ 'nem',       0 ],
+
+    # Russian
+    [ 'да',        1 ],
+    [ 'd',         1 ],
+    [ 'нет',       0 ],
+
+    # Ukrainian
+    [ 'так',       1 ],
+    [ 't',         1 ],
+    [ 'ні',        0 ],
+
+    # Greek
+    [ 'ναι',       1 ],
+    [ 'όχι',       0 ],
+    [ 'οχι',       0 ],
+
+    # Turkish
+    [ 'evet',      1 ],
+    [ 'e',         1 ],  # ambiguous with Finnish
+    [ 'hayır',     0 ],
+    [ 'hayir',     0 ],
+
+    # Japanese
+    [ 'はい',      1 ],
+    [ 'いいえ',    0 ],
+
+    # Chinese (Mandarin)
+    [ '是',        1 ],
+    [ '不是',      0 ],
+);
+
+# no "use open": decode input and encode output explicitly
+sub _out {
+    my ($s, $charset) = @_;
+    return encode($charset, $s);
+}
+
+sub ask_i18n_yesno {
+    my ($question, $charset) = @_;
+
+    # Localized canonical answer labels.
+    my $yes = gtx('yes');
+    my $no  = gtx('no');
+
+    # Build the reverse lookup table.
+    # Bit 1 means yes, bit 2 means no.
+    # A value of 3 means ambiguous.
+
+    my %lookup;
+
+    for my $entry (@yesno_tokens) {
+        my ($token, $value) = @$entry;
+
+        $lookup{fc($token)} |= $value ? 1 : 2;
+    }
+
+    # Construct the help answer list.
+    # Include localized labels and universal English answers.
+
+    my %seen;
+    my @labels = grep {
+        !$seen{fc($_)}++
+    } ($yes, $no, 'yes', 'no');
+
+    my $answer_list;
+
+    if (@labels == 2) {
+        $answer_list = sprintf(
+            gtx('%s or %s'),
+            @labels
+        );
+    }
+    elsif (@labels == 3) {
+        $answer_list = sprintf(
+            gtx('%s, %s, or %s'),
+            @labels
+        );
+    }
+    else {
+        $answer_list = sprintf(
+            gtx('%s, %s, %s, or %s'),
+            @labels
+        );
+    }
+
+    while (1) {
+        printf "%s [%s/%s] ", $question, $yes, $no;
+
+        local $! = 0;
+        my $answer = <STDIN>;
+
+        if (!defined $answer) {
+            return (undef, $! ? 'input-error' : 'eof');
+        }
+
+        chomp $answer;
+        $answer = decode($charset, $answer);
+        $answer =~ s/\A\s+|\s+\z//g;
+        my $key = fc($answer);
+
+        my $result = $lookup{$key} // 0;
+
+        return (1, undef) if $result == 1;
+        return (0, undef) if $result == 2;
+
+        if ($result == 3) {
+            printf _out(gtx(
+                "Ambiguous answer: %s\n", $charset
+            )), _out($answer, $charset);
+        }
+        else {
+            printf _out(gtx(
+                "Unrecognized answer: %s\n", $charset
+            )), _out($answer, $charset);
+        }
+
+        printf gtx(
+            "Please answer with %s.\n"
+        ), $answer_list;
+    }
+}
+
+1;


=====================================
adduser
=====================================
@@ -36,9 +36,14 @@ use Debian::AdduserLogging 3.160;
 use Debian::AdduserRetvalues 3.160;
 use Debian::AdduserStatefile 3.160;
 use Debian::AdduserCreateHomedir 3.160;
+use Debian::AdduserYesNo 3.160;
+
 BEGIN {
     if ( Debian::AdduserCommon->VERSION != version->declare('3.160') ||
          Debian::AdduserLogging->VERSION != version->declare('3.160') ||
+         Debian::AdduserStatefile->VERSION != version->declare('3.160') ||
+         Debian::AdduserCreateHomedir->VERSION != version->declare('3.160') ||
+         Debian::AdduserYesNo->VERSION != version->declare('3.160') ||
          Debian::AdduserRetvalues->VERSION != version->declare('3.160') ) {
            die "wrong module version in adduser, check your packaging or path";
     }
@@ -90,7 +95,6 @@ BEGIN {
     }
 }
 
-my $yesexpr = langinfo(YESEXPR());
 my $charset = langinfo($codeset);
 if ($encode_loaded) {
     binmode(STDOUT, ":encoding($charset)");
@@ -159,7 +163,7 @@ my $returnvalue = RET_OK;
 
 our @names;
 
-log_trace("ARGV %s", join(@ARGV,"-"));
+log_trace("ARGV %s", join("-", at ARGV));
 GetOptions(
     'add-authorized-key=s' => \@authorized_keys,
     'add-extra-groups' => \$add_extra_groups,
@@ -198,7 +202,7 @@ GetOptions(
     'verbose' => sub { $verbose = 1; },
     'version|v' => sub { &version; exit },
 ) or &usage_error;
-log_trace("ARGV %s", join(@ARGV,"-"));
+log_trace("ARGV %s", join("-", at ARGV));
 
 
 # make sure that message levels apply for reading configuration
@@ -208,7 +212,7 @@ set_msglevel(
     sanitize_string($stdoutmsglevel or STDOUTDEFLEVEL),
     sanitize_string($logmsglevel or LOGMSGDEFLEVEL),
 );
-log_trace("ARGV %s", join(@ARGV,"-"));
+log_trace("ARGV %s", join("-", at ARGV));
 log_trace("special_home %s", $special_home);
 log_trace("special_home %s", encode($charset, $special_home));
 log_trace("special_home %s", decode($charset, $special_home));
@@ -268,7 +272,7 @@ log_trace("action $action");
 # checks related to @names #
 ############################
 
-log_trace("ARGV %s", join(@ARGV,"-"));
+log_trace("ARGV %s", join("-", at ARGV));
 while (defined(my $arg = shift(@ARGV))) {
     $arg = decode($charset, $arg);
     log_trace("process argument %s", $arg);
@@ -969,7 +973,7 @@ if ($action eq "adduser") {
             exit( RET_NO_ID_IN_RANGE );
         }
         log_trace( "gid_option %s, ingroup_name %s", $gid_option, $ingroup_name );
-        if ( defined $gid_option && $gid_option == -1 && defined $ingroup_name && $ingroup_name == "") {
+        if ( defined $gid_option && $gid_option == -1 && defined $ingroup_name && $ingroup_name eq "") {
             log_warn( mtx("USERGROUPS=no, USER_GID=-1 and USERS_GROUP empty. A user needs a primary group!") );
             log_fatal( mtx("The user `%s' was not created."), $new_name );
             exit( RET_NO_PRIMARY_GROUP );
@@ -1349,48 +1353,42 @@ sub unlock_user {
     my ($user_name, $system) = @_;
     log_debug( "unlock_user %s called, system %s", $user_name, $system );
     my $ret = existing_user_status(\%config, $user_name, undef);
-    if ($ret & EXISTING_FOUND) {
-        if ($ret & EXISTING_LOCKED) {
-            my $default_shell = $system ? "/usr/sbin/nologin" : "/bin/bash";
 
-            # Get current shell state if available
-            my $shell = get_state_value($user_name, "shell") // $default_shell;
+    if (!($ret & EXISTING_FOUND)) {
+        log_fatal( mtx("User `%s' does not exist\n"), $user_name );
+        exit( RET_OBJECT_DOES_NOT_EXIST );
+    }
+    if (!($ret & EXISTING_LOCKED)) {
+        log_info( mtx("User `%s' is already unlocked.\n"), $user_name );
+        return;
+    }
 
-            # Build usermod argument list
-            my @usermod_args = (
-                '-e', '-1',       # set account expiry to never
-                '-s', $shell,     # set shell
-                $user_name        # username
-            );
+    my $default_shell = $system ? "/usr/sbin/nologin" : "/bin/bash";
+    my $shell = get_state_value($user_name, "shell") // $default_shell;
 
-            # Add -U only if account has a password
-            if ($ret & EXISTING_HAS_PASSWORD) {
-                push @usermod_args, '-U';
-            } else {
-                log_info( mtx(
-                    "Unlocking password `%s' would result in a passwordless account. Leaving password locked\n",
-                    $user_name
-                ));
-            }
+    my @usermod_args = (
+        '-e', '-1',       # account expiry: never
+        '-s', $shell,
+        $user_name,
+    );
+    if ($ret & EXISTING_HAS_PASSWORD) {
+        push @usermod_args, '-U';
+    } else {
+        log_info( mtx("Unlocking password `%s' would result in a passwordless account. Leaving password locked\n"),
+                  $user_name );
+    }
 
-            log_info( mtx("Unlocking user `%s' ...", $user_name) );
-            log_trace( "usermod `%s' ...", join(" ", @usermod_args) );
-            my $unlock_ret = systemcall_useradd($name_check_level, 'usermod', @usermod_args);
+    log_info( mtx("Unlocking user `%s' ..."), $user_name );
+    log_trace( "usermod `%s' ...", join(" ", @usermod_args) );
+    my $unlock_ret = systemcall_useradd($name_check_level, 'usermod', @usermod_args);
 
-            if( $unlock_ret == 0 ) {
-                log_info( mtx("user `%s' successfully unlocked.\n", $user_name) );
-                set_state_value($user_name, "shell", undef);
-                set_state_value($user_name, "locked", undef);
-            } else {
-                log_fatal( mtx("error %s while unlocking user `%s'. Exiting.\n", $unlock_ret, $user_name) );
-                exit( RET_SYSTEMCALL_ERROR );
-            }
-        }
-        log_info( mtx("User `%s' is already unlocked.\n"), $user_name );
-    } else {
-        log_fatal( mtx("User `%s' does not exist\n"), $user_name );
-        exit( RET_OBJECT_DOES_NOT_EXIST );
+    if ($unlock_ret) {      # truthiness, not "== 0": success may return "" or 0
+        log_fatal( mtx("error %s while unlocking user `%s'. Exiting.\n"), $unlock_ret, $user_name );
+        exit( RET_SYSTEMCALL_ERROR );
     }
+    log_info( mtx("user `%s' successfully unlocked.\n"), $user_name );
+    set_state_value($user_name, "shell", undef);
+    set_state_value($user_name, "locked", undef);
 }
 
 sub interactive_command_with_confirmation {
@@ -1399,9 +1397,6 @@ sub interactive_command_with_confirmation {
     $always_confirm //= 0;   # default to false if not provided
     return unless -t STDIN;  # skip non-interactive
 
-    my $yesexpr = langinfo(YESEXPR);
-    my $noexpr  = langinfo(NOEXPR);
-
     my $retry = 1;
 
     while ($retry) {
@@ -1423,30 +1418,17 @@ sub interactive_command_with_confirmation {
 
         # Prompt for confirmation if requested
         if ($always_confirm) {
-            my $answer;
-            do {
-                print gtx("Is the information correct? [Y/n] ");
-                $answer = <STDIN>;
-
-                unless (defined $answer) {
-                    warn "No input available, assuming 'yes'\n";
-                    last;
-                }
-
-                chomp($answer);
-                $answer =~ s/^\s+|\s+$//g;
-
-                if ($answer =~ m/$yesexpr/o || $answer eq '') {
-                    $retry = 0;  # accepted
-                    last;
-                } elsif ($answer =~ m/$noexpr/o) {
-                    $retry = 1;  # retry command
-                } else {
-                    print "Please answer yes or no.\n";
-                    $answer = undef;  # repeat prompt
-                }
+            my ($answer, $error) = ask_i18n_yesno(
+                gtx("Is the information correct?"),
+                $charset,
+            );
 
-            } while (!defined $answer);
+            if (defined $answer) {
+                $retry = !$answer;
+            } elsif ($error eq 'eof') {
+                warn "No input available, assuming 'yes'\n";
+                $retry = 0;
+            }
         }
     }
 }


=====================================
debian/copyright
=====================================
@@ -24,7 +24,7 @@ Copyright: 1999-2016 John Zaitseff
            2016 Dr. Helge Kreutzmann <debian at helgefjell.de>
 License: GPL-2+
 
-Files: adduser
+Files: adduser adduser.conf
 Copyright: 1994 Debian Association, Inc.
            1995 Ted Hajek <tedhajek at boombox.micro.umn.edu>
            1995 Ian A. Murdock <imurdock at debian.org>
@@ -39,9 +39,10 @@ Copyright: 1994 Debian Association, Inc.
            2022 Matt Barry <matt at hazelmollusk.org>
            2022 Benjamin Drung <benjamin.drung at canonical.com>
            2023 Guillem Jover <guillem at debian.org>
+           2026 Juanes <me at juanes.sh>
 License: GPL-2+
 
-Files: deluser
+Files: deluser deluser.conf
 Copyright: 1995 Ted Hajek <tedhajek at boombox.micro.umn.edu>
            1995 Ian A. Murdock <imurdock at debian.org>
            1997-1999 Guy Maor <maor at debian.org>
@@ -67,10 +68,12 @@ Copyright: 1995 Ted Hajek <tedhajek at boombox.micro.umn.edu>
            2021-2022 Jason Franklin <jason at oneway.dev>
            2022 Matt Barry <matt at hazelmollusk.org>
            2023 Guillem Jover <guillem at debian.org>
+           2026 Juanes <me at juanes.sh>
 License: GPL-2+
 
-Files: AdduserLogging.pm AdduserRetvalues.pm AdduserCreateHomedir.pm
+Files: AdduserLogging.pm AdduserStatefile.pm AdduserRetvalues.pm AdduserCreateHomedir.pm AdduserYesNo.pm
 Copyright: 2024-2026 Marc Haber <mh+debian-packages at zugschlus.de>
+           2026 Juanes <me at juanes.sh>
 License: GPL-2+
 
 Files: doc/adduser.conf.5
@@ -358,6 +361,7 @@ Copyright: 2016 Afif Elghraoui <afif at debian.org>
            2022-2026 Marc Haber <mh+debian-packages at zugschlus.de>
            2023 Mateus Rodrigues de Morais <mateus.morais at canonical.com>
            2022 Matt Barry <matt at hazelmollusk.org>
+           2026 Juanes <me at juanes.sh>
 License: GPL-2+
 
 License: GPL-2+


=====================================
debian/rules
=====================================
@@ -26,6 +26,7 @@ override_dh_install:
 	sed -e s/DVERSION/$(cversion)/g AdduserRetvalues.pm > debian/adduser/usr/share/perl5/Debian/AdduserRetvalues.pm
 	sed -e s/DVERSION/$(cversion)/g AdduserStatefile.pm > debian/adduser/usr/share/perl5/Debian/AdduserStatefile.pm
 	sed -e s/DVERSION/$(cversion)/g AdduserCreateHomedir.pm > debian/adduser/usr/share/perl5/Debian/AdduserCreateHomedir.pm
+	sed -e s/DVERSION/$(cversion)/g AdduserYesNo.pm > debian/adduser/usr/share/perl5/Debian/AdduserYesNo.pm
 	ln -s adduser debian/adduser/usr/sbin/addgroup
 	ln -s deluser debian/adduser/usr/sbin/delgroup
 


=====================================
deluser
=====================================
@@ -32,6 +32,7 @@ use Debian::AdduserStatefile 3.160;
 BEGIN {
     if ( Debian::AdduserCommon->VERSION != version->declare('3.160') ||
          Debian::AdduserLogging->VERSION != version->declare('3.160') ||
+         Debian::AdduserStatefile->VERSION != version->declare('3.160') ||
          Debian::AdduserRetvalues->VERSION != version->declare('3.160') ) {
            die "wrong module version in adduser, check your packaging or path";
     }
@@ -330,20 +331,21 @@ if($action eq "deluser") {
 
     # if account is to be locked (not deleted), leave files alone
     if ($do_lock) {
-        if ($config{"backup"} or $config{"remove"} or $config{"remove_all_files"}) {
+        if ($config{"backup"} or $config{"remove_home"} or $config{"remove_all_files"}) {
             log_warn( mtx("Account will be locked; files will not be backed up or removed.") );
             log_warn( mtx("Hint: Use --force-delete to delete the account as normal.") )
         }
 
-        log_info( mtx("Locking user account `%s' ...", $user));
+        log_info( mtx("Locking user account `%s' ..."), $user);
         acquire_lock();
-        set_state_value($user, "shell", $egpwn_shell);
+        set_state_value($user, "shell", sanitize_string($egpwn_shell, simplepathre));
         set_state_value($user, "locked", 1);
         my $lock_ret = &systemcall('usermod', "-e", 1, "-f", 0, "-L", "-s", "/usr/sbin/nologin", $user);
         if( $lock_ret == 0 ) {
-            log_info( mtx("user `%s' successfully locked.\n", $user) );
+            # TODO: this is always true, systemcall() exits on failure
+            log_info( mtx("user `%s' successfully locked.\n"), $user);
         } else {
-            log_fatal( mtx("error %s while unlocking user `%s'. Exiting.\n", $lock_ret, $user) );
+            log_fatal( mtx("error %s while locking user `%s'. Exiting.\n"), $lock_ret, $user);
             exit( RET_SYSTEMCALL_ERROR );
         }
         release_lock();
@@ -351,11 +353,32 @@ if($action eq "deluser") {
         exit( RET_OK )
     }
 
+    # The account is going to be removed. Before any file is backed up or
+    # removed, lock it so that nobody can log in, and terminate everything
+    # that still runs as that user, so that nobody can modify the file
+    # system underneath us (symlink races and the like).
+    # Password lock plus account expiry; the shell is left alone and no
+    # state is recorded, so that a normal removal leaves no trace in the
+    # state file. A removal that fails later can simply be run again.
+    log_info( mtx("Locking user account `%s' ..."), $user );
+    systemcall('usermod', "-e", 1, "-f", 0, "-L", $user);
+
+    if ($pw_uid == 0) {
+        log_warn( mtx("Not terminating processes of uid 0.") );
+    } elsif (kill_user_processes($user, $pw_uid) != 0) {
+        log_fatal( mtx("Could not terminate all processes of user `%s'. The account stays locked. Exiting."), $user );
+        exit( RET_SYSTEMCALL_ERROR );
+    }
+
+    # the lists are filled below, the files are removed after the account
+    my(@files, at dirs);
+
     if($config{"remove_home"} || $config{"remove_all_files"}) {
         log_trace( mtx("remove_home or remove_all_files beginning") );
         log_info( mtx("Looking for files to backup/remove ...") );
         my @mountpoints;
         my $exclude_fstypes = $config{"exclude_fstypes"};
+
         my $mount;
         if( !open($mount, q{<}, '/proc/mounts') ) {
             log_fatal( mtx("failed to open /proc/mounts: %s") , $! );
@@ -364,6 +387,8 @@ if($action eq "deluser") {
         while (<$mount>) {
           my @temparray = split;
           my ($fstype, $fname) = ($temparray[2], $temparray[1]);
+          # /proc/mounts escapes blanks and the like as \040
+          $fname =~ s/\\([0-7]{3})/chr(oct($1))/ge;
 
           next if $fname eq '/';
           next if $fname eq '/home';
@@ -374,7 +399,6 @@ if($action eq "deluser") {
             log_fatal( mtx("failed to close /proc/mounts: %s"), $!);
             exit( RET_FILE_ERROR );
         }
-        my(@files, at dirs);
         if($config{"remove_home"}) {
             # collect all files in user home
             sub home_match {
@@ -417,12 +441,28 @@ if($action eq "deluser") {
             # collect all files on system belonging to that user
             log_trace("remove_all_files beginning");
             sub find_match {
-                my ($dev,$ino,$mode,$nlink,$uid,$gid) = lstat;
-                log_trace("find_match %s", $_);
-                my $name = sanitize_string( decode($charset, $File::Find::name), pathre, 1 );
-                log_trace("find_match sanitized %s", $name);
+                # With no_chdir, $File::Find::name is the full path.
+                # Everything below, and everything that ends up in @files
+                # and @dirs, uses this raw path. It must never be run
+                # through sanitize_string() in replace mode: that replaces
+                # unusual characters with "_" and can turn the name of a file
+                # owned by the user into the name of somebody else's file,
+                # which would then be backed up and removed. Untaint it
+                # explicitly; it is only acted upon after the lstat()
+                # below confirmed that the user owns it.
+                my ($path) = $File::Find::name =~ /\A(.*)\z/s;
+                my @st = lstat($path) or return;    # vanished or unreadable
+                my $uid = $st[4];
+                # determine the type now, from the lstat() buffer: no second
+                # lookup by name, symlinks are not followed
+                my $type = -l _ ? 'file' : -d _ ? 'dir' :
+                           (-f _ || -S _ || -p _) ? 'file' : 'special';
+                # character version, for messages and for matching the
+                # (decoded) NO_DEL_PATHS patterns only
+                my $name = decode($charset, $path);
+                log_trace("find_match %s", $name);
                 foreach my $mount (@mountpoints) {
-                    if( $name eq $mount ) {
+                    if( $path eq $mount ) {
                         log_warn( mtx("Not backing up/removing `%s', it is a mount point."), $name );
                         $File::Find::prune=1;
                         return;
@@ -436,17 +476,11 @@ if($action eq "deluser") {
                     }
                 }
                 log_trace("name %s, uid %s, pw_uid %s", $name, $uid, $pw_uid);
-                (defined($uid) && ($uid == $pw_uid)) &&
-                    (
-                        (-f $name && push(@files, $name)) ||
-                        (-l $name && push(@files, $name)) ||
-                        (-d $name && push(@dirs,  $name)) ||
-                        (-S $name && push(@files, $name)) ||
-                        (-p $name && push(@files, $name))
-                );
-                if ( -b $name || -c $name ) {
-                    log_warn( mtx("Cannot handle special file %s"), $name );
-                }
+                return unless $uid == $pw_uid;
+                if    ($type eq 'file') { push(@files, $path); }
+                elsif ($type eq 'dir')  { push(@dirs,  $path); }
+                else { log_warn( mtx("Cannot handle special file %s"), $name ); }
+
             } # sub find_match
 
             File::Find::find({wanted => \&find_match, untaint => 1, no_chdir => 1}, '/');
@@ -476,13 +510,6 @@ if($action eq "deluser") {
             unlink($filesfilename);
         }
 
-        if(@files || @dirs) {
-            log_info( mtx("Removing files ...") );
-            unlink(@files) if(@files);
-            foreach(reverse(sort(@dirs))) {
-                rmdir unless /^$config{dhome}$/ || /^\/$/;
-            }
-        }
     }
 
     if (-x '/usr/bin/crontab') {
@@ -497,11 +524,23 @@ if($action eq "deluser") {
     }
 
     log_info( mtx("Removing user `%s' ..."), $user);
+    # Hold the lock until the files are gone, so that adduser cannot hand
+    # out the freed uid to somebody else in the meantime.
     acquire_lock();
     systemcall('/usr/sbin/userdel', $user);
-    release_lock();
     delete_state_user($user);
 
+    # The account is gone and has no processes, so nobody can interfere
+    # with the removal of the files collected (and backed up) above.
+    if(@files || @dirs) {
+        log_info( mtx("Removing files ...") );
+        unlink(@files) if(@files);
+        foreach(reverse(sort(@dirs))) {
+            rmdir unless $_ eq $config{dhome} || $_ eq '/';
+        }
+    }
+    release_lock();
+
     systemcall('/usr/local/sbin/deluser.local', $user, $pw_uid,
         $pw_gid, $pw_homedir) if (-x "/usr/local/sbin/deluser.local");
 
@@ -647,6 +686,65 @@ sub exist_group {
     return(defined egetgrnam($exist_group));
 }
 
+# user_pids($uid)
+#
+# Returns the pids of all live processes that have $uid as real, effective,
+# saved or filesystem uid. Zombies are skipped, they cannot be killed.
+sub user_pids {
+    my ($uid) = @_;
+    my @pids;
+    opendir(my $proc, '/proc') or return @pids;
+    while (defined(my $entry = readdir($proc))) {
+        next unless $entry =~ /\A([0-9]+)\z/;
+        my $pid = $1;                       # untainted
+        next if $pid == $$;
+        open(my $status, '<', "/proc/$pid/status") or next;   # already gone
+        local $/;
+        my $content = <$status>;
+        close($status);
+        next unless defined $content;
+        next if $content =~ /^State:\s+Z/m;
+        if ($content =~ /^Uid:\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/m) {
+            push(@pids, $pid) if grep { $_ == $uid } ($1, $2, $3, $4);
+        }
+    }
+    closedir($proc);
+    return @pids;
+}
+
+# kill_user_processes($name, $uid)
+#
+# Terminates all processes of the user: logind is asked to terminate the
+# user's sessions (and the per-user service manager that would respawn
+# processes), the remaining processes get SIGTERM, and whatever is still
+# there after a grace period gets SIGKILL until nothing is left.
+# Returns the number of processes that could not be terminated.
+sub kill_user_processes {
+    my ($name, $uid) = @_;
+    ($uid) = $uid =~ /\A(\d+)\z/ or return 0;
+
+    my @pids = user_pids($uid);
+    return 0 unless @pids;
+    log_info( mtx("Terminating %d process(es) of user `%s' ..."), scalar(@pids), $name );
+
+    systemcall_silent('/usr/bin/loginctl', 'terminate-user', $uid)
+        if (-x '/usr/bin/loginctl');
+    @pids = user_pids($uid);
+    kill('TERM', @pids) if @pids;
+    for (1..12) {                           # about 3 seconds grace
+        select(undef, undef, undef, 0.25);
+        @pids = user_pids($uid);
+        last unless @pids;
+    }
+    for (1..40) {                           # new ones may be forked meanwhile
+        last unless @pids;
+        kill('KILL', @pids);
+        select(undef, undef, undef, 0.25);
+        @pids = user_pids($uid);
+    }
+    return scalar(@pids);
+}
+
 sub check_backup_suffix {
     my $tar = &which('tar');
     my $suffix = "gz";


=====================================
doc/deluser.8
=====================================
@@ -149,6 +149,36 @@ To change this,
 the \fB\-\-backup\-suffix\fP option can be set
 to any suffix supported by \fBtar \-\-auto\-compress\fP.
 .PP
+Before anything is backed up or removed,
+\fBdeluser\fP locks the account
+(password lock and account expiry, so that no login is possible)
+and terminates all processes owned by the user.
+This prevents the user from logging in
+or from changing the files while they are being worked on.
+Sessions are first terminated through \fBloginctl\fP(1) if it is available;
+remaining processes receive SIGTERM and,
+after a short grace period, SIGKILL.
+Processes of uid 0 are never terminated.
+This happens for every removal,
+also if neither \fB\-\-remove\-home\fP
+nor \fB\-\-remove\-all\-files\fP is given.
+If a process cannot be terminated,
+\fBdeluser\fP exits with an error and leaves the account locked.
+Running \fBdeluser\fP again continues the removal.
+.PP
+The order of operations is:
+lock the account and terminate its processes,
+find and back up the files,
+remove the account,
+remove the files.
+The files are removed last
+so that a failing backup or a failing account removal
+does not leave an account without its files.
+\fBdeluser\fP holds the \fBadduser\fP lock
+from the removal of the account until the files are gone,
+so that the freed user id cannot be given to a new user
+in the meantime.
+.PP
 \fBdeluser\fP will refuse to remove the root account.
 .PP
 If the \fB\-\-system\fP option is given on the command line, the


=====================================
testsuite/lib_test.pm
=====================================
@@ -102,6 +102,37 @@ sub find_unused_gid {
     }
 }
 
+# cleanup routines: tests remove what they created, so that they leave the
+# system as they found it (runsuite.sh restores /etc, but not anything else)
+
+sub cleanup_user {
+    my ($username) = @_;
+    return unless defined(getpwnam($username));
+    print "Cleaning up user $username... ";
+    my $output = `deluser $username 2>&1`;
+    my $error = ($?>>8);
+    if ($error) {
+        print "failed\n  deluser $username returned an errorcode != 0 ($error)\n$output";
+        exit $error;
+    }
+    assert(check_user_not_exist ($username));
+    print "ok\n";
+}
+
+sub cleanup_group {
+    my ($groupname) = @_;
+    return unless defined(getgrnam($groupname));
+    print "Cleaning up group $groupname... ";
+    my $output = `delgroup $groupname 2>&1`;
+    my $error = ($?>>8);
+    if ($error) {
+        print "failed\n  delgroup $groupname returned an errorcode != 0 ($error)\n$output";
+        exit $error;
+    }
+    assert(!check_group_exist ($groupname));
+    print "ok\n";
+}
+
 # checking routines
 
 sub check_user_exist {
@@ -136,8 +167,8 @@ sub check_user_not_exist {
 sub check_homedir_exist {
     my ($username, $homedir) = @_;
     my $dir = (getpwnam($username))[7];
-    if ((defined($homedir)) && (! $dir eq $homedir)) {
-        print "check_homedir_exist: wrong homedir ($homedir != $dir)\n";
+    if (defined($homedir) && (!defined($dir) || $dir ne $homedir)) {
+        print "check_homedir_exist: wrong homedir ($homedir != " . ($dir // 'undef') . ")\n";
         return 1;
     }
     if (! -d $dir) {
@@ -210,9 +241,11 @@ sub check_user_in_group {
     }
     # ok, but $group is maybe $user's primary group ...
     my @pw = getpwnam($user);
-    my $primary_gid = $pw[3];
-    if (getgrgid($primary_gid) eq $group) {
-        return 0;
+    if (@pw) {
+        my $primary_group = getgrgid($pw[3]);
+        if (defined($primary_group) && $primary_group eq $group) {
+            return 0;
+        }
     }
 
     print "check_user_in_group: User $user not in group $group\n";
@@ -230,9 +263,18 @@ sub check_user_has_gid {
     }
     # ok, but $group is maybe $user's primary group ...
     my @pw = getpwnam($user);
-    my $primary_gid = $pw[3];
-    if (getgrgid($primary_gid) eq $name) {
-        return 0;
+    if (@pw) {
+        my $primary_group = getgrgid($pw[3]);
+        if (defined($primary_group) && $primary_group eq $name) {
+            return 0;
+        }
+    }
+    my @pw = getpwnam($user);
+    if (@pw) {
+        my $primary_group = getgrgid($pw[3]);
+        if (defined($primary_group) && defined($name) && $primary_group eq $name) {
+            return 0;
+        }
     }
 
     print "check_user_has_gid: User $user has no gid $gid\n";


=====================================
testsuite/test03.pl
=====================================
@@ -31,4 +31,6 @@ if (!defined (getpwnam($username))) {
 	print "ok\n";
 }
 
+cleanup_user($username);
+
 # vim: tabstop=4 shiftwidth=4 expandtab


=====================================
testsuite/test04.pl
=====================================
@@ -31,4 +31,6 @@ if (!defined (getpwnam($username))) {
 	print "ok\n";
 }
 
+cleanup_user($username);
+
 # vim: tabstop=4 shiftwidth=4 expandtab


=====================================
testsuite/test05.pl
=====================================
@@ -30,4 +30,6 @@ if (!defined (getpwnam($username))) {
 	print "ok\n";
 }
 
+cleanup_user($username);
+
 # vim: tabstop=4 shiftwidth=4 expandtab


=====================================
testsuite/test06.pl
=====================================
@@ -29,4 +29,6 @@ if (!defined (getpwnam($username))) {
 	print "ok\n";
 }
 
+cleanup_user($username);
+
 # vim: tabstop=4 shiftwidth=4 expandtab


=====================================
testsuite/test07.pl
=====================================
@@ -31,4 +31,6 @@ if (!defined (getpwnam($username))) {
 	print "ok\n";
 }
 
+cleanup_user($username);
+
 # vim: tabstop=4 shiftwidth=4 expandtab


=====================================
testsuite/test08.pl
=====================================
@@ -133,7 +133,7 @@ if (!defined (getpwnam($sysusername))) {
 	assert(check_user_exist ($sysusername));
 
         foreach my $group (split ' ', $config{"extra_groups"}) {
-          assert(!check_user_in_group($username,$group));
+          assert(!check_user_in_group($sysusername,$group));
         }
 	print "ok\n";
 }


=====================================
testsuite/test09.pl
=====================================
@@ -35,7 +35,7 @@ if (!defined (getgrnam($groupname))) {
 print "Testing (9.2) $cmd... ";
 $output=`$cmd 2>&1`;
 $error = ($?>>8);
-if ($error ne 11) {
+if ($error != 11) {
   print "failed\n  $cmd returned an errorcode != 11 ($error)\n";
   exit 1;
 }
@@ -52,7 +52,7 @@ $cmd = "addgroup --system $groupname";
 print "Testing (9.3) $cmd... ";
 $output=`$cmd 2>&1`;
 $error = ($?>>8);
-if ($error ne 13) {
+if ($error != 13) {
   print "failed\n  $cmd returned an errorcode != 13 ($error)\n";
   exit $error;
 }
@@ -69,7 +69,7 @@ $cmd = "delgroup --system --remove-home $groupname";
 print "Testing (9.4) $cmd... ";
 $output=`$cmd 2>&1`;
 $error = ($?>>8);
-if ($error ne 53) {
+if ($error != 53) {
   print "failed\n  $cmd returned an errorcode != 53 ($error)\n";
   exit $error;
 }
@@ -111,7 +111,7 @@ $cmd = "addgroup $sysgroupname";
 print "Testing (9.7) $cmd... ";
 $output=`$cmd 2>&1`;
 $error = ($?>>8);
-if ($error ne 11) {
+if ($error != 11) {
   print "failed\n  $cmd returned an errorcode != 11 ($error)\n";
   exit 1;
 }
@@ -121,4 +121,7 @@ if ($output !~ /^fatal: The group `adduser09sgtest\d+' already exists\.$/ ) {
 }
 print "ok\n";
 
+cleanup_group($groupname);
+cleanup_group($sysgroupname);
+
 # vim: tabstop=4 shiftwidth=4 expandtab


=====================================
testsuite/test11.pl
=====================================
@@ -14,9 +14,18 @@ sub testusercomment {
     $cmd = 'adduser --comment="'. $comment. '" --home=/nonexistent --disabled-password '. "$username";
     if (!defined (getpwnam($username))) {
         print "Testing $cmd... ";
-        `$cmd`;
+        my $output = `$cmd 2>&1`;
         my $error = ($?>>8);
         if( $fail_expected > 0 ) {
+            # must fail, and for the expected reason
+            if (!$error) {
+                print "failed\n  $cmd unexpectedly succeeded\n";
+                exit 1;
+            }
+            if ($output !~ /^fatal: unwanted chars in comment/m) {
+                print "failed\n  $cmd returned unexpected output ($output)\n";
+                exit 1;
+            }
             assert(check_user_not_exist ($username));
         } else {
             if ($error) {



View it on GitLab: https://salsa.debian.org/debian/adduser/-/compare/f6e2e7fe2b7b0a20f18cec23aa1cb9c0dae26623...03dd525625ba89170b449fb67a0b215b81679600

-- 
View it on GitLab: https://salsa.debian.org/debian/adduser/-/compare/f6e2e7fe2b7b0a20f18cec23aa1cb9c0dae26623...03dd525625ba89170b449fb67a0b215b81679600
You're receiving this email because of your account on salsa.debian.org. Manage all notifications: https://salsa.debian.org/-/profile/notifications | Help: https://salsa.debian.org/help


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://alioth-lists.debian.net/pipermail/pkg-shadow-devel/attachments/20261130/295b3214/attachment-0001.htm>


More information about the Pkg-shadow-devel mailing list