-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathReenrollmentBase.cs
More file actions
139 lines (113 loc) · 7.47 KB
/
ReenrollmentBase.cs
File metadata and controls
139 lines (113 loc) · 7.47 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
// Copyright 2021 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 System;
using System.Collections.Generic;
using Keyfactor.Logging;
using Keyfactor.Orchestrators.Extensions;
using Keyfactor.Orchestrators.Common.Enums;
using Microsoft.Extensions.Logging;
using static Keyfactor.PKI.PKIConstants.X509;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace Keyfactor.Extensions.Orchestrator.RemoteFile
{
public abstract class ReenrollmentBase : RemoteFileJobTypeBase, IReenrollmentJobExtension
{
public string ExtensionName => "Keyfactor.Extensions.Orchestrator.RemoteFile";
internal RemoteCertificateStore certificateStore = new RemoteCertificateStore();
internal enum SupportedKeyTypeEnum
{
RSA,
ECC
}
//TODO:
// 1) Set SANs, Alias and Overwrite "for real" once product figures out how to pass that
// 2) Add "CreateCSROnDevice" (Y/N) to config.json
// 3) Add "TempFilePathForODKG" (string) to config.json
// 4) Add Reenrollment to manifest.json for all store types
// 5) Rename ProcessJobToDo to ProcessJob
// 6) Modify ReenrollmentBase to implement IReenrollmentJobExtension
// 6) Update README. Remember to explain the differences between ODKG and OOKG
public JobResult ProcessJob(ReenrollmentJobConfiguration config, SubmitReenrollmentCSR submitReenrollment)
{
ILogger logger = LogHandler.GetClassLogger(this.GetType());
ICertificateStoreSerializer certificateStoreSerializer = GetCertificateStoreSerializer(config.CertificateStoreDetails.Properties);
try
{
SetJobProperties(config, config.CertificateStoreDetails, logger);
certificateStore = new RemoteCertificateStore(config.CertificateStoreDetails.ClientMachine, UserName, UserPassword, config.CertificateStoreDetails.StorePath, StorePassword, SSHPort, IncludePortInSPN);
certificateStore.Initialize(SudoImpersonatedUser, UseShellCommands);
certificateStore.LoadCertificateStore(certificateStoreSerializer, false);
if (!certificateStore.DoesStoreExist())
{
if (ApplicationSettings.CreateStoreIfMissing)
certificateStore.CreateCertificateStore(certificateStoreSerializer, config.CertificateStoreDetails.Properties, config.CertificateStoreDetails.StorePath, logger);
else
throw new RemoteFileException($"Certificate store {config.CertificateStoreDetails.StorePath} does not exist on server {config.CertificateStoreDetails.ClientMachine}.");
}
// validate parameters
string KeyTypes = string.Join(",", Enum.GetNames(typeof(SupportedKeyTypeEnum)));
if (!Enum.TryParse(KeyType.ToUpper(), out SupportedKeyTypeEnum KeyTypeEnum))
{
throw new RemoteFileException($"Unsupported KeyType value {KeyType}. Supported types are {KeyTypes}.");
}
PathFile storePathFile = RemoteCertificateStore.SplitStorePathFile(config.CertificateStoreDetails.StorePath);
// generate CSR and call back to enroll certificate
string csr = string.Empty;
AsymmetricAlgorithm privateKey;
csr = certificateStore.GenerateCSR(SubjectText, config.Overwrite, config.Alias, KeyTypeEnum, KeySize, config.SANs, out privateKey);
X509Certificate2 cert = submitReenrollment.Invoke(csr);
if (cert == null)
throw new RemoteFileException("Enrollment of CSR failed. Please check Keyfactor Command logs for more information on potential enrollment errors.");
switch (privateKey)
{
case RSA rsa:
cert = cert.CopyWithPrivateKey(rsa);
break;
case ECDsa ecdsa:
cert = cert.CopyWithPrivateKey(ecdsa);
break;
case DSA dsa:
cert = cert.CopyWithPrivateKey(dsa);
break;
default:
throw new NotSupportedException($"Unsupported key type: {privateKey?.GetType().Name}");
}
// save certificate
certificateStore.AddCertificate(config.Alias ?? cert.Thumbprint, Convert.ToBase64String(cert.Export(X509ContentType.Pfx)), config.Overwrite, null, RemoveRootCertificate);
certificateStore.SaveCertificateStore(certificateStoreSerializer.SerializeRemoteCertificateStore(certificateStore.GetCertificateStore(), storePathFile.Path, storePathFile.File, StorePassword, certificateStore.RemoteHandler));
try
{
if (!string.IsNullOrEmpty(PostJobApplicationRestart))
certificateStore.RunPostJobCommand(PostJobApplicationRestart, config.CertificateStoreDetails.StorePath, certificateStoreSerializer.GetPrivateKeyPath());
}
catch (Exception ex)
{
logger.LogError($"Exception for {config.Capability} attempting post job command for {PostJobApplicationRestart}: {RemoteFileException.FlattenExceptionMessages(ex, string.Empty)} for job id {config.JobId}");
return new JobResult() { Result = OrchestratorJobStatusJobResult.Warning, JobHistoryId = config.JobHistoryId, FailureMessage = RemoteFileException.FlattenExceptionMessages(ex, $"Site {config.CertificateStoreDetails.StorePath} on server {config.CertificateStoreDetails.ClientMachine}: Certificate was successfully added to store, but post job command for {PostJobApplicationRestart} failed with: ") };
}
finally
{
logger.LogDebug($"END add Operation for {config.CertificateStoreDetails.StorePath} on {config.CertificateStoreDetails.ClientMachine}.");
}
}
catch (Exception ex)
{
string errorMessage = $"Exception for {config.Capability}: {RemoteFileException.FlattenExceptionMessages(ex, string.Empty)} for job id {config.JobId}";
logger.LogError(errorMessage);
return new JobResult() { Result = OrchestratorJobStatusJobResult.Failure, JobHistoryId = config.JobHistoryId, FailureMessage = $"Site {config.CertificateStoreDetails.StorePath} on server {config.CertificateStoreDetails.ClientMachine}: {errorMessage}" };
}
finally
{
if (certificateStore.RemoteHandler != null)
certificateStore.Terminate();
}
logger.LogDebug($"...End {config.Capability} job for job id {config.JobId}");
return new JobResult() { Result = OrchestratorJobStatusJobResult.Success, JobHistoryId = config.JobHistoryId };
}
}
}