This repository has been archived by the owner on Oct 20, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 34
/
certutil.go
198 lines (178 loc) · 5.26 KB
/
certutil.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
// Copyright 2020 Orange SA
//
// 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 apis
package cert
import (
"bytes"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"math/big"
mathrand "math/rand"
"strings"
"time"
"github.com/Orange-OpenSource/nifikop/api/v1alpha1"
certv1 "github.com/jetstack/cert-manager/pkg/apis/certmanager/v1alpha2"
keystore "github.com/pavel-v-chernykh/keystore-go"
corev1 "k8s.io/api/core/v1"
)
// passChars are the characters used when generating passwords
var passChars []rune = []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"abcdefghijklmnopqrstuvwxyz" +
"0123456789")
// DecodeKey will take a PEM encoded Private Key and convert to raw der bytes
func DecodeKey(raw []byte) (parsedKey []byte, err error) {
block, _ := pem.Decode(raw)
if block == nil {
err = errors.New("failed to decode PEM data")
return
}
var keytype certv1.KeyEncoding
var key interface{}
if key, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil {
if key, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil {
return
}
keytype = certv1.PKCS8
} else {
keytype = certv1.PKCS1
}
rsaKey := key.(*rsa.PrivateKey)
if keytype == certv1.PKCS1 {
parsedKey = x509.MarshalPKCS1PrivateKey(rsaKey)
} else {
parsedKey, _ = x509.MarshalPKCS8PrivateKey(rsaKey)
}
return
}
// DecodeCertificate returns an x509.Certificate for a PEM encoded certificate
func DecodeCertificate(raw []byte) (cert *x509.Certificate, err error) {
block, _ := pem.Decode(raw)
if block == nil {
err = errors.New("Failed to decode x509 certificate from PEM")
return
}
cert, err = x509.ParseCertificate(block.Bytes)
return
}
// GeneratePass generates a random password
func GeneratePass(length int) (passw []byte) {
mathrand.Seed(time.Now().UnixNano())
var b strings.Builder
for i := 0; i < length; i++ {
b.WriteRune(passChars[mathrand.Intn(len(passChars))])
}
passw = []byte(b.String())
return
}
// EnsureSecretPassJKS ensures a JKS password is present in a certificate secret
func EnsureSecretPassJKS(secret *corev1.Secret) (injected *corev1.Secret, err error) {
// If the JKS Pass is already present - return
if _, ok := secret.Data[v1alpha1.PasswordKey]; ok {
return secret, nil
}
injected = secret.DeepCopy()
injected.Data[v1alpha1.PasswordKey] = GeneratePass(16)
return
}
// GenerateJKS creates a JKS with a random password from a client cert/key combination
func GenerateJKS(clientCert, clientKey, clientCA []byte) (out, passw []byte, err error) {
if len(clientCA) == 0 {
certs := strings.SplitAfter(string(clientCert), "-----END CERTIFICATE-----")
clientCert = []byte(certs[0])
clientCA = []byte(certs[len(certs)-1])
if len(certs) == 3 {
clientCA = []byte(certs[len(certs)-2])
}
}
cert, err := DecodeCertificate(clientCert)
if err != nil {
return
}
key, err := DecodeKey(clientKey)
if err != nil {
return
}
ca, err := DecodeCertificate(clientCA)
if err != nil {
return
}
certBundle := []keystore.Certificate{{
Type: "X.509",
Content: cert.Raw,
}}
jks := keystore.KeyStore{
cert.Subject.CommonName: &keystore.PrivateKeyEntry{
Entry: keystore.Entry{
CreationDate: time.Now(),
},
PrivKey: key,
CertChain: certBundle,
},
}
jks["trusted_ca"] = &keystore.TrustedCertificateEntry{
Entry: keystore.Entry{
CreationDate: time.Now(),
},
Certificate: keystore.Certificate{
Type: "X.509",
Content: ca.Raw,
},
}
var outBuf bytes.Buffer
passw = GeneratePass(16)
err = keystore.Encode(&outBuf, jks, passw)
return outBuf.Bytes(), passw, err
}
// GenerateTestCert is used from unit tests for generating certificates
func GenerateTestCert() (cert, key []byte, expectedDn string, err error) {
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return
}
priv, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return
}
template := x509.Certificate{
SerialNumber: serialNumber,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
IsCA: true,
Subject: pkix.Name{
CommonName: "test-cn",
Organization: []string{"test-ou"},
},
}
cert, err = x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
if err != nil {
return
}
buf := new(bytes.Buffer)
keyBuf := new(bytes.Buffer)
if err = pem.Encode(buf, &pem.Block{Type: "CERTIFICATE", Bytes: cert}); err != nil {
return
}
if err = pem.Encode(keyBuf, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)}); err != nil {
return
}
cert = buf.Bytes()
key = keyBuf.Bytes()
expectedDn = "CN=test-cn,O=test-ou"
return
}