forked from ciao-project/ciao
-
Notifications
You must be signed in to change notification settings - Fork 0
/
certs.go
254 lines (216 loc) · 7.02 KB
/
certs.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
//
// Copyright (c) 2016 Intel Corporation
//
// 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.
//
// Initial implementation based on
// golang/src/pkg/crypto/tls/generate_cert.go
//
// which is:
//
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the golang LICENSE file.
//
package certs
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/pem"
"fmt"
"io"
"math/big"
"net"
"time"
"github.com/01org/ciao/ssntp"
)
func publicKey(priv interface{}) interface{} {
switch k := priv.(type) {
case *rsa.PrivateKey:
return &k.PublicKey
case *ecdsa.PrivateKey:
return &k.PublicKey
default:
return nil
}
}
func pemBlockForKey(priv interface{}) (*pem.Block, error) {
switch k := priv.(type) {
case *rsa.PrivateKey:
return &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(k)}, nil
case *ecdsa.PrivateKey:
b, err := x509.MarshalECPrivateKey(k)
if err != nil {
return nil, fmt.Errorf("Unable to marshal ECDSA private key: %v", err)
}
return &pem.Block{Type: "EC PRIVATE KEY", Bytes: b}, nil
default:
return nil, fmt.Errorf("No private key found")
}
}
func keyFromPemBlock(block *pem.Block) (interface{}, error) {
if block.Type == "EC PRIVATE KEY" {
return x509.ParseECPrivateKey(block.Bytes)
}
return x509.ParsePKCS1PrivateKey(block.Bytes)
}
func addOIDs(role ssntp.Role, oids []asn1.ObjectIdentifier) []asn1.ObjectIdentifier {
if role.IsAgent() {
oids = append(oids, ssntp.RoleAgentOID)
}
if role.IsScheduler() {
oids = append(oids, ssntp.RoleSchedulerOID)
}
if role.IsController() {
oids = append(oids, ssntp.RoleControllerOID)
}
if role.IsNetAgent() {
oids = append(oids, ssntp.RoleNetAgentOID)
}
if role.IsServer() {
oids = append(oids, ssntp.RoleServerOID)
}
if role.IsCNCIAgent() {
oids = append(oids, ssntp.RoleCNCIAgentOID)
}
return oids
}
func generatePrivateKey(ell bool) (interface{}, error) {
if ell == false {
return rsa.GenerateKey(rand.Reader, 2048)
}
return ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
}
func addMgmtIPs(mgmtIPs []string, ips []net.IP) []net.IP {
for _, i := range mgmtIPs {
if ip := net.ParseIP(i); ip != nil {
ips = append(ips, ip)
}
}
return ips
}
func addDNSNames(hosts []string, names []string) []string {
for _, h := range hosts {
if ip := net.ParseIP(h); ip != nil {
continue
} else {
names = append(names, h)
}
}
return names
}
// CreateCertTemplate provides the certificate template from which client or server certificated can be derived.
func CreateCertTemplate(role ssntp.Role, organization string, email string, hosts []string, mgmtIPs []string) (*x509.Certificate, error) {
notBefore := time.Now()
notAfter := notBefore.Add(365 * 24 * time.Hour)
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return nil, fmt.Errorf("Gailed to generate certificate serial number: %v", err)
}
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Organization: []string{organization},
},
NotBefore: notBefore,
NotAfter: notAfter,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
EmailAddresses: []string{email},
BasicConstraintsValid: true,
}
template.DNSNames = addDNSNames(hosts, template.DNSNames)
template.IPAddresses = addMgmtIPs(mgmtIPs, template.IPAddresses)
template.UnknownExtKeyUsage = addOIDs(role, template.UnknownExtKeyUsage)
return &template, nil
}
// CreateServerCert creates the server certificate and the CA certificate. Both are written out PEM encoded.
func CreateServerCert(template *x509.Certificate, useElliptic bool, certOutput io.Writer, caCertOutput io.Writer) error {
priv, err := generatePrivateKey(useElliptic)
if err != nil {
return fmt.Errorf("Unable to create private key: %v", err)
}
template.IsCA = true
// Create self-signed certificate
derBytes, err := x509.CreateCertificate(rand.Reader, template, template, publicKey(priv), priv)
if err != nil {
return fmt.Errorf("Unable to create server certificate: %v", err)
}
// Write out CA cert
err = pem.Encode(caCertOutput, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
if err != nil {
return fmt.Errorf("Unable to encode PEM block: %v", err)
}
// Write out certificate (including private key)
err = pem.Encode(certOutput, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
if err != nil {
return fmt.Errorf("Unable to encode PEM block: %v", err)
}
block, err := pemBlockForKey(priv)
if err != nil {
return fmt.Errorf("Unable to get PEM block from key: %v", err)
}
err = pem.Encode(certOutput, block)
if err != nil {
return fmt.Errorf("Unable to encode PEM block: %v", err)
}
return nil
}
// CreateClientCert creates the client certificate signed by the giver server certificate. It is written PEM encoded.
func CreateClientCert(template *x509.Certificate, useElliptic bool, serverCert []byte, certOutput io.Writer) error {
priv, err := generatePrivateKey(useElliptic)
if err != nil {
return fmt.Errorf("Unable to create private key: %v", err)
}
template.IsCA = false
// Parent public key first
certBlock, rest := pem.Decode(serverCert)
parentCert, err := x509.ParseCertificate(certBlock.Bytes)
if err != nil {
return fmt.Errorf("Unable to parse server cert: %v", err)
}
// Parent private key
privKeyBlock, _ := pem.Decode(rest)
if privKeyBlock == nil {
return fmt.Errorf("Unable to extract private key from server cert: %v", err)
}
serverPrivKey, err := keyFromPemBlock(privKeyBlock)
if err != nil {
return fmt.Errorf("Unable to parse private key from server cert: %v", err)
}
// Create certificate signed by private key from serverCert
derBytes, err := x509.CreateCertificate(rand.Reader, template, parentCert, publicKey(priv), serverPrivKey)
if err != nil {
return fmt.Errorf("Unable to create client certificate: %v", err)
}
// Write out certificate (including private key)
err = pem.Encode(certOutput, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
if err != nil {
return fmt.Errorf("Unable to encode PEM block: %v", err)
}
block, err := pemBlockForKey(priv)
if err != nil {
return fmt.Errorf("Unable to get PEM block from key: %v", err)
}
err = pem.Encode(certOutput, block)
if err != nil {
return fmt.Errorf("Unable to encode PEM block: %v", err)
}
return nil
}