-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
353 lines (304 loc) · 8.92 KB
/
main.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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
// Copyright 2016 Manlio Perillo. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// tls-cert is a command used to simplify the generation of certificate for
// server and client. The command requires two positional arguments with the
// Organization and Common Name.
//
// When a server certificate is generated, Common Name should be set to the
// server primary DNS name and Organization should be set to the name of the
// software. Additional DNS names and IP addresses are not supported.
//
// When a client certificate is generated, Common Name should be set to the
// user email address and Organization to the name of the software.
//
// When a CA certificate is generated, Common Name should be set to the user
// name and Organization to the user full name.
//
// The generated certificate can be verified using
// openssl x509 -noout -text -in name.crt
//
// A PKCS12 file for use in a browser (for client authentication) can be
// generated with
// openssl pkcs12 -inkey name.key -in name.crt -export -out name.p12
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"flag"
"fmt"
"io/ioutil"
"log"
"math/big"
"os"
"time"
)
type Certificate struct {
Certificate *x509.Certificate
PrivateKey *rsa.PrivateKey
}
// A Config structure is used to generate a TLS certificate.
type Config struct {
Organization string
CommonName string
KeySize int
KeyUsage x509.KeyUsage
ExtKeyUsage x509.ExtKeyUsage
Lifetime time.Duration
}
const help = `
When a server certificate is generated, Common Name should be set to the
server primary DNS name and Organization should be set to the name of the
software.
When a client certificate is generated, Common Name should be set to the user
email address and Organization to the name of the software.
When a CA certificate is generated, Common Name should be set to the user name
and Organization to the user full name.
`
var (
usage = flag.String("usage", "server", "usage of the certificate")
lifetime = flag.Int("lifetime", 0, "certificate lifetime in days")
caName = flag.String("ca", "", "name of the CA to use for signing")
)
var (
// The default RSA key size.
// CA certificates have a long lifetime so 4096 is used, while server and
// client certificates have a short lifetime and TLS should be as fast as
// possible, so 2048 is used.
defaultKeySize = map[string]int{
"ca": 4096,
"server": 2048,
"client": 2048,
}
// The default certificate lifetime, in days.
defaultLifetime = map[string]int{
"ca": 10 * 365,
"server": 365,
"client": 365,
}
)
func main() {
// Setup log.
log.SetFlags(0)
// Parse command line.
flag.Usage = func() {
fmt.Fprintln(os.Stderr, "Usage: tls-cert [flags] Organization CommonName")
fmt.Fprintln(os.Stderr, "Flags:")
flag.PrintDefaults()
fmt.Fprint(os.Stderr, help)
os.Exit(2)
}
flag.Parse()
if flag.NArg() != 2 {
flag.Usage()
os.Exit(2)
}
if *usage != "ca" && *usage != "server" && *usage != "client" {
flag.Usage()
os.Exit(2)
}
var keyName string
var certName string
O := flag.Arg(0)
CN := flag.Arg(1)
if *lifetime == 0 {
*lifetime = defaultLifetime[*usage]
}
config := Config{
Organization: O,
CommonName: CN,
KeySize: defaultKeySize[*usage],
Lifetime: time.Duration(*lifetime) * 24 * time.Hour,
}
switch *usage {
case "ca":
config.KeyUsage = x509.KeyUsageCertSign
config.ExtKeyUsage = x509.ExtKeyUsageAny
keyName = fmt.Sprintf("%s-%s.key", CN, "ca")
certName = fmt.Sprintf("%s-%s.crt", CN, "ca")
case "server":
config.KeyUsage = x509.KeyUsageKeyEncipherment
config.ExtKeyUsage = x509.ExtKeyUsageServerAuth
keyName = fmt.Sprintf("%s-%s.key", O, "server")
certName = fmt.Sprintf("%s-%s.crt", O, "server")
case "client":
config.KeyUsage = x509.KeyUsageKeyEncipherment
config.ExtKeyUsage = x509.ExtKeyUsageClientAuth
keyName = fmt.Sprintf("%s-%s.key", O, "client")
certName = fmt.Sprintf("%s-%s.crt", O, "client")
}
key, err := GenerateKey(config)
if err != nil {
log.Fatal(err)
}
if err := WriteKey(key, keyName); err != nil {
log.Fatal(err)
}
var cert []byte
if *caName == "" {
cert, err = CreateSelfSignedCert(key, config)
if err != nil {
log.Fatal(err)
}
} else {
ca, err := LoadCA(*caName)
if err != nil {
log.Fatal(err)
}
cert, err = CreateCert(key, ca, config)
if err != nil {
log.Fatal(err)
}
}
if err := WriteCert(cert, certName); err != nil {
log.Fatal(err)
}
}
// GenerateKey generates a private key.
func GenerateKey(config Config) (*rsa.PrivateKey, error) {
key, err := rsa.GenerateKey(rand.Reader, config.KeySize)
if err != nil {
return nil, fmt.Errorf("generating private key: %v", err)
}
return key, nil
}
// CreateSelfSignedCert creates a self signed certificate using specified
// private key.
func CreateSelfSignedCert(key *rsa.PrivateKey, config Config) ([]byte, error) {
now := time.Now()
max := new(big.Int).Lsh(big.NewInt(1), 128)
n, err := rand.Int(rand.Reader, max)
if err != nil {
return nil, fmt.Errorf("generating serial number: %v", err)
}
template := x509.Certificate{
SerialNumber: n,
Subject: pkix.Name{
Organization: []string{config.Organization},
CommonName: config.CommonName,
},
NotBefore: now,
NotAfter: now.Add(config.Lifetime),
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign | config.KeyUsage,
BasicConstraintsValid: true,
IsCA: true,
}
if config.ExtKeyUsage != x509.ExtKeyUsageAny {
template.ExtKeyUsage = []x509.ExtKeyUsage{config.ExtKeyUsage}
}
cert, err := x509.CreateCertificate(rand.Reader, &template, &template,
&key.PublicKey, key)
if err != nil {
return nil, fmt.Errorf("creating certificate: %v", err)
}
return cert, nil
}
// CreateCert creates a certificate using the specified private key (only the
// public part will be used) and signed using specified CA.
func CreateCert(key *rsa.PrivateKey, ca *Certificate, config Config) ([]byte, error) {
now := time.Now()
max := new(big.Int).Lsh(big.NewInt(1), 128)
n, err := rand.Int(rand.Reader, max)
if err != nil {
return nil, fmt.Errorf("generating serial number: %v", err)
}
template := x509.Certificate{
SerialNumber: n,
Subject: pkix.Name{
Organization: []string{config.Organization},
CommonName: config.CommonName,
},
NotBefore: now,
NotAfter: now.Add(config.Lifetime),
KeyUsage: x509.KeyUsageDigitalSignature | config.KeyUsage,
ExtKeyUsage: []x509.ExtKeyUsage{config.ExtKeyUsage},
}
cert, err := x509.CreateCertificate(rand.Reader, &template, ca.Certificate,
&key.PublicKey, ca.PrivateKey)
if err != nil {
return nil, fmt.Errorf("creating certificate: %v", err)
}
return cert, nil
}
// WriteKey writes the private key to path. The file will be accessible only
// to current user.
func WriteKey(key *rsa.PrivateKey, path string) error {
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
defer file.Close()
b := pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(key),
}
if err := pem.Encode(file, &b); err != nil {
// Encode can fail only for I/O errors.
return fmt.Errorf("writing private key to %q: %v", path, err)
}
return nil
}
// WriteCert writes the certificate to path.
func WriteCert(cert []byte, path string) error {
file, err := os.Create(path)
if err != nil {
return err
}
defer file.Close()
b := pem.Block{
Type: "CERTIFICATE",
Bytes: cert,
}
if err := pem.Encode(file, &b); err != nil {
return fmt.Errorf("writing certificate to %q: %v", path, err)
}
return nil
}
// LoadCA loads CA certificate and private key pair.
func LoadCA(name string) (*Certificate, error) {
// NOTE(mperillo): We do not use the tls.LoadX509KeyPair function, since
// the certificate is stored as raw bytes, and not as x509.Certificate.
// It also supports chained certificates, and we don't need them.
certName := fmt.Sprintf("%s-%s.crt", name, "ca")
keyName := fmt.Sprintf("%s-%s.key", name, "ca")
// Load certificate.
data, err := loadPem(certName)
if err != nil {
return nil, fmt.Errorf("reading CA certificate file: %v", err)
}
cert, err := x509.ParseCertificate(data)
if err != nil {
return nil, fmt.Errorf("parsing CA certificate: %v", err)
}
// Load private key.
data, err = loadPem(keyName)
if err != nil {
return nil, fmt.Errorf("reading CA key file: %v", err)
}
key, err := x509.ParsePKCS1PrivateKey(data)
if err != nil {
return nil, fmt.Errorf("parsing CA key: %v", err)
}
ca := Certificate{
Certificate: cert,
PrivateKey: key,
}
return &ca, nil
}
func loadPem(path string) ([]byte, error) {
buf, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
// Ignore errors and additional blocks.
// Any problem will be report by either ParsePKCS1PrivateKey or
// ParseCertificate functions.
data, _ := pem.Decode(buf)
if data == nil {
return []byte(""), nil
}
return data.Bytes, nil
}