-
Notifications
You must be signed in to change notification settings - Fork 277
/
zts-rolecert.go
303 lines (265 loc) · 9.12 KB
/
zts-rolecert.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
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
// Copyright 2017 Yahoo Holdings, Inc.
// Licensed under the terms of the Apache version 2.0 license. See LICENSE file for terms.
package main
import (
"bytes"
"crypto"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"flag"
"fmt"
"github.com/ardielle/ardielle-go/rdl"
"io/ioutil"
"log"
"net"
"net/url"
"strings"
"github.com/AthenZ/athenz/clients/go/zts"
"github.com/AthenZ/athenz/libs/go/athenzutils"
)
type signer struct {
key crypto.Signer
algorithm x509.SignatureAlgorithm
}
var (
// VERSION gets set by the build script via the LDFLAGS.
VERSION string
// BUILD_DATE gets set by the build script via the LDFLAGS.
BUILD_DATE string
)
func printVersion() {
if VERSION == "" {
fmt.Println("zts-rolecert (development version)")
} else {
fmt.Println("zts-rolecert " + VERSION + " " + BUILD_DATE)
}
}
func main() {
var ztsURL, svcKeyFile, svcCertFile, roleKeyFile, dom, svc, oldRoleCertFile string
var caCertFile, roleCertFile, roleDomain, roleName, dnsDomain string
var subjC, subjO, subjOU, ip, uri string
var spiffe, csr, proxy, showVersion bool
var expiryTime int
flag.StringVar(&roleKeyFile, "role-key-file", "", "role cert private key file (default: service identity private key)")
flag.StringVar(&roleCertFile, "role-cert-file", "", "output role certificate file")
flag.StringVar(&caCertFile, "cacert", "", "CA certificate file")
flag.StringVar(&svcKeyFile, "svc-key-file", "", "service identity private key file (required)")
flag.StringVar(&svcCertFile, "svc-cert-file", "", "service identity certificate file (required)")
flag.StringVar(&dom, "domain", "", "domain of service")
flag.StringVar(&svc, "service", "", "name of service")
flag.StringVar(&ztsURL, "zts", "", "url of the ZTS Service (required)")
flag.StringVar(&roleDomain, "role-domain", "", "requested role domain name (required)")
flag.StringVar(&roleName, "role-name", "", "requested role name in the role-domain (required)")
flag.StringVar(&dnsDomain, "dns-domain", "", "dns domain suffix to be included in the csr (required)")
flag.StringVar(&subjC, "subj-c", "US", "Subject C/Country field")
flag.StringVar(&subjO, "subj-o", "Oath Inc.", "Subject O/Organization field")
flag.StringVar(&subjOU, "subj-ou", "Athenz", "Subject OU/OrganizationalUnit field")
flag.StringVar(&ip, "ip", "", "IP address")
flag.StringVar(&oldRoleCertFile, "old-role-cert", "", "optional old role cert path to determin priority")
flag.BoolVar(&spiffe, "spiffe", true, "include spiffe uri in csr")
flag.BoolVar(&csr, "csr", false, "request csr only")
flag.IntVar(&expiryTime, "expiry-time", 0, "expiry time in minutes")
flag.BoolVar(&proxy, "proxy", true, "enable proxy mode for request")
flag.BoolVar(&showVersion, "version", false, "Show version")
flag.Parse()
if showVersion {
printVersion()
return
}
if svcKeyFile == "" || svcCertFile == "" || roleDomain == "" || roleName == "" ||
ztsURL == "" || dnsDomain == "" {
log.Fatalln("Error: missing required attributes. Run with -help for command line arguments")
}
// If a separate private key is not provided for role cert csr, use service identity private key
if roleKeyFile == "" {
roleKeyFile = svcKeyFile
}
// let's extract our domain/service values from our certificate
domain, service, err := extractServiceDetailsFromCert(svcCertFile)
if err != nil {
log.Fatalf("Unable to extract service details from certificate: %v\n", err)
}
hyphenDomain := strings.Replace(domain, ".", "-", -1)
host := fmt.Sprintf("%s.%s.%s", service, hyphenDomain, dnsDomain)
principal := fmt.Sprintf("%s.%s", domain, service)
if spiffe {
uri = fmt.Sprintf("spiffe://%s/ra/%s", roleDomain, roleName)
}
//note: RFC 6125 states that if the SAN (Subject Alternative Name) exists,
//it is used, not the CA. So, we will always put the Athens name in the CN
//(it is *not* a DNS domain name), and put the host name into the SAN.
commonName := fmt.Sprintf("%s:role.%s", roleDomain, roleName)
subj := pkix.Name{
CommonName: commonName,
OrganizationalUnit: []string{subjOU},
Organization: []string{subjO},
Country: []string{subjC},
}
// load private key
keyBytes, err := ioutil.ReadFile(roleKeyFile)
if err != nil {
log.Fatalf("Unable to read private key file %s, err: %v\n", roleKeyFile, err)
}
// get our private key signer for csr
pkSigner, err := newSigner(keyBytes)
if err != nil {
log.Fatalf("Unable to retrieve private key %s, err: %v\n", svcKeyFile, err)
}
csrData, err := generateCSR(pkSigner, subj, host, principal, dnsDomain, ip, uri)
if err != nil {
log.Fatalf("Unable to generate CSR for %s, err: %v\n", roleName, err)
}
// if we're provided the csr flag then we're going to display
// it and return right away
if csr {
fmt.Println(csrData)
return
}
client, err := athenzutils.ZtsClient(ztsURL, svcKeyFile, svcCertFile, caCertFile, proxy)
if err != nil {
log.Fatalf("Unable to initialize ZTS Client for %s, err: %v\n", ztsURL, err)
}
getRoleCertificate(client, csrData, roleDomain, roleName, roleCertFile, int64(expiryTime), oldRoleCertFile)
}
func extractServiceDetailsFromCert(certFile string) (string, string, error) {
data, err := ioutil.ReadFile(certFile)
if err != nil {
return "", "", err
}
block, _ := pem.Decode(data)
if block == nil {
return "", "", fmt.Errorf("cannot decode pem from certificate file: %s", certFile)
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return "", "", err
}
cn := cert.Subject.CommonName
idx := strings.LastIndex(cn, ".")
if idx < 0 {
return "", "", fmt.Errorf("cannot determine domain/service from certificate: %s", cn)
}
return cn[:idx], cn[idx+1:], nil
}
func generateCSR(keySigner *signer, subj pkix.Name, host, principal, dnsDomain, ip, uri string) (string, error) {
template := x509.CertificateRequest{
Subject: subj,
SignatureAlgorithm: keySigner.algorithm,
}
if host != "" {
template.DNSNames = []string{host}
}
if ip != "" {
template.IPAddresses = []net.IP{net.ParseIP(ip)}
}
rfc822 := fmt.Sprintf("%s@%s", principal, dnsDomain)
template.EmailAddresses = []string{rfc822}
if uri != "" {
uriptr, err := url.Parse(uri)
if err == nil {
template.URIs = []*url.URL{uriptr}
}
}
principalUri := fmt.Sprintf("athenz://principal/%s", principal)
principalUriPtr, err := url.Parse(principalUri)
if err == nil {
if len(template.URIs) > 0 {
template.URIs = append(template.URIs, principalUriPtr)
} else {
template.URIs = []*url.URL{principalUriPtr}
}
}
csr, err := x509.CreateCertificateRequest(rand.Reader, &template, keySigner.key)
if err != nil {
return "", fmt.Errorf("cannot create CSR: %v", err)
}
block := &pem.Block{
Type: "CERTIFICATE REQUEST",
Bytes: csr,
}
var buf bytes.Buffer
err = pem.Encode(&buf, block)
if err != nil {
return "", fmt.Errorf("cannot encode CSR to PEM: %v", err)
}
return buf.String(), nil
}
func CertFromFile(filename string) (*x509.Certificate, error) {
pemBytes, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
return CertFromPEMBytes(pemBytes)
}
func CertFromPEMBytes(pemBytes []byte) (*x509.Certificate, error) {
var derBytes []byte
block, _ := pem.Decode(pemBytes)
if block == nil {
return nil, fmt.Errorf("Cannot parse cert (empty pem)")
}
derBytes = block.Bytes
cert, err := x509.ParseCertificate(derBytes)
if err != nil {
return nil, err
}
return cert, nil
}
func getRoleCertificate(client *zts.ZTSClient, csr, roleDomain, roleName, roleCertFile string, expiryTime int64, oldRoleCertFile string) {
var notBefore *rdl.Timestamp
var notAfter *rdl.Timestamp
if oldRoleCertFile != "" {
// Extract before / after dates from old certificate
prevRolCert, err := CertFromFile(oldRoleCertFile)
if err != nil {
log.Fatalf("Unable to read cert %s, err: %v\n", oldRoleCertFile, err)
}
notBefore = &rdl.Timestamp{
Time: prevRolCert.NotBefore,
}
notAfter = &rdl.Timestamp{
Time: prevRolCert.NotAfter,
}
}
roleRequest := &zts.RoleCertificateRequest{
Csr: csr,
ExpiryTime: expiryTime,
PrevCertNotBefore: notBefore,
PrevCertNotAfter: notAfter,
}
roleCertificate, err := client.PostRoleCertificateRequestExt(roleRequest)
if err != nil {
log.Fatalf("PostRoleCertificateRequestExt failed for %s:role.%s, err: %v\n", roleDomain, roleName, err)
}
if roleCertFile != "" {
err = ioutil.WriteFile(roleCertFile, []byte(roleCertificate.X509Certificate), 0644)
if err != nil {
log.Fatalf("Unable to save role token certificate in %s, err: %v\n", roleCertFile, err)
}
} else {
fmt.Println(roleCertificate.X509Certificate)
}
}
func newSigner(privateKeyPEM []byte) (*signer, error) {
block, _ := pem.Decode(privateKeyPEM)
if block == nil {
return nil, fmt.Errorf("unable to load private key")
}
switch block.Type {
case "EC PRIVATE KEY":
key, err := x509.ParseECPrivateKey(block.Bytes)
if err != nil {
return nil, err
}
return &signer{key: key, algorithm: x509.ECDSAWithSHA256}, nil
case "RSA PRIVATE KEY":
key, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
return &signer{key: key, algorithm: x509.SHA256WithRSA}, nil
default:
return nil, fmt.Errorf("unsupported private key type: %s", block.Type)
}
}