-
Notifications
You must be signed in to change notification settings - Fork 1
/
ca.go
261 lines (225 loc) · 7.32 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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
// Package tinyca implements a small and flexible Certificate Authority.
// The CA issues client certificates signed by a root certificate and private key.
//
// tinyca exposes a simple HTTP API to issue certificates.
// tinyca is primarily meant to issue client certificates for mTLS authentication.
//
// The CA also provides an interface to customize the certificate template.
// This allows applications to add application-specific data to issued certificates,
// along with the standard bifrost fields.
package tinyca
import (
"context"
"crypto/rand"
"crypto/x509"
"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 CA issues client certificates signed by a root certificate and private key.
type CA struct {
cert *bifrost.Certificate
key *bifrost.PrivateKey
gauntlet Gauntlet
// metrics
issuedTotal *metrics.Counter
requestsTotal *metrics.Counter
requestsDuration *metrics.Histogram
}
// New returns a new Certificate Authority.
// CA signs client certificates with the provided root certificate and private key.
// CA uses the provided gauntlet func to customise issued certificates.
func New(
cert *bifrost.Certificate,
key *bifrost.PrivateKey,
gauntlet Gauntlet,
) (*CA, error) {
if !cert.IsCA() {
return nil, fmt.Errorf("bifrost: root certificate is not a valid CA")
}
if gauntlet == nil {
gauntlet = func(csr *bifrost.CertificateRequest) (*x509.Certificate, error) {
return nil, nil
}
}
issued := bfMetricName("issued_certs_total", cert.Namespace)
reqsTotal := bfMetricName("requests_total", cert.Namespace)
reqsDur := bfMetricName("requests_duration_seconds", cert.Namespace)
return &CA{
cert: cert,
key: key,
gauntlet: gauntlet,
issuedTotal: bifrost.StatsForNerds.GetOrCreateCounter(issued),
requestsTotal: bifrost.StatsForNerds.GetOrCreateCounter(reqsTotal),
requestsDuration: bifrost.StatsForNerds.GetOrCreateHistogram(reqsDur),
}, 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()
nb := r.URL.Query().Get("not-before")
na := r.URL.Query().Get("not-after")
ctx := r.Context()
notBefore, notAfter, err := ParseValidity(nb, na)
if err != nil {
writeHTTPError(ctx, w, err.Error(), http.StatusBadRequest)
return
}
contentType, _, err := webapp.GetContentType(r.Header, webapp.MimeTypeText)
if err != nil {
msg := fmt.Sprintf("error parsing Content-Type header: %s", err)
writeHTTPError(ctx, w, msg, http.StatusBadRequest)
return
}
if ct := contentType; ct != webapp.MimeTypeText && ct != webapp.MimeTypeBytes {
msg := fmt.Sprintf("unsupported Content-Type %s", ct)
writeHTTPError(ctx, w, msg, http.StatusUnsupportedMediaType)
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
writeHTTPError(ctx, w, err.Error(), http.StatusInternalServerError)
return
}
csr, err := readCsr(contentType, body)
if err != nil {
writeHTTPError(ctx, w, err.Error(), http.StatusBadRequest)
return
}
cert, err := ca.IssueCertificate(csr, notBefore, notAfter)
if err != nil {
statusCode := http.StatusInternalServerError
switch {
case errors.Is(err, bifrost.ErrCertificateRequestInvalid):
statusCode = http.StatusBadRequest
case errors.Is(err, bifrost.ErrCertificateRequestDenied):
statusCode = http.StatusForbidden
}
writeHTTPError(ctx, 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.ErrorContext(ctx, "error writing certificate response", "err", err)
}
ca.requestsDuration.Update(time.Since(startTime).Seconds())
}
// IssueCertificate issues a client certificate for a valid certificate request parsed from asn1CSR.
func (ca CA) IssueCertificate(asn1CSR []byte, notBefore, notAfter time.Time) ([]byte, error) {
csr, err := bifrost.ParseCertificateRequest(asn1CSR)
if err != nil {
return nil, err
}
if csr.Namespace != ca.cert.Namespace {
return nil, fmt.Errorf("%w, namespace mismatch", bifrost.ErrCertificateRequestInvalid)
}
if notBefore.IsZero() || notAfter.IsZero() || notAfter.Before(notBefore) {
return nil, fmt.Errorf(
"%w, invalid validity period",
bifrost.ErrCertificateRequestInvalid,
)
}
template, err := ca.gauntlet(csr)
if err != nil {
return nil, fmt.Errorf("%w, %s", bifrost.ErrCertificateRequestDenied, err)
}
if template == nil {
template = TLSClientCertTemplate()
}
template.NotBefore = notBefore
template.NotAfter = notAfter
// Overwrite the fields we care about.
if template.SerialNumber == nil {
sn, 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,
)
}
template.SerialNumber = sn
}
template.SignatureAlgorithm = bifrost.SignatureAlgorithm
template.Issuer = ca.cert.Issuer
template.Subject.Organization = []string{ca.cert.Namespace.String()}
template.Subject.CommonName = csr.PublicKey.UUID(ca.cert.Namespace).String()
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
}
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
}
func writeHTTPError(ctx context.Context, w http.ResponseWriter, msg string, statusCode int) {
slog.ErrorContext(ctx, msg, "statusCode", statusCode)
http.Error(w, msg, statusCode)
}