-
Notifications
You must be signed in to change notification settings - Fork 63
/
tpp.go
862 lines (785 loc) · 26.7 KB
/
tpp.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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
/*
* Copyright 2018-2021 Venafi, Inc.
*
* 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 tpp
import (
"bytes"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"regexp"
"strings"
"time"
"github.com/Venafi/vcert/v4/pkg/certificate"
"github.com/Venafi/vcert/v4/pkg/endpoint"
)
const defaultKeySize = 2048
const defaultSignatureAlgorithm = x509.SHA256WithRSA
const defaultClientID = "vcert-sdk"
const defaultScope = "certificate:manage,revoke"
const defaultWorkloadName = "Default"
type customField struct {
Name string
Values []string
}
type application struct {
ObjectName string
Class string
DriverName string
ValidationHost string `json:",omitempty"`
ValidationPort string `json:",omitempty"`
}
type device struct {
PolicyDN string
ObjectName string
Host string
Applications []application
}
type certificateRequest struct {
PolicyDN string `json:",omitempty"`
CADN string `json:",omitempty"`
ObjectName string `json:",omitempty"`
Subject string `json:",omitempty"`
OrganizationalUnit string `json:",omitempty"`
Organization string `json:",omitempty"`
City string `json:",omitempty"`
State string `json:",omitempty"`
Country string `json:",omitempty"`
SubjectAltNames []sanItem `json:",omitempty"`
Contact string `json:",omitempty"`
CASpecificAttributes []nameValuePair `json:",omitempty"`
Origin string `json:",omitempty"`
PKCS10 string `json:",omitempty"`
KeyAlgorithm string `json:",omitempty"`
KeyBitSize int `json:",omitempty"`
EllipticCurve string `json:",omitempty"`
DisableAutomaticRenewal bool `json:",omitempty"`
CustomFields []customField `json:",omitempty"`
Devices []device `json:",omitempty"`
CertificateType string `json:",omitempty"`
}
type certificateRetrieveRequest struct {
CertificateDN string `json:",omitempty"`
Format string `json:",omitempty"`
Password string `json:",omitempty"`
IncludePrivateKey bool `json:",omitempty"`
IncludeChain bool `json:",omitempty"`
FriendlyName string `json:",omitempty"`
RootFirstOrder bool `json:",omitempty"`
}
type certificateRetrieveResponse struct {
CertificateData string `json:",omitempty"`
Format string `json:",omitempty"`
Filename string `json:",omitempty"`
Status string `json:",omitempty"`
Stage int `json:",omitempty"`
}
type RevocationReason int
// RevocationReasonsMap maps *certificate.RevocationRequest.Reason to TPP-specific webSDK codes
var RevocationReasonsMap = map[string]RevocationReason{
"": 0, // NoReason
"none": 0, //
"key-compromise": 1, // UserKeyCompromised
"ca-compromise": 2, // CAKeyCompromised
"affiliation-changed": 3, // UserChangedAffiliation
"superseded": 4, // CertificateSuperseded
"cessation-of-operation": 5, // OriginalUseNoLongerValid
}
type certificateRevokeRequest struct {
CertificateDN string `json:",omitempty"`
Thumbprint string `json:",omitempty"`
Reason RevocationReason `json:",omitempty"`
Comments string `json:",omitempty"`
Disable bool `json:",omitempty"`
}
/* {Requested:true Success:true Error:} -- means requested
{Requested:false Success:true Error:} -- means already revoked */
type certificateRevokeResponse struct {
Requested bool `json:",omitempty"`
Success bool `json:",omitempty"`
Error string `json:",omitempty"`
}
type certificateRenewRequest struct {
CertificateDN string `json:",omitempty"`
PKCS10 string `json:",omitempty"`
}
type certificateRenewResponse struct {
Success bool `json:",omitempty"`
Error string `json:",omitempty"`
}
type sanItem struct {
Type int `json:""`
Name string `json:""`
}
type nameValuePair struct {
Name string `json:",omitempty"`
Value string `json:",omitempty"`
}
type nameSliceValuePair struct {
Name string
Value []string
}
type certificateRequestResponse struct {
CertificateDN string `json:",omitempty"`
Error string `json:",omitempty"`
}
type importRequest struct {
PolicyDN string `json:",omitempty"`
ObjectName string `json:",omitempty"`
CertificateData string `json:",omitempty"`
PrivateKeyData string `json:",omitempty"`
Password string `json:",omitempty"`
Reconcile bool `json:",omitempty"`
}
type authorizeResponse struct {
APIKey string `json:",omitempty"`
ValidUntil string `json:",omitempty"` //todo: add usage
}
type authorizeResquest struct {
Username string `json:",omitempty"`
Password string `json:",omitempty"`
}
type refreshAccessTokenResquest struct {
Client_id string `json:"client_id"`
Refresh_token string `json:"refresh_token"`
}
type oauthGetRefreshTokenRequest struct {
Client_id string `json:"client_id"`
Username string `json:"username"`
Password string `json:"password"`
Scope string `json:"scope"`
}
type OauthGetRefreshTokenResponse struct {
Access_token string `json:"access_token,omitempty"`
Expires int `json:"expires,omitempty"`
Identity string `json:"identity,omitempty"`
Refresh_token string `json:"refresh_token,omitempty"`
Scope string `json:"scope,omitempty"`
Token_type string `json:"token_type,omitempty"`
}
type oauthRefreshAccessTokenRequest struct {
Refresh_token string `json:"refresh_token,omitempty"`
Client_id string `json:"client_id"`
}
type oauthCertificateTokenRequest struct {
Client_id string `json:"client_id"`
Scope string `json:"scope,omitempty"`
}
type OauthRefreshAccessTokenResponse struct {
Access_token string `json:"access_token,omitempty"`
Expires int `json:"expires,omitempty"`
Identity string `json:"identity,omitempty"`
Refresh_token string `json:"refresh_token,omitempty"`
Token_type string `json:"token_type,omitempty"`
}
type OauthVerifyTokenResponse struct {
AccessIssuedOn string `json:"access_issued_on_ISO8601,omitempty"`
ClientID string `json:"application,omitempty"`
Expires string `json:"expires_ISO8601,omitempty"`
GrantIssuedOn string `json:"grant_issued_on_ISO8601,omitempty"`
Identity string `json:"identity,omitempty"`
Scope string `json:"scope,omitempty"`
ValidFor int `json:"valid_for,omitempty"`
}
type policyRequest struct {
ObjectDN string `json:",omitempty"`
Class string `json:",omitempty"`
AttributeName string `json:",omitempty"`
}
type metadataItem struct {
AllowedValues []string `json:",omitempty"`
Classes []string `json:",omitempty"`
ConfigAttribute string `json:",omitempty"`
DefaultValues []string `json:",omitempty"`
DN string `json:",omitempty"`
ErrorMessage string `json:",omitempty"`
Guid string `json:",omitempty"`
Help string `json:",omitempty"`
Label string `json:",omitempty"`
Name string `json:",omitempty"`
Policyable bool `json:",omitempty"`
RegularExpression string `json:",omitempty"`
RenderHidden bool `json:",omitempty"`
RenderReadOnly bool `json:",omitempty"`
Type int `json:",omitempty"`
}
type metadataKeyValueSet struct {
Key metadataItem `json:",omitempty"`
Value []string `json:",omitempty"`
}
type metadataGetItemsRequest struct {
ObjectDN string `json:"DN"`
}
type metadataGetItemsResponse struct {
Items []metadataItem `json:",omitempty"`
Locked bool `json:",omitempty"`
}
type metadataGetResponse struct {
Data []metadataKeyValueSet
Locked bool `json:",omitempty"`
}
type guidData struct {
ItemGuid string `json:",omitempty"`
List []string `json:",omitempty"`
}
type metadataSetRequest struct {
DN string `json:"DN"`
GuidData []guidData `json:"GuidData"`
KeepExisting bool `json:"KeepExisting"`
}
type metadataSetResponse struct {
Locked bool `json:",omitempty"`
Result int `json:",omitempty"`
}
type DNToGUIDResponse struct {
ClassName string `json:"ClassName"`
GUID string `json:"GUID"`
HierarchicalGUID string `json:"HierarchicalGUID"`
Result int `json:"Result"`
Revision int `json:"Revision"`
}
type DNToGUIDRequest struct {
ObjectDN string `json:"ObjectDN"`
}
type systemStatusVersionResponse string
type urlResource string
const (
urlResourceAuthorize urlResource = "vedsdk/authorize/"
urlResourceAuthorizeIsAuthServer urlResource = "vedauth/authorize/isAuthServer"
urlResourceAuthorizeCertificate urlResource = "vedauth/authorize/certificate"
urlResourceAuthorizeOAuth urlResource = "vedauth/authorize/oauth"
urlResourceAuthorizeVerify urlResource = "vedauth/authorize/verify"
urlResourceRefreshAccessToken urlResource = "vedauth/authorize/token" // #nosec
urlResourceRevokeAccessToken urlResource = "vedauth/revoke/token" // #nosec
urlResourceCertificateImport urlResource = "vedsdk/certificates/import"
urlResourceCertificatePolicy urlResource = "vedsdk/certificates/checkpolicy"
urlResourceCertificateRenew urlResource = "vedsdk/certificates/renew"
urlResourceCertificateRequest urlResource = "vedsdk/certificates/request"
urlResourceCertificateRetrieve urlResource = "vedsdk/certificates/retrieve"
urlResourceCertificateRevoke urlResource = "vedsdk/certificates/revoke"
urlResourceCertificatesAssociate urlResource = "vedsdk/certificates/associate"
urlResourceCertificatesDissociate urlResource = "vedsdk/certificates/dissociate"
urlResourceCertificate urlResource = "vedsdk/certificates/"
urlResourceCertificateSearch = urlResourceCertificate
urlResourceCertificatesList = urlResourceCertificate
urlResourceConfigDnToGuid urlResource = "vedsdk/config/dntoguid"
urlResourceConfigReadDn urlResource = "vedsdk/config/readdn"
urlResourceFindPolicy urlResource = "vedsdk/config/findpolicy"
urlResourceMetadataSet urlResource = "vedsdk/metadata/set"
urlResourceAllMetadataGet urlResource = "vedsdk/metadata/getitems"
urlResourceMetadataGet urlResource = "vedsdk/metadata/get"
urlResourceSystemStatusVersion urlResource = "vedsdk/systemstatus/version"
urlResourceCreatePolicy urlResource = "vedsdk/Config/Create"
urlResourceWritePolicy urlResource = "vedsdk/Config/WritePolicy"
urlResourceIsValidPolicy urlResource = "vedsdk/Config/isvalid"
urlResourceReadPolicy urlResource = "vedsdk/certificates/checkpolicy"
urlResourceCleanPolicy urlResource = "vedsdk/config/clearpolicyattribute"
urlResourceSshCertReq urlResource = "vedsdk/SSHCertificates/request"
urlResourceSshCertRet urlResource = "vedsdk/SSHCertificates/retrieve"
urlResourceSshCAPubKey urlResource = "vedsdk/SSHCertificates/Template/Retrieve/PublicKeyData"
urlResourceSshCADetails urlResource = "vedsdk/SSHCertificates/Template/Retrieve"
urlResourceSshTemplateAvaliable urlResource = "vedsdk/SSHCertificates/Template/Available"
urlResourceDNToGUID urlResource = "vedsdk/Config/DnToGuid"
)
const (
tppAttributeOrg = "Organization"
tppAttributeOrgUnit = "Organizational Unit"
tppAttributeCountry = "Country"
tppAttributeState = "State"
tppAttributeLocality = "City"
tppAttributeKeyAlgorithm = "Key Algorithm"
tppAttributeKeySize = "Key Bit Strength"
tppAttributeEllipticCurve = "Elliptic Curve"
tppAttributeRequestHash = "PKCS10 Hash Algorithm"
tppAttributeManagementType = "Management Type"
tppAttributeManualCSR = "Manual Csr"
)
type tppPolicyData struct {
Error string `json:",omitempty"`
Result int `json:",omitempty"`
Values []string `json:",omitempty"`
Locked bool `json:",omitempty"`
}
type retrieveChainOption int
const (
retrieveChainOptionRootLast retrieveChainOption = iota
retrieveChainOptionRootFirst
retrieveChainOptionIgnore
)
const (
pkcs10HashAlgorithmSha1 = 0
pkcs10HashAlgorithmSha256 = 1
pkcs10HashAlgorithmSha384 = 2
pkcs10HashAlgorithmSha512 = 3
)
func retrieveChainOptionFromString(order string) retrieveChainOption {
switch strings.ToLower(order) {
case "root-first":
return retrieveChainOptionRootFirst
case "ignore":
return retrieveChainOptionIgnore
default:
return retrieveChainOptionRootLast
}
}
func (c *Connector) request(method string, resource urlResource, data interface{}) (statusCode int, statusText string, body []byte, err error) {
url := c.baseURL + string(resource)
var payload io.Reader
var b []byte
if method == "POST" || method == "PUT" {
b, _ = json.Marshal(data)
payload = bytes.NewReader(b)
}
r, _ := http.NewRequest(method, url, payload)
r.Close = true
if c.accessToken != "" {
r.Header.Add("Authorization", fmt.Sprintf("Bearer %s", c.accessToken))
} else if c.apiKey != "" {
r.Header.Add("x-venafi-api-key", c.apiKey)
}
r.Header.Add("content-type", "application/json")
r.Header.Add("cache-control", "no-cache")
res, err := c.getHTTPClient().Do(r)
if res != nil {
statusCode = res.StatusCode
statusText = res.Status
}
if err != nil {
return
}
defer res.Body.Close()
body, err = ioutil.ReadAll(res.Body)
// Do not enable trace in production
trace := false // IMPORTANT: sensitive information can be diclosured
// I hope you know what are you doing
if trace {
log.Println("#################")
log.Printf("Headers are:\n%s", r.Header)
if method == "POST" || method == "PUT" {
log.Printf("JSON sent for %s\n%s\n", url, string(b))
} else {
log.Printf("%s request sent to %s\n", method, url)
}
log.Printf("Response:\n%s\n", string(body))
} else if c.verbose {
log.Printf("Got %s status for %s %s\n", statusText, method, url)
}
return
}
func (c *Connector) getHTTPClient() *http.Client {
if c.client != nil {
return c.client
}
var netTransport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}).DialContext,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
tlsConfig := http.DefaultTransport.(*http.Transport).TLSClientConfig
/* #nosec */
if c.trust != nil {
if tlsConfig == nil {
tlsConfig = &tls.Config{}
} else {
tlsConfig = tlsConfig.Clone()
}
tlsConfig.RootCAs = c.trust
}
netTransport.TLSClientConfig = tlsConfig
c.client = &http.Client{
Timeout: time.Second * 30,
Transport: netTransport,
}
return c.client
}
// GenerateRequest creates a new certificate request, based on the zone/policy configuration and the user data
func (c *Connector) GenerateRequest(config *endpoint.ZoneConfiguration, req *certificate.Request) (err error) {
if config == nil {
config, err = c.ReadZoneConfiguration()
if err != nil {
return fmt.Errorf("could not read zone configuration: %s", err)
}
}
tppMgmtType := config.CustomAttributeValues[tppAttributeManagementType]
if tppMgmtType == "Monitoring" || tppMgmtType == "Unassigned" {
return fmt.Errorf("Unable to request certificate from TPP, current TPP configuration would not allow the request to be processed")
}
config.UpdateCertificateRequest(req)
switch req.CsrOrigin {
case certificate.LocalGeneratedCSR:
if config.CustomAttributeValues[tppAttributeManualCSR] == "0" {
return fmt.Errorf("Unable to request certificate by local generated CSR when zone configuration is 'Manual Csr' = 0")
}
err = req.GeneratePrivateKey()
if err != nil {
return err
}
err = req.GenerateCSR()
if err != nil {
return err
}
case certificate.UserProvidedCSR:
if config.CustomAttributeValues[tppAttributeManualCSR] == "0" {
return fmt.Errorf("Unable to request certificate with user provided CSR when zone configuration is 'Manual Csr' = 0")
}
if len(req.GetCSR()) == 0 {
return fmt.Errorf("CSR was supposed to be provided by user, but it's empty")
}
case certificate.ServiceGeneratedCSR:
}
return nil
}
func getPolicyDN(zone string) string {
modified := zone
reg := regexp.MustCompile(`^\\VED\\Policy`)
if reg.FindStringIndex(modified) == nil {
reg = regexp.MustCompile(`^\\`)
if reg.FindStringIndex(modified) == nil {
modified = "\\" + modified
}
modified = "\\VED\\Policy" + modified
}
return modified
}
func getDeviceDN(zone string, location certificate.Location) string {
workload := location.Workload
if workload == "" {
workload = "Default"
}
return getPolicyDN(zone + "\\" + location.Instance + "\\" + workload)
}
func getCertificateDN(zone, cn string) string {
return getPolicyDN(zone + "\\" + cn)
}
func stripBackSlashes(s string) string {
var r = regexp.MustCompile(`\\+`)
result := r.ReplaceAll([]byte(s), []byte("\\"))
return string(result)
}
func parseConfigResult(httpStatusCode int, httpStatus string, body []byte) (tppData tppPolicyData, err error) {
tppData = tppPolicyData{}
switch httpStatusCode {
case http.StatusOK:
tppData, err := parseConfigData(body)
if err != nil {
return tppData, err
}
return tppData, nil
default:
return tppData, fmt.Errorf("Unexpected status code on TPP Config Operation. Status: %s", httpStatus)
}
}
func parseConfigData(b []byte) (data tppPolicyData, err error) {
err = json.Unmarshal(b, &data)
return
}
func parseRequestResult(httpStatusCode int, httpStatus string, body []byte) (string, error) {
switch httpStatusCode {
case http.StatusOK, http.StatusCreated:
reqData, err := parseRequestData(body)
if err != nil {
return "", err
}
return reqData.CertificateDN, nil
default:
return "", fmt.Errorf("Unexpected status code on TPP Certificate Request.\n Status:\n %s. \n Body:\n %s\n", httpStatus, body)
}
}
func parseRequestData(b []byte) (data certificateRequestResponse, err error) {
err = json.Unmarshal(b, &data)
return
}
func parseRetrieveResult(httpStatusCode int, httpStatus string, body []byte) (certificateRetrieveResponse, error) {
var retrieveResponse certificateRetrieveResponse
switch httpStatusCode {
case http.StatusOK, http.StatusAccepted:
retrieveResponse, err := parseRetrieveData(body)
if err != nil {
return retrieveResponse, err
}
return retrieveResponse, nil
default:
return retrieveResponse, fmt.Errorf("Unexpected status code on TPP Certificate Retrieval. Status: %s", httpStatus)
}
}
func parseRetrieveData(b []byte) (data certificateRetrieveResponse, err error) {
err = json.Unmarshal(b, &data)
return
}
func parseRevokeResult(httpStatusCode int, httpStatus string, body []byte) (certificateRevokeResponse, error) {
var revokeResponse certificateRevokeResponse
switch httpStatusCode {
case http.StatusOK, http.StatusAccepted:
revokeResponse, err := parseRevokeData(body)
if err != nil {
return revokeResponse, err
}
return revokeResponse, nil
default:
return revokeResponse, fmt.Errorf("Unexpected status code on TPP Certificate Revocation. Status: %s", httpStatus)
}
}
func parseRevokeData(b []byte) (data certificateRevokeResponse, err error) {
err = json.Unmarshal(b, &data)
return
}
func parseRenewResult(httpStatusCode int, httpStatus string, body []byte) (resp certificateRenewResponse, err error) {
resp, err = parseRenewData(body)
if err != nil {
return resp, fmt.Errorf("failed to parse certificate renewal response. status: %s", httpStatus)
}
return resp, nil
}
func parseRenewData(b []byte) (data certificateRenewResponse, err error) {
err = json.Unmarshal(b, &data)
return
}
func newPEMCollectionFromResponse(base64Response string, chainOrder certificate.ChainOption) (*certificate.PEMCollection, error) {
if base64Response != "" {
certBytes, err := base64.StdEncoding.DecodeString(base64Response)
if err != nil {
return nil, err
}
return certificate.PEMCollectionFromBytes(certBytes, chainOrder)
}
return nil, nil
}
type _strValue struct {
Locked bool
Value string
}
type serverPolicy struct {
CertificateAuthority _strValue
CsrGeneration _strValue
KeyGeneration _strValue
KeyPair struct {
KeyAlgorithm _strValue
KeySize struct {
Locked bool
Value int
}
EllipticCurve struct {
Locked bool
Value string
}
}
ManagementType _strValue
PrivateKeyReuseAllowed bool
SubjAltNameDnsAllowed bool
SubjAltNameEmailAllowed bool
SubjAltNameIpAllowed bool
SubjAltNameUpnAllowed bool
SubjAltNameUriAllowed bool
Subject struct {
City _strValue
Country _strValue
Organization _strValue
OrganizationalUnit struct {
Locked bool
Values []string
}
State _strValue
}
UniqueSubjectEnforced bool
WhitelistedDomains []string
WildcardsAllowed bool
}
func (sp serverPolicy) toZoneConfig(zc *endpoint.ZoneConfiguration) {
zc.Country = sp.Subject.Country.Value
zc.Organization = sp.Subject.Organization.Value
zc.OrganizationalUnit = sp.Subject.OrganizationalUnit.Values
zc.Province = sp.Subject.State.Value
zc.Locality = sp.Subject.City.Value
key := endpoint.AllowedKeyConfiguration{}
err := key.KeyType.Set(sp.KeyPair.KeyAlgorithm.Value)
if err != nil {
return
}
if sp.KeyPair.KeySize.Value != 0 {
key.KeySizes = []int{sp.KeyPair.KeySize.Value}
}
if sp.KeyPair.EllipticCurve.Value != "" {
curve := certificate.EllipticCurveNotSet
err = curve.Set(sp.KeyPair.EllipticCurve.Value)
if err == nil {
key.KeyCurves = append(key.KeyCurves, curve)
}
}
zc.KeyConfiguration = &key
}
func (sp serverPolicy) toPolicy() (p endpoint.Policy) {
addStartEnd := func(s string) string {
if !strings.HasPrefix(s, "^") {
s = "^" + s
}
if !strings.HasSuffix(s, "$") {
s = s + "$"
}
return s
}
escapeOne := func(s string) string {
return addStartEnd(regexp.QuoteMeta(s))
}
escapeArray := func(l []string) []string {
escaped := make([]string, len(l))
for i, r := range l {
escaped[i] = escapeOne(r)
}
return escaped
}
const allAllowedRegex = ".*"
if len(sp.WhitelistedDomains) == 0 {
p.SubjectCNRegexes = []string{allAllowedRegex}
} else {
p.SubjectCNRegexes = make([]string, len(sp.WhitelistedDomains))
for i, d := range sp.WhitelistedDomains {
if sp.WildcardsAllowed {
p.SubjectCNRegexes[i] = addStartEnd(`([\p{L}\p{N}-*]+\.)*` + regexp.QuoteMeta(d))
} else {
p.SubjectCNRegexes[i] = addStartEnd(`([\p{L}\p{N}-]+\.)*` + regexp.QuoteMeta(d))
}
}
}
if sp.Subject.OrganizationalUnit.Locked {
p.SubjectOURegexes = escapeArray(sp.Subject.OrganizationalUnit.Values)
} else {
p.SubjectOURegexes = []string{allAllowedRegex}
}
if sp.Subject.Organization.Locked {
p.SubjectORegexes = []string{escapeOne(sp.Subject.Organization.Value)}
} else {
p.SubjectORegexes = []string{allAllowedRegex}
}
if sp.Subject.City.Locked {
p.SubjectLRegexes = []string{escapeOne(sp.Subject.City.Value)}
} else {
p.SubjectLRegexes = []string{allAllowedRegex}
}
if sp.Subject.State.Locked {
p.SubjectSTRegexes = []string{escapeOne(sp.Subject.State.Value)}
} else {
p.SubjectSTRegexes = []string{allAllowedRegex}
}
if sp.Subject.Country.Locked {
p.SubjectCRegexes = []string{escapeOne(sp.Subject.Country.Value)}
} else {
p.SubjectCRegexes = []string{allAllowedRegex}
}
if sp.SubjAltNameDnsAllowed {
if len(sp.WhitelistedDomains) == 0 {
p.DnsSanRegExs = []string{allAllowedRegex}
} else {
p.DnsSanRegExs = make([]string, len(sp.WhitelistedDomains))
for i, d := range sp.WhitelistedDomains {
if sp.WildcardsAllowed {
p.DnsSanRegExs[i] = addStartEnd(`([\p{L}\p{N}-*]+\.)*` + regexp.QuoteMeta(d))
} else {
p.DnsSanRegExs[i] = addStartEnd(`([\p{L}\p{N}-]+\.)*` + regexp.QuoteMeta(d))
}
}
}
} else {
p.DnsSanRegExs = []string{}
}
if sp.SubjAltNameIpAllowed {
p.IpSanRegExs = []string{allAllowedRegex}
} else {
p.IpSanRegExs = []string{}
}
if sp.SubjAltNameEmailAllowed {
p.EmailSanRegExs = []string{allAllowedRegex}
} else {
p.EmailSanRegExs = []string{}
}
if sp.SubjAltNameUriAllowed {
p.UriSanRegExs = []string{allAllowedRegex}
} else {
p.UriSanRegExs = []string{}
}
if sp.SubjAltNameUpnAllowed {
p.UpnSanRegExs = []string{allAllowedRegex}
} else {
p.UpnSanRegExs = []string{}
}
if sp.KeyPair.KeyAlgorithm.Locked {
var keyType certificate.KeyType
if err := keyType.Set(sp.KeyPair.KeyAlgorithm.Value); err != nil {
panic(err)
}
key := endpoint.AllowedKeyConfiguration{KeyType: keyType}
if keyType == certificate.KeyTypeRSA {
if sp.KeyPair.KeySize.Locked {
for _, i := range certificate.AllSupportedKeySizes() {
if i >= sp.KeyPair.KeySize.Value {
key.KeySizes = append(key.KeySizes, i)
}
}
} else {
key.KeySizes = certificate.AllSupportedKeySizes()
}
} else {
var curve certificate.EllipticCurve
if sp.KeyPair.EllipticCurve.Locked {
if err := curve.Set(sp.KeyPair.EllipticCurve.Value); err != nil {
panic(err)
}
key.KeyCurves = append(key.KeyCurves, curve)
} else {
key.KeyCurves = certificate.AllSupportedCurves()
}
}
p.AllowedKeyConfigurations = append(p.AllowedKeyConfigurations, key)
} else {
var ks []int
for _, s := range certificate.AllSupportedKeySizes() {
if !sp.KeyPair.KeySize.Locked || s >= sp.KeyPair.KeySize.Value {
ks = append(ks, s)
}
}
p.AllowedKeyConfigurations = append(p.AllowedKeyConfigurations, endpoint.AllowedKeyConfiguration{
KeyType: certificate.KeyTypeRSA, KeySizes: ks,
})
if sp.KeyPair.EllipticCurve.Locked {
var curve certificate.EllipticCurve
if err := curve.Set(sp.KeyPair.EllipticCurve.Value); err != nil {
panic(err)
}
p.AllowedKeyConfigurations = append(p.AllowedKeyConfigurations, endpoint.AllowedKeyConfiguration{
KeyType: certificate.KeyTypeECDSA, KeyCurves: []certificate.EllipticCurve{curve},
})
} else {
p.AllowedKeyConfigurations = append(p.AllowedKeyConfigurations, endpoint.AllowedKeyConfiguration{
KeyType: certificate.KeyTypeECDSA, KeyCurves: certificate.AllSupportedCurves(),
})
}
}
p.AllowWildcards = sp.WildcardsAllowed
p.AllowKeyReuse = sp.PrivateKeyReuseAllowed
return
}