-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathManagementBase.cs
More file actions
156 lines (135 loc) · 9.83 KB
/
Copy pathManagementBase.cs
File metadata and controls
156 lines (135 loc) · 9.83 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
// 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 Keyfactor.Logging;
using Keyfactor.Orchestrators.Common.Enums;
using Keyfactor.Orchestrators.Extensions;
using Keyfactor.PKI.Extensions;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.X509;
using System;
using System.IO;
using System.Linq.Expressions;
using static Org.BouncyCastle.Math.EC.ECCurve;
namespace Keyfactor.Extensions.Orchestrator.RemoteFile
{
public abstract class ManagementBase : RemoteFileJobTypeBase, IManagementJobExtension
{
public string ExtensionName => "Keyfactor.Extensions.Orchestrator.RemoteFile.Management";
internal RemoteCertificateStore certificateStore = new RemoteCertificateStore();
public JobResult ProcessJob(ManagementJobConfiguration config)
{
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);
PathFile storePathFile = RemoteCertificateStore.SplitStorePathFile(config.CertificateStoreDetails.StorePath);
switch (config.OperationType)
{
case CertStoreOperationType.Add:
logger.LogDebug($"BEGIN add Operation for {config.CertificateStoreDetails.StorePath} on {config.CertificateStoreDetails.ClientMachine}.");
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}.");
}
certificateStore.LoadCertificateStore(certificateStoreSerializer, false);
certificateStore.AddCertificate(config.JobCertificate.Alias ?? GetThumbprint(config.JobCertificate, logger), config.JobCertificate.Contents, config.Overwrite, config.JobCertificate.PrivateKeyPassword, 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}.");
}
break;
case CertStoreOperationType.Remove:
logger.LogDebug($"BEGIN Delete Operation for {config.CertificateStoreDetails.StorePath} on {config.CertificateStoreDetails.ClientMachine}.");
if (!certificateStore.DoesStoreExist())
{
throw new RemoteFileException($"Certificate store {config.CertificateStoreDetails.StorePath} does not exist on server {config.CertificateStoreDetails.ClientMachine}.");
}
else
{
certificateStore.LoadCertificateStore(certificateStoreSerializer, false);
certificateStore.DeleteCertificateByAlias(config.JobCertificate.Alias);
certificateStore.SaveCertificateStore(certificateStoreSerializer.SerializeRemoteCertificateStore(certificateStore.GetCertificateStore(), storePathFile.Path, storePathFile.File, StorePassword, certificateStore.RemoteHandler));
}
logger.LogDebug($"END Delete Operation for {config.CertificateStoreDetails.StorePath} on {config.CertificateStoreDetails.ClientMachine}.");
break;
case CertStoreOperationType.Create:
logger.LogDebug($"BEGIN create Operation for {config.CertificateStoreDetails.StorePath} on {config.CertificateStoreDetails.ClientMachine}.");
if (certificateStore.DoesStoreExist())
{
logger.LogWarning($"Certificate store {config.CertificateStoreDetails.StorePath} already exists.");
return new JobResult() { Result = OrchestratorJobStatusJobResult.Warning, JobHistoryId = config.JobHistoryId, FailureMessage = $"Certificate store {config.CertificateStoreDetails.StorePath} already exists. Site {config.CertificateStoreDetails.StorePath} on server {config.CertificateStoreDetails.ClientMachine}" };
}
else
{
certificateStore.CreateCertificateStore(certificateStoreSerializer, config.CertificateStoreDetails.Properties, config.CertificateStoreDetails.StorePath, logger);
}
logger.LogDebug($"END create Operation for {config.CertificateStoreDetails.StorePath} on {config.CertificateStoreDetails.ClientMachine}.");
break;
default:
return new JobResult() { Result = OrchestratorJobStatusJobResult.Failure, JobHistoryId = config.JobHistoryId, FailureMessage = $"Site {config.CertificateStoreDetails.StorePath} on server {config.CertificateStoreDetails.ClientMachine}: Unsupported operation: {config.OperationType.ToString()}" };
}
}
catch (Exception ex)
{
logger.LogError($"Exception for {config.Capability}: {RemoteFileException.FlattenExceptionMessages(ex, string.Empty)} for job id {config.JobId}");
return new JobResult() { Result = OrchestratorJobStatusJobResult.Failure, JobHistoryId = config.JobHistoryId, FailureMessage = RemoteFileException.FlattenExceptionMessages(ex, $"Site {config.CertificateStoreDetails.StorePath} on server {config.CertificateStoreDetails.ClientMachine}:") };
}
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 };
}
private string GetThumbprint (ManagementJobCertificate jobCertificate, ILogger logger)
{
logger.MethodEntry(LogLevel.Debug);
string thumbprint = string.Empty;
if (string.IsNullOrEmpty(jobCertificate.PrivateKeyPassword))
{
X509Certificate x = new X509Certificate(Convert.FromBase64String(jobCertificate.Contents));
thumbprint = x.Thumbprint();
}
else
{
using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(jobCertificate.Contents)))
{
Pkcs12StoreBuilder storeBuilder = new Pkcs12StoreBuilder();
Pkcs12Store store = storeBuilder.Build();
store.Load(ms, jobCertificate.PrivateKeyPassword.ToCharArray());
foreach (string alias in store.Aliases)
{
thumbprint = store.GetCertificate(alias).Certificate.Thumbprint();
break;
}
}
}
logger.MethodExit(LogLevel.Debug);
return thumbprint;
}
}
}