-
Notifications
You must be signed in to change notification settings - Fork 30
/
tls.go
182 lines (155 loc) · 4.9 KB
/
tls.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
// This file may have been modified by vArmor Authors. ("vArmor Modifications").
// All vArmor Modifications are Copyright 2022 vArmor Authors.
//
// Copyright 2021 Kyverno Authors
//
// 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 tls
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"math/big"
"net"
"strings"
"time"
"github.com/bytedance/vArmor/internal/config"
)
// CertificateProps Properties of TLS certificate which should be issued for webhook server.
type CertificateProps struct {
Service string
Namespace string
APIServerHost string
ServerIP string
}
// PemPair The pair of TLS certificate corresponding private key, both in PEM format.
type PemPair struct {
Certificate []byte
PrivateKey []byte
}
// KeyPair ...
type KeyPair struct {
Cert *x509.Certificate
Key *rsa.PrivateKey
}
// CertificateToPem ...
func CertificateToPem(certificateDER []byte) []byte {
certificate := &pem.Block{
Type: "CERTIFICATE",
Bytes: certificateDER,
}
return pem.EncodeToMemory(certificate)
}
// PrivateKeyToPem Creates PEM block from private key object.
func PrivateKeyToPem(rsaKey *rsa.PrivateKey) []byte {
privateKey := &pem.Block{
Type: "PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(rsaKey),
}
return pem.EncodeToMemory(privateKey)
}
// GenerateCACert creates the self-signed CA cert and private key.
// It will be used to sign the webhook server certificate.
func GenerateCACert(certValidityDuration time.Duration) (*KeyPair, *PemPair, error) {
now := time.Now()
begin := now.Add(-1 * time.Hour)
end := now.Add(certValidityDuration)
templ := &x509.Certificate{
SerialNumber: big.NewInt(0),
Subject: pkix.Name{
CommonName: config.CertCommonName,
},
NotBefore: begin,
NotAfter: end,
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment | x509.KeyUsageCertSign,
BasicConstraintsValid: true,
IsCA: true,
}
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, nil, fmt.Errorf("error generating key: %v", err)
}
der, err := x509.CreateCertificate(rand.Reader, templ, templ, key.Public(), key)
if err != nil {
return nil, nil, fmt.Errorf("error creating certificate: %v", err)
}
pemPair := &PemPair{
Certificate: CertificateToPem(der),
PrivateKey: PrivateKeyToPem(key),
}
cert, err := x509.ParseCertificate(der)
if err != nil {
return nil, nil, fmt.Errorf("error parsing certificate %v", err)
}
caCert := &KeyPair{
Cert: cert,
Key: key,
}
return caCert, pemPair, nil
}
// GenerateCertPem takes the results of GenerateCACert and uses it to create the
// PEM-encoded public certificate and private key, respectively.
func GenerateCertPem(caCert *KeyPair, props CertificateProps, certValidityDuration time.Duration, managerIP string, debug bool) (*PemPair, error) {
now := time.Now()
begin := now.Add(-1 * time.Hour)
end := now.Add(certValidityDuration)
csCommonName := props.Service
dnsNames := make([]string, 3)
dnsNames[0] = csCommonName
dnsNames[1] = fmt.Sprintf("%s.%s", props.Service, props.Namespace)
dnsNames[2] = GenerateInClusterServiceName(props)
var ips []net.IP
apiServerIP := net.ParseIP(props.APIServerHost)
if apiServerIP != nil {
ips = append(ips, apiServerIP)
} else {
dnsNames = append(dnsNames, props.APIServerHost)
}
if managerIP != "" && debug {
if strings.Contains(managerIP, ":") {
host, _, _ := net.SplitHostPort(managerIP)
managerIP = host
}
ip := net.ParseIP(managerIP)
ips = append(ips, ip)
}
templ := &x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{
CommonName: csCommonName,
},
DNSNames: dnsNames,
IPAddresses: ips,
NotBefore: begin,
NotAfter: end,
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, fmt.Errorf("error generating key for webhook %v", err)
}
der, err := x509.CreateCertificate(rand.Reader, templ, caCert.Cert, key.Public(), caCert.Key)
if err != nil {
return nil, fmt.Errorf("error creating certificate for webhook %v", err)
}
pemPair := &PemPair{
Certificate: CertificateToPem(der),
PrivateKey: PrivateKeyToPem(key),
}
return pemPair, nil
}