翼度科技»论坛 编程开发 python 查看内容

为ssh服务器添加2fa认证,一个python脚本全搞定

3

主题

3

帖子

9

积分

新手上路

Rank: 1

积分
9
服务器ssh如果被别人登陆就是一场灾难,所以我研究了ssh认证,我发现Google Authenticator PAM可以实现ssh的2fa认证,但是安装和配置比较麻烦。因此我用python实现了ssh的2fa认证。考虑到很多Linux服务器默认安装python,所以我用py脚本,并只使用标准库,不需要安装第三方py库,方便部署。

  • 首先保存如下脚本到文件:/bin/login,设置执行权限:chmod +x /bin/login,记得修改TOTP_SECRET密钥
[code]#!/bin/env pythonimport osimport sysimport signalimport getpassimport subprocessimport hmacimport timeimport base64import hashlib# 随机生成长度为16的全大写字符串作为2fa的密钥TOTP_SECRET = 'KHGSRAEPVAFPPAGX'try:    def gen_totp(secret: str, input=int(time.time()/30), digits=6):        if (missing_padding := len(secret) % 8) != 0:            secret += "=" * (8 - missing_padding)        byte_secret = base64.b32decode(secret, casefold=True)        result = bytearray()        while input != 0:            result.append(input & 0xFF)            input >>= 8        byte_input = bytes(bytearray(reversed(result)).rjust(8, b"\0"))        hasher = hmac.new(byte_secret, byte_input, hashlib.sha1)        hmac_hash = bytearray(hasher.digest())        offset = hmac_hash[-1] & 0xF        code = ((hmac_hash[offset] & 0x7F)

举报 回复 使用道具