forked from square/certstrap
/
csr.go
215 lines (195 loc) · 6.19 KB
/
csr.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
/*-
* Copyright 2015 Square Inc.
* Copyright 2014 CoreOS
*
* 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.
*/
package pkix
import (
"bytes"
"crypto"
"crypto/ecdsa"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/pem"
"errors"
"fmt"
"math/big"
"net"
"strings"
)
const (
csrPEMBlockType = "CERTIFICATE REQUEST"
)
var (
csrPkixName = pkix.Name{
Country: []string{},
Organization: []string{},
OrganizationalUnit: nil,
Locality: nil,
Province: nil,
StreetAddress: nil,
PostalCode: nil,
SerialNumber: "",
CommonName: "",
}
)
// ParseAndValidateIPs parses a comma-delimited list of IP addresses into an array of IP addresses
func ParseAndValidateIPs(ipList string) (res []net.IP, err error) {
// IP list can potentially be a blank string, ""
if len(ipList) > 0 {
ips := strings.Split(ipList, ",")
for _, ip := range ips {
parsedIP := net.ParseIP(ip)
if parsedIP == nil {
return nil, fmt.Errorf("Invalid IP address: %s", ip)
}
res = append(res, parsedIP)
}
}
return
}
// CreateCertificateSigningRequest sets up a request to create a csr file with the given parameters
func CreateCertificateSigningRequest(key *Key, organizationalUnit string, ipList []net.IP, domainList []string, organization string, country string, province string, locality string, commonName string) (*CertificateSigningRequest, error) {
csrPkixName.CommonName = commonName
if len(organizationalUnit) > 0 {
csrPkixName.OrganizationalUnit = []string{organizationalUnit}
}
if len(organization) > 0 {
csrPkixName.Organization = []string{organization}
}
if len(country) > 0 {
csrPkixName.Country = []string{country}
}
if len(province) > 0 {
csrPkixName.Province = []string{province}
}
if len(locality) > 0 {
csrPkixName.Locality = []string{locality}
}
csrTemplate := &x509.CertificateRequest{
Subject: csrPkixName,
IPAddresses: ipList,
DNSNames: domainList,
}
csrBytes, err := x509.CreateCertificateRequest(rand.Reader, csrTemplate, key.Private)
if err != nil {
return nil, err
}
return NewCertificateSigningRequestFromDER(csrBytes), nil
}
// CertificateSigningRequest is a wrapper around a x509 CertificateRequest and its DER-formatted bytes
type CertificateSigningRequest struct {
// derBytes is always set for valid Certificate
derBytes []byte
cr *x509.CertificateRequest
}
// NewCertificateSigningRequestFromDER inits CertificateSigningRequest from DER-format bytes
func NewCertificateSigningRequestFromDER(derBytes []byte) *CertificateSigningRequest {
return &CertificateSigningRequest{derBytes: derBytes}
}
// NewCertificateSigningRequestFromPEM inits CertificateSigningRequest from PEM-format bytes
// data should contain at most one certificate
func NewCertificateSigningRequestFromPEM(data []byte) (*CertificateSigningRequest, error) {
pemBlock, _ := pem.Decode(data)
if pemBlock == nil {
return nil, errors.New("cannot find the next PEM formatted block")
}
if pemBlock.Type != csrPEMBlockType || len(pemBlock.Headers) != 0 {
return nil, errors.New("unmatched type or headers")
}
return &CertificateSigningRequest{derBytes: pemBlock.Bytes}, nil
}
// build cr field if needed
func (c *CertificateSigningRequest) buildPKCS10CertificateSigningRequest() error {
if c.cr != nil {
return nil
}
var err error
c.cr, err = x509.ParseCertificateRequest(c.derBytes)
if err != nil {
return err
}
return nil
}
// GetRawCertificateSigningRequest returns a copy of this certificate request as an x509.CertificateRequest.
func (c *CertificateSigningRequest) GetRawCertificateSigningRequest() (*x509.CertificateRequest, error) {
if err := c.buildPKCS10CertificateSigningRequest(); err != nil {
return nil, err
}
return c.cr, nil
}
// CheckSignature verifies that the signature is a valid signature
// using the public key in CertificateSigningRequest.
func (c *CertificateSigningRequest) CheckSignature() error {
if err := c.buildPKCS10CertificateSigningRequest(); err != nil {
return err
}
return checkSignature(c.cr, c.cr.SignatureAlgorithm, c.cr.RawTBSCertificateRequest, c.cr.Signature)
}
// checkSignature verifies a signature made by the key on a CSR, such
// as on the CSR itself.
func checkSignature(csr *x509.CertificateRequest, algo x509.SignatureAlgorithm, signed, signature []byte) error {
var hashType crypto.Hash
switch algo {
case x509.SHA1WithRSA, x509.ECDSAWithSHA1:
hashType = crypto.SHA1
case x509.SHA256WithRSA, x509.ECDSAWithSHA256:
hashType = crypto.SHA256
case x509.SHA384WithRSA, x509.ECDSAWithSHA384:
hashType = crypto.SHA384
case x509.SHA512WithRSA, x509.ECDSAWithSHA512:
hashType = crypto.SHA512
default:
return x509.ErrUnsupportedAlgorithm
}
if !hashType.Available() {
return x509.ErrUnsupportedAlgorithm
}
h := hashType.New()
h.Write(signed)
digest := h.Sum(nil)
switch pub := csr.PublicKey.(type) {
case *rsa.PublicKey:
return rsa.VerifyPKCS1v15(pub, hashType, digest, signature)
case *ecdsa.PublicKey:
ecdsaSig := new(struct{ R, S *big.Int })
if _, err := asn1.Unmarshal(signature, ecdsaSig); err != nil {
return err
}
if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
return errors.New("x509: ECDSA signature contained zero or negative values")
}
if !ecdsa.Verify(pub, digest, ecdsaSig.R, ecdsaSig.S) {
return errors.New("x509: ECDSA verification failure")
}
return nil
}
return x509.ErrUnsupportedAlgorithm
}
// Export returns PEM-format bytes
func (c *CertificateSigningRequest) Export() ([]byte, error) {
pemBlock := &pem.Block{
Type: csrPEMBlockType,
Headers: nil,
Bytes: c.derBytes,
}
buf := new(bytes.Buffer)
if err := pem.Encode(buf, pemBlock); err != nil {
return nil, err
}
return buf.Bytes(), nil
}