-
Notifications
You must be signed in to change notification settings - Fork 0
/
helper_cert.go
170 lines (147 loc) · 5.34 KB
/
helper_cert.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
/*
* Copyright © 2015-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author Aeneas Rekkas <aeneas+oss@aeneas.io>
* @copyright 2015-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>
* @license Apache-2.0
*/
package server
import (
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"strings"
"time"
"github.com/ory/hydra/config"
"github.com/ory/hydra/jwk"
"github.com/ory/hydra/pkg"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
const (
tlsKeyName = "hydra.https-tls"
)
func loadCertificateFromFile(cmd *cobra.Command, c *config.Config) *tls.Certificate {
keyPath := viper.GetString("HTTPS_TLS_KEY_PATH")
certPath := viper.GetString("HTTPS_TLS_CERT_PATH")
if kp, _ := cmd.Flags().GetString("https-tls-key-path"); kp != "" {
keyPath = kp
} else if cp, _ := cmd.Flags().GetString("https-tls-cert-path"); cp != "" {
certPath = cp
} else if keyPath == "" || certPath == "" {
return nil
}
cert, err := tls.LoadX509KeyPair(certPath, keyPath)
if err != nil {
c.GetLogger().WithError(errors.WithStack(err)).Warn("Could not load x509 key pair, will use self-issued certificate instead.")
return nil
}
return &cert
}
func loadCertificateFromEnv(c *config.Config) *tls.Certificate {
keyString := viper.GetString("HTTPS_TLS_KEY")
certString := viper.GetString("HTTPS_TLS_CERT")
if keyString == "" || certString == "" {
return nil
}
keyString = strings.Replace(keyString, "\\n", "\n", -1)
certString = strings.Replace(certString, "\\n", "\n", -1)
var cert tls.Certificate
var err error
if cert, err = tls.X509KeyPair([]byte(certString), []byte(keyString)); err != nil {
c.GetLogger().Warningf("Could not parse x509 key pair from env: %s", cert)
return nil
}
return &cert
}
func getOrCreateTLSCertificate(cmd *cobra.Command, c *config.Config) tls.Certificate {
if cert := loadCertificateFromFile(cmd, c); cert != nil {
c.GetLogger().Info("Loaded tls certificate from file")
return *cert
} else if cert := loadCertificateFromEnv(c); cert != nil {
c.GetLogger().Info("Loaded certificate from environment variable")
return *cert
}
ctx := c.Context()
expectDependency(c.GetLogger(), ctx.KeyManager)
privateKey, err := createOrGetJWK(c, tlsKeyName, "", "private")
if err != nil {
c.GetLogger().WithError(err).Fatalf(`Could not fetch TLS keys - did you forget to run "hydra migrate sql" or forget to set the SYSTEM_SECRET?`)
}
if len(privateKey.Certificates) == 0 {
cert, err := createSelfSignedCertificate(privateKey.Key)
if err != nil {
c.GetLogger().WithError(err).Fatalf(`Could not generate a self signed TLS certificate.`)
}
privateKey.Certificates = []*x509.Certificate{cert}
if err := ctx.KeyManager.DeleteKey(tlsKeyName, privateKey.KeyID); err != nil {
c.GetLogger().WithError(err).Fatalf(`Could not update (delete) the self signed TLS certificate.`)
}
if err := ctx.KeyManager.AddKey(tlsKeyName, privateKey); err != nil {
c.GetLogger().WithError(err).Fatalf(`Could not update (add) the self signed TLS certificate.`)
}
}
block, err := jwk.PEMBlockForKey(privateKey.Key)
if err != nil {
pkg.Must(err, "Could not encode key to PEM: %s", err)
}
if len(privateKey.Certificates) == 0 {
c.GetLogger().Fatal("TLS certificate chain can not be empty")
}
pemCert := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: privateKey.Certificates[0].Raw})
pemKey := pem.EncodeToMemory(block)
cert, err := tls.X509KeyPair(pemCert, pemKey)
pkg.Must(err, "Could not decode certificate: %s", err)
return cert
}
func createSelfSignedCertificate(key interface{}) (cert *x509.Certificate, err error) {
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return cert, errors.Errorf("Failed to generate serial number: %s", err)
}
certificate := &x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Organization: []string{"Hydra"},
CommonName: "Hydra",
},
Issuer: pkix.Name{
Organization: []string{"Hydra"},
CommonName: "Hydra",
},
NotBefore: time.Now().UTC(),
NotAfter: time.Now().UTC().Add(time.Hour * 24 * 7),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
certificate.IsCA = true
certificate.KeyUsage |= x509.KeyUsageCertSign
certificate.DNSNames = append(certificate.DNSNames, "localhost")
der, err := x509.CreateCertificate(rand.Reader, certificate, certificate, publicKey(key), key)
if err != nil {
return cert, errors.Errorf("Failed to create certificate: %s", err)
}
cert, err = x509.ParseCertificate(der)
if err != nil {
return cert, errors.Errorf("Failed to encode private key: %s", err)
}
return cert, nil
}