diff --git a/modules/system-customize.sh b/modules/system-customize.sh index a216cf9..53a00f2 100644 --- a/modules/system-customize.sh +++ b/modules/system-customize.sh @@ -38,7 +38,7 @@ fi readonly MOTD_ETC_ROOT MOTD_STATE_DIR MOTD_LOCK_FILE MOTD_TRANSACTION_PARENT MOTD_TRUSTED_UID MOTD_TRUSTED_GID readonly MOTD_SCRIPT="$MOTD_ETC_ROOT/update-motd.d/00-custom-welcome" readonly MOTD_SNAPSHOT_VERSION=1 -readonly MOTD_PAYLOAD_SHA256="22fb713f1c0e60f6a19a3b1b9629c3121a1f2e4f5890237163e7b74706ea3983" +readonly MOTD_PAYLOAD_SHA256="5c36a6d573019a7135974b199c4eeca74876d1e5bc436d910db80e1c7c2a772e" readonly -a MOTD_TARGET_IDS=(motd issue issue_net custom_welcome uname motd_news) readonly -a MOTD_TARGET_PATHS=( "$MOTD_ETC_ROOT/motd" "$MOTD_ETC_ROOT/issue" "$MOTD_ETC_ROOT/issue.net" @@ -832,9 +832,9 @@ motd_validate_residue_file() { motd_cleanup_root_stages() { local saved path name failed=false saved=$(shopt -p nullglob dotglob || true); shopt -s nullglob - for path in "$MOTD_STATE_DIR"/.initial.pointer.* "$MOTD_STATE_DIR"/.previous.pointer.* "$MOTD_STATE_DIR"/.pending.*; do + for path in "$MOTD_STATE_DIR"/.initial.pointer.* "$MOTD_STATE_DIR"/.previous.pointer.* "$MOTD_STATE_DIR"/.pending.* "$MOTD_STATE_DIR"/.pam.stage.*; do name=${path##*/} - [[ "$name" =~ ^\.(initial|previous)\.pointer\.[0-9a-f]{32}$ || "$name" =~ ^\.pending\.[0-9a-f]{32}$ ]] || { error "未知 MOTD root residue: $path"; failed=true; continue; } + [[ "$name" =~ ^\.(initial|previous)\.pointer\.[0-9a-f]{32}$ || "$name" =~ ^\.pending\.[0-9a-f]{32}$ || "$name" =~ ^\.pam\.stage\.[0-9a-f]{32}$ ]] || { error "未知 MOTD root residue: $path"; failed=true; continue; } motd_validate_secure_file "$path" && rm -f -- "$path" || { error "不可信或无法清理的 MOTD residue: $path"; failed=true; } done eval "$saved" @@ -862,6 +862,7 @@ motd_validate_state_root_entries() { generations) motd_validate_secure_directory "$path" || failed=true ;; transactions) motd_validate_secure_directory "$path" || failed=true ;; initial.current|previous.current|pending) ;; + last-login-hook) motd_validate_secure_directory "$path" || failed=true ;; *) if ! motd_validate_state_legacy_object "$path"; then error "非法 MOTD state root legacy 对象: $path"; failed=true @@ -1653,12 +1654,16 @@ motd_install_body() { motd_validate_all_target_stages || return 1 motd_commit_target_plan install false || return 1 motd_mark_transaction_committed || return 1 - motd_complete_transaction + motd_complete_transaction || return 1 + # 欢迎面板已提交后再配置中文上次登录;失败只保留原英文,不回滚已提交的面板。 + motd_login_hook_install || warn "中文上次登录未配置,保留原英文" } motd_restore_body() { local scope="$1" result=0 generation motd_prepare_state_layout || return 1 + # 先撤本工具的 PAM/drop-in hook,再恢复 MOTD 文件组,避免恢复后仍抑制原英文。 + motd_login_hook_restore || { error "恢复中文上次登录 hook 失败,保持 hook 状态以便重试"; return 1; } motd_reconcile_state || return 1 motd_validate_target_parents || return 1 motd_begin_transaction restore || return 1 @@ -1696,6 +1701,349 @@ motd_run_locked_operation() { return "$status" } +# === 中文上次登录 SSH hook === +# 复用同一 payload 的 --last-login,不把登录数据写入 /run/motd.dynamic; +# 由 sshd 的 PAM 会话中紧随 pam_motd 的可选 pam_exec 输出,PrintLastLog 只关闭原英文。 +readonly MOTD_LOGIN_PAM_SERVICE="$MOTD_ETC_ROOT/pam.d/sshd" +readonly MOTD_LOGIN_DROPIN_DIR="$MOTD_ETC_ROOT/ssh/sshd_config.d" +readonly MOTD_LOGIN_DROPIN="$MOTD_LOGIN_DROPIN_DIR/60-linux-setup-last-login.conf" +readonly MOTD_LOGIN_STATE_DIR="$MOTD_STATE_DIR/last-login-hook" + +# 目标同目录的临时文件,保证 mv -Tf 是同一文件系统内的 rename; +# 状态目录与 /etc 分挂载时,放在状态目录会让 mv 退化为复制+替换。 +motd_login_stage_near() { + local destination="$1" label="$2" parent token path + parent=${destination%/*} + [[ -n "$parent" && -d "$parent" && ! -L "$parent" ]] || return 1 + token=$(motd_random_id) || return 1 + path="$parent/.linux-setup-last-login.$label.$token" + [[ ! -e "$path" && ! -L "$path" ]] || return 1 + printf '%s\n' "$path" +} + +# 崩溃残留只可能是本工具前缀的临时文件;校验属主/类型后清除,遇到异常即停止。 +motd_login_cleanup_residue() { + local dir path name saved failed=false + saved=$(shopt -p nullglob dotglob || true); shopt -s nullglob dotglob + for dir in "$MOTD_LOGIN_PAM_SERVICE" "$MOTD_LOGIN_DROPIN"; do + dir=${dir%/*} + for path in "$dir"/.linux-setup-last-login.*; do + name=${path##*/} + if [[ ! "$name" =~ ^\.linux-setup-last-login\.[a-z]+\.[0-9a-f]{32}$ ]] || + [[ -L "$path" || ! -f "$path" ]] || + [[ "$(stat -c '%u:%g' -- "$path" 2>/dev/null)" != "$MOTD_TRUSTED_UID:$MOTD_TRUSTED_GID" ]] || + ! rm -f -- "$path"; then + failed=true + fi + done + done + eval "$saved" + [[ "$failed" == false ]] +} + +motd_login_hook_state_path() { printf '%s/%s\n' "$MOTD_LOGIN_STATE_DIR" "$1"; } + +motd_login_pam_exec_path() { + local candidate + # 仅测试模式允许注入探测路径,生产环境始终走固定系统路径。 + if [[ "${MOTD_TEST_MODE:-0}" == 1 && -n "${MOTD_LOGIN_PAM_EXEC:-}" ]]; then + [[ -f "$MOTD_LOGIN_PAM_EXEC" ]] && { printf '%s\n' "$MOTD_LOGIN_PAM_EXEC"; return 0; } + return 1 + fi + for candidate in /usr/lib/x86_64-linux-gnu/security/pam_exec.so \ + /usr/lib/aarch64-linux-gnu/security/pam_exec.so \ + /usr/lib/security/pam_exec.so /lib/security/pam_exec.so \ + /lib/x86_64-linux-gnu/security/pam_exec.so /lib/aarch64-linux-gnu/security/pam_exec.so; do + [[ -f "$candidate" ]] && { printf '%s\n' "$candidate"; return 0; } + done + return 1 +} + +# Debian 13 的 lslogins --help 只写 --lastlog/--lastlog2,却实际接受 +# --lastlog-file/--lastlog2-file;因此不用 help 文本判定,改用空文件功能探测。 +# 全部文件指向 /dev/null、用户为不存在的合成名,不触碰任何真实登录记录。 +# util-linux 2.39 及更早只有 --lastlog,payload 侧同样按 modern→legacy 回退。 +motd_login_lslogins_args() { + local mode + for mode in modern legacy; do + local -a args=(--wtmp-file /dev/null) + if [[ "$mode" == modern ]]; then + args+=(--lastlog-file /dev/null --lastlog2-file /dev/null) + else + args+=(--lastlog /dev/null) + fi + LC_ALL=C lslogins "${args[@]}" --time-format iso --raw --noheadings --notruncate \ + --output LAST-LOGIN,LAST-HOSTNAME --logins __linux_setup_probe__ >/dev/null 2>&1 || continue + printf '%s\n' "$mode" + return 0 + done + return 1 +} + +motd_login_lslogins_supported() { motd_login_lslogins_args >/dev/null; } + +# 只 reload 正在运行的正确 SSH 服务;socket 激活的监听端不在这里重启。 +motd_login_ssh_service() { + if [[ "${MOTD_TEST_MODE:-0}" == 1 && -n "${MOTD_LOGIN_SSH_SERVICE:-}" ]]; then + printf '%s\n' "$MOTD_LOGIN_SSH_SERVICE" + return 0 + fi + command -v systemctl >/dev/null 2>&1 || return 1 + if systemctl list-unit-files ssh.service --no-legend 2>/dev/null | grep -q '^ssh\.service'; then + systemctl is-active --quiet ssh.service 2>/dev/null || return 1 + printf 'ssh.service\n' + return 0 + fi + if systemctl list-unit-files sshd.service --no-legend 2>/dev/null | grep -q '^sshd\.service'; then + systemctl is-active --quiet sshd.service 2>/dev/null || return 1 + printf 'sshd.service\n' + return 0 + fi + return 1 +} + +# 先确认候选配置有效且 PrintLastLog no,再重载活动服务,避免磁盘与活进程不一致。 +motd_login_reload_sshd() { + local service + service=$(motd_login_ssh_service) || return 1 + motd_login_hook_verify_sshd || return 1 + if [[ "${MOTD_TEST_MODE:-0}" == 1 && -n "${MOTD_LOGIN_RELOAD_STUB:-}" ]]; then + "$MOTD_LOGIN_RELOAD_STUB" "$service" + return + fi + systemctl reload "$service" +} + +motd_login_hook_supported() { + local command_name + for command_name in lslogins sshd awk sed grep; do + command -v "$command_name" >/dev/null 2>&1 || return 1 + done + motd_login_lslogins_supported || return 1 + motd_login_ssh_service >/dev/null || return 1 + motd_login_pam_exec_path >/dev/null || return 1 + [[ -f "$MOTD_LOGIN_PAM_SERVICE" && ! -L "$MOTD_LOGIN_PAM_SERVICE" ]] || return 1 + [[ -d "$MOTD_LOGIN_DROPIN_DIR" && ! -L "$MOTD_LOGIN_DROPIN_DIR" ]] || return 1 + [[ -f "$MOTD_SCRIPT" && ! -L "$MOTD_SCRIPT" ]] || return 1 + grep -Fq -- '--last-login' "$MOTD_SCRIPT" || return 1 +} + +# 单一 drop-in 已存在但不是本工具的文件:不覆盖管理员配置,也不关英文。 +motd_login_hook_dropin_owned() { + [[ -e "$MOTD_LOGIN_DROPIN" || -L "$MOTD_LOGIN_DROPIN" ]] && + ! motd_login_hook_dropin_present +} + +# 管理员已自行配置 session pam_exec 时不接管,保留前态。 +motd_login_hook_admin_conflict() { + [[ -f "$MOTD_LOGIN_PAM_SERVICE" ]] || return 1 + grep -Eq '^[[:space:]]*session[[:space:]].*pam_exec\.so' "$MOTD_LOGIN_PAM_SERVICE" && + ! motd_login_hook_pam_present +} + +# 旧快照:目标组里没有本次 hook 记录时视为未启用,不据缺失文件猜测历史。 +motd_login_hook_is_managed() { + local marker + marker=$(motd_login_hook_state_path marker) || return 1 + [[ -f "$marker" && ! -L "$marker" ]] && grep -Fxq 'last-login-hook=1' "$marker" +} + +motd_login_hook_dropin_present() { + [[ -f "$MOTD_LOGIN_DROPIN" && ! -L "$MOTD_LOGIN_DROPIN" ]] && + grep -Fxq '# linux-setup:managed-last-login' "$MOTD_LOGIN_DROPIN" +} + +motd_login_hook_pam_present() { + [[ -f "$MOTD_LOGIN_PAM_SERVICE" ]] && + grep -Fq 'linux-setup:last-login-hook' "$MOTD_LOGIN_PAM_SERVICE" +} + +# 只记录"本工具装过"这一个事实:PAM 与 drop-in 都按标记行增删, +# 因此不整文件备份,管理员安装后的改动不会被旧快照覆盖。 +motd_login_hook_backup() { + motd_login_hook_is_managed && return 0 + motd_ensure_secure_directory "$MOTD_LOGIN_STATE_DIR" || return 1 + (umask 077; set -o noclobber; : > "$(motd_login_hook_state_path marker)") 2>/dev/null || return 1 + printf 'last-login-hook=1\n' > "$(motd_login_hook_state_path marker)" || return 1 + chmod 0600 "$MOTD_LOGIN_STATE_DIR"/* || return 1 +} + +# 只在最后一条 pam_motd 之后追加一行;找不到锚点或已有管理员 pam_exec 时保持前态。 +motd_login_hook_pam_stage() { + local destination="$1" stage index last=-1 line + local -a lines=() + while IFS= read -r line || [[ -n "$line" ]]; do + lines+=("$line") + [[ "$line" =~ ^[[:space:]]*session[[:space:]].*pam_motd\.so ]] && last=$(( ${#lines[@]} - 1 )) + done < "$MOTD_LOGIN_PAM_SERVICE" + (( last >= 0 )) || return 2 + stage=$(motd_login_stage_near "$destination" pam) || return 1 + : > "$stage" || { rm -f -- "$stage"; return 1; } + for index in "${!lines[@]}"; do + printf '%s\n' "${lines[$index]}" >> "$stage" || { rm -f -- "$stage"; return 1; } + (( index == last )) || continue + printf 'session optional pam_exec.so type=open_session stdout quiet %s --last-login # linux-setup:last-login-hook\n' "$MOTD_SCRIPT" >> "$stage" || { rm -f -- "$stage"; return 1; } + done + # 保留原文件权限,避免把管理员收紧过的 0640 PAM 配置放宽。 + chmod "$(stat -c '%a' -- "$destination" 2>/dev/null || printf 644)" "$stage" || { rm -f -- "$stage"; return 1; } + mv -Tf -- "$stage" "$destination" || { rm -f -- "$stage"; return 1; } +} + + +motd_login_hook_verify_sshd() { + local effective usepam + sshd -t || return 1 + effective=$(sshd -T 2>/dev/null) || return 1 + usepam=$(awk '$1 == "usepam" {print $2; exit}' <<< "$effective") + # 只有生效配置启用 UsePAM,PAM 里的 pam_exec 才会执行;否则关英文就是纯倒退。 + [[ "$usepam" == yes ]] || return 1 + [[ "$(awk '$1 == "printlastlog" {print $2; exit}' <<< "$effective")" == no ]] +} + +# 恢复英文提示时只确认配置有效并 reload 成功;不猜测管理员原本的 PrintLastLog 值。 +motd_login_hook_reload_restored() { + sshd -t || return 1 + motd_login_ssh_service >/dev/null || return 1 + if [[ "${MOTD_TEST_MODE:-0}" == 1 && -n "${MOTD_LOGIN_RELOAD_STUB:-}" ]]; then + "$MOTD_LOGIN_RELOAD_STUB" "$(motd_login_ssh_service)" + return + fi + systemctl reload "$(motd_login_ssh_service)" +} + +motd_login_hook_install() { + local status dropin_stage + motd_login_cleanup_residue || { warn "存在不可信的登录 hook 临时残留,停止"; return 0; } + if ! motd_login_hook_supported; then + warn "缺少 lslogins/pam_exec/sshd/systemd 服务或 PAM 锚点,保留原英文上次登录" + return 0 + fi + if motd_login_hook_admin_conflict; then + warn "检测到管理员自建的 PAM pam_exec 配置,保持原状不改动" + return 0 + fi + if motd_login_hook_dropin_owned; then + warn "已有管理员 sshd drop-in: $MOTD_LOGIN_DROPIN,保持原状不改动" + return 0 + fi + # 重复执行保持幂等:已启用时只补一次 reload,不再插入第二行。 + if motd_login_hook_is_managed && motd_login_hook_pam_present && motd_login_hook_dropin_present; then + if motd_login_hook_verify_sshd && motd_login_reload_sshd; then + success "中文上次登录: 已配置(新会话生效,原英文行已停止)" + return 0 + fi + warn "中文上次登录重载未确认,回滚并保留原英文" + motd_login_hook_rollback_disk || warn "中文上次登录回滚未完成,保留状态以便重试" + return 0 + fi + motd_login_hook_backup || { warn "中文上次登录状态写入失败,保留原状"; return 0; } + if motd_login_hook_pam_stage "$MOTD_LOGIN_PAM_SERVICE" 2>/dev/null; then + : + else + status=$? + warn "PAM 配置没有可用的 pam_motd 锚点,保留原状" + motd_login_hook_rollback_disk || true + return 0 + fi + dropin_stage=$(motd_login_stage_near "$MOTD_LOGIN_DROPIN" dropin) || { + motd_login_hook_rollback_disk || true; return 0; } + (umask 077; set -o noclobber; : > "$dropin_stage") 2>/dev/null || { motd_login_hook_rollback_disk || true; return 0; } + printf '# linux-setup:managed-last-login\n# 由 Linux Scripts Collection 自动生成。\nPrintLastLog no\n' > "$dropin_stage" || { + rm -f -- "$dropin_stage"; motd_login_hook_rollback_disk || true; return 0; } + chmod 0644 "$dropin_stage" || { rm -f -- "$dropin_stage"; motd_login_hook_rollback_disk || true; return 0; } + mv -Tf -- "$dropin_stage" "$MOTD_LOGIN_DROPIN" || { + rm -f -- "$dropin_stage"; motd_login_hook_rollback_disk || true; return 0; } + if ! motd_login_hook_verify_sshd; then + warn "sshd -t/-T 未确认中文上次登录生效,回滚并保留原英文" + motd_login_hook_rollback_disk || true + return 0 + fi + if ! motd_login_reload_sshd; then + warn "sshd 重载失败或活动服务不可确认,回滚并保留原英文" + motd_login_hook_rollback_disk || true + return 0 + fi + success "中文上次登录: 已配置(新会话生效,原英文行已停止)" +} + +# 只摘本工具写入的那一行,保留安装后管理员对 PAM 的其他改动。 +motd_login_hook_pam_remove_line() { + local stage + [[ -f "$MOTD_LOGIN_PAM_SERVICE" ]] || return 0 + grep -Fq 'linux-setup:last-login-hook' "$MOTD_LOGIN_PAM_SERVICE" || return 0 + stage=$(motd_login_stage_near "$MOTD_LOGIN_PAM_SERVICE" pam) || return 1 + grep -v 'linux-setup:last-login-hook' "$MOTD_LOGIN_PAM_SERVICE" > "$stage" || { rm -f -- "$stage"; return 1; } + chmod "$(stat -c '%a' -- "$MOTD_LOGIN_PAM_SERVICE")" "$stage" || { rm -f -- "$stage"; return 1; } + mv -Tf -- "$stage" "$MOTD_LOGIN_PAM_SERVICE" || { rm -f -- "$stage"; return 1; } +} + +# 只撤本工具 drop-in 的三行;管理员后来追加的内容原样保留。 +motd_login_hook_dropin_restore() { + local stage + [[ -e "$MOTD_LOGIN_DROPIN" ]] || return 0 + stage=$(motd_login_stage_near "$MOTD_LOGIN_DROPIN" dropin) || return 1 + # 只删除"表头两行 + PrintLastLog no"这一整块;管理员自行添加的同名指令保留。 + awk ' + $0 == "# linux-setup:managed-last-login" { held = $0; next } + held != "" && $0 == "# 由 Linux Scripts Collection 自动生成。" { held = held "\n" $0; next } + held != "" && $0 == "PrintLastLog no" { held = ""; next } + held != "" { print held; held = "" } + { print } + END { if (held != "") print held } + ' "$MOTD_LOGIN_DROPIN" > "$stage" || { rm -f -- "$stage"; return 1; } + chmod "$(stat -c '%a' -- "$MOTD_LOGIN_DROPIN")" "$stage" || { rm -f -- "$stage"; return 1; } + if [[ ! -s "$stage" ]]; then + rm -f -- "$stage" "$MOTD_LOGIN_DROPIN" || return 1 + return 0 + fi + mv -Tf -- "$stage" "$MOTD_LOGIN_DROPIN" || { rm -f -- "$stage"; return 1; } +} + +# 安装期失败回滚:活服务从未加载过新配置,只需把磁盘改回并校验配置本身, +# 不做 reload(sshd -t 此时正是失败原因,重载没有意义)。 +motd_login_hook_rollback_disk() { + motd_login_hook_is_managed || return 0 + if motd_login_hook_dropin_present; then + motd_login_hook_dropin_restore || { warn "撤回 sshd drop-in 失败,保留状态"; return 1; } + fi + motd_login_hook_pam_remove_line || { warn "撤回 PAM hook 行失败,保留状态"; return 1; } + sshd -t || warn "回滚后 sshd -t 仍失败,需人工检查" + rm -f -- "$(motd_login_hook_state_path marker)" 2>/dev/null || true + rmdir -- "$MOTD_LOGIN_STATE_DIR" 2>/dev/null || true + return 0 +} + +# 回滚先恢复英文并 reload 成功,再撤 PAM 行;任一步失败保留状态供重试,不报完成。 +# english.pending 标记英文已写回磁盘但尚未重载成功,重试时必须先补这次 reload, +# 否则会在活服务仍是中文配置时直接摘掉 PAM 行。 +motd_login_hook_restore() { + local english_pending + motd_login_hook_is_managed || return 0 + motd_login_cleanup_residue || { warn "存在不可信的登录 hook 临时残留,停止恢复"; return 1; } + english_pending=$(motd_login_hook_state_path english.pending) + if [[ -f "$english_pending" ]]; then + if ! motd_login_hook_reload_restored; then + warn "英文提示已写回磁盘但 sshd 重载仍失败,保留 PAM hook 以便重试" + return 1 + fi + rm -f -- "$english_pending" || return 1 + elif motd_login_hook_dropin_present || [[ -e "$MOTD_LOGIN_DROPIN" ]]; then + # drop-in 路径由本工具独占创建;即使管理员删了标记行,也只剥离精确匹配的三行。 + motd_login_hook_dropin_restore || { warn "恢复 sshd drop-in 失败,保留 PAM hook 以便重试"; return 1; } + : > "$english_pending" || return 1 + chmod 0600 "$english_pending" || return 1 + if ! motd_login_hook_reload_restored; then + warn "恢复英文提示后 sshd 重载失败,保留 PAM hook 以便重试" + return 1 + fi + rm -f -- "$english_pending" || return 1 + fi + motd_login_hook_pam_remove_line || { warn "移除 PAM hook 行失败,保留状态以便重试"; return 1; } + rm -f -- "$english_pending" "$(motd_login_hook_state_path marker)" 2>/dev/null || true + rmdir -- "$MOTD_LOGIN_STATE_DIR" 2>/dev/null || true + success "中文上次登录: 已恢复(原英文提示已重载生效)" +} + motd_install_group() { info "配置动态欢迎信息..." motd_run_locked_operation install || return $? @@ -1752,32 +2100,127 @@ motd_columns() { } COLS=$(motd_columns) +motd_mode="${1:-}" +case "$motd_mode" in + ""|--last-login) ;; + *) printf 'usage: %s [--last-login]\n' "${0##*/}" >&2; exit 2 ;; +esac + hostname_value=$(hostname 2>/dev/null) +is_ipv4_address() { + local value="$1" octet + local IFS=. + local -a octets=() + [[ "$value" =~ ^[0-9]{1,3}(\.[0-9]{1,3}){3}$ ]] || return 1 + read -r -a octets <<< "$value" + (( ${#octets[@]} == 4 )) || return 1 + for octet in "${octets[@]}"; do + [[ "$octet" =~ ^(0|[1-9][0-9]{0,2})$ ]] || return 1 + (( 10#$octet <= 255 )) || return 1 + done +} + +is_ipv6_address() { + local value="$1" + [[ "$value" == *:* && ${#value} -le 45 ]] || return 1 + [[ "$value" =~ ^[0-9A-Fa-f:.]+$ ]] || return 1 + [[ "$value" =~ [0-9A-Fa-f] ]] || return 1 + [[ "$value" != *:::* ]] || return 1 +} + +is_hostname() { + local value="$1" + (( ${#value} >= 1 && ${#value} <= 255 )) || return 1 + [[ "$value" =~ ^[A-Za-z0-9]([A-Za-z0-9._-]*[A-Za-z0-9])?$ ]] +} + +# 把 lslogins 的时间规范成服务器本地 YYYY-MM-DD HH:MM:SS,并校验分量范围。 +login_normalize_time() { + local raw="$1" + local year month day hour minute second + [[ "$raw" =~ ^([0-9]{4})-([0-9]{2})-([0-9]{2})[T[:space:]]([0-9]{2}):([0-9]{2}):([0-9]{2}) ]] || return 1 + year=${BASH_REMATCH[1]}; month=${BASH_REMATCH[2]}; day=${BASH_REMATCH[3]} + hour=${BASH_REMATCH[4]}; minute=${BASH_REMATCH[5]}; second=${BASH_REMATCH[6]} + (( 10#$month >= 1 && 10#$month <= 12 )) || return 1 + (( 10#$day >= 1 && 10#$day <= 31 )) || return 1 + (( 10#$hour <= 23 && 10#$minute <= 59 && 10#$second <= 60 )) || return 1 + printf '%s-%s-%s %s:%s:%s' "$year" "$month" "$day" "$hour" "$minute" "$second" +} + +# 只读上一笔登录:全空 wtmp/btmp、legacy lastlog,避免把本次连接当历史。 +# util-linux 2.41 起 --lastlog 有歧义,优先 --lastlog-file;更早版本回退 --lastlog。 +login_query() { + local user="$1" output + command -v lslogins >/dev/null 2>&1 || return 1 + [[ -n "$user" ]] || return 1 + [[ "$user" =~ ^[A-Za-z0-9._][A-Za-z0-9._-]{0,63}$ ]] || return 1 + for output in \ + "--wtmp-file /dev/null --lastlog-file /var/log/lastlog --lastlog2-file /dev/null" \ + "--wtmp-file /dev/null --lastlog /var/log/lastlog"; do + local -a base_args=() + read -r -a base_args <<< "$output" + local result + result=$(LC_ALL=C lslogins "${base_args[@]}" --time-format iso --raw --noheadings --notruncate \ + --output LAST-LOGIN,LAST-HOSTNAME --logins "$user" 2>/dev/null) || continue + [[ -n "${result//[[:space:]]/}" ]] || continue + printf '%s\n' "$result" + return 0 + done + return 1 +} + +render_last_login() { + local user="${PAM_USER:-}" raw time host kind + raw=$(login_query "$user") || return 0 + time=$(login_normalize_time "${raw%%[[:space:]]*}") || return 0 + host="${raw#"${raw%%[[:space:]]*}"}" + host="${host#"${host%%[![:space:]]*}"}" + host="${host%"${host##*[![:space:]]}"}" + print_row 10 " ${LABEL}上次登录${FG_RESET} " "${TEXT}|${time}" + if is_ipv4_address "$host" || is_ipv6_address "$host"; then + kind=ip + elif is_hostname "$host"; then + kind=host + else + kind="" + fi + case "$kind" in + ip) print_row 10 " ${LABEL}来源 IP${FG_RESET} " "${LOGIN_SOURCE}|${host}" ;; + host) print_row 10 " ${LABEL}来源${FG_RESET} " "${LOGIN_SOURCE}|${host}" ;; + esac +} [[ -n "$hostname_value" ]] || hostname_value=$(uname -n) kernel=$(uname -r) architecture=$(uname -m) +# 运行时长按“数字/单位”切成无颜色片段,配色在下方颜色变量就绪后再套用; +# 拼接结果与旧版纯文本逐字节相同。 +uptime_parts=() uptime_seconds=$(awk '{printf "%d", $1}' /proc/uptime 2>/dev/null) if [[ -n "$uptime_seconds" ]]; then - uptime_value=$(awk -v total="$uptime_seconds" 'BEGIN { + while IFS=$'\t' read -r uptime_kind uptime_text; do + uptime_parts+=("${uptime_kind}|${uptime_text}") + done < <(awk -v total="$uptime_seconds" 'BEGIN { days=int(total/86400) hours=int(total%86400/3600) minutes=int(total%3600/60) if (days > 0) { - if (hours > 0) printf "%d 天 %d 小时", days, hours - else printf "%d 天", days + printf "number\t%d\nunit\t 天\n", days + if (hours > 0) printf "number\t %d\nunit\t 小时\n", hours } else if (hours > 0) { - printf "%d 小时 %d 分", hours, minutes + printf "number\t%d\nunit\t 小时\nnumber\t %d\nunit\t 分\n", hours, minutes } else if (minutes > 0) { - printf "%d 分", minutes + printf "number\t%d\nunit\t 分\n", minutes } else { - printf "不到 1 分" + printf "unit\t不到 1 分\n" } }') else uptime_value=$(uptime 2>/dev/null | sed -E 's/.*up[[:space:]]+//; s/,[[:space:]]+[0-9]+ user.*//') + [[ -n "$uptime_value" ]] || uptime_value=- + uptime_parts=("unit|${uptime_value}") fi -[[ -n "$uptime_value" ]] || uptime_value=- +(( ${#uptime_parts[@]} > 0 )) || uptime_parts=("unit|-") # 发行版:优先 os-release 的 NAME/VERSION_ID,其次 PRETTY_NAME,最后内核名。 system_value=$(awk -F= ' @@ -1860,30 +2303,44 @@ fi ESC=$'\033' if [[ -n "${NO_COLOR+x}" || "${TERM:-}" == dumb ]]; then RESET=""; FG_RESET=""; TEXT=""; LABEL=""; DIM=""; HOST=""; RULE="" - SYSTEM=""; DOT=""; CPU=""; ARCH=""; UPTIME=""; LOAD=""; TRACK="" - SECTION=""; BOLD=""; GREEN=""; YELLOW=""; RED="" + SYSTEM=""; CPU=""; ARCH=""; UPTIME=""; UPTIME_ACCENT=""; LOAD=""; TRACK="" + KERNEL=""; LOGIN_SOURCE="" + SECTION=""; BOLD=""; UNBOLD=""; GREEN=""; YELLOW=""; RED="" else RESET="${ESC}[0m" FG_RESET="${ESC}[39m" TEXT="${ESC}[38;2;248;248;242m" LABEL="${ESC}[38;2;168;181;217m" DIM="${ESC}[38;2;183;191;219m" - HOST="${ESC}[38;2;139;233;253m" + HOST="${ESC}[38;2;71;220;200m" RULE="${ESC}[38;2;130;183;255m" - SYSTEM="${ESC}[38;2;166;227;161m" - DOT="${ESC}[38;2;166;227;161m" + SYSTEM="${ESC}[38;2;255;142;158m" CPU="${ESC}[38;2;255;184;108m" - ARCH="${ESC}[38;2;214;172;255m" + ARCH="${ESC}[38;2;163;178;196m" UPTIME="${ESC}[38;2;186;194;222m" - LOAD="${ESC}[38;2;137;220;235m" + UPTIME_ACCENT="${ESC}[38;2;109;255;187m" + LOAD="${ESC}[38;2;36;240;208m" + KERNEL="${ESC}[38;2;255;147;77m" + LOGIN_SOURCE="${ESC}[38;2;255;121;198m" TRACK="${ESC}[38;2;83;91;120m" SECTION="${ESC}[38;2;98;114;164m" BOLD="${ESC}[1m" + UNBOLD="${ESC}[22m" GREEN="${ESC}[38;2;80;250;123m" YELLOW="${ESC}[38;2;241;250;140m" RED="${ESC}[38;5;203m" fi +# 运行时长:数字用强调色加粗,单位沿用灰蓝且显式退出粗体,避免继承前缀的字重。 +uptime_segments=() +for uptime_part in "${uptime_parts[@]}"; do + case "${uptime_part%%|*}" in + number) uptime_segments+=("${UPTIME_ACCENT}${BOLD}|${uptime_part#*|}") ;; + *) uptime_segments+=("${UNBOLD}${UPTIME}|${uptime_part#*|}") ;; + esac +done +unset uptime_part + BAR_CELLS=6 # 窄终端放不下占用条:先保证文字不折行,再考虑图形。 (( COLS >= 40 )) || BAR_CELLS=0 @@ -2043,6 +2500,12 @@ print_row() { printf '%s\n' "$RESET" } +# --last-login 只输出登录历史行,欢迎面板仍由 run-parts 无参模式生成并写入 /run/motd.dynamic。 +if [[ "$motd_mode" == "--last-login" ]]; then + render_last_login + exit 0 +fi + load_average=$(awk '{printf "%.2f / %.2f / %.2f", $1, $2, $3}' /proc/loadavg 2>/dev/null) [[ -n "$load_average" ]] || load_average=- @@ -2099,13 +2562,13 @@ printf '\n' print_row 11 "${RULE}│${RESET} ${BOLD}${TEXT}欢迎登录 " "${HOST}|${hostname_value}" print_row 2 "${RULE}│${RESET} " "${DIM}|今天想做点什么?" printf '%s%s%s\n' "$SECTION" "$hero_rule" "$RESET" -print_row 7 " ${LABEL}系统${FG_RESET} " "${SYSTEM}|${system_value}" "${DOT}| ●" -print_row 7 " ${LABEL}运行${FG_RESET} " "${UPTIME}|${uptime_value}" +print_row 7 " ${LABEL}系统${FG_RESET} " "${SYSTEM}${BOLD}|${system_value}" +print_row 7 " ${LABEL}运行${FG_RESET} " "${uptime_segments[@]}" print_row 7 " ${LABEL}CPU${FG_RESET} " "${CPU}|${cpu_model}" "${TEXT}|${cpu_count_text}" print_row 7 " ${LABEL}负载${FG_RESET} " "${LOAD}|${load_average}" print_row 7 " ${LABEL}内存${FG_RESET} " "${memory_segments[@]}" print_row 7 " ${LABEL}根盘${FG_RESET} " "${disk_segments[@]}" -print_row 7 " ${LABEL}内核${FG_RESET} " "${TEXT}|${kernel}" "${ARCH}|(${architecture})" +print_row 7 " ${LABEL}内核${FG_RESET} " "${KERNEL}${BOLD}|${kernel}" "${UNBOLD}${ARCH}|(${architecture})" SCRIPT } diff --git a/tests/test-motd.sh b/tests/test-motd.sh index 98f6bd7..a6ece78 100644 --- a/tests/test-motd.sh +++ b/tests/test-motd.sh @@ -251,7 +251,7 @@ extract_payload "$ROOT_DIR/tools/setup-motd.sh">"$TEST_DIR/t"; extract_payload "$ROOT_DIR/modules/system-customize.sh">"$TEST_DIR/m"; cmp -s "$TEST_DIR/t" "$TEST_DIR/m"||fail payload; pass "MOTD payloads stay identical"; -assert_eq 22fb713f1c0e60f6a19a3b1b9629c3121a1f2e4f5890237163e7b74706ea3983 "$(sha256sum "$TEST_DIR/t"|awk '{print $1}')" "payload hash" +assert_eq 5c36a6d573019a7135974b199c4eeca74876d1e5bc436d910db80e1c7c2a772e "$(sha256sum "$TEST_DIR/t"|awk '{print $1}')" "payload hash" # 固定版式断言按显式 80 列跑,避免宿主长主机名/云内核在 40 列兜底里自然折行后误失败。 payload_output=$(COLUMNS=80 bash "$TEST_DIR/t" | sed -E $'s/\033\\[[0-9;]*m//g' | sed 's/[[:space:]]*$//'); payload_lines=$(printf '%s\n' "$payload_output" | sed '/^$/d'); @@ -275,9 +275,43 @@ assert_eq 6 "$(bar_cells "$disk_line")" "disk bar has 6 cells"; for plain_line in 4 5 6 7 10; do assert_eq 0 "$(bar_cells "$(printf '%s\n' "$payload_lines" | sed -n "${plain_line}p")")" "no bar on line $plain_line"; done -printf '%s\n' "$payload_lines" | sed -n '4p' | grep -q '●' || fail "system line dot"; +! printf '%s\n' "$payload_lines" | sed -n '4p' | grep -q '●' || fail "system line must not keep the green dot"; assert_eq " 内核 $(uname -r)($(uname -m))" "$(printf '%s\n' "$payload_lines" | sed -n '10p')" "payload kernel arch"; pass "payload bars limited to memory and root disk"; +# 定稿配色:主机名、系统版本、负载、标签、内核、架构,以及内存/根盘的正常态绿色。 +hero_raw=$(COLUMNS=80 bash "$TEST_DIR/t" | sed '/^$/d' | sed -n '1p'); +[[ "$hero_raw" == *$'\033[38;2;71;220;200m'*"$(hostname)"* ]] || fail "hostname must use #47DCC8"; +system_raw=$(COLUMNS=80 bash "$TEST_DIR/t" | sed '/^$/d' | sed -n '4p'); +[[ "$system_raw" == *$'\033[38;2;255;142;158m'*$'\033[1m'* ]] || fail "system version must be bold #FF8E9E"; +[[ "$system_raw" != *'●'* ]] || fail "system line must not carry the status dot"; +[[ "$system_raw" == *$'\033[38;2;168;181;217m系统'* ]] || fail "labels must use #A8B5D9"; +load_raw=$(COLUMNS=80 bash "$TEST_DIR/t" | sed '/^$/d' | sed -n '7p'); +[[ "$load_raw" == *$'\033[38;2;36;240;208m'* ]] || fail "load must use #24F0D0"; +kernel_raw_check=$(COLUMNS=80 bash "$TEST_DIR/t" | sed '/^$/d' | sed -n '10p'); +[[ "$kernel_raw_check" == *$'\033[38;2;255;147;77m'*$'\033[1m'*"$(uname -r)"* ]] || fail "kernel must be bold #FF934D"; +[[ "$kernel_raw_check" == *$'\033[22m'*$'\033[38;2;163;178;196m('* ]] || fail "architecture must be #A3B2C4 and leave the bold run"; +grep -qF 'GREEN="${ESC}[38;2;80;250;123m"' "$TEST_DIR/t" || fail "healthy memory/disk colour must stay #50FA7B"; +pass "payload adopts the approved log palette" +mkdir "$TEST_DIR/bin-accent" +cat >"$TEST_DIR/bin-accent/motd-fixture"<<'FIXTURE' +#!/usr/bin/env bash +awk() { + if [[ "${!#}" == /proc/uptime ]]; then + printf '%s\n' '90061.00 0.00 0.00' | command awk "${@:1:$#-1}" + else + command awk "$@" + fi +} +. "$1" "" +FIXTURE +chmod 0700 "$TEST_DIR/bin-accent/motd-fixture"; +uptime_out=$(COLUMNS=80 bash "$TEST_DIR/bin-accent/motd-fixture" "$TEST_DIR/t"); +uptime_raw=$(printf '%s\n' "$uptime_out" | sed '/^$/d' | sed -n '5p'); +payload_lines_stable=$(printf '%s\n' "$uptime_out" | sed -E $'s/\033\[[0-9;]*m//g' | sed 's/[[:space:]]*$//' | sed '/^$/d'); +[[ "$uptime_raw" == *$'\033[38;2;109;255;187m'*$'\033[1m1'* ]] || fail "uptime numbers must be bold #6DFFBB"; +[[ "$uptime_raw" == *$'\033[22m'*$'\033[38;2;186;194;222m 天'* ]] || fail "uptime units must leave bold and stay #BAC2DE"; +assert_eq ' 运行 1 天 1 小时' "$(printf '%s\n' "$payload_lines_stable" | sed -n '5p')" "uptime text stays byte-identical"; +pass "payload accent-colours uptime numbers only" mkdir "$TEST_DIR/bin-vm" "$TEST_DIR/bin-physical" cat >"$TEST_DIR/bin-vm/lscpu"<<'LSCPU' #!/usr/bin/env bash @@ -295,7 +329,7 @@ cpu_raw=$(COLUMNS=80 PATH="$TEST_DIR/bin-vm:$PATH" bash "$TEST_DIR/t" | sed '/^$ [[ "$cpu_raw" == *$'\033[38;2;255;184;108mExample EPYC'* ]] || fail "cpu model highlight color"; [[ "$cpu_raw" == *$'\033[38;2;248;248;242m(8 vCPU)'* ]] || fail "cpu count normal color"; kernel_raw=$(COLUMNS=80 bash "$TEST_DIR/t" | sed '/^$/d' | sed -n '10p'); -[[ "$kernel_raw" == *$'\033[38;2;214;172;255m('* ]] || fail "architecture color"; +[[ "$kernel_raw" == *$'\033[38;2;163;178;196m('* ]] || fail "architecture color"; pass "payload cpu and architecture colors" # 独立宽度判据:直接用 coreutils 在 UTF-8 locale 下的 wc -L 计算显示列宽, @@ -377,7 +411,7 @@ df() { printf '%s\n' 'Filesystem 1024-blocks Used Available Capacity Mounted on' '/dev/vda1 104857600 78643200 26214400 75% /' fi } -. "$1" +. "$1" "" FIXTURE chmod 0700 "$TEST_DIR/bin-stable/motd-fixture"; plain_out=$(env NO_COLOR=1 COLUMNS=80 bash "$TEST_DIR/bin-stable/motd-fixture" "$TEST_DIR/t"); @@ -1500,4 +1534,294 @@ for rollback_impl in tool module; do ) done + +# === 中文上次登录 hook(--last-login、PAM 插入、单一 sshd drop-in)=== +# 全部在合成 fixture 内,不读真实 lastlog、不碰现役服务。 +mkdir "$TEST_DIR/login-bin" +cat >"$TEST_DIR/login-bin/lslogins"<<'LSLOGINS' +#!/usr/bin/env bash +# 与 Debian 13 现场一致:--help 只列 --lastlog/--lastlog2,功能上接受 *-file。 +if [[ "${1:-}" == --help ]]; then + printf '%s\n' ' --wtmp-file --lastlog --lastlog2 ' \ + ' --time-format --raw --noheadings --notruncate --output --logins ' + exit 0 +fi +# 旧版 util-linux 模拟:不认 --lastlog-file/--lastlog2-file,只认 --lastlog。 +if [[ "${LSLOGINS_FIXTURE_HELP:-full}" != full ]]; then + for arg in "$@"; do + case "$arg" in + --lastlog-file|--lastlog2-file) echo "lslogins: unrecognized option '$arg'" >&2; exit 1 ;; + --lastlog) [[ "${LSLOGINS_FIXTURE_HELP:-full}" != neither ]] || exit 1 ;; + esac + done +fi +[[ -n "${LSLOGINS_FIXTURE:-}" ]] || exit 1 +cat -- "$LSLOGINS_FIXTURE" +LSLOGINS +cat >"$TEST_DIR/login-bin/sshd"<<'SSHD' +#!/usr/bin/env bash +[[ -n "${SSHD_FIXTURE_LOG:-}" ]] && printf '%s\n' "$*" >>"$SSHD_FIXTURE_LOG" +case "$1" in + -t) [[ "${SSHD_FIXTURE_T:-ok}" == ok ]] ;; + -T) [[ "${SSHD_FIXTURE_T:-ok}" == ok ]] && { + printf 'usepam %s\n' "${SSHD_FIXTURE_USEPAM:-yes}" + printf 'printlastlog %s\n' "${SSHD_FIXTURE_PRINTLASTLOG:-no}" + } ;; + *) exit 1 ;; +esac +SSHD +cat >"$TEST_DIR/login-bin/reload-stub"<<'RELOAD' +#!/usr/bin/env bash +[[ -n "${SSHD_FIXTURE_LOG:-}" ]] && printf 'reload %s\n' "$1" >>"$SSHD_FIXTURE_LOG" +if [[ "${MOTD_LOGIN_RELOAD_RESULT:-ok}" == ok ]]; then + exit 0 +fi +# 失败只消耗一次,便于用例验证重试路径。 +MOTD_LOGIN_RELOAD_RESULT=ok +exit 1 +RELOAD +chmod 0700 "$TEST_DIR/login-bin/lslogins" "$TEST_DIR/login-bin/sshd" "$TEST_DIR/login-bin/reload-stub" + +login_fixture() { + local root="$1" hist="$2" + create_fixture "$root"; export_paths "$root" + cp "$TEST_DIR/t" "$MOTD_ETC_ROOT/update-motd.d/00-custom-welcome" + mkdir -m 0700 "$MOTD_ETC_ROOT/pam.d" "$MOTD_ETC_ROOT/ssh" "$MOTD_ETC_ROOT/ssh/sshd_config.d" + printf '%s\n' \ + '@include common-auth' \ + 'session optional pam_motd.so motd=/run/motd.dynamic' \ + 'session optional pam_motd.so noupdate' \ + 'session optional pam_mail.so standard noenv # [1]' >"$MOTD_ETC_ROOT/pam.d/sshd" + : >"$MOTD_ETC_ROOT/ssh/sshd_config.d/50-cloud-init.conf" + printf '%s\n' "$hist" >"$root/lslogins.out" + chmod 0600 "$root/lslogins.out" + : >"$root/pam_exec.so" + LSLOGINS_FIXTURE="$root/lslogins.out" + SSHD_FIXTURE_LOG="$root/sshd.log" + MOTD_LOGIN_PAM_EXEC="$root/pam_exec.so" + MOTD_LOGIN_SSH_SERVICE=sshd.service + MOTD_LOGIN_RELOAD_STUB="$TEST_DIR/login-bin/reload-stub" + export LSLOGINS_FIXTURE SSHD_FIXTURE_LOG MOTD_LOGIN_PAM_EXEC MOTD_LOGIN_SSH_SERVICE MOTD_LOGIN_RELOAD_STUB + export SSHD_FIXTURE_T=ok SSHD_FIXTURE_PRINTLASTLOG=no SSHD_FIXTURE_USEPAM=yes + # stub 目录前置:任何用例都不会落到真实 lslogins/sshd,避免读取真实登录记录。 + PATH="$TEST_DIR/login-bin:$PATH" + export PATH + : >"$root/sshd.log" +} +login_payload() { COLUMNS=80 PAM_USER="$1" PATH="$TEST_DIR/login-bin:$PATH" bash "$TEST_DIR/t" --last-login 2>&1; } + +( + root="$TEST_DIR/login-ipv4"; login_fixture "$root" '2026-12-01T03:25:52+08:00 203.0.113.7' + load_motd + [[ -f "$MOTD_LOGIN_PAM_SERVICE" ]] || fail "fixture pam service missing" + motd_login_hook_install >/dev/null 2>&1 + grep -Fq 'linux-setup:last-login-hook' "$MOTD_LOGIN_PAM_SERVICE" || fail "PAM hook not inserted" + grep -Fq '# linux-setup:managed-last-login' "$MOTD_LOGIN_DROPIN" || fail "sshd drop-in not written" + grep -Fxq 'PrintLastLog no' "$MOTD_LOGIN_DROPIN" || fail "drop-in must set PrintLastLog no" + [[ "$(grep -c 'linux-setup:last-login-hook' "$MOTD_LOGIN_PAM_SERVICE")" == 1 ]] || fail "hook must be inserted once" + awk '/pam_motd\.so/{m=NR} /linux-setup:last-login-hook/{h=NR} END{exit !(h==m+1)}' "$MOTD_LOGIN_PAM_SERVICE" || fail "hook must directly follow the last pam_motd line" + # 只 reload 活动服务,且必须是在 sshd 校验通过之后。 + grep -Fxq 'reload sshd.service' "$SSHD_FIXTURE_LOG" || fail "install must reload the active ssh service" + pass "login hook installs one PAM line after pam_motd and one managed drop-in" +) +( + root="$TEST_DIR/login-idempotent"; login_fixture "$root" '2026-12-01T03:25:52+08:00 203.0.113.7' + load_motd + motd_login_hook_install >/dev/null 2>&1 + after_first=$(cat "$MOTD_LOGIN_PAM_SERVICE") + motd_login_hook_install >/dev/null 2>&1 + assert_eq "$after_first" "$(cat "$MOTD_LOGIN_PAM_SERVICE")" "second install must not add a second PAM line" + assert_eq 1 "$(grep -c 'linux-setup:last-login-hook' "$MOTD_LOGIN_PAM_SERVICE")" "hook stays single" + pass "install is idempotent and keeps one managed PAM line" +) +( + root="$TEST_DIR/login-admin-exec"; login_fixture "$root" '2026-12-01T03:25:52+08:00 203.0.113.7' + load_motd + printf '%s\n' 'session optional pam_exec.so /usr/local/bin/admin-hook' >>"$MOTD_LOGIN_PAM_SERVICE" + before_pam=$(cat "$MOTD_LOGIN_PAM_SERVICE") + motd_login_hook_install >/dev/null 2>&1 + assert_eq "$before_pam" "$(cat "$MOTD_LOGIN_PAM_SERVICE")" "admin pam_exec must block the hook" + [[ ! -e "$MOTD_LOGIN_DROPIN" ]] || fail "admin pam_exec conflict must not disable the English message" + pass "administrator pam_exec line keeps prior state" +) +( + root="$TEST_DIR/login-ipv6"; login_fixture "$root" '2026-12-01T03:25:52+08:00 2001:db8::42' + load_motd; motd_login_hook_install >/dev/null 2>&1 + out=$(login_payload root); plain=$(printf '%s' "$out" | sed -E $'s/\033\\[[0-9;]*m//g') + [[ "$plain" == *'上次登录 2026-12-01 03:25:52'* ]] || fail "IPv6 last-login time line" + [[ "$plain" == *'来源 IP 2001:db8::42'* ]] || fail "IPv6 source uses 来源 IP" + [[ "$out" == *$'\033[38;2;248;248;242m2026-12-01 03:25:52'* ]] || fail "last-login time must be #F8F8F2" + [[ "$out" == *$'\033[38;2;255;121;198m2001:db8::42'* ]] || fail "source must be #FF79C6" + ! printf '%s' "$plain" | grep -q '欢迎登录\|系统 \|内核' || fail "--last-login must not repeat the welcome panel" + pass "IPv4/IPv6 time and source render in the approved colours" +) +( + root="$TEST_DIR/login-hostname"; login_fixture "$root" '2026-12-01T03:25:52+08:00 build.example.internal' + load_motd; out=$(login_payload root); plain=$(printf '%s' "$out" | sed -E $'s/\033\\[[0-9;]*m//g') + [[ "$plain" == *'来源 build.example.internal'* ]] || fail "hostname source uses 来源 label" + [[ "$plain" != *'来源 IP'* ]] || fail "hostname must not be labelled 来源 IP" + pass "hostname source uses 来源" +) +( + root="$TEST_DIR/login-nohistory"; login_fixture "$root" '' + load_motd; out=$(login_payload root) + [[ -z "$out" ]] || fail "missing history must print nothing, got: $out" + pass "missing history stays silent" +) +( + root="$TEST_DIR/login-ipnohost"; login_fixture "$root" '2026-12-01T03:25:52+08:00 ' + load_motd; out=$(login_payload root); plain=$(printf '%s' "$out" | sed -E $'s/\033\\[[0-9;]*m//g') + [[ "$plain" == *'上次登录 2026-12-01 03:25:52'* ]] || fail "missing source must still print time" + [[ "$plain" != *'来源'* ]] || fail "missing source must omit the source row" + pass "missing source prints only the timestamp" +) +( + root="$TEST_DIR/login-nodep"; login_fixture "$root" '2026-12-01T03:25:52+08:00 203.0.113.7' + load_motd + # 空 PATH:command -v lslogins 失败,安装器必须在触碰任何文件前退出; + # 不用 mv 造缺失,避免回退到宿主的真实 lslogins 读真实 lastlog。 + before_pam=$(cat "$MOTD_LOGIN_PAM_SERVICE"); before_hash=$(sha256sum "$MOTD_LOGIN_PAM_SERVICE") + PATH= motd_login_hook_install >/dev/null 2>&1 + export LSLOGINS_FIXTURE_HELP=old + # 旧版只有 --lastlog:探测走 legacy 分支仍视为可用,不应静默跳过。 + motd_login_hook_supported || fail "legacy lslogins with --lastlog must still be supported" + out=$(login_payload root); plain=$(printf '%s' "$out" | sed -E $'s/\033\\[[0-9;]*m//g') + [[ "$plain" == *'上次登录 2026-12-01 03:25:52'* ]] || fail "legacy lslogins fallback must render" + export LSLOGINS_FIXTURE_HELP=full + assert_eq "$before_pam" "$(cat "$MOTD_LOGIN_PAM_SERVICE")" "missing dependency leaves PAM untouched" + assert_eq "$before_hash" "$(sha256sum "$MOTD_LOGIN_PAM_SERVICE")" "missing dependency leaves PAM bytes" + [[ ! -e "$MOTD_LOGIN_DROPIN" ]] || fail "missing dependency must not disable the English message" + [[ ! -e "$MOTD_LOGIN_STATE_DIR" ]] || fail "missing dependency must not create hook state" + pass "missing dependency keeps the original English message" +) +( + root="$TEST_DIR/login-nocap"; login_fixture "$root" '2026-12-01T03:25:52+08:00 203.0.113.7' + load_motd + before_hash=$(sha256sum "$MOTD_LOGIN_PAM_SERVICE") + # 现代与 legacy 参数都不被接受:必须在写任何文件前放弃。 + LSLOGINS_FIXTURE_HELP=neither motd_login_hook_install >/dev/null 2>&1 + [[ ! -e "$MOTD_LOGIN_DROPIN" && ! -e "$MOTD_LOGIN_STATE_DIR" ]] || fail "unsupported lslogins must not install" + assert_eq "$before_hash" "$(sha256sum "$MOTD_LOGIN_PAM_SERVICE")" "unsupported lslogins leaves PAM untouched" + pass "unsupported lslogins keeps the original English message" +) +( + root="$TEST_DIR/login-conflict"; login_fixture "$root" '2026-12-01T03:25:52+08:00 203.0.113.7' + load_motd + rm -f "$MOTD_LOGIN_PAM_SERVICE" + printf '%s\n' 'session optional pam_unix.so' >"$MOTD_LOGIN_PAM_SERVICE" + motd_login_hook_install >/dev/null 2>&1 + grep -Fq 'linux-setup:last-login-hook' "$MOTD_LOGIN_PAM_SERVICE" && fail "admin PAM without anchor must be left alone" + [[ ! -e "$MOTD_LOGIN_DROPIN" ]] || fail "no drop-in without a valid anchor" + pass "administrator PAM conflict keeps prior state" +) +( + root="$TEST_DIR/login-sshd-fail"; login_fixture "$root" '2026-12-01T03:25:52+08:00 203.0.113.7' + load_motd + before_pam=$(cat "$MOTD_LOGIN_PAM_SERVICE") + export SSHD_FIXTURE_T=fail + motd_login_hook_install >/dev/null 2>&1 + assert_eq "$before_pam" "$(cat "$MOTD_LOGIN_PAM_SERVICE")" "sshd -t failure restores PAM" + [[ ! -e "$MOTD_LOGIN_DROPIN" ]] || fail "sshd -t failure must remove the drop-in" + export SSHD_FIXTURE_T=ok + pass "sshd validation failure rolls back and keeps English" +) +( + root="$TEST_DIR/login-printlastlog"; login_fixture "$root" '2026-12-01T03:25:52+08:00 203.0.113.7' + load_motd; before_pam=$(cat "$MOTD_LOGIN_PAM_SERVICE") + export SSHD_FIXTURE_PRINTLASTLOG=yes + motd_login_hook_install >/dev/null 2>&1 + assert_eq "$before_pam" "$(cat "$MOTD_LOGIN_PAM_SERVICE")" "unconfirmed PrintLastLog restores PAM" + [[ ! -e "$MOTD_LOGIN_DROPIN" ]] || fail "unconfirmed PrintLastLog must not stay installed" + export SSHD_FIXTURE_PRINTLASTLOG=no + pass "sshd -T must confirm PrintLastLog no before suppressing English" +) +( + root="$TEST_DIR/login-usepam-off"; login_fixture "$root" '2026-12-01T03:25:52+08:00 203.0.113.7' + load_motd; before_pam=$(cat "$MOTD_LOGIN_PAM_SERVICE") + export SSHD_FIXTURE_USEPAM=no + motd_login_hook_install >/dev/null 2>&1 + assert_eq "$before_pam" "$(cat "$MOTD_LOGIN_PAM_SERVICE")" "UsePAM no restores PAM" + [[ ! -e "$MOTD_LOGIN_DROPIN" ]] || fail "UsePAM no must not disable the English message" + export SSHD_FIXTURE_USEPAM=yes + pass "english is only suppressed when the effective config uses PAM" +) +( + root="$TEST_DIR/login-residue"; login_fixture "$root" '2026-12-01T03:25:52+08:00 203.0.113.7' + load_motd + : >"$MOTD_ETC_ROOT/pam.d/.linux-setup-last-login.pam.0123456789abcdef0123456789abcdef" + motd_login_hook_install >/dev/null 2>&1 + [[ ! -e "$MOTD_ETC_ROOT/pam.d/.linux-setup-last-login.pam.0123456789abcdef0123456789abcdef" ]] || fail "trusted residue must be cleaned" + grep -Fq 'linux-setup:last-login-hook' "$MOTD_LOGIN_PAM_SERVICE" || fail "install must proceed after cleaning residue" + pass "crash residue next to /etc targets is cleaned before writing" +) +( + root="$TEST_DIR/login-rollback"; login_fixture "$root" '2026-12-01T03:25:52+08:00 203.0.113.7' + load_motd + pam_before=$(cat "$MOTD_LOGIN_PAM_SERVICE") + motd_login_hook_install >/dev/null 2>&1 + [[ -e "$MOTD_LOGIN_DROPIN" ]] || fail "rollback fixture did not install" + motd_login_hook_restore >/dev/null 2>&1 + assert_eq "$pam_before" "$(cat "$MOTD_LOGIN_PAM_SERVICE")" "restore reinstates PAM byte-for-byte" + [[ ! -e "$MOTD_LOGIN_DROPIN" ]] || fail "restore removes the drop-in it created" + [[ ! -e "$MOTD_LOGIN_STATE_DIR" ]] || fail "restore removes the hook state dir" + pass "restore reverses the drop-in before the PAM edit" +) +( + root="$TEST_DIR/login-preserve-existing"; login_fixture "$root" '2026-12-01T03:25:52+08:00 203.0.113.7' + load_motd + printf '# admin drop-in\nPrintLastLog yes\n' >"$MOTD_LOGIN_DROPIN" + before_dropin=$(cat "$MOTD_LOGIN_DROPIN"); before_pam=$(cat "$MOTD_LOGIN_PAM_SERVICE") + motd_login_hook_install >/dev/null 2>&1 + assert_eq "$before_dropin" "$(cat "$MOTD_LOGIN_DROPIN")" "admin drop-in is left untouched" + assert_eq "$before_pam" "$(cat "$MOTD_LOGIN_PAM_SERVICE")" "admin drop-in conflict leaves PAM untouched" + motd_login_hook_restore >/dev/null 2>&1 + assert_eq "$before_dropin" "$(cat "$MOTD_LOGIN_DROPIN")" "restore does not touch an admin drop-in" + pass "administrator drop-in blocks the hook and survives untouched" +) +( + root="$TEST_DIR/login-admin-edit-after"; login_fixture "$root" '2026-12-01T03:25:52+08:00 203.0.113.7' + load_motd + motd_login_hook_install >/dev/null 2>&1 + printf 'PasswordAuthentication no\n' >>"$MOTD_LOGIN_DROPIN" + grep -Fq 'linux-setup:last-login-hook' "$MOTD_LOGIN_PAM_SERVICE" || fail "fixture did not install" + motd_login_hook_restore >/dev/null 2>&1 || fail "restore after admin edit failed" + assert_eq 'PasswordAuthentication no' "$(cat "$MOTD_LOGIN_DROPIN")" "admin lines added after install survive restore" + ! grep -Fq 'PrintLastLog no' "$MOTD_LOGIN_DROPIN" || fail "only the managed block is stripped" + pass "recovery keeps administrator edits made after install" +) +( + root="$TEST_DIR/login-reload-install-fail"; login_fixture "$root" '2026-12-01T03:25:52+08:00 203.0.113.7' + load_motd + before_pam=$(cat "$MOTD_LOGIN_PAM_SERVICE") + export MOTD_LOGIN_RELOAD_RESULT=fail + motd_login_hook_install >/dev/null 2>&1 + assert_eq "$before_pam" "$(cat "$MOTD_LOGIN_PAM_SERVICE")" "reload failure restores PAM" + [[ ! -e "$MOTD_LOGIN_DROPIN" ]] || fail "reload failure must remove the drop-in" + [[ ! -e "$MOTD_LOGIN_STATE_DIR" ]] || fail "reload failure must clear hook state" + export MOTD_LOGIN_RELOAD_RESULT=ok + pass "failed reload rolls the disk back to the English message" +) +( + root="$TEST_DIR/login-reload-restore-fail"; login_fixture "$root" '2026-12-01T03:25:52+08:00 203.0.113.7' + load_motd + motd_login_hook_install >/dev/null 2>&1 + export MOTD_LOGIN_RELOAD_RESULT=fail + ! motd_login_hook_restore >/dev/null 2>&1 || fail "restore must report failure when reload fails" + grep -Fq 'linux-setup:last-login-hook' "$MOTD_LOGIN_PAM_SERVICE" || fail "failed restore must keep the PAM hook" + [[ ! -e "$MOTD_LOGIN_DROPIN" ]] || fail "failed restore must already have the English drop-in back" + export MOTD_LOGIN_RELOAD_RESULT=ok + motd_login_hook_restore >/dev/null 2>&1 || fail "restore must succeed once reload works" + ! grep -Fq 'linux-setup:last-login-hook' "$MOTD_LOGIN_PAM_SERVICE" || fail "retried restore removes the hook" + pass "restore reloads the English message before dropping the PAM hook" +) +( + root="$TEST_DIR/login-legacy-snapshot"; login_fixture "$root" '2026-12-01T03:25:52+08:00 203.0.113.7' + load_motd + motd_run_locked_operation install + # 旧版本快照没有 hook 状态目录,恢复必须只处理 MOTD 组而不猜 hook 历史。 + motd_login_hook_restore >/dev/null 2>&1 + motd_run_locked_operation restore previous + assert_eq original "$(cat "$MOTD_ETC_ROOT/motd")" "legacy snapshot restore keeps working" + pass "legacy snapshot without hook state restores cleanly" +) printf 'All MOTD rollback final validation tests passed.\n' diff --git a/tools/setup-motd.sh b/tools/setup-motd.sh index c45997a..ff9fd33 100755 --- a/tools/setup-motd.sh +++ b/tools/setup-motd.sh @@ -24,7 +24,7 @@ fi readonly MOTD_ETC_ROOT MOTD_STATE_DIR MOTD_LOCK_FILE MOTD_TRANSACTION_PARENT MOTD_TRUSTED_UID MOTD_TRUSTED_GID readonly MOTD_SCRIPT="$MOTD_ETC_ROOT/update-motd.d/00-custom-welcome" readonly MOTD_SNAPSHOT_VERSION=1 -readonly MOTD_PAYLOAD_SHA256="22fb713f1c0e60f6a19a3b1b9629c3121a1f2e4f5890237163e7b74706ea3983" +readonly MOTD_PAYLOAD_SHA256="5c36a6d573019a7135974b199c4eeca74876d1e5bc436d910db80e1c7c2a772e" readonly -a MOTD_TARGET_IDS=(motd issue issue_net custom_welcome uname motd_news) readonly -a MOTD_TARGET_PATHS=( "$MOTD_ETC_ROOT/motd" "$MOTD_ETC_ROOT/issue" "$MOTD_ETC_ROOT/issue.net" @@ -818,9 +818,9 @@ motd_validate_residue_file() { motd_cleanup_root_stages() { local saved path name failed=false saved=$(shopt -p nullglob dotglob || true); shopt -s nullglob - for path in "$MOTD_STATE_DIR"/.initial.pointer.* "$MOTD_STATE_DIR"/.previous.pointer.* "$MOTD_STATE_DIR"/.pending.*; do + for path in "$MOTD_STATE_DIR"/.initial.pointer.* "$MOTD_STATE_DIR"/.previous.pointer.* "$MOTD_STATE_DIR"/.pending.* "$MOTD_STATE_DIR"/.pam.stage.*; do name=${path##*/} - [[ "$name" =~ ^\.(initial|previous)\.pointer\.[0-9a-f]{32}$ || "$name" =~ ^\.pending\.[0-9a-f]{32}$ ]] || { error "未知 MOTD root residue: $path"; failed=true; continue; } + [[ "$name" =~ ^\.(initial|previous)\.pointer\.[0-9a-f]{32}$ || "$name" =~ ^\.pending\.[0-9a-f]{32}$ || "$name" =~ ^\.pam\.stage\.[0-9a-f]{32}$ ]] || { error "未知 MOTD root residue: $path"; failed=true; continue; } motd_validate_secure_file "$path" && rm -f -- "$path" || { error "不可信或无法清理的 MOTD residue: $path"; failed=true; } done eval "$saved" @@ -848,6 +848,7 @@ motd_validate_state_root_entries() { generations) motd_validate_secure_directory "$path" || failed=true ;; transactions) motd_validate_secure_directory "$path" || failed=true ;; initial.current|previous.current|pending) ;; + last-login-hook) motd_validate_secure_directory "$path" || failed=true ;; *) if ! motd_validate_state_legacy_object "$path"; then error "非法 MOTD state root legacy 对象: $path"; failed=true @@ -1639,12 +1640,16 @@ motd_install_body() { motd_validate_all_target_stages || return 1 motd_commit_target_plan install false || return 1 motd_mark_transaction_committed || return 1 - motd_complete_transaction + motd_complete_transaction || return 1 + # 欢迎面板已提交后再配置中文上次登录;失败只保留原英文,不回滚已提交的面板。 + motd_login_hook_install || warn "中文上次登录未配置,保留原英文" } motd_restore_body() { local scope="$1" result=0 generation motd_prepare_state_layout || return 1 + # 先撤本工具的 PAM/drop-in hook,再恢复 MOTD 文件组,避免恢复后仍抑制原英文。 + motd_login_hook_restore || { error "恢复中文上次登录 hook 失败,保持 hook 状态以便重试"; return 1; } motd_reconcile_state || return 1 motd_validate_target_parents || return 1 motd_begin_transaction restore || return 1 @@ -1682,6 +1687,349 @@ motd_run_locked_operation() { return "$status" } +# === 中文上次登录 SSH hook === +# 复用同一 payload 的 --last-login,不把登录数据写入 /run/motd.dynamic; +# 由 sshd 的 PAM 会话中紧随 pam_motd 的可选 pam_exec 输出,PrintLastLog 只关闭原英文。 +readonly MOTD_LOGIN_PAM_SERVICE="$MOTD_ETC_ROOT/pam.d/sshd" +readonly MOTD_LOGIN_DROPIN_DIR="$MOTD_ETC_ROOT/ssh/sshd_config.d" +readonly MOTD_LOGIN_DROPIN="$MOTD_LOGIN_DROPIN_DIR/60-linux-setup-last-login.conf" +readonly MOTD_LOGIN_STATE_DIR="$MOTD_STATE_DIR/last-login-hook" + +# 目标同目录的临时文件,保证 mv -Tf 是同一文件系统内的 rename; +# 状态目录与 /etc 分挂载时,放在状态目录会让 mv 退化为复制+替换。 +motd_login_stage_near() { + local destination="$1" label="$2" parent token path + parent=${destination%/*} + [[ -n "$parent" && -d "$parent" && ! -L "$parent" ]] || return 1 + token=$(motd_random_id) || return 1 + path="$parent/.linux-setup-last-login.$label.$token" + [[ ! -e "$path" && ! -L "$path" ]] || return 1 + printf '%s\n' "$path" +} + +# 崩溃残留只可能是本工具前缀的临时文件;校验属主/类型后清除,遇到异常即停止。 +motd_login_cleanup_residue() { + local dir path name saved failed=false + saved=$(shopt -p nullglob dotglob || true); shopt -s nullglob dotglob + for dir in "$MOTD_LOGIN_PAM_SERVICE" "$MOTD_LOGIN_DROPIN"; do + dir=${dir%/*} + for path in "$dir"/.linux-setup-last-login.*; do + name=${path##*/} + if [[ ! "$name" =~ ^\.linux-setup-last-login\.[a-z]+\.[0-9a-f]{32}$ ]] || + [[ -L "$path" || ! -f "$path" ]] || + [[ "$(stat -c '%u:%g' -- "$path" 2>/dev/null)" != "$MOTD_TRUSTED_UID:$MOTD_TRUSTED_GID" ]] || + ! rm -f -- "$path"; then + failed=true + fi + done + done + eval "$saved" + [[ "$failed" == false ]] +} + +motd_login_hook_state_path() { printf '%s/%s\n' "$MOTD_LOGIN_STATE_DIR" "$1"; } + +motd_login_pam_exec_path() { + local candidate + # 仅测试模式允许注入探测路径,生产环境始终走固定系统路径。 + if [[ "${MOTD_TEST_MODE:-0}" == 1 && -n "${MOTD_LOGIN_PAM_EXEC:-}" ]]; then + [[ -f "$MOTD_LOGIN_PAM_EXEC" ]] && { printf '%s\n' "$MOTD_LOGIN_PAM_EXEC"; return 0; } + return 1 + fi + for candidate in /usr/lib/x86_64-linux-gnu/security/pam_exec.so \ + /usr/lib/aarch64-linux-gnu/security/pam_exec.so \ + /usr/lib/security/pam_exec.so /lib/security/pam_exec.so \ + /lib/x86_64-linux-gnu/security/pam_exec.so /lib/aarch64-linux-gnu/security/pam_exec.so; do + [[ -f "$candidate" ]] && { printf '%s\n' "$candidate"; return 0; } + done + return 1 +} + +# Debian 13 的 lslogins --help 只写 --lastlog/--lastlog2,却实际接受 +# --lastlog-file/--lastlog2-file;因此不用 help 文本判定,改用空文件功能探测。 +# 全部文件指向 /dev/null、用户为不存在的合成名,不触碰任何真实登录记录。 +# util-linux 2.39 及更早只有 --lastlog,payload 侧同样按 modern→legacy 回退。 +motd_login_lslogins_args() { + local mode + for mode in modern legacy; do + local -a args=(--wtmp-file /dev/null) + if [[ "$mode" == modern ]]; then + args+=(--lastlog-file /dev/null --lastlog2-file /dev/null) + else + args+=(--lastlog /dev/null) + fi + LC_ALL=C lslogins "${args[@]}" --time-format iso --raw --noheadings --notruncate \ + --output LAST-LOGIN,LAST-HOSTNAME --logins __linux_setup_probe__ >/dev/null 2>&1 || continue + printf '%s\n' "$mode" + return 0 + done + return 1 +} + +motd_login_lslogins_supported() { motd_login_lslogins_args >/dev/null; } + +# 只 reload 正在运行的正确 SSH 服务;socket 激活的监听端不在这里重启。 +motd_login_ssh_service() { + if [[ "${MOTD_TEST_MODE:-0}" == 1 && -n "${MOTD_LOGIN_SSH_SERVICE:-}" ]]; then + printf '%s\n' "$MOTD_LOGIN_SSH_SERVICE" + return 0 + fi + command -v systemctl >/dev/null 2>&1 || return 1 + if systemctl list-unit-files ssh.service --no-legend 2>/dev/null | grep -q '^ssh\.service'; then + systemctl is-active --quiet ssh.service 2>/dev/null || return 1 + printf 'ssh.service\n' + return 0 + fi + if systemctl list-unit-files sshd.service --no-legend 2>/dev/null | grep -q '^sshd\.service'; then + systemctl is-active --quiet sshd.service 2>/dev/null || return 1 + printf 'sshd.service\n' + return 0 + fi + return 1 +} + +# 先确认候选配置有效且 PrintLastLog no,再重载活动服务,避免磁盘与活进程不一致。 +motd_login_reload_sshd() { + local service + service=$(motd_login_ssh_service) || return 1 + motd_login_hook_verify_sshd || return 1 + if [[ "${MOTD_TEST_MODE:-0}" == 1 && -n "${MOTD_LOGIN_RELOAD_STUB:-}" ]]; then + "$MOTD_LOGIN_RELOAD_STUB" "$service" + return + fi + systemctl reload "$service" +} + +motd_login_hook_supported() { + local command_name + for command_name in lslogins sshd awk sed grep; do + command -v "$command_name" >/dev/null 2>&1 || return 1 + done + motd_login_lslogins_supported || return 1 + motd_login_ssh_service >/dev/null || return 1 + motd_login_pam_exec_path >/dev/null || return 1 + [[ -f "$MOTD_LOGIN_PAM_SERVICE" && ! -L "$MOTD_LOGIN_PAM_SERVICE" ]] || return 1 + [[ -d "$MOTD_LOGIN_DROPIN_DIR" && ! -L "$MOTD_LOGIN_DROPIN_DIR" ]] || return 1 + [[ -f "$MOTD_SCRIPT" && ! -L "$MOTD_SCRIPT" ]] || return 1 + grep -Fq -- '--last-login' "$MOTD_SCRIPT" || return 1 +} + +# 单一 drop-in 已存在但不是本工具的文件:不覆盖管理员配置,也不关英文。 +motd_login_hook_dropin_owned() { + [[ -e "$MOTD_LOGIN_DROPIN" || -L "$MOTD_LOGIN_DROPIN" ]] && + ! motd_login_hook_dropin_present +} + +# 管理员已自行配置 session pam_exec 时不接管,保留前态。 +motd_login_hook_admin_conflict() { + [[ -f "$MOTD_LOGIN_PAM_SERVICE" ]] || return 1 + grep -Eq '^[[:space:]]*session[[:space:]].*pam_exec\.so' "$MOTD_LOGIN_PAM_SERVICE" && + ! motd_login_hook_pam_present +} + +# 旧快照:目标组里没有本次 hook 记录时视为未启用,不据缺失文件猜测历史。 +motd_login_hook_is_managed() { + local marker + marker=$(motd_login_hook_state_path marker) || return 1 + [[ -f "$marker" && ! -L "$marker" ]] && grep -Fxq 'last-login-hook=1' "$marker" +} + +motd_login_hook_dropin_present() { + [[ -f "$MOTD_LOGIN_DROPIN" && ! -L "$MOTD_LOGIN_DROPIN" ]] && + grep -Fxq '# linux-setup:managed-last-login' "$MOTD_LOGIN_DROPIN" +} + +motd_login_hook_pam_present() { + [[ -f "$MOTD_LOGIN_PAM_SERVICE" ]] && + grep -Fq 'linux-setup:last-login-hook' "$MOTD_LOGIN_PAM_SERVICE" +} + +# 只记录"本工具装过"这一个事实:PAM 与 drop-in 都按标记行增删, +# 因此不整文件备份,管理员安装后的改动不会被旧快照覆盖。 +motd_login_hook_backup() { + motd_login_hook_is_managed && return 0 + motd_ensure_secure_directory "$MOTD_LOGIN_STATE_DIR" || return 1 + (umask 077; set -o noclobber; : > "$(motd_login_hook_state_path marker)") 2>/dev/null || return 1 + printf 'last-login-hook=1\n' > "$(motd_login_hook_state_path marker)" || return 1 + chmod 0600 "$MOTD_LOGIN_STATE_DIR"/* || return 1 +} + +# 只在最后一条 pam_motd 之后追加一行;找不到锚点或已有管理员 pam_exec 时保持前态。 +motd_login_hook_pam_stage() { + local destination="$1" stage index last=-1 line + local -a lines=() + while IFS= read -r line || [[ -n "$line" ]]; do + lines+=("$line") + [[ "$line" =~ ^[[:space:]]*session[[:space:]].*pam_motd\.so ]] && last=$(( ${#lines[@]} - 1 )) + done < "$MOTD_LOGIN_PAM_SERVICE" + (( last >= 0 )) || return 2 + stage=$(motd_login_stage_near "$destination" pam) || return 1 + : > "$stage" || { rm -f -- "$stage"; return 1; } + for index in "${!lines[@]}"; do + printf '%s\n' "${lines[$index]}" >> "$stage" || { rm -f -- "$stage"; return 1; } + (( index == last )) || continue + printf 'session optional pam_exec.so type=open_session stdout quiet %s --last-login # linux-setup:last-login-hook\n' "$MOTD_SCRIPT" >> "$stage" || { rm -f -- "$stage"; return 1; } + done + # 保留原文件权限,避免把管理员收紧过的 0640 PAM 配置放宽。 + chmod "$(stat -c '%a' -- "$destination" 2>/dev/null || printf 644)" "$stage" || { rm -f -- "$stage"; return 1; } + mv -Tf -- "$stage" "$destination" || { rm -f -- "$stage"; return 1; } +} + + +motd_login_hook_verify_sshd() { + local effective usepam + sshd -t || return 1 + effective=$(sshd -T 2>/dev/null) || return 1 + usepam=$(awk '$1 == "usepam" {print $2; exit}' <<< "$effective") + # 只有生效配置启用 UsePAM,PAM 里的 pam_exec 才会执行;否则关英文就是纯倒退。 + [[ "$usepam" == yes ]] || return 1 + [[ "$(awk '$1 == "printlastlog" {print $2; exit}' <<< "$effective")" == no ]] +} + +# 恢复英文提示时只确认配置有效并 reload 成功;不猜测管理员原本的 PrintLastLog 值。 +motd_login_hook_reload_restored() { + sshd -t || return 1 + motd_login_ssh_service >/dev/null || return 1 + if [[ "${MOTD_TEST_MODE:-0}" == 1 && -n "${MOTD_LOGIN_RELOAD_STUB:-}" ]]; then + "$MOTD_LOGIN_RELOAD_STUB" "$(motd_login_ssh_service)" + return + fi + systemctl reload "$(motd_login_ssh_service)" +} + +motd_login_hook_install() { + local status dropin_stage + motd_login_cleanup_residue || { warn "存在不可信的登录 hook 临时残留,停止"; return 0; } + if ! motd_login_hook_supported; then + warn "缺少 lslogins/pam_exec/sshd/systemd 服务或 PAM 锚点,保留原英文上次登录" + return 0 + fi + if motd_login_hook_admin_conflict; then + warn "检测到管理员自建的 PAM pam_exec 配置,保持原状不改动" + return 0 + fi + if motd_login_hook_dropin_owned; then + warn "已有管理员 sshd drop-in: $MOTD_LOGIN_DROPIN,保持原状不改动" + return 0 + fi + # 重复执行保持幂等:已启用时只补一次 reload,不再插入第二行。 + if motd_login_hook_is_managed && motd_login_hook_pam_present && motd_login_hook_dropin_present; then + if motd_login_hook_verify_sshd && motd_login_reload_sshd; then + success "中文上次登录: 已配置(新会话生效,原英文行已停止)" + return 0 + fi + warn "中文上次登录重载未确认,回滚并保留原英文" + motd_login_hook_rollback_disk || warn "中文上次登录回滚未完成,保留状态以便重试" + return 0 + fi + motd_login_hook_backup || { warn "中文上次登录状态写入失败,保留原状"; return 0; } + if motd_login_hook_pam_stage "$MOTD_LOGIN_PAM_SERVICE" 2>/dev/null; then + : + else + status=$? + warn "PAM 配置没有可用的 pam_motd 锚点,保留原状" + motd_login_hook_rollback_disk || true + return 0 + fi + dropin_stage=$(motd_login_stage_near "$MOTD_LOGIN_DROPIN" dropin) || { + motd_login_hook_rollback_disk || true; return 0; } + (umask 077; set -o noclobber; : > "$dropin_stage") 2>/dev/null || { motd_login_hook_rollback_disk || true; return 0; } + printf '# linux-setup:managed-last-login\n# 由 Linux Scripts Collection 自动生成。\nPrintLastLog no\n' > "$dropin_stage" || { + rm -f -- "$dropin_stage"; motd_login_hook_rollback_disk || true; return 0; } + chmod 0644 "$dropin_stage" || { rm -f -- "$dropin_stage"; motd_login_hook_rollback_disk || true; return 0; } + mv -Tf -- "$dropin_stage" "$MOTD_LOGIN_DROPIN" || { + rm -f -- "$dropin_stage"; motd_login_hook_rollback_disk || true; return 0; } + if ! motd_login_hook_verify_sshd; then + warn "sshd -t/-T 未确认中文上次登录生效,回滚并保留原英文" + motd_login_hook_rollback_disk || true + return 0 + fi + if ! motd_login_reload_sshd; then + warn "sshd 重载失败或活动服务不可确认,回滚并保留原英文" + motd_login_hook_rollback_disk || true + return 0 + fi + success "中文上次登录: 已配置(新会话生效,原英文行已停止)" +} + +# 只摘本工具写入的那一行,保留安装后管理员对 PAM 的其他改动。 +motd_login_hook_pam_remove_line() { + local stage + [[ -f "$MOTD_LOGIN_PAM_SERVICE" ]] || return 0 + grep -Fq 'linux-setup:last-login-hook' "$MOTD_LOGIN_PAM_SERVICE" || return 0 + stage=$(motd_login_stage_near "$MOTD_LOGIN_PAM_SERVICE" pam) || return 1 + grep -v 'linux-setup:last-login-hook' "$MOTD_LOGIN_PAM_SERVICE" > "$stage" || { rm -f -- "$stage"; return 1; } + chmod "$(stat -c '%a' -- "$MOTD_LOGIN_PAM_SERVICE")" "$stage" || { rm -f -- "$stage"; return 1; } + mv -Tf -- "$stage" "$MOTD_LOGIN_PAM_SERVICE" || { rm -f -- "$stage"; return 1; } +} + +# 只撤本工具 drop-in 的三行;管理员后来追加的内容原样保留。 +motd_login_hook_dropin_restore() { + local stage + [[ -e "$MOTD_LOGIN_DROPIN" ]] || return 0 + stage=$(motd_login_stage_near "$MOTD_LOGIN_DROPIN" dropin) || return 1 + # 只删除"表头两行 + PrintLastLog no"这一整块;管理员自行添加的同名指令保留。 + awk ' + $0 == "# linux-setup:managed-last-login" { held = $0; next } + held != "" && $0 == "# 由 Linux Scripts Collection 自动生成。" { held = held "\n" $0; next } + held != "" && $0 == "PrintLastLog no" { held = ""; next } + held != "" { print held; held = "" } + { print } + END { if (held != "") print held } + ' "$MOTD_LOGIN_DROPIN" > "$stage" || { rm -f -- "$stage"; return 1; } + chmod "$(stat -c '%a' -- "$MOTD_LOGIN_DROPIN")" "$stage" || { rm -f -- "$stage"; return 1; } + if [[ ! -s "$stage" ]]; then + rm -f -- "$stage" "$MOTD_LOGIN_DROPIN" || return 1 + return 0 + fi + mv -Tf -- "$stage" "$MOTD_LOGIN_DROPIN" || { rm -f -- "$stage"; return 1; } +} + +# 安装期失败回滚:活服务从未加载过新配置,只需把磁盘改回并校验配置本身, +# 不做 reload(sshd -t 此时正是失败原因,重载没有意义)。 +motd_login_hook_rollback_disk() { + motd_login_hook_is_managed || return 0 + if motd_login_hook_dropin_present; then + motd_login_hook_dropin_restore || { warn "撤回 sshd drop-in 失败,保留状态"; return 1; } + fi + motd_login_hook_pam_remove_line || { warn "撤回 PAM hook 行失败,保留状态"; return 1; } + sshd -t || warn "回滚后 sshd -t 仍失败,需人工检查" + rm -f -- "$(motd_login_hook_state_path marker)" 2>/dev/null || true + rmdir -- "$MOTD_LOGIN_STATE_DIR" 2>/dev/null || true + return 0 +} + +# 回滚先恢复英文并 reload 成功,再撤 PAM 行;任一步失败保留状态供重试,不报完成。 +# english.pending 标记英文已写回磁盘但尚未重载成功,重试时必须先补这次 reload, +# 否则会在活服务仍是中文配置时直接摘掉 PAM 行。 +motd_login_hook_restore() { + local english_pending + motd_login_hook_is_managed || return 0 + motd_login_cleanup_residue || { warn "存在不可信的登录 hook 临时残留,停止恢复"; return 1; } + english_pending=$(motd_login_hook_state_path english.pending) + if [[ -f "$english_pending" ]]; then + if ! motd_login_hook_reload_restored; then + warn "英文提示已写回磁盘但 sshd 重载仍失败,保留 PAM hook 以便重试" + return 1 + fi + rm -f -- "$english_pending" || return 1 + elif motd_login_hook_dropin_present || [[ -e "$MOTD_LOGIN_DROPIN" ]]; then + # drop-in 路径由本工具独占创建;即使管理员删了标记行,也只剥离精确匹配的三行。 + motd_login_hook_dropin_restore || { warn "恢复 sshd drop-in 失败,保留 PAM hook 以便重试"; return 1; } + : > "$english_pending" || return 1 + chmod 0600 "$english_pending" || return 1 + if ! motd_login_hook_reload_restored; then + warn "恢复英文提示后 sshd 重载失败,保留 PAM hook 以便重试" + return 1 + fi + rm -f -- "$english_pending" || return 1 + fi + motd_login_hook_pam_remove_line || { warn "移除 PAM hook 行失败,保留状态以便重试"; return 1; } + rm -f -- "$english_pending" "$(motd_login_hook_state_path marker)" 2>/dev/null || true + rmdir -- "$MOTD_LOGIN_STATE_DIR" 2>/dev/null || true + success "中文上次登录: 已恢复(原英文提示已重载生效)" +} + motd_install_group() { info "配置动态欢迎信息..." motd_run_locked_operation install || return $? @@ -1738,32 +2086,127 @@ motd_columns() { } COLS=$(motd_columns) +motd_mode="${1:-}" +case "$motd_mode" in + ""|--last-login) ;; + *) printf 'usage: %s [--last-login]\n' "${0##*/}" >&2; exit 2 ;; +esac + hostname_value=$(hostname 2>/dev/null) +is_ipv4_address() { + local value="$1" octet + local IFS=. + local -a octets=() + [[ "$value" =~ ^[0-9]{1,3}(\.[0-9]{1,3}){3}$ ]] || return 1 + read -r -a octets <<< "$value" + (( ${#octets[@]} == 4 )) || return 1 + for octet in "${octets[@]}"; do + [[ "$octet" =~ ^(0|[1-9][0-9]{0,2})$ ]] || return 1 + (( 10#$octet <= 255 )) || return 1 + done +} + +is_ipv6_address() { + local value="$1" + [[ "$value" == *:* && ${#value} -le 45 ]] || return 1 + [[ "$value" =~ ^[0-9A-Fa-f:.]+$ ]] || return 1 + [[ "$value" =~ [0-9A-Fa-f] ]] || return 1 + [[ "$value" != *:::* ]] || return 1 +} + +is_hostname() { + local value="$1" + (( ${#value} >= 1 && ${#value} <= 255 )) || return 1 + [[ "$value" =~ ^[A-Za-z0-9]([A-Za-z0-9._-]*[A-Za-z0-9])?$ ]] +} + +# 把 lslogins 的时间规范成服务器本地 YYYY-MM-DD HH:MM:SS,并校验分量范围。 +login_normalize_time() { + local raw="$1" + local year month day hour minute second + [[ "$raw" =~ ^([0-9]{4})-([0-9]{2})-([0-9]{2})[T[:space:]]([0-9]{2}):([0-9]{2}):([0-9]{2}) ]] || return 1 + year=${BASH_REMATCH[1]}; month=${BASH_REMATCH[2]}; day=${BASH_REMATCH[3]} + hour=${BASH_REMATCH[4]}; minute=${BASH_REMATCH[5]}; second=${BASH_REMATCH[6]} + (( 10#$month >= 1 && 10#$month <= 12 )) || return 1 + (( 10#$day >= 1 && 10#$day <= 31 )) || return 1 + (( 10#$hour <= 23 && 10#$minute <= 59 && 10#$second <= 60 )) || return 1 + printf '%s-%s-%s %s:%s:%s' "$year" "$month" "$day" "$hour" "$minute" "$second" +} + +# 只读上一笔登录:全空 wtmp/btmp、legacy lastlog,避免把本次连接当历史。 +# util-linux 2.41 起 --lastlog 有歧义,优先 --lastlog-file;更早版本回退 --lastlog。 +login_query() { + local user="$1" output + command -v lslogins >/dev/null 2>&1 || return 1 + [[ -n "$user" ]] || return 1 + [[ "$user" =~ ^[A-Za-z0-9._][A-Za-z0-9._-]{0,63}$ ]] || return 1 + for output in \ + "--wtmp-file /dev/null --lastlog-file /var/log/lastlog --lastlog2-file /dev/null" \ + "--wtmp-file /dev/null --lastlog /var/log/lastlog"; do + local -a base_args=() + read -r -a base_args <<< "$output" + local result + result=$(LC_ALL=C lslogins "${base_args[@]}" --time-format iso --raw --noheadings --notruncate \ + --output LAST-LOGIN,LAST-HOSTNAME --logins "$user" 2>/dev/null) || continue + [[ -n "${result//[[:space:]]/}" ]] || continue + printf '%s\n' "$result" + return 0 + done + return 1 +} + +render_last_login() { + local user="${PAM_USER:-}" raw time host kind + raw=$(login_query "$user") || return 0 + time=$(login_normalize_time "${raw%%[[:space:]]*}") || return 0 + host="${raw#"${raw%%[[:space:]]*}"}" + host="${host#"${host%%[![:space:]]*}"}" + host="${host%"${host##*[![:space:]]}"}" + print_row 10 " ${LABEL}上次登录${FG_RESET} " "${TEXT}|${time}" + if is_ipv4_address "$host" || is_ipv6_address "$host"; then + kind=ip + elif is_hostname "$host"; then + kind=host + else + kind="" + fi + case "$kind" in + ip) print_row 10 " ${LABEL}来源 IP${FG_RESET} " "${LOGIN_SOURCE}|${host}" ;; + host) print_row 10 " ${LABEL}来源${FG_RESET} " "${LOGIN_SOURCE}|${host}" ;; + esac +} [[ -n "$hostname_value" ]] || hostname_value=$(uname -n) kernel=$(uname -r) architecture=$(uname -m) +# 运行时长按“数字/单位”切成无颜色片段,配色在下方颜色变量就绪后再套用; +# 拼接结果与旧版纯文本逐字节相同。 +uptime_parts=() uptime_seconds=$(awk '{printf "%d", $1}' /proc/uptime 2>/dev/null) if [[ -n "$uptime_seconds" ]]; then - uptime_value=$(awk -v total="$uptime_seconds" 'BEGIN { + while IFS=$'\t' read -r uptime_kind uptime_text; do + uptime_parts+=("${uptime_kind}|${uptime_text}") + done < <(awk -v total="$uptime_seconds" 'BEGIN { days=int(total/86400) hours=int(total%86400/3600) minutes=int(total%3600/60) if (days > 0) { - if (hours > 0) printf "%d 天 %d 小时", days, hours - else printf "%d 天", days + printf "number\t%d\nunit\t 天\n", days + if (hours > 0) printf "number\t %d\nunit\t 小时\n", hours } else if (hours > 0) { - printf "%d 小时 %d 分", hours, minutes + printf "number\t%d\nunit\t 小时\nnumber\t %d\nunit\t 分\n", hours, minutes } else if (minutes > 0) { - printf "%d 分", minutes + printf "number\t%d\nunit\t 分\n", minutes } else { - printf "不到 1 分" + printf "unit\t不到 1 分\n" } }') else uptime_value=$(uptime 2>/dev/null | sed -E 's/.*up[[:space:]]+//; s/,[[:space:]]+[0-9]+ user.*//') + [[ -n "$uptime_value" ]] || uptime_value=- + uptime_parts=("unit|${uptime_value}") fi -[[ -n "$uptime_value" ]] || uptime_value=- +(( ${#uptime_parts[@]} > 0 )) || uptime_parts=("unit|-") # 发行版:优先 os-release 的 NAME/VERSION_ID,其次 PRETTY_NAME,最后内核名。 system_value=$(awk -F= ' @@ -1846,30 +2289,44 @@ fi ESC=$'\033' if [[ -n "${NO_COLOR+x}" || "${TERM:-}" == dumb ]]; then RESET=""; FG_RESET=""; TEXT=""; LABEL=""; DIM=""; HOST=""; RULE="" - SYSTEM=""; DOT=""; CPU=""; ARCH=""; UPTIME=""; LOAD=""; TRACK="" - SECTION=""; BOLD=""; GREEN=""; YELLOW=""; RED="" + SYSTEM=""; CPU=""; ARCH=""; UPTIME=""; UPTIME_ACCENT=""; LOAD=""; TRACK="" + KERNEL=""; LOGIN_SOURCE="" + SECTION=""; BOLD=""; UNBOLD=""; GREEN=""; YELLOW=""; RED="" else RESET="${ESC}[0m" FG_RESET="${ESC}[39m" TEXT="${ESC}[38;2;248;248;242m" LABEL="${ESC}[38;2;168;181;217m" DIM="${ESC}[38;2;183;191;219m" - HOST="${ESC}[38;2;139;233;253m" + HOST="${ESC}[38;2;71;220;200m" RULE="${ESC}[38;2;130;183;255m" - SYSTEM="${ESC}[38;2;166;227;161m" - DOT="${ESC}[38;2;166;227;161m" + SYSTEM="${ESC}[38;2;255;142;158m" CPU="${ESC}[38;2;255;184;108m" - ARCH="${ESC}[38;2;214;172;255m" + ARCH="${ESC}[38;2;163;178;196m" UPTIME="${ESC}[38;2;186;194;222m" - LOAD="${ESC}[38;2;137;220;235m" + UPTIME_ACCENT="${ESC}[38;2;109;255;187m" + LOAD="${ESC}[38;2;36;240;208m" + KERNEL="${ESC}[38;2;255;147;77m" + LOGIN_SOURCE="${ESC}[38;2;255;121;198m" TRACK="${ESC}[38;2;83;91;120m" SECTION="${ESC}[38;2;98;114;164m" BOLD="${ESC}[1m" + UNBOLD="${ESC}[22m" GREEN="${ESC}[38;2;80;250;123m" YELLOW="${ESC}[38;2;241;250;140m" RED="${ESC}[38;5;203m" fi +# 运行时长:数字用强调色加粗,单位沿用灰蓝且显式退出粗体,避免继承前缀的字重。 +uptime_segments=() +for uptime_part in "${uptime_parts[@]}"; do + case "${uptime_part%%|*}" in + number) uptime_segments+=("${UPTIME_ACCENT}${BOLD}|${uptime_part#*|}") ;; + *) uptime_segments+=("${UNBOLD}${UPTIME}|${uptime_part#*|}") ;; + esac +done +unset uptime_part + BAR_CELLS=6 # 窄终端放不下占用条:先保证文字不折行,再考虑图形。 (( COLS >= 40 )) || BAR_CELLS=0 @@ -2029,6 +2486,12 @@ print_row() { printf '%s\n' "$RESET" } +# --last-login 只输出登录历史行,欢迎面板仍由 run-parts 无参模式生成并写入 /run/motd.dynamic。 +if [[ "$motd_mode" == "--last-login" ]]; then + render_last_login + exit 0 +fi + load_average=$(awk '{printf "%.2f / %.2f / %.2f", $1, $2, $3}' /proc/loadavg 2>/dev/null) [[ -n "$load_average" ]] || load_average=- @@ -2085,13 +2548,13 @@ printf '\n' print_row 11 "${RULE}│${RESET} ${BOLD}${TEXT}欢迎登录 " "${HOST}|${hostname_value}" print_row 2 "${RULE}│${RESET} " "${DIM}|今天想做点什么?" printf '%s%s%s\n' "$SECTION" "$hero_rule" "$RESET" -print_row 7 " ${LABEL}系统${FG_RESET} " "${SYSTEM}|${system_value}" "${DOT}| ●" -print_row 7 " ${LABEL}运行${FG_RESET} " "${UPTIME}|${uptime_value}" +print_row 7 " ${LABEL}系统${FG_RESET} " "${SYSTEM}${BOLD}|${system_value}" +print_row 7 " ${LABEL}运行${FG_RESET} " "${uptime_segments[@]}" print_row 7 " ${LABEL}CPU${FG_RESET} " "${CPU}|${cpu_model}" "${TEXT}|${cpu_count_text}" print_row 7 " ${LABEL}负载${FG_RESET} " "${LOAD}|${load_average}" print_row 7 " ${LABEL}内存${FG_RESET} " "${memory_segments[@]}" print_row 7 " ${LABEL}根盘${FG_RESET} " "${disk_segments[@]}" -print_row 7 " ${LABEL}内核${FG_RESET} " "${TEXT}|${kernel}" "${ARCH}|(${architecture})" +print_row 7 " ${LABEL}内核${FG_RESET} " "${KERNEL}${BOLD}|${kernel}" "${UNBOLD}${ARCH}|(${architecture})" SCRIPT }