-
Notifications
You must be signed in to change notification settings - Fork 1
/
ca.go
235 lines (209 loc) · 6.74 KB
/
ca.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
// Package tinyca implements a Certificate Authority that issues certificates
// for client authentication.
package tinyca
import (
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"fmt"
"io"
"log/slog"
"math"
"math/big"
"net/http"
"time"
"github.com/RealImage/bifrost"
"github.com/RealImage/bifrost/internal/webapp"
"github.com/RealImage/bifrost/web"
"github.com/VictoriaMetrics/metrics"
"github.com/google/uuid"
)
// CA is a simple Certificate Authority.
// The only supported operation is to issue client certificates.
// Client certificates are signed by the configured root certificate and private key.
type CA struct {
cert *bifrost.Certificate
key *bifrost.PrivateKey
// metrics
issuedTotal *metrics.Counter
requestsTotal *metrics.Counter
requestsDuration *metrics.Histogram
}
// New returns a new CA.
// The CA issues certificates for the given namespace.
func New(cert *bifrost.Certificate, key *bifrost.PrivateKey) (*CA, error) {
iss := bfMetricName("issued_certs_total", cert.Namespace)
rt := bfMetricName("requests_total", cert.Namespace)
rd := bfMetricName("requests_duration_seconds", cert.Namespace)
return &CA{
cert: cert,
key: key,
issuedTotal: bifrost.StatsForNerds.NewCounter(iss),
requestsTotal: bifrost.StatsForNerds.NewCounter(rt),
requestsDuration: bifrost.StatsForNerds.NewHistogram(rd),
}, nil
}
func bfMetricName(name string, ns uuid.UUID) string {
return fmt.Sprintf(`bifrost_ca_%s{ns="%s"}`, name, ns)
}
// ServeHTTP issues a certificate if a valid certificate request is read from the request.
//
// Requests carrying a content-type of "text/plain" should have a PEM encoded certificate request.
// Requests carrying a content-type of "application/octet-stream" should submit the ASN.1 DER
// encoded form instead.
func (ca CA) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ca.requestsTotal.Inc()
startTime := time.Now()
notBefore := time.Now()
if nb := r.URL.Query().Get("not-before"); nb != "" {
var err error
if notBefore, err = time.Parse(time.RFC3339, nb); err != nil {
http.Error(w, "invalid not-before query parameter", http.StatusBadRequest)
return
}
}
notAfter := notBefore.AddDate(0, 0, 1)
if na := r.URL.Query().Get("not-after"); na != "" {
var err error
if notAfter, err = time.Parse(time.RFC3339, na); err != nil {
http.Error(w, "invalid not-after query parameter", http.StatusBadRequest)
return
}
}
contentType, _, err := webapp.GetContentType(r.Header, webapp.MimeTypeText)
if err != nil {
e := fmt.Sprintf("error parsing Content-Type header: %s", err)
http.Error(w, e, http.StatusBadRequest)
return
}
if ct := contentType; ct != webapp.MimeTypeText && ct != webapp.MimeTypeBytes {
msg := fmt.Sprintf("unsupported Content-Type %s", ct)
http.Error(w, msg, http.StatusUnsupportedMediaType)
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
csr, err := readCsr(contentType, body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
template := &x509.Certificate{
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
NotBefore: notBefore,
NotAfter: notAfter,
}
cert, err := ca.IssueCertificate(csr, template)
if err != nil {
statusCode := http.StatusInternalServerError
if errors.Is(err, bifrost.ErrCertificateRequestInvalid) {
statusCode = http.StatusBadRequest
}
if errors.Is(err, bifrost.ErrNamespaceMismatch) {
statusCode = http.StatusForbidden
}
http.Error(w, err.Error(), statusCode)
return
}
responseType, err := webapp.GetResponseMimeType(
r.Header,
contentType,
webapp.MimeTypeText,
webapp.MimeTypeBytes,
webapp.MimeTypeHtml,
)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
switch responseType {
case webapp.MimeTypeAll, webapp.MimeTypeText:
w.Header().Set(webapp.HeaderNameContentType, webapp.MimeTypeTextCharset)
err = pem.Encode(w, &pem.Block{Type: "CERTIFICATE", Bytes: cert})
case webapp.MimeTypeBytes:
w.Header().Set(webapp.HeaderNameContentType, webapp.MimeTypeBytes)
_, err = w.Write(cert)
case webapp.MimeTypeHtml:
w.Header().Set(webapp.HeaderNameContentType, webapp.MimeTypeHtmlCharset)
certPem := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert})
data := map[string]any{"certPem": string(certPem)}
err = web.Templates.ExecuteTemplate(w, "certificate.html", data)
default:
msg := fmt.Sprintf("media type %s unacceptable", responseType)
http.Error(w, msg, http.StatusNotAcceptable)
return
}
if err != nil {
slog.Error("error writing certificate response", "err", err)
}
ca.requestsDuration.Update(time.Since(startTime).Seconds())
}
func readCsr(contentType string, body []byte) ([]byte, error) {
asn1Data := body
switch contentType {
case webapp.MimeTypeBytes:
// DER encoded
case "", webapp.MimeTypeText:
// PEM
block, _ := pem.Decode(body)
if block == nil {
return nil, fmt.Errorf("bifrost: error decoding certificate request PEM block")
}
asn1Data = block.Bytes
}
return asn1Data, nil
}
// IssueCertificate issues a client certificate for a certificate request.
// The certificate is issued with the Subject Common Name set to the
// UUID of the client public key and the Subject Organization
// set to the identity namespace UUID.
func (ca CA) IssueCertificate(asn1CSR []byte, template *x509.Certificate) ([]byte, error) {
csr, err := bifrost.ParseCertificateRequest(asn1CSR)
if err != nil {
return nil, err
}
if csr.Namespace != ca.cert.Namespace {
return nil, bifrost.ErrNamespaceMismatch
}
if t := template; t.NotBefore.IsZero() || t.NotAfter.IsZero() ||
t.NotAfter.Before(t.NotBefore) {
return nil, fmt.Errorf(
"bifrost: %w invalid validity period",
bifrost.ErrCertificateRequestInvalid,
)
}
serialNumber, err := rand.Int(rand.Reader, big.NewInt(int64(math.MaxInt64)))
if err != nil {
return nil, fmt.Errorf("bifrost: unexpected error generating certificate serial: %w", err)
}
// Override the fields we care about.
template.SerialNumber = serialNumber
template.SignatureAlgorithm = bifrost.SignatureAlgorithm
template.PublicKeyAlgorithm = bifrost.PublicKeyAlgorithm
template.Issuer = ca.cert.Issuer
template.Subject = pkix.Name{
Organization: []string{ca.cert.Namespace.String()},
CommonName: csr.PublicKey.UUID(ca.cert.Namespace).String(),
}
template.PublicKey = csr.PublicKey.PublicKey
template.Signature = csr.Signature
template.BasicConstraintsValid = true
certBytes, err := x509.CreateCertificate(
rand.Reader,
template,
ca.cert.Certificate,
csr.PublicKey.PublicKey,
ca.key,
)
if err != nil {
return nil, err
}
ca.issuedTotal.Inc()
return certBytes, nil
}