-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCreateCertificateRequestBuilder.cs
More file actions
265 lines (229 loc) · 10.7 KB
/
Copy pathCreateCertificateRequestBuilder.cs
File metadata and controls
265 lines (229 loc) · 10.7 KB
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
/*
Copyright � 2025 Keyfactor
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.
*/
using Google.Cloud.Security.PrivateCA.V1;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using Keyfactor.AnyGateway.Extensions;
using Keyfactor.Logging;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using X509Extension = Google.Cloud.Security.PrivateCA.V1.X509Extension;
namespace Keyfactor.Extensions.CAPlugin.GCPCAS.Client
{
public class CreateCertificateRequestBuilder : ICreateCertificateRequestBuilder
{
ILogger _logger = LogHandler.GetClassLogger<CreateCertificateRequestBuilder>();
private string _csrString;
private string _certificateTemplate;
private string _subject;
private Dictionary<string, string[]> _sans;
private int _certificateLifetimeDays = GCPCASPluginConfig.DefaultCertificateLifetime;
// Store additional extensions
private List<Google.Cloud.Security.PrivateCA.V1.X509Extension> _additionalExtensions = new List<X509Extension>();
public ICreateCertificateRequestBuilder WithCsr(string csr)
{
_logger.MethodEntry();
_csrString = csr;
_logger.MethodExit();
return this;
}
public ICreateCertificateRequestBuilder WithEnrollmentProductInfo(EnrollmentProductInfo productInfo)
{
_logger.MethodEntry();
if (productInfo.ProductID == GCPCASPluginConfig.NoTemplateName)
{
_certificateTemplate = null;
_logger.LogDebug($"{GCPCASPluginConfig.NoTemplateName} template selected.");
}
else
{
_logger.LogDebug($"Configuring request with {productInfo.ProductID} Certificate Template.");
_certificateTemplate = productInfo.ProductID;
}
if (productInfo.ProductParameters != null)
{
_logger.LogDebug($"Parsing Custom Enrollment Parameters");
if (productInfo.ProductParameters.TryGetValue(GCPCASPluginConfig.EnrollmentParametersConstants.CertificateLifetimeDays, out string certificateLifetimeDaysString))
{
if (int.TryParse(certificateLifetimeDaysString, out _certificateLifetimeDays))
{
_logger.LogDebug($"Using validity of {_certificateLifetimeDays} days.");
}
}
_logger.LogTrace($"Looping through extensions for Auto Enrollment Params");
// Extract Additional Extensions
foreach (var param in productInfo.ProductParameters)
{
if (param.Key.StartsWith("ExtensionData"))
{
string oid = param.Key.Replace("ExtensionData-", ""); // Extract OID from key
string base64Value = param.Value;
_logger.LogTrace($"Loggin oid and value {oid} {base64Value}");
if (oid != "2.5.29.17") //can't send Sans as an extension to google, they do not like this and you will get an error
{
var extension = CreateX509Extension(oid, base64Value);
if (extension != null)
{
_logger.LogTrace($"Adding Extension");
_additionalExtensions.Add(extension);
}
}
}
}
}
_logger.MethodExit();
return this;
}
public ICreateCertificateRequestBuilder WithEnrollmentType(EnrollmentType enrollmentType)
{
_logger.MethodEntry();
_logger.MethodExit();
return this;
}
public ICreateCertificateRequestBuilder WithRequestFormat(RequestFormat requestFormat)
{
_logger.MethodEntry();
if (requestFormat != RequestFormat.PKCS10)
{
throw new Exception($"Unsupported CSR format: {requestFormat}");
}
_logger.MethodExit();
return this;
}
public ICreateCertificateRequestBuilder WithSans(Dictionary<string, string[]> san)
{
_logger.MethodEntry();
_sans = new Dictionary<string, string[]>();
if (san != null && san.Count > 0)
{
foreach (var kvp in san)
{
if (kvp.Value != null && kvp.Value.Length > 0)
{
_logger.LogTrace($"San Type: {kvp.Key}, Values: {string.Join(", ", kvp.Value)}");
_sans[kvp.Key] = kvp.Value;
}
}
_logger.LogTrace($"Found {_sans.Count} SAN types");
}
_logger.MethodExit();
return this;
}
public ICreateCertificateRequestBuilder WithSubject(string subject)
{
_logger.MethodEntry();
if (!string.IsNullOrWhiteSpace(subject))
{
_logger.LogTrace($"Found subject {subject}");
_subject = subject;
}
_logger.MethodExit();
return this;
}
public CreateCertificateRequest Build(string locationId, string projectId, string caPool, string caId = null)
{
_logger.MethodEntry();
CaPoolName caPoolName = new CaPoolName(projectId, locationId, caPool);
CertificateConfig certConfig = new CertificateConfig();
certConfig.SubjectConfig = new CertificateConfig.Types.SubjectConfig();
if (!string.IsNullOrEmpty(_subject))
{
_logger.LogTrace($"Subject {_subject}");
Subject parsedSubject = SubjectParser.ParseFromString(_subject);
_logger.LogTrace($"Parsed Subject {JsonConvert.SerializeObject(parsedSubject)}");
certConfig.SubjectConfig.Subject = parsedSubject;
}
if (_sans != null && _sans.Count > 0)
{
_logger.LogTrace($"Getting Subject Alt Names from typed dictionary");
SubjectAltNames parsedSubjectAltNames = SubjectAltNamesParser.ParseFromTypedDictionary(_sans);
_logger.LogTrace($"Parsed AltNames {JsonConvert.SerializeObject(parsedSubjectAltNames)}");
certConfig.SubjectConfig.SubjectAltName = parsedSubjectAltNames;
}
if (!string.IsNullOrEmpty(_csrString))
{
_logger.LogTrace($"Putting Csr in public key {_csrString}");
ByteString csrByteString = ByteString.CopyFromUtf8(_csrString);
certConfig.PublicKey = new PublicKey
{
Format = PublicKey.Types.KeyFormat.Pem,
Key = csrByteString
};
_logger.LogTrace($"Serialized PublicKey {JsonConvert.SerializeObject(certConfig.PublicKey)}");
}
certConfig.X509Config = new X509Parameters();
if (_additionalExtensions.Count > 0)
{
_logger.LogTrace($"Adding additional Extensions");
_logger.LogTrace($"Serialized Additional Extensions {JsonConvert.SerializeObject(_additionalExtensions)}");
certConfig.X509Config.AdditionalExtensions.AddRange(_additionalExtensions);
}
_logger.LogTrace($"Creating The Certificate");
Certificate theCertificate = new Certificate
{
Lifetime = Duration.FromTimeSpan(new TimeSpan(_certificateLifetimeDays, 0, 0, 0)),
Config = certConfig
};
_logger.LogTrace($"Serialized theCertificate {JsonConvert.SerializeObject(theCertificate)}");
if (!string.IsNullOrWhiteSpace(_certificateTemplate))
{
CertificateTemplateName template = new CertificateTemplateName(projectId, locationId, _certificateTemplate);
theCertificate.CertificateTemplate = template.ToString();
_logger.LogTrace($"Serialized theCertificate after template {JsonConvert.SerializeObject(theCertificate)}");
}
CreateCertificateRequest theRequest = new CreateCertificateRequest
{
ParentAsCaPoolName = caPoolName,
CertificateId = Guid.NewGuid().ToString(),
Certificate = theCertificate,
};
if (!string.IsNullOrEmpty(caId))
{
theRequest.IssuingCertificateAuthorityId = caId.ToString();
_logger.LogTrace($"Set IssuingCertificateAuthority to {theRequest.IssuingCertificateAuthorityId}");
}
_logger.MethodExit();
return theRequest;
}
/// <summary>
/// Creates a properly formatted X509Extension from an OID and Base64-encoded value.
/// </summary>
private X509Extension CreateX509Extension(string oid, string base64EncodedValue)
{
try
{
_logger.MethodEntry();
// Decode the Base64-encoded value
byte[] decodedBytes = Convert.FromBase64String(base64EncodedValue);
_logger.MethodExit();
// Create the X.509 extension with the correct format
return new X509Extension
{
ObjectId = new ObjectId
{
ObjectIdPath = { oid.Split('.').Select(int.Parse) } // Convert OID to int array
},
Value = ByteString.CopyFrom(decodedBytes) // Store properly DER-encoded value
};
}
catch (Exception ex)
{
_logger.LogError($"Error processing extension {oid}: {ex.Message}");
return null;
}
}
}
}