-
Notifications
You must be signed in to change notification settings - Fork 689
/
SignCommandRunner.cs
250 lines (219 loc) · 9.46 KB
/
SignCommandRunner.cs
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
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using NuGet.Common;
using NuGet.Packaging;
using NuGet.Packaging.Signing;
using NuGet.Protocol;
namespace NuGet.Commands
{
/// <summary>
/// Command Runner used to run the business logic for nuget sign command
/// </summary>
public class SignCommandRunner : ISignCommandRunner
{
public async Task<int> ExecuteCommandAsync(SignArgs signArgs)
{
// resolve path into multiple packages if needed.
IEnumerable<string> packagesToSign = signArgs.PackagePaths.SelectMany(packagePath =>
{
IEnumerable<string> packages = LocalFolderUtility.ResolvePackageFromPath(packagePath);
LocalFolderUtility.EnsurePackageFileExists(packagePath, packages);
return packages;
});
var success = true;
X509Certificate2 cert = null;
try
{
cert = await GetCertificateAsync(signArgs);
}
catch (Exception e)
{
success = false;
ExceptionUtilities.LogException(e, signArgs.Logger);
}
if (success)
{
signArgs.Logger.LogInformation(Environment.NewLine);
signArgs.Logger.LogInformation(Strings.SignCommandDisplayCertificate);
signArgs.Logger.LogInformation(CertificateUtility.X509Certificate2ToString(cert, HashAlgorithmName.SHA256));
if (!string.IsNullOrEmpty(signArgs.Timestamper))
{
signArgs.Logger.LogInformation(Strings.SignCommandDisplayTimestamper);
signArgs.Logger.LogInformation(signArgs.Timestamper);
}
if (!string.IsNullOrEmpty(signArgs.OutputDirectory))
{
signArgs.Logger.LogInformation(Strings.SignCommandOutputPath);
signArgs.Logger.LogInformation(signArgs.OutputDirectory);
}
using (var signRequest = new AuthorSignPackageRequest(cert, signArgs.SignatureHashAlgorithm, signArgs.TimestampHashAlgorithm))
{
return await ExecuteCommandAsync(
packagesToSign,
signRequest,
signArgs.Timestamper,
signArgs.Logger,
signArgs.OutputDirectory,
signArgs.Overwrite,
signArgs.Token);
}
}
return success ? 0 : 1;
}
public async Task<int> ExecuteCommandAsync(
IEnumerable<string> packagesToSign,
SignPackageRequest signPackageRequest,
string timestamper,
ILogger logger,
string outputDirectory,
bool overwrite,
CancellationToken token)
{
var success = true;
try
{
SigningUtility.Verify(signPackageRequest, logger);
}
catch (Exception e)
{
success = false;
ExceptionUtilities.LogException(e, logger);
}
if (success)
{
var signatureProvider = GetSignatureProvider(timestamper);
foreach (var packagePath in packagesToSign)
{
// Set the output of the signing operation to a temp file because signing cannot be done in place.
var tempPackageFile = new FileInfo(Path.GetTempFileName());
try
{
string outputPath;
if (string.IsNullOrEmpty(outputDirectory))
{
outputPath = packagePath;
}
else
{
outputPath = Path.Combine(outputDirectory, Path.GetFileName(packagePath));
}
using (var options = SigningOptions.CreateFromFilePaths(
packagePath,
tempPackageFile.FullName,
overwrite,
signatureProvider,
logger))
{
await SigningUtility.SignAsync(options, signPackageRequest, token);
}
if (tempPackageFile.Length > 0)
{
FileUtility.Replace(tempPackageFile.FullName, outputPath);
}
else
{
throw new SignatureException(Strings.Error_UnableToSignPackage);
}
}
catch (Exception e)
{
success = false;
ExceptionUtilities.LogException(e, logger);
}
finally
{
FileUtility.Delete(tempPackageFile.FullName);
}
}
}
if (success)
{
logger.LogInformation(Strings.SignCommandSuccess);
}
return success ? 0 : 1;
}
private static ISignatureProvider GetSignatureProvider(string timestamper)
{
Rfc3161TimestampProvider timestampProvider = null;
if (!string.IsNullOrEmpty(timestamper))
{
timestampProvider = new Rfc3161TimestampProvider(new Uri(timestamper));
}
return new X509SignatureProvider(timestampProvider);
}
private static async Task<X509Certificate2> GetCertificateAsync(SignArgs signArgs)
{
var certFindOptions = new CertificateSourceOptions()
{
CertificatePath = signArgs.CertificatePath,
CertificatePassword = signArgs.CertificatePassword,
Fingerprint = signArgs.CertificateFingerprint,
StoreLocation = signArgs.CertificateStoreLocation,
StoreName = signArgs.CertificateStoreName,
SubjectName = signArgs.CertificateSubjectName,
NonInteractive = signArgs.NonInteractive,
PasswordProvider = signArgs.PasswordProvider,
Token = signArgs.Token
};
// get matching certificates
var matchingCertCollection = await CertificateProvider.GetCertificatesAsync(certFindOptions);
if (matchingCertCollection.Count > 1)
{
#if IS_DESKTOP
if (signArgs.NonInteractive || !RuntimeEnvironmentHelper.IsWindows)
{
// if on non-windows os or in non interactive mode - display the certs and error out
signArgs.Logger.LogInformation(CertificateUtility.X509Certificate2CollectionToString(matchingCertCollection, HashAlgorithmName.SHA256));
throw new SignCommandException(
LogMessage.CreateError(NuGetLogCode.NU3001,
string.Format(CultureInfo.CurrentCulture, Strings.SignCommandMultipleCertException,
nameof(SignArgs.CertificateFingerprint))));
}
else
{
// Else launch UI to select
matchingCertCollection = X509Certificate2UI.SelectFromCollection(
FilterCodeSigningCertificates(matchingCertCollection),
Strings.SignCommandDialogTitle,
Strings.SignCommandDialogMessage,
X509SelectionFlag.SingleSelection);
}
#else
// if on non-windows os or in non interactive mode - display and error out
signArgs.Logger.LogError(CertificateUtility.X509Certificate2CollectionToString(matchingCertCollection, HashAlgorithmName.SHA256));
throw new SignCommandException(
LogMessage.CreateError(NuGetLogCode.NU3001,
string.Format(CultureInfo.CurrentCulture, Strings.SignCommandMultipleCertException,
nameof(SignArgs.CertificateFingerprint))));
#endif
}
if (matchingCertCollection.Count == 0)
{
throw new SignCommandException(
LogMessage.CreateError(NuGetLogCode.NU3001,
Strings.SignCommandNoCertException));
}
return matchingCertCollection[0];
}
private static X509Certificate2Collection FilterCodeSigningCertificates(X509Certificate2Collection matchingCollection)
{
var filteredCollection = new X509Certificate2Collection();
foreach (var certificate in matchingCollection)
{
if (CertificateUtility.IsValidForPurposeFast(certificate, Oids.CodeSigningEku))
{
filteredCollection.Add(certificate);
}
}
return filteredCollection;
}
}
}