@marcel91200 / caddy Mirror · read-only
Fork 0

Fast and extensible multi-platform HTTP/1-2-3 web server with automatic HTTPS

Mirrored from https://github.com/Slazee/caddy.git

Synced Nov 11, 01:00 UTC

master
go 158 lines 4.7 KB
Raw
1 // Copyright 2015 Matthew Holt and The Caddy Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package caddypki
16
17 import (
18 "bytes"
19 "crypto"
20 "crypto/ecdsa"
21 "crypto/ed25519"
22 "crypto/rsa"
23 "crypto/x509"
24 "encoding/pem"
25 "errors"
26 "fmt"
27 "os"
28
29 "github.com/caddyserver/certmagic"
30 "go.step.sm/crypto/pemutil"
31 )
32
33 func pemDecodeCertificate(pemDER []byte) (*x509.Certificate, error) {
34 pemBlock, remaining := pem.Decode(pemDER)
35 if pemBlock == nil {
36 return nil, fmt.Errorf("no PEM block found")
37 }
38 if len(remaining) > 0 {
39 return nil, fmt.Errorf("input contained more than a single PEM block")
40 }
41 if pemBlock.Type != "CERTIFICATE" {
42 return nil, fmt.Errorf("expected PEM block type to be CERTIFICATE, but got '%s'", pemBlock.Type)
43 }
44 return x509.ParseCertificate(pemBlock.Bytes)
45 }
46
47 func pemDecodeCertificateChain(pemDER []byte) ([]*x509.Certificate, error) {
48 chain, err := pemutil.ParseCertificateBundle(pemDER)
49 if err != nil {
50 return nil, fmt.Errorf("failed parsing certificate chain: %w", err)
51 }
52
53 return chain, nil
54 }
55
56 func pemEncodeCert(der []byte) ([]byte, error) {
57 return pemEncode("CERTIFICATE", der)
58 }
59
60 func pemEncode(blockType string, b []byte) ([]byte, error) {
61 var buf bytes.Buffer
62 err := pem.Encode(&buf, &pem.Block{Type: blockType, Bytes: b})
63 return buf.Bytes(), err
64 }
65
66 func trusted(cert *x509.Certificate) bool {
67 chains, err := cert.Verify(x509.VerifyOptions{})
68 return len(chains) > 0 && err == nil
69 }
70
71 // KeyPair represents a public-private key pair, where the
72 // public key is also called a certificate.
73 type KeyPair struct {
74 // The certificate. By default, this should be the path to
75 // a PEM file unless format is something else.
76 Certificate string `json:"certificate,omitempty"`
77
78 // The private key. By default, this should be the path to
79 // a PEM file unless format is something else.
80 PrivateKey string `json:"private_key,omitempty"` //nolint:gosec // false positive: yes it's exported, since it needs to encode/decode as JSON; and is often just a filepath
81
82 // The format in which the certificate and private
83 // key are provided. Default: pem_file
84 Format string `json:"format,omitempty"`
85 }
86
87 // Load loads the certificate chain and (optional) private key from
88 // the corresponding files, using the configured format. If a
89 // private key is read, it will be verified to belong to the first
90 // certificate in the chain.
91 func (kp KeyPair) Load() ([]*x509.Certificate, crypto.Signer, error) {
92 switch kp.Format {
93 case "", "pem_file":
94 certData, err := os.ReadFile(kp.Certificate)
95 if err != nil {
96 return nil, nil, err
97 }
98 chain, err := pemDecodeCertificateChain(certData)
99 if err != nil {
100 return nil, nil, err
101 }
102
103 var key crypto.Signer
104 if kp.PrivateKey != "" {
105 keyData, err := os.ReadFile(kp.PrivateKey)
106 if err != nil {
107 return nil, nil, err
108 }
109 key, err = certmagic.PEMDecodePrivateKey(keyData)
110 if err != nil {
111 return nil, nil, err
112 }
113 if err := verifyKeysMatch(chain[0], key); err != nil {
114 return nil, nil, err
115 }
116 }
117
118 return chain, key, nil
119
120 default:
121 return nil, nil, fmt.Errorf("unsupported format: %s", kp.Format)
122 }
123 }
124
125 // verifyKeysMatch verifies that the public key in the [x509.Certificate] matches
126 // the public key of the [crypto.Signer].
127 func verifyKeysMatch(crt *x509.Certificate, signer crypto.Signer) error {
128 switch pub := crt.PublicKey.(type) {
129 case *rsa.PublicKey:
130 pk, ok := signer.Public().(*rsa.PublicKey)
131 if !ok {
132 return fmt.Errorf("private key type %T does not match issuer public key type %T", signer.Public(), pub)
133 }
134 if !pub.Equal(pk) {
135 return errors.New("private key does not match issuer public key")
136 }
137 case *ecdsa.PublicKey:
138 pk, ok := signer.Public().(*ecdsa.PublicKey)
139 if !ok {
140 return fmt.Errorf("private key type %T does not match issuer public key type %T", signer.Public(), pub)
141 }
142 if !pub.Equal(pk) {
143 return errors.New("private key does not match issuer public key")
144 }
145 case ed25519.PublicKey:
146 pk, ok := signer.Public().(ed25519.PublicKey)
147 if !ok {
148 return fmt.Errorf("private key type %T does not match issuer public key type %T", signer.Public(), pub)
149 }
150 if !pub.Equal(pk) {
151 return errors.New("private key does not match issuer public key")
152 }
153 default:
154 return fmt.Errorf("unsupported key type: %T", pub)
155 }
156
157 return nil
158 }