Github two-step verification 2FA (two-factor) mechanism based on TOTP algorithm Python3.10 implementation

Starting from March this year (2023), Github began to force users to enable two-step verification 2FA (two-factor) login verification. There is no doubt that it is for security reasons. After all, once a Github account is stolen, all The code warehouse will be destroyed. For the necessity of two-factor login, please see: Don’t let your server (vps) become a chicken (ssh brute force cracking), key verification, two-way factor login Worth having.

To put it bluntly, dual-factor login is a measure to prove "you are yourself" through a third-party device. Github officially recommends downloading apps such as 1Password, Authy, and Microsoft Authenticator on the mobile terminal to verify by scanning the QR code. In fact, this is not necessary. Trouble, this time we use Python/Golang code to implement two-factor login verification.

TOTP algorithm

Time-based One-Time Password (TOTP) is a time-based one-time password algorithm used to enhance authentication security.

TOTP generates one-time passwords based on the HMAC (Hash-based Message Authentication Code) algorithm and timestamp. A secret key is shared between the user and the server, usually exchanged when initializing authentication. Based on this key, the server generates an initial value for verification.

At each time step (usually 30 seconds), a hash value is generated using the HMAC algorithm based on the current timestamp and the shared secret. Then, a fixed-length dynamic password is extracted from the hash value. This dynamic password is valid within the set time step and will automatically expire after that.

When authenticating, the user needs to enter the dynamic password generated within the current time step. The server will use the same algorithm and shared secret to verify that the password provided by the user matches. Since the dynamic password will become invalid after the time step expires, even if it is intercepted, it cannot be reused in the next time step.

TOTP is widely used in the implementation of two-factor authentication (2FA) and multi-factor authentication (MFA). By combining the user's password with a dynamic password generated each time, TOTP provides an additional layer of security, effectively reducing the risk of password theft or guessing.

Common TOTP applications include authentication applications such as Google Authenticator and Authy, which generate dynamic passwords based on TOTP algorithms and bind them to users' online accounts to provide a more secure login method.

To put it bluntly, it is a key with a life cycle. This key will expire after 30 seconds. The client and server share a key and verify the legitimacy of the key through the HMAC algorithm.

TOTP algorithm implementation (Python3.10)

First, a key should be generated on the server side, which is shared between the client and the authentication server. The key can be a string, but Github officially changed the key into a QR code to facilitate users to scan the code for verification on the mobile terminal. Open the Github account and select Settings-"Two-step verification:

Click the green button and choose to turn on two-step verification.

At this point, the system will automatically generate a QR code, which is our shared key:

The string form of this key can be obtained by clicking on the setup key hyperlink.

After getting the system key, we install the Python-based TOTP library:

pip3 install pyotp

Then write code to generate the verification code of the current timing:

import pyotp  
import time  
  
# 设置服务端密钥  
secret_key = "Github服务端生成的密钥(即二维码)"  
  
# 使用密钥和时间间隔(默认为 30 秒)创建一个 TOTP 对象  
totp = pyotp.TOTP(secret_key)  
  
# 生成当前的 OTP  
current_otp = totp.now()  
print(f"当前OTP: {current_otp}")

operation result:

python -u "d:\jiyun\积云\boo3_public\test_totp.py"  
当前OTP: 809888

You can see that based on the key, we generated a verification code that is valid within 30 seconds, and then fill in the verification code into the Verify the code from the app text box on the page. It is simple and convenient and does not require the participation of the mobile terminal.

Golang1.21 implements TOTP algorithm

If the client language is Golang, you can also easily implement the TOTP algorithm. First, make sure that Golang1.18 or above is installed on your local machine. Here We are using the latest Golang1.21:

PS C:\Users\zcxey> go version  
go version go1.21.1 windows/amd64

Then install the corresponding totp package through go get:

go get github.com/pquerna/otp  
go get github.com/pquerna/otp/totp

Then write the entry code main.go file:

package main  
  
import (  
	"encoding/base32"  
	"fmt"  
	"time"  
  
	"github.com/pquerna/otp"  
	"github.com/pquerna/otp/totp"  
)  
  
// Demo function, not used in main  
// Generates Passcode using a UTF-8 (not base32) secret and custom parameters  
func GeneratePassCode(utf8string string) string {  
	secret := base32.StdEncoding.EncodeToString([]byte(utf8string))  
	passcode, err := totp.GenerateCodeCustom(secret, time.Now(), totp.ValidateOpts{  
		Period:    30,  
		Skew:      1,  
		Digits:    otp.DigitsSix,  
		Algorithm: otp.AlgorithmSHA512,  
	})  
	if err != nil {  
		panic(err)  
	}  
	return passcode  
}  
  
func main() {  
  
	passcode := GeneratePassCode("Github官方生成的密钥")  
  
	fmt.Print(passcode)  
  
}

Here, the verification code is generated through the GeneratePassCode function. The default validity period is also 30 seconds. The algorithm is based on otp.AlgorithmSHA512.

operation result:

go run "d:\jiyun\积云\boo3_public\main.go"  
692540

Then fill in the verification code into the Verify the code from the app text box on the page. Different from Python, Golang can be run directly on any platform after being compiled directly, which is theoretically much more convenient than Python.

Conclusion

Overall, GitHub's two-factor login provides greater account security, protecting users from unauthorized access and potential data leakage. It is a simple and effective security measure that is worth taking by users to protect their GitHub accounts and related code assets. But having said that, Github officially promotes the paid 1Password software, which should have some interest bindings, but for For those of us who know how to code, this is not a big deal.

Guess you like

Origin blog.csdn.net/zcxey2911/article/details/133417344