aboutsummaryrefslogtreecommitdiff
path: root/certificate.go
blob: 173fe75687860e6cffa58e818e350a90aae867ed (plain) (blame)
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
package main

// This file contains all code to create certificates.

import (
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"io/ioutil"
	"math/big"
	"strings"
	"time"

	"github.com/gibheer/pki"
)

var (
	// the possible valid key usages to check against the commandline
	ValidKeyUsages = map[string]x509.KeyUsage{
		"digitalsignature":  x509.KeyUsageDigitalSignature,
		"contentcommitment": x509.KeyUsageContentCommitment,
		"keyencipherment":   x509.KeyUsageKeyEncipherment,
		"dataencipherment":  x509.KeyUsageDataEncipherment,
		"keyagreement":      x509.KeyUsageKeyAgreement,
		"certsign":          x509.KeyUsageCertSign,
		"crlsign":           x509.KeyUsageCRLSign,
		"encipheronly":      x509.KeyUsageEncipherOnly,
		"decipheronly":      x509.KeyUsageDecipherOnly,
	}
	// the valid extended key usages, to check against the commandline
	ValidExtKeyUsages = map[string]x509.ExtKeyUsage{
		"any":                        x509.ExtKeyUsageAny,
		"serverauth":                 x509.ExtKeyUsageServerAuth,
		"clientauth":                 x509.ExtKeyUsageClientAuth,
		"codesigning":                x509.ExtKeyUsageCodeSigning,
		"emailprotection":            x509.ExtKeyUsageEmailProtection,
		"ipsecendsystem":             x509.ExtKeyUsageIPSECEndSystem,
		"ipsectunnel":                x509.ExtKeyUsageIPSECTunnel,
		"ipsecuser":                  x509.ExtKeyUsageIPSECUser,
		"timestamping":               x509.ExtKeyUsageTimeStamping,
		"ocspsigning":                x509.ExtKeyUsageOCSPSigning,
		"microsoftservergatedcrypto": x509.ExtKeyUsageMicrosoftServerGatedCrypto,
		"netscapeservergatedcrypto":  x509.ExtKeyUsageNetscapeServerGatedCrypto,
	}

	CmdCreateCert = &Command{
		Use:     "create-cert",
		Short:   "create a certificate from a sign request",
		Long:    "Create a certificate based on a certificate sign request.",
		Example: "create-cert -private-key=foo.ecdsa -csr=foo.csr",
		Run:     create_cert,
	}
	// certificate specific creation stuff
	FlagCertificateGeneration pki.CertificateOptions
)

type (
	// holds all certificate related flags, which need parsing afterwards
	certiticateRequestRawFlags struct {
		manual struct {
			serialNumber   string // the serial number for the cert
			commonName     string // the common name used in the cert
			dnsNames       string // all alternative names in the certificate (comma separated list)
			ipAddresses    string // all IP addresses in the certificate (comma separated list)
			emailAddresses string // alternative email addresses
		}
		automatic struct {
			Country            string // the country names which should end up in the cert (comma separated list)
			Organization       string // the organization names (comma separated list)
			OrganizationalUnit string // the organizational units (comma separated list)
			Locality           string // the city or locality (comma separated list)
			Province           string // the province name (comma separated list)
			StreetAddress      string // the street addresses of the organization (comma separated list)
			PostalCode         string // the postal codes of the locality
		}
	}

	// the raw flags collected through flags
	certGenerationRaw struct {
		serial      int64
		notBefore   string
		notAfter    string
		isCA        bool
		length      int
		caPath      string // path to the ca file if isCA is false
		keyUsage    string // comma separated list of key usages
		extKeyUsage string // comma separated list of extended key usages
		crlUrl      string // comma separated list of crl urls
	}
)

// add flag to load certificate flags
func InitFlagCert(cmd *Command) {
	cmd.Flags().Int64Var(&flagContainer.certGeneration.serial, "serial", 0, "serial number of all certificates")
	cmd.Flags().BoolVar(&flagContainer.certGeneration.isCA, "is-ca", false, "check if the resulting certificate should be a ca")
	cmd.Flags().IntVar(
		&flagContainer.certGeneration.
			length,
		"length",
		0,
		"the number of certificates allowed in the chain between this cert and the end certificate",
	)
	cmd.Flags().StringVar(
		&flagContainer.certGeneration.notBefore,
		"not-before",
		time.Now().Format(time.RFC3339),
		"time before the certificate is not valid in RFC3339 format (default now)",
	)
	cmd.Flags().StringVar(
		&flagContainer.certGeneration.notAfter,
		"not-after",
		time.Now().Add(time.Duration(180*24*time.Hour)).Format(time.RFC3339),
		"time after which the certificate is not valid in RFC3339 format (default now + 180 days)",
	)
	cmd.Flags().StringVar(
		&flagContainer.certGeneration.keyUsage,
		"key-usage", "",
		"comma separated list of key usages",
	)
	cmd.Flags().StringVar(
		&flagContainer.certGeneration.extKeyUsage,
		"ext-key-usage", "",
		"comma separated list of extended key usage flags",
	)
	cmd.Flags().StringVar(
		&flagContainer.certGeneration.crlUrl,
		"crl-url", "",
		"comma separated list where crl lists can be found",
	)
}

// create a certificate
func create_cert(cmd *Command, args []string) {
	err := checkFlags(checkPrivateKey, checkOutput, checkCSR, checkCertFlags, checkFlagsEither(checkIsCA, checkCA))
	if err != nil {
		crash_with_help(cmd, ErrorFlagInput, "Flags invalid: %s", err)
	}

	var cert *pki.Certificate
	if FlagCertificateGeneration.IsCA && FlagCertificate == nil {
		cert, err = FlagCertificateSignRequest.ToCertificate(
			FlagPrivateKey,
			FlagCertificateGeneration,
			nil,
		)
	} else if !FlagCertificateGeneration.IsCA && FlagCertificate != nil {
		cert, err = FlagCertificateSignRequest.ToCertificate(
			FlagPrivateKey,
			FlagCertificateGeneration,
			FlagCertificate,
		)
	} else {
		crash_with_help(cmd, ErrorFlagInput, "Usage of 'is-ca' and 'ca' is invalid.")
	}

	if err != nil {
		crash_with_help(cmd, ErrorProgram, "Error generating certificate: %s", err)
	}
	pem_block, err := cert.MarshalPem()
	if err != nil {
		crash_with_help(cmd, ErrorProgram, "Error when marshalling to pem: %s", err)
	}
	_, err = pem_block.WriteTo(FlagOutput)
	if err != nil {
		crash_with_help(cmd, ErrorProgram, "Could not write to output: %s", err)
	}
}

// parse the certificate data
func checkCertFlags() error {
	FlagCertificateGeneration.IsCA = flagContainer.certGeneration.isCA
	FlagCertificateGeneration.CALength = flagContainer.certGeneration.length
	FlagCertificateGeneration.SerialNumber = big.NewInt(flagContainer.certGeneration.serial)

	var err error
	if notbefore := flagContainer.certGeneration.notBefore; notbefore != "" {
		FlagCertificateGeneration.NotBefore, err = parseTimeRFC3339(notbefore)
		if err != nil {
			return err
		}
	}
	if notafter := flagContainer.certGeneration.notAfter; notafter != "" {
		FlagCertificateGeneration.NotAfter, err = parseTimeRFC3339(notafter)
		if err != nil {
			return err
		}
	}

	if err := convertCertKeyUsage(); err != nil {
		return err
	}
	if err := convertCertExtKeyUsage(); err != nil {
		return err
	}
	if err := convertCertCrlUrl(); err != nil {
		return err
	}
	return nil
}

// check if the flag is enabled to make the certificate a ca
func checkIsCA() error {
	if FlagCertificateGeneration.IsCA {
		return nil
	}
	return fmt.Errorf("Not selected to be a CA")
}

// parse the key usage string
func convertCertKeyUsage() error {
	if keyUstr := flagContainer.certGeneration.keyUsage; keyUstr != "" {
		keyUarr := strings.Split(keyUstr, ",")
		var keyUresult x509.KeyUsage
		for _, usage := range keyUarr {
			if value, ok := ValidKeyUsages[strings.ToLower(usage)]; ok {
				keyUresult = keyUresult | value
			} else {
				return fmt.Errorf("unsupported key usage '%s'", usage)
			}
		}
		FlagCertificateGeneration.KeyUsage = keyUresult
	}
	return nil
}

// parse the extended key usage flags
func convertCertExtKeyUsage() error {
	if eKeyUstr := flagContainer.certGeneration.extKeyUsage; eKeyUstr != "" {
		eKeyUarr := strings.Split(eKeyUstr, ",")
		eKeyUResult := make([]x509.ExtKeyUsage, 0)
		for _, usage := range eKeyUarr {
			if value, ok := ValidExtKeyUsages[strings.ToLower(usage)]; ok {
				eKeyUResult = append(eKeyUResult, value)
			} else {
				return fmt.Errorf("unsupported extended key usage '%s'", usage)
			}
		}
		FlagCertificateGeneration.KeyExtendedUsage = eKeyUResult
	}
	return nil
}

// parse the crl urls
func convertCertCrlUrl() error {
	if str := flagContainer.certGeneration.crlUrl; str != "" {
		FlagCertificateGeneration.CRLUrls = strings.Split(str, ",")
	}
	return nil
}

// add flag to load a certificate
func InitFlagCA(cmd *Command) {
	cmd.Flags().StringVar(&flagContainer.caPath, "ca", "", "path to the certificate authority")
}

// parse the certificate authority
func checkCA() error {
	rest, err := ioutil.ReadFile(flagContainer.caPath)
	if err != nil {
		return fmt.Errorf("Error reading certificate authority: %s", err)
	}

	var ca_asn1 []byte
	var block *pem.Block
	for len(rest) > 0 {
		block, rest = pem.Decode(rest)
		if block != nil && block.Type == pki.PemLabelCertificate {
			ca_asn1 = block.Bytes
			break
		}
	}
	if len(ca_asn1) == 0 {
		return fmt.Errorf("No certificate in '%s' found.", flagContainer.caPath)
	}

	ca, err := pki.LoadCertificate(ca_asn1)
	if err != nil {
		return fmt.Errorf("Invalid certificate: %s", err)
	}
	FlagCertificate = ca
	return nil
}

// add flag to load certificate sign request
func InitFlagCSR(cmd *Command) {
	cmd.Flags().StringVar(&flagContainer.signRequestPath, "csr", "", "path to the certificate sign request")
}

// parse the certificate sign request
func checkCSR() error {
	rest, err := ioutil.ReadFile(flagContainer.signRequestPath)
	if err != nil {
		return fmt.Errorf("Error reading certificate sign request: %s", err)
	}

	var csr_asn1 []byte
	var block *pem.Block
	for len(rest) > 0 {
		block, rest = pem.Decode(rest)
		if block.Type == pki.PemLabelCertificateRequest {
			csr_asn1 = block.Bytes
			break
		}
	}
	if len(csr_asn1) == 0 {
		return fmt.Errorf(
			"No certificate sign request found in %s",
			flagContainer.signRequestPath,
		)
	}

	csr, err := pki.LoadCertificateSignRequest(csr_asn1)
	if err != nil {
		return fmt.Errorf("Invalid certificate sign request: %s", err)
	}
	FlagCertificateSignRequest = csr
	return nil
}

// parse the string as a RFC3339 time
func parseTimeRFC3339(tr string) (time.Time, error) {
	return time.Parse(time.RFC3339, tr)
}