在更改配置文件后,都要重启相应的服务

在下文中,默认的 root 用户已经被禁止登录

除非已经确认新的配置生效,否则请永远不要关闭当前 SSH 窗口

使用非对称密钥登录SSH

  1. 生成非对称密钥

    ssh-keygen -t ecdsa -b 521 -C "$(whoami)@$(hostname)-$(date -I)"
  2. 将公钥文件加入 authorized_keys

    # 通过任何方式上传公钥到服务器
    rsync -av /local_path_to/redhat.pub user@remote:/upload_to_path/file_path
    mkdir -p ~/.ssh
    cat ~/.ssh/redhat.pub >> ~/.ssh/authorized_keys
  3. 更改文件夹权限

    chmod 700 ~/
    chmod 700 ~/.ssh
    chmod 600 ~/.ssh/authorized_keys
  4. 使用私钥进行SSH认证

    服务器 sshd_config 文件应设置为允许密钥登陆且允许该用户登录

    由于生成密钥时指定了算法为 ECDSA,所以 sshd 可以不开启 RSAAuthentication

    ssh -i /path/to/key_file user@remote
  5. 禁止使用密码登录

    修改 sshd_config 文件

    sudo vim /etc/ssh/sshd_config

    更改下述属性值

    PasswordAuthentication 选项更改为 no

    ChallengeResponseAuthentication 选项更改为 no

双因素认证

  1. 在此步之前请务必确保公钥登陆方式生效

  2. 安装 Google Authenticator

    sudo dnf install -y google-authenticator
  3. 生成配置文件

    google-authenticator

    此命令会交互式的询问几个问题,简记如下:

    1. Do you want authentication tokens to be time-based (y/n) y
    2. Do you want me to update your "/home/user/.google_authenticator" file (y/n)?y
    3. Do you want to disallow multiple uses of the same authentication token?This restricts you to one login about every 30s, but it increases your chances to notice or even prevent man-in-the-middle attacks (y/n)** y
    4. By default, tokens are good for 30 seconds. In order to compensate for possible time-skew between the client and the server, we allow an extra token before and after the current time. If you experience problems with poor time synchronization, you can increase the window from its default size of +-1min (window size of 3) to about +-4min (window size of 17 acceptable tokens).
      Do you want to do so?(y/n)** n
    5. If the computer that you are logging into isn't hardened against brute-force login attempts, you can enable rate-limiting for the authentication module. By default, this limits attackers to no more than 3 login attempts every 30s.
      Do you want to enable rate-limiting (y/n) y
  4. 编辑 /etc/pam.d/sshd 文件

    sudo vim /etc/pam.d/sshd

    注释如下行

    #auth       substack     password-auth

    文件尾追加如下行

    auth sufficient pam_google_authenticator.so
  5. 编辑 /etc/ssh/sshd_config 文件

    sudo vim /etc/ssh/sshd_config

    更改下述属性值

    ChallengeResponseAuthentication yes
    PasswordAuthentication no

    文件尾追加如下行

    AuthenticationMethods publickey,password publickey,keyboard-interactive
  6. 重启 sshd

    sudo systemctl restart sshd

标签: none

添加新评论