Debian Codegraph @

internal/authmodel/certificate.go

raw symbols SCIP
1 package authmodel
2
3 import (
4 "crypto/sha256"
5 "crypto/x509"
6 "encoding/hex"
7 "net/http"
8
9 "github.com/rs/zerolog"
10 "github.com/sassoftware/relic/v7/config"
11 "github.com/sassoftware/relic/v7/internal/httperror"
12 "github.com/sassoftware/relic/v7/internal/realip"
13 "github.com/sassoftware/relic/v7/internal/zhttp"
14 "github.com/sassoftware/relic/v7/lib/audit"
15 "github.com/sassoftware/relic/v7/lib/x509tools"
16 )
17
18 // CertificateAuth requires all callers have a client certificate that either
19 // has its fingerprint explicitly configured with access, or is signed by a
20 // configured CA.
21 type CertificateAuth struct {
22 Config *config.Config
23 }
24
25 func (a *CertificateAuth) Authenticate(req *http.Request) (UserInfo, error) {
26 peerCerts, err := realip.PeerCertificates(req)
27 if err != nil {
28 return nil, err
29 } else if len(peerCerts) == 0 {
30 return nil, httperror.ErrCertificateRequired
31 }
32 cert := peerCerts[0]
33 encoded := fingerprint(cert)
34 var useDN bool
35 var saved error
36 client := a.Config.Clients[encoded]
37 if client == nil {
38 for _, c2 := range a.Config.Clients {
39 match, err := c2.Match(peerCerts)
40 if match {
41 client = c2
42 useDN = true
43 break
44 } else if err != nil {
45 // preserve any potentially interesting validation errors
46 saved = err
47 }
48 }
49 }
50 if client == nil {
51 zhttp.AppendAccessLog(req, func(e *zerolog.Event) {
52 e.Str("fingerprint", encoded)
53 e.Str("subject", formatSubject(cert))
54 if saved != nil {
55 e.AnErr("validation_error", saved)
56 }
57 })
58 return nil, httperror.ErrCertificateNotRecognized
59 }
60
61 user := &CertificateInfo{
62 Name: client.Nickname,
63 Roles: client.Roles,
64 }
65 if user.Name == "" {
66 user.Name = encoded[:12]
67 }
68 if useDN {
69 user.Subject = formatSubject(cert)
70 }
71 // amend access log with user info
72 zhttp.AppendAccessLog(req, func(e *zerolog.Event) {
73 e.Str("user", user.Name)
74 if user.Subject != "" {
75 e.Str("subject", user.Subject)
76 }
77 })
78 return user, nil
79 }
80
81 type CertificateInfo struct {
82 Name string
83 Subject string
84 Roles []string
85 }
86
87 func (c *CertificateInfo) AuditContext(info *audit.Info) {
88 info.Attributes["client.name"] = c.Name
89 if c.Subject != "" {
90 info.Attributes["client.dn"] = c.Subject
91 }
92 }
93
94 func (c *CertificateInfo) Allowed(keyConf *config.KeyConfig) bool {
95 for _, keyRole := range keyConf.Roles {
96 for _, clientRole := range c.Roles {
97 if keyRole == clientRole {
98 return true
99 }
100 }
101 }
102 return false
103 }
104
105 func fingerprint(cert *x509.Certificate) string {
106 digest := sha256.Sum256(cert.RawSubjectPublicKeyInfo)
107 return hex.EncodeToString(digest[:])
108 }
109
110 func formatSubject(cert *x509.Certificate) string {
111 return x509tools.FormatPkixName(cert.RawSubject, x509tools.NameStyleOpenSsl)
112 }