forked from sandia-minimega/minimega
/
generate_cert.go
97 lines (80 loc) · 2.37 KB
/
generate_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
// 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 LICENSE file.
// Generate a self-signed X.509 certificate for a TLS server.
// modified by fritz for generating temporary certs for serving tls https in
// protonuke.
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"io/ioutil"
"math/big"
log "minilog"
"os"
"time"
)
var (
validFor = time.Duration(365 * 24 * time.Hour)
isCA = false
rsaBits = 1024
)
func generateCerts() (string, string) {
if *f_httpTLSCert != "" && *f_httpTLSKey != "" {
return *f_httpTLSCert, *f_httpTLSKey
}
host, err := os.Hostname()
if err != nil {
log.Fatalln(err)
}
priv, err := rsa.GenerateKey(rand.Reader, rsaBits)
if err != nil {
log.Fatal("failed to generate private key: %s", err)
}
var notBefore time.Time
notBefore = time.Now()
notAfter := notBefore.Add(validFor)
// end of ASN.1 time
endOfTime := time.Date(2049, 12, 31, 23, 59, 59, 0, time.UTC)
if notAfter.After(endOfTime) {
notAfter = endOfTime
}
template := x509.Certificate{
SerialNumber: new(big.Int).SetInt64(0),
Subject: pkix.Name{
Organization: []string{"protonuke"},
},
NotBefore: notBefore,
NotAfter: notAfter,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
template.DNSNames = append(template.DNSNames, host)
if isCA {
template.IsCA = true
template.KeyUsage |= x509.KeyUsageCertSign
}
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
if err != nil {
log.Fatal("Failed to create certificate: %s", err)
}
certOut, err := ioutil.TempFile("", "protonuke_cert_")
if err != nil {
log.Fatal("failed to open cert for writing: %s", err)
}
pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
certOut.Close()
log.Debugln("wrote cert to: ", certOut.Name())
keyOut, err := ioutil.TempFile("", "protonuke_key_")
if err != nil {
log.Fatal("failed to open key.pem for writing: %v", err)
}
pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
keyOut.Close()
log.Debugln("wrote key to: ", keyOut.Name())
return certOut.Name(), keyOut.Name()
}