/
helpers.go
214 lines (189 loc) · 5.67 KB
/
helpers.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
package crypto
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/pem"
"errors"
"fmt"
"io/ioutil"
"math/big"
"os"
"strings"
"time"
"github.com/smallstep/pkcs7"
)
func GenerateRandomCertificateSerialNumber() (*big.Int, error) {
limit := new(big.Int).Lsh(big.NewInt(1), 128)
return rand.Int(rand.Reader, limit)
}
func SimpleSelfSignedRSAKeypair(cn string, days int) (key *rsa.PrivateKey, cert *x509.Certificate, err error) {
key, err = rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return key, cert, err
}
serialNumber, err := GenerateRandomCertificateSerialNumber()
if err != nil {
return key, cert, err
}
timeNow := time.Now()
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
CommonName: cn,
},
NotBefore: timeNow,
NotAfter: timeNow.Add(time.Duration(days) * 24 * time.Hour),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
DNSNames: []string{cn},
}
certBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key)
if err != nil {
return key, cert, err
}
cert, err = x509.ParseCertificate(certBytes)
if err != nil {
return key, cert, err
}
return key, cert, err
}
func ReadPEMCertificateFile(path string) (*x509.Certificate, error) {
certs, err := ReadPEMCertificatesFile(path)
if err != nil {
return nil, err
}
if len(certs) != 1 {
return nil, errors.New("incorrect number of certificates")
}
return certs[0], nil
}
const (
rsaPrivateKeyPEMBlockType = "RSA PRIVATE KEY"
certificatePEMBlockType = "CERTIFICATE"
)
func ReadPEMCertificatesFile(path string) ([]*x509.Certificate, error) {
pemData, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
var asn1data []byte
rest := pemData
for {
var block *pem.Block
block, rest = pem.Decode(rest)
if block == nil || block.Type != certificatePEMBlockType {
return nil, errors.New("failed to decode PEM block containing certificate")
}
asn1data = append(asn1data, block.Bytes...)
if len(rest) == 0 {
break
}
}
return x509.ParseCertificates(asn1data)
}
func ReadPEMRSAKeyFile(path string) (*rsa.PrivateKey, error) {
return ReadEncryptedPEMRSAKeyFile(path, nil)
}
func ReadEncryptedPEMRSAKeyFile(path string, password []byte) (*rsa.PrivateKey, error) {
pemData, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
pemBlock, _ := pem.Decode(pemData)
if pemBlock == nil {
return nil, errors.New("PEM decode failed")
}
if pemBlock.Type != rsaPrivateKeyPEMBlockType {
return nil, fmt.Errorf("expecting PEM type of %s, but got %s", rsaPrivateKeyPEMBlockType, pemBlock.Type)
}
if x509.IsEncryptedPEMBlock(pemBlock) {
if password == nil {
return nil, errors.New("no supplied password for encrypted PEM")
}
derBytes, err := x509.DecryptPEMBlock(pemBlock, password)
if err != nil {
return nil, err
}
return x509.ParsePKCS1PrivateKey(derBytes)
} else if password != nil {
return nil, errors.New("supplied PEM password, but not encrypted")
}
return x509.ParsePKCS1PrivateKey(pemBlock.Bytes)
}
func WritePEMCertificateFile(cert *x509.Certificate, path string) error {
file, err := os.Create(path)
if err != nil {
return err
}
defer file.Close()
return pem.Encode(
file,
&pem.Block{
Type: certificatePEMBlockType,
Bytes: cert.Raw,
})
}
func WritePEMRSAKeyFile(key *rsa.PrivateKey, path string) error {
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0700)
if err != nil {
return err
}
defer file.Close()
return pem.Encode(
file,
&pem.Block{
Type: rsaPrivateKeyPEMBlockType,
Bytes: x509.MarshalPKCS1PrivateKey(key),
})
}
func WriteEncryptedPEMRSAKeyFile(key *rsa.PrivateKey, password []byte, path string) error {
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0700)
if err != nil {
return err
}
defer file.Close()
encPemBlock, err := x509.EncryptPEMBlock(
rand.Reader,
rsaPrivateKeyPEMBlockType,
x509.MarshalPKCS1PrivateKey(key),
password,
x509.PEMCipher3DES)
if err != nil {
return err
}
return pem.Encode(file, encPemBlock)
}
// TopicFromCert extracts the push certificate topic from the provided certificate.
func TopicFromCert(cert *x509.Certificate) (string, error) {
var oidASN1UserID = asn1.ObjectIdentifier{0, 9, 2342, 19200300, 100, 1, 1}
for _, v := range cert.Subject.Names {
if v.Type.Equal(oidASN1UserID) {
uid, ok := v.Value.(string)
if ok && strings.HasPrefix(uid, "com.apple.mgmt") {
return uid, nil
}
return "", errors.New("invalid Push Topic (UserID OID) in certificate. Must start with 'com.apple.mgmt', was: " + uid)
}
}
return "", errors.New("could not find Push Topic (UserID OID) in certificate")
}
// PKCS7Verifier verifies PKCS7 objects with a configurable clock skew
type PKCS7Verifier struct {
// MaxSkew is the maximum amount of clock skew permitted between the the server time and the pkcs7 signature validity
MaxSkew time.Duration
}
// Verify checks the signatures of a PKCS7 object
func (v *PKCS7Verifier) Verify(p7 *pkcs7.PKCS7) error {
// verify with skew added to beginning of validity window
err := p7.VerifyWithChainAtTime(nil, time.Now().Add(v.MaxSkew))
// if verification fails due to missing the validity window, try verifying with the skew added to the end of the validity window
// the pkcs7 lib doesn't return a concrete error, so check against the error string
if err != nil && strings.Contains(err.Error(), "is outside of certificate validity") {
return p7.VerifyWithChainAtTime(nil, time.Now().Add(-v.MaxSkew))
}
return err
}