-
Notifications
You must be signed in to change notification settings - Fork 6
/
x509.go
54 lines (49 loc) · 1.3 KB
/
x509.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package daemonauth
import (
"crypto/x509"
"encoding/pem"
"fmt"
"os"
"github.com/shaj13/go-guardian/v2/auth"
x509Strategy "github.com/shaj13/go-guardian/v2/auth/strategies/x509"
)
type (
// X509CACertFiler is the interface for X509CACertFile method for x509 auth.
X509CACertFiler interface {
X509CACertFile() string
}
)
func initX509(i interface{}) (string, auth.Strategy, error) {
name := "x509"
caFiler, ok := i.(X509CACertFiler)
if !ok {
return name, nil, fmt.Errorf("missing ca certificates")
}
caCertsFile := caFiler.X509CACertFile()
cert, err := x509CertificateFromFile(caCertsFile)
if err != nil {
return name, nil, fmt.Errorf("initX509 retrieve cert from file %s: %w", caCertsFile, err)
}
roots := x509.NewCertPool()
roots.AddCert(cert)
opts := x509.VerifyOptions{
KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
Roots: roots,
}
return name, x509Strategy.New(opts), nil
}
func x509CertificateFromFile(s string) (*x509.Certificate, error) {
ca, err := os.ReadFile(s)
if err != nil {
return nil, fmt.Errorf("read file: %w", err)
}
p, _ := pem.Decode(ca)
if p == nil {
return nil, fmt.Errorf("pem decode: %w", err)
}
cert, err := x509.ParseCertificate(p.Bytes)
if err != nil {
return nil, fmt.Errorf("x509 parse certificate: %w", err)
}
return cert, nil
}