Golang实现更安全的HTTP基本认证(Basic Authentication)

当搜索使用Go的HTTP基本身份验证示例时,我能找到的每个结果都不幸包含了过时的代码(即不使用Go1.4中引入的r.BasicAuth()功能)或不能防止定时攻击。本文介绍如何实现更安全的HTTP基本认证代码。

了解基本认证

你一定遇到,当通过浏览器访问一些URL时提示输入用户名和密码。再你输入用户名和密码后,浏览器发送包含Authorization头信息的HTTP请求至服务端,类似这样:

Authorization: Basic YWxpY2U6cGE1NXdvcmQ=

Authorization头信息包括值为:Basic,后面跟上username:password 格式的用户名和密码的base64编码值,上面示例内容为alice:pa55word的编码值。

当服务端接收到该请求,从Authorization头信息中解码出用户和密码,然后比较是否有效。如果凭证不正确返回401 Unauthorized响应,然后浏览器重新返回提示输入用户名和密码。

基本认证可用于多种场景,但想要快速简单地保护低价值资源不受窥探时,它通常非常适合。为了更安全包含资源,还应该需要下列几种措施:

  • 使用HTTPS连接。如果不使用HTTPS,Authorization头信息可能被攻击者截获并解码,从使用凭证获取受保护资源。
  • 使用强密码。强密码含难被攻击者猜到或暴力破解。
  • 增加频率限制。避免攻击者采用暴力破解方式进行攻击。

另外,大多数编程语言和命令行工具(如curl和wget)以及web浏览器都支持基本的身份验证。

保护WEB应用

最简单保护应用的方式是创建一些中间件,主要实现三个方面内容:

  • 如果存在Authorization头信息,从中抽取用户名和密码。最简单可以通过Go1.4引入的r.BasicAuth() 方法实现。
  • 与期望正确的用户名和密码进行比较。为了避免时间攻击风险,应该使用subtle.ConstantTimeCompare()进行比较。

大多数语言使用==比较符两个字符串是否相等,如果第一个字符不同则直接返回。理论上这存在时间攻击的机会,对于大量请求比较平均响应时间的差异,从而猜测有多少字符已经正确,通过不断增加尝试次数,就可能获得正确的用户名和密码。为了避免时间攻击,我们使用subtle.ConstantTimeCompare()方法进行比较。

  • 如果用户名和密码不正确或请求不包含Authorization头信息,中间件应该发送401 Unauthorized响应并设置WWW-Authenticate头,通知客户端应该使用基本认证进行访问。否则中间件应该容许请求被处理并调用下一个处理器。

根据上面的阐述,中间件实现代码类似下面代码:

func basicAuth(next http.HandlerFunc) http.HandlerFunc {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // 从请求头中出去用户和密码,如果认证请求头不存在或值无效,则ok为false
		username, password, ok := r.BasicAuth()
		if ok {
            // SHA-256算法计算用户名和密码
			usernameHash := sha256.Sum256([]byte(username))
			passwordHash := sha256.Sum256([]byte(password))
			expectedUsernameHash := sha256.Sum256([]byte("your expected username"))
			expectedPasswordHash := sha256.Sum256([]byte("your expected password"))


            // subtle.ConstantTimeCompare() 函数检查用户名和密码,相等返回1,否则返回0;
            // 重要的是先进行hash使得两者长度相等,从而避免泄露信息。
			usernameMatch := (subtle.ConstantTimeCompare(usernameHash[:], expectedUsernameHash[:]) == 1)
			passwordMatch := (subtle.ConstantTimeCompare(passwordHash[:], expectedPasswordHash[:]) == 1)

            // 如果比较结果正确,调用下一个处理器。
            // 最后调用return,为了让后面代码不被执行
			if usernameMatch && passwordMatch {
				next.ServeHTTP(w, r)
				return
			}
		}

        // If the Authentication header is not present, is invalid, or the
        // username or password is wrong, then set a WWW-Authenticate 
        // header to inform the client that we expect them to use basic
        // authentication and send a 401 Unauthorized response.
        // 如果认证头不存在或无效,亦或凭证不正确,
        // 则需要设置WWW-Authenticate头信息并发送401未认证响应,为了通知客户端使用基本认证
		w.Header().Set("WWW-Authenticate", `Basic realm="restricted", charset="UTF-8"`)
		http.Error(w, "Unauthorized", http.StatusUnauthorized)
	})
}

上面代码使用sha256对用户名和密码进行哈希,并不是为了存储,而是为了获得等长字符串,使得比较时间为常量,降低碰撞风险。

您可能想问这里的realm是什么,以及为什么我们在WWW-Authenticate响应标头中将其设置为“restricted”。realm值用于创建应用中受保护的空间。举例,应用有文档域或管理域,分别需要不同的凭证。web浏览器会针对相同域的用户名和密码进行缓存,避免每次请求都需要提示认证。

如果应用不需要多个域,可以设置realm值为固定值restricted。为了安全性和灵活性,一般将预期用户名和密码值存储在环境变量中,或者在启动应用程序时将它们作为命令行标志值传入,而不是将它们硬编码到应用程序中。

完整示例

下面看一个小型、功能完整的WEB应用示例。创建目录,然后增加main.go文件,初始化模块并使用mkcert工具创建本地信任证书:

$:~/gowork$ mkdir basic-auth-example            
$:~/gowork$ cd basic-auth-example/
$:~/gowork/basic-auth-example$ touch main.go
$:~/gowork/basic-auth-example$ go mod init basic-auth-example
go: creating new go.mod: module basic-auth-example
go: to add module requirements and sums:
	go mod tidy
$:~/gowork/basic-auth-example$ mkcert localhost
Note: the local CA is not installed in the system trust store.
Note: the local CA is not installed in the Firefox and/or Chrome/Chromium trust store.
Run "mkcert -install" for certificates to be trusted automatically ⚠️

Created a new certificate valid for the following names 📜
 - "localhost"

The certificate is at "./localhost.pem" and the key at "./localhost-key.pem" ✅

It will expire on 10 July 2025 🗓

$:~/gowork/basic-auth-example$ ls
go.mod  localhost-key.pem  localhost.pem  main.go

在main.go文件增加下面代码,期望的用户名和密码从环境变量中获取,和前文描述内容一致,使用中间件方式进行基本认证。

package main

import (
	"crypto/sha256"
	"crypto/subtle"
	"fmt"
	"log"
	"net/http"
	"os"
	"time"
)

type application struct {
	auth struct {
		username string
		password string
	}
}

func main() {
	app := new(application)

	// 从环境变量获取期望用户名和密码
	app.auth.username = os.Getenv("AUTH_USERNAME")
	app.auth.password = os.Getenv("AUTH_PASSWORD")

	if app.auth.username == "" {
		log.Fatal("basic auth username must be provided")
	}

	if app.auth.password == "" {
		log.Fatal("basic auth password must be provided")
	}

	// 创建HTTP服务器
	mux := http.NewServeMux()
	mux.HandleFunc("/unprotected", app.unprotectedHandler)
	mux.HandleFunc("/protected", app.basicAuth(app.protectedHandler))

	srv := &http.Server{
		Addr:         ":4000",
		Handler:      mux,
		IdleTimeout:  time.Minute,
		ReadTimeout:  10 * time.Second,
		WriteTimeout: 30 * time.Second,
	}

	log.Printf("starting server on %s", srv.Addr)
	err := srv.ListenAndServeTLS("./localhost.pem", "./localhost-key.pem")
	log.Fatal(err)
}

// 保护资源处理器
func (app *application) protectedHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "This is the protected handler")
}

// 未保护资源处理器
func (app *application) unprotectedHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "This is the unprotected handler")
}

// 基本认证中间件模式
func (app *application) basicAuth(next http.HandlerFunc) http.HandlerFunc {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		username, password, ok := r.BasicAuth()
		if ok {
			usernameHash := sha256.Sum256([]byte(username))
			passwordHash := sha256.Sum256([]byte(password))
			expectedUsernameHash := sha256.Sum256([]byte(app.auth.username))
			expectedPasswordHash := sha256.Sum256([]byte(app.auth.password))

			usernameMatch := (subtle.ConstantTimeCompare(usernameHash[:], expectedUsernameHash[:]) == 1)
			passwordMatch := (subtle.ConstantTimeCompare(passwordHash[:], expectedPasswordHash[:]) == 1)

			if usernameMatch && passwordMatch {
				next.ServeHTTP(w, r)
				return
			}
		}

		w.Header().Set("WWW-Authenticate", `Basic realm="restricted", charset="UTF-8"`)
		http.Error(w, "Unauthorized", http.StatusUnauthorized)
	})
}

现状使用临时一对环境变量启动应用:

AUTH_USERNAME=alice AUTH_PASSWORD=p8fnxeqj5a7zbrqp go run .
2023/04/10 11:38:00 starting server on :4000

curl访问

这时访问url:https://localhost:4000/protected,浏览器弹出提示认证表单。当然我们也可以通过curl验证认证是否正常工作。

$:~/Downloads$ curl -i https://localhost:4000/unprotected -k
HTTP/2 200 
content-type: text/plain; charset=utf-8
content-length: 32
date: Mon, 10 Apr 2023 05:42:52 GMT

This is the unprotected handler
$:~/Downloads$ curl -i https://localhost:4000/protected -k
HTTP/2 401 
content-type: text/plain; charset=utf-8
www-authenticate: Basic realm="restricted", charset="UTF-8"
x-content-type-options: nosniff
content-length: 13
date: Mon, 10 Apr 2023 05:44:25 GMT

Unauthorized
$:~/Downloads$ curl -i -u alice:p8fnxeqj5a7zbrqp https://localhost:4000/protected -k
HTTP/2 200 
content-type: text/plain; charset=utf-8
content-length: 30
date: Mon, 10 Apr 2023 05:44:47 GMT

This is the protected handler
$:~/Downloads$ curl -i -u alice:wrongPa55word https://localhost:4000/protected -k
HTTP/2 401 
content-type: text/plain; charset=utf-8
www-authenticate: Basic realm="restricted", charset="UTF-8"
x-content-type-options: nosniff
content-length: 13
date: Mon, 10 Apr 2023 05:45:03 GMT

Unauthorized

Go 客户端访问

最后,我们也可以通过go直接访问受保护资源。需要在请求上调用 req.SetBasicAuth("alice", "p8fnxeqj5a7zbrqp") 方法,代码如下:

package main

import (
    "fmt"
    "io"
    "log"
    "net/http"
    "time"
)

func main() {
    client := http.Client{Timeout: 5 * time.Second}

    req, err := http.NewRequest(http.MethodGet, "https://localhost:4000/protected", http.NoBody)
    if err != nil {
        log.Fatal(err)
    }

    req.SetBasicAuth("alice", "p8fnxeqj5a7zbrqp")

    res, err := client.Do(req)
    if err != nil {
        log.Fatal(err)
    }

    defer res.Body.Close()

    resBody, err := io.ReadAll(res.Body)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Status: %dn", res.StatusCode)
    fmt.Printf("Body: %sn", string(resBody))
}    

总结

本文介绍了Go如何实现安全http基本认证,首先介绍原理,后面给出详细实现过程,最后通过curl和GO http客户端进行验证。详细内容参考:https://www.alexedwards.net/blog/basic-authentication-in-go

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇

)">
下一篇>>