forked from hyperledger/fabric
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ca.go
309 lines (270 loc) · 6.4 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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package ca
import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"io/ioutil"
"math/big"
"net"
"os"
"path/filepath"
"strings"
"time"
"github.com/hyperledger/fabric/internal/cryptogen/csp"
"github.com/pkg/errors"
)
type CA struct {
Name string
Country string
Province string
Locality string
OrganizationalUnit string
StreetAddress string
PostalCode string
Signer crypto.Signer
SignCert *x509.Certificate
}
// NewCA creates an instance of CA and saves the signing key pair in
// baseDir/name
func NewCA(
baseDir,
org,
name,
country,
province,
locality,
orgUnit,
streetAddress,
postalCode string,
) (*CA, error) {
var ca *CA
err := os.MkdirAll(baseDir, 0755)
if err != nil {
return nil, err
}
priv, err := csp.GeneratePrivateKey(baseDir)
if err != nil {
return nil, err
}
template := x509Template()
//this is a CA
template.IsCA = true
template.KeyUsage |= x509.KeyUsageDigitalSignature |
x509.KeyUsageKeyEncipherment | x509.KeyUsageCertSign |
x509.KeyUsageCRLSign
template.ExtKeyUsage = []x509.ExtKeyUsage{
x509.ExtKeyUsageClientAuth,
x509.ExtKeyUsageServerAuth,
}
//set the organization for the subject
subject := subjectTemplateAdditional(country, province, locality, orgUnit, streetAddress, postalCode)
subject.Organization = []string{org}
subject.CommonName = name
template.Subject = subject
template.SubjectKeyId = computeSKI(priv)
x509Cert, err := genCertificateECDSA(
baseDir,
name,
&template,
&template,
&priv.PublicKey,
priv,
)
if err != nil {
return nil, err
}
ca = &CA{
Name: name,
Signer: &csp.ECDSASigner{
PrivateKey: priv,
},
SignCert: x509Cert,
Country: country,
Province: province,
Locality: locality,
OrganizationalUnit: orgUnit,
StreetAddress: streetAddress,
PostalCode: postalCode,
}
return ca, err
}
// SignCertificate creates a signed certificate based on a built-in template
// and saves it in baseDir/name
func (ca *CA) SignCertificate(
baseDir,
name string,
orgUnits,
alternateNames []string,
pub *ecdsa.PublicKey,
ku x509.KeyUsage,
eku []x509.ExtKeyUsage,
) (*x509.Certificate, error) {
template := x509Template()
template.KeyUsage = ku
template.ExtKeyUsage = eku
//set the organization for the subject
subject := subjectTemplateAdditional(
ca.Country,
ca.Province,
ca.Locality,
ca.OrganizationalUnit,
ca.StreetAddress,
ca.PostalCode,
)
subject.CommonName = name
subject.OrganizationalUnit = append(subject.OrganizationalUnit, orgUnits...)
template.Subject = subject
for _, san := range alternateNames {
// try to parse as an IP address first
ip := net.ParseIP(san)
if ip != nil {
template.IPAddresses = append(template.IPAddresses, ip)
} else {
template.DNSNames = append(template.DNSNames, alternateNames...)
}
}
cert, err := genCertificateECDSA(
baseDir,
name,
&template,
ca.SignCert,
pub,
ca.Signer,
)
if err != nil {
return nil, err
}
return cert, nil
}
// compute Subject Key Identifier
func computeSKI(privKey *ecdsa.PrivateKey) []byte {
// Marshall the public key
raw := elliptic.Marshal(privKey.Curve, privKey.PublicKey.X, privKey.PublicKey.Y)
// Hash it
hash := sha256.Sum256(raw)
return hash[:]
}
// default template for X509 subject
func subjectTemplate() pkix.Name {
return pkix.Name{
Country: []string{"US"},
Locality: []string{"San Francisco"},
Province: []string{"California"},
}
}
// Additional for X509 subject
func subjectTemplateAdditional(
country,
province,
locality,
orgUnit,
streetAddress,
postalCode string,
) pkix.Name {
name := subjectTemplate()
if len(country) >= 1 {
name.Country = []string{country}
}
if len(province) >= 1 {
name.Province = []string{province}
}
if len(locality) >= 1 {
name.Locality = []string{locality}
}
if len(orgUnit) >= 1 {
name.OrganizationalUnit = []string{orgUnit}
}
if len(streetAddress) >= 1 {
name.StreetAddress = []string{streetAddress}
}
if len(postalCode) >= 1 {
name.PostalCode = []string{postalCode}
}
return name
}
// default template for X509 certificates
func x509Template() x509.Certificate {
// generate a serial number
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, _ := rand.Int(rand.Reader, serialNumberLimit)
// set expiry to around 10 years
expiry := 3650 * 24 * time.Hour
// round minute and backdate 5 minutes
notBefore := time.Now().Round(time.Minute).Add(-5 * time.Minute).UTC()
//basic template to use
x509 := x509.Certificate{
SerialNumber: serialNumber,
NotBefore: notBefore,
NotAfter: notBefore.Add(expiry).UTC(),
BasicConstraintsValid: true,
}
return x509
}
// generate a signed X509 certificate using ECDSA
func genCertificateECDSA(
baseDir,
name string,
template,
parent *x509.Certificate,
pub *ecdsa.PublicKey,
priv interface{},
) (*x509.Certificate, error) {
//create the x509 public cert
certBytes, err := x509.CreateCertificate(rand.Reader, template, parent, pub, priv)
if err != nil {
return nil, err
}
//write cert out to file
fileName := filepath.Join(baseDir, name+"-cert.pem")
certFile, err := os.Create(fileName)
if err != nil {
return nil, err
}
//pem encode the cert
err = pem.Encode(certFile, &pem.Block{Type: "CERTIFICATE", Bytes: certBytes})
certFile.Close()
if err != nil {
return nil, err
}
x509Cert, err := x509.ParseCertificate(certBytes)
if err != nil {
return nil, err
}
return x509Cert, nil
}
// LoadCertificateECDSA load a ecdsa cert from a file in cert path
func LoadCertificateECDSA(certPath string) (*x509.Certificate, error) {
var cert *x509.Certificate
var err error
walkFunc := func(path string, info os.FileInfo, err error) error {
if strings.HasSuffix(path, ".pem") {
rawCert, err := ioutil.ReadFile(path)
if err != nil {
return err
}
block, _ := pem.Decode(rawCert)
if block == nil || block.Type != "CERTIFICATE" {
return errors.Errorf("%s: wrong PEM encoding", path)
}
cert, err = x509.ParseCertificate(block.Bytes)
if err != nil {
return errors.Errorf("%s: wrong DER encoding", path)
}
}
return nil
}
err = filepath.Walk(certPath, walkFunc)
if err != nil {
return nil, err
}
return cert, err
}