基于 Linux SSH + Google Authenticator + Aeroshell 的 双因子认证(2FA)登录方案

124 阅读6分钟

背景与问题分析

在传统的服务器远程访问场景中,SSH(Secure Shell)作为最常用的安全协议之一,被广泛应用于 Linux 系统管理与自动化运维中。 然而,默认的 SSH 登录机制通常仅依赖账户密码或公钥进行身份认证,这种单一认证方式在实际生产环境中已逐渐暴露出安全隐患——一旦密码被暴力破解、钓鱼窃取或公钥文件泄露,攻击者便可直接获得系统访问权限。

随着企业安全合规和零信任架构理念的普及,多因素认证(Multi-Factor Authentication, MFA) 成为了提升系统访问安全的重要手段。 本文将介绍如何在 Linux 环境中,通过整合 SSH 与 Google Authenticator(基于 TOTP 的一次性动态密码算法),构建一种基于 账户密码 + 动态验证码(OTP) 的双因子登录机制,从而在不影响运维效率的前提下,大幅提升远程访问的安全防护能力。

背景与问题分析

在传统的 SSH 登录认证中,主要存在以下安全风险:

密码泄露风险 用户往往重复使用弱密码或相同密码,容易被撞库、暴力破解或钓鱼攻击获取。

密钥泄露与滥用 公钥登录虽然避免了密码暴力破解,但私钥一旦泄露,攻击者仍可无感登录。

缺乏登录行为确认机制 单因素认证无法区分合法用户与被盗凭证的攻击者,缺乏实时验证手段。

合规与审计需求上升 在金融、医疗及政企场景中,安全审计与访问追溯要求越来越严格,传统 SSH 已无法满足双重身份验证要求。

为此,引入 基于 TOTP(Time-based One-Time Password)的一次性验证码机制,可在用户输入密码后,要求额外输入手机端动态验证码,形成 “你知道的(密码) + 你拥有的(设备)” 的双因子安全体系。 这种方式既能与现有 SSH 体系无缝兼容,又能满足安全合规和运维便利性的平衡。

安装Google Authenticator

# Debian / Ubuntu
sudo apt update
sudo apt install libpam-google-authenticator
##由于验证码是基于时间动态生成,所以务必设置ntp服务。
sudo apt install ntpdate -y
sudo ntpdate time.google.com
date
# CentOS / RHEL / Rocky / Alma
sudo yum install google-authenticator -y
sudo yum install ntpdate -y
sudo ntpdate time.google.com
###为当前用户生成密钥
google-authenticator
###会询问如下问题:
Do you want authentication tokens to be time-based (y/n)  → y
Do you want me to update your "/home/xxx/.google_authenticator" file (y/n) → y
Do you want to disallow multiple uses of the same token (y/n) → y
Do you want to increase the default window from 30s to 60s (y/n) → n
Do you want to enable rate-limiting (y/n) → y

安装过程会提示如下的一串key,保存它。 会生成如下一串密钥

服务端配置修改

/etc/pam.d/sshd

# PAM configuration for the Secure Shell service
# Standard Un*x authentication.
@include common-auth


# ✅ 新增:Google Authenticator 验证模块
auth required pam_google_authenticator.so
# ✅ 新增:Google Authenticator 验证模块

# Disallow non-root logins when /etc/nologin exists.
account    required     pam_nologin.so

# Uncomment and edit /etc/security/access.conf if you need to set complex
# access limits that are hard to express in sshd_config.
# account  required     pam_access.so

# Standard Un*x authorization.
@include common-account

# SELinux needs to be the first session rule.  This ensures that any
# lingering context has been cleared.  Without this it is possible that a
# module could execute code in the wrong domain.
session [success=ok ignore=ignore module_unknown=ignore default=bad]        pam_selinux.so close

# Set the loginuid process attribute.
session    required     pam_loginuid.so

# Create a new session keyring.
session    optional     pam_keyinit.so force revoke

# Standard Un*x session setup and teardown.
@include common-session

# Print the message of the day upon successful login.
# This includes a dynamically generated part from /run/motd.dynamic
# and a static (admin-editable) part from /etc/motd.
session    optional     pam_motd.so  motd=/run/motd.dynamic
session    optional     pam_motd.so noupdate

# Print the status of the user's mailbox upon successful login.
session    optional     pam_mail.so standard noenv # [1]

# Set up user limits from /etc/security/limits.conf.
session    required     pam_limits.so

# Read environment variables from /etc/environment and
# /etc/security/pam_env.conf.
session    required     pam_env.so # [1]
# In Debian 4.0 (etch), locale-related environment variables were moved to
# /etc/default/locale, so read that as well.
session    required     pam_env.so user_readenv=1 envfile=/etc/default/locale

# SELinux needs to intervene at login time to ensure that the process starts
# in the proper default security context.  Only sessions which are intended
# to run in the user's context should be run after this.
session [success=ok ignore=ignore module_unknown=ignore default=bad]        pam_selinux.so open

# Standard Un*x password updating.
@include common-password

具体内容参考 如下两个配置,携带✅标记的参数就是默认配置中变动的内容。

/etc/ssh/sshd_config配置


# This is the sshd server system-wide configuration file.  See
# sshd_config(5) for more information.

# This sshd was compiled with PATH=/usr/local/bin:/usr/bin:/bin:/usr/games

# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented.  Uncommented options override the
# default value.

Include /etc/ssh/sshd_config.d/*.conf

#Port 22
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::

#HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_ecdsa_key
#HostKey /etc/ssh/ssh_host_ed25519_key

# Ciphers and keying
#RekeyLimit default none

# Logging
#SyslogFacility AUTH
#LogLevel INFO

# Authentication:

#LoginGraceTime 2m
PermitRootLogin yes
#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10

#PubkeyAuthentication yes

# Expect .ssh/authorized_keys2 to be disregarded by default in future.
#AuthorizedKeysFile     .ssh/authorized_keys .ssh/authorized_keys2

#AuthorizedPrincipalsFile none

#AuthorizedKeysCommand none
#AuthorizedKeysCommandUser nobody

# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes

# To disable tunneled clear text passwords, change to no here!
#PasswordAuthentication yes
#PermitEmptyPasswords no

# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)

# ✅ 新增:开启keyboard交互式认证
KbdInteractiveAuthentication yes
#✅ 新增:开启keyboard交互式认证

# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no

# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes
#GSSAPIStrictAcceptorCheck yes
#GSSAPIKeyExchange no

# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the KbdInteractiveAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via KbdInteractiveAuthentication may bypass
# the setting of "PermitRootLogin prohibit-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and KbdInteractiveAuthentication to 'no'.
UsePAM yes

#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PermitTTY yes
PrintMotd no
#PrintLastLog yes
#TCPKeepAlive yes
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval 0
#ClientAliveCountMax 3
#UseDNS no
#PidFile /run/sshd.pid
#MaxStartups 10:30:100
#PermitTunnel no
#ChrootDirectory none
#VersionAddendum none

# no default banner path
#Banner none

# Allow client to pass locale environment variables
AcceptEnv LANG LC_*

# override default of no subsystems
Subsystem       sftp    /usr/lib/openssh/sftp-server

# Example of overriding settings on a per-user basis
#Match User anoncvs
#       X11Forwarding no
#       AllowTcpForwarding no
#       PermitTTY no
#       ForceCommand cvs server


#AuthenticationMethods  keyboard-interactive
## ✅新增:开启认证方式
AuthenticationMethods password keyboard-interactive

aeroshell客户端

点击添加SSH主机

在这里插入图片描述

选择多因子认证,勾选密码+OTP认证。填入刚刚Google Authenticator的OTP 密钥。其他正常填写即可,保存。 在这里插入图片描述

结束语

至此,我们完成了基于 Linux SSH + Google Authenticator + Aeroshell 的 双因子认证(2FA)登录方案。 通过结合账户密码与一次性动态验证码(OTP),Aeroshell 为服务器远程登录提供了更安全、可视化的多因素认证方式。 这种集成不仅能有效防御暴力破解与密码泄露风险,还能兼容公钥登录场景,帮助运维人员在 Linux、Ubuntu、CentOS 等系统中快速部署安全的 SSH 登录环境。 借助 Aeroshell 智能终端客户端 的图形化配置界面与 2FA 支持,用户无需复杂命令即可轻松启用 MFA 安全登录,让服务器访问更加高效、安全、智能。