-
Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathUtils.cs
301 lines (265 loc) · 11.3 KB
/
Utils.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
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
#if NET
using System.Formats.Tar;
#endif
namespace Microsoft.SignCheck
{
public static class Utils
{
#if NET
private static readonly HttpClient s_client = new(new SocketsHttpHandler { PooledConnectionLifetime = TimeSpan.FromMinutes(10) });
#endif
/// <summary>
/// Generate a hash for a string value using a given hash algorithm.
/// </summary>
/// <param name="value">The value to hash.</param>
/// <param name="hashName">The name of the <see cref="HashAlgorithm"/> to use.</param>
/// <returns>A string containing the hash result.</returns>
public static string GetHash(string value, string hashName)
{
byte[] bytes = Encoding.UTF8.GetBytes(value);
HashAlgorithm ha = CreateHashAlgorithm(hashName);
byte[] hash = ha.ComputeHash(bytes);
var sb = new StringBuilder();
foreach (byte b in hash)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
public static HashAlgorithm CreateHashAlgorithm(string hashName)
{
switch (hashName.ToUpperInvariant())
{
case "SHA256" or "SHA-256":
return SHA256.Create();
case "SHA1" or "SHA-1":
return SHA1.Create();
case "MD5":
return MD5.Create();
case "SHA384" or "SHA-384":
return SHA384.Create();
case "SHA512" or "SHA-512":
return SHA512.Create();
default:
throw new ArgumentException($"Unsupported hash algorithm name '{hashName}'", nameof(hashName));
}
}
/// <summary>
/// Converts a string containing wildcards (*, ?) into a regular expression pattern string.
/// </summary>
/// <param name="wildcardPattern">The string pattern.</param>
/// <returns>A string containing regular expression pattern.</returns>
public static string ConvertToRegexPattern(string wildcardPattern)
{
string escapedPattern = Regex.Escape(wildcardPattern).Replace(@"\*", ".*").Replace(@"\?", ".");
if ((wildcardPattern.EndsWith("*")) || (wildcardPattern.EndsWith("?")))
{
return escapedPattern;
}
else
{
return String.Concat(escapedPattern, "$");
}
}
/// <summary>
/// Gets the DateTime value from a string
/// Returns the specified default value if the match is unsuccessful or the timestamp value is 0.
/// </summary>
/// <param name="timestamp">The timestamp string to parse.</param>
/// <param name="defaultValue">The default DateTime value to return if parsing fails.</param>
/// <returns>The parsed DateTime value or the default value.</returns>
public static DateTime DateTimeOrDefault(this string timestamp, DateTime defaultValue)
{
if (string.IsNullOrEmpty(timestamp))
{
return defaultValue;
}
timestamp = Regex.Replace(timestamp, @"\s{2,}", " ").Trim();
// Try to parse the timestamp as a Unix timestamp (seconds since epoch)
if (long.TryParse(timestamp, out long unixTime) && unixTime > 0)
{
return DateTimeOffset.FromUnixTimeSeconds(unixTime).UtcDateTime;
}
// Try to parse the timestamp as a DateTime string
if (DateTime.TryParse(timestamp, out DateTime dateTime))
{
return dateTime;
}
if (TryParseCodeSignTimestamp(timestamp, out dateTime))
{
return dateTime;
}
if (TryParseOpensslTimestamp(timestamp, out dateTime))
{
return dateTime;
}
return defaultValue;
}
/// <summary>
/// Gets the value of a named group from a regex match.
/// Returns null if the match is unsuccessful.
/// </summary>
/// <param name="match">The regex match.</param>
/// <param name="groupName">The name of the group.</param>
/// <returns>The value of the named group or null if the match is unsuccessful.</returns>
public static string GroupValueOrDefault(this Match match, string groupName) =>
match.Success ? match.Groups[groupName].Value : null;
/// <summary>
/// Captures the console output of an action.
/// </summary>
/// <param name="action">The action to execute.</param>
/// <returns>A tuple containing the result of the action, the standard output, and the error output.</returns>
public static (bool, string, string) CaptureConsoleOutput(Func<bool> action)
{
var consoleOutput = Console.Out;
StringWriter outputWriter = new StringWriter();
Console.SetOut(outputWriter);
var errorOutput = Console.Error;
StringWriter errorOutputWriter = new StringWriter();
Console.SetError(errorOutputWriter);
try
{
bool result = action();
return (result, outputWriter.ToString(), errorOutputWriter.ToString());
}
finally
{
Console.SetOut(consoleOutput);
Console.SetError(errorOutput);
}
}
/// <summary>
/// Runs a bash command and returns the output, error, and exit code.
/// </summary>
/// <param name="command">The command to run.</param>
/// <returns>A tuple containing the exit code, output, and error.</returns>
public static (int exitCode, string output, string error) RunBashCommand(string command, string workingDirectory = null)
{
if (string.IsNullOrEmpty(workingDirectory))
{
workingDirectory = Environment.CurrentDirectory;
}
var psi = new ProcessStartInfo
{
FileName = "bash",
Arguments = $"-c \"{command}\"",
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
WorkingDirectory = workingDirectory,
};
using (var process = Process.Start(psi))
{
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
process.WaitForExit(10000); // 10 seconds
return (process.ExitCode, output, error);
}
}
#if NET
/// <summary>
/// Download the Microsoft and Azure Linux public keys and import them into the keyring.
/// </summary>
public static void DownloadAndConfigurePublicKeys(string tempDir)
{
string[] keyUrls = new string[]
{
"https://packages.microsoft.com/keys/microsoft.asc", // Microsoft public key
"https://raw.githubusercontent.com/microsoft/azurelinux/3.0/SPECS/azurelinux-repos/MICROSOFT-RPM-GPG-KEY" // Azure linux public key
};
foreach (string keyUrl in keyUrls)
{
string keyPath = Path.Combine(tempDir, Path.GetFileName(keyUrl));
using (Stream stream = s_client.GetStreamAsync(keyUrl).Result)
{
using (FileStream fileStream = File.Create(keyPath))
{
stream.CopyTo(fileStream);
}
}
(int exitCode, _, string error) = RunBashCommand($"gpg --import {keyPath}");
if (exitCode != 0)
{
throw new Exception($"Failed to import Microsoft public key: {(string.IsNullOrEmpty(error) ? "unknown error" : error)}");
}
}
}
/// <summary>
/// Gets the next entry in a tar archive.
/// </summary>
public static TarEntry TryGetNextTarEntry(this TarReader reader)
{
try
{
return reader.GetNextEntry();
}
catch (EndOfStreamException)
{
// The stream is empty
return null;
}
}
#endif
/// <summary>
/// Parses a code signing timestamp string into a DateTime object.
/// </summary>
private static bool TryParseCodeSignTimestamp(string timestamp, out DateTime dateTime)
{
// Normalize single-digit day and hour by adding a leading zero where necessary (e.g., "Feb 1," or "at 7:" => "Feb 01," or "at 07:")
string normalizedTimestamp = Regex.Replace(timestamp, @"(?<=\b[A-Za-z]{3}\s)(\d)(?=,\s)|(?<=at\s)(\d)(?=:)", match =>
{
return "0" + match.Value;
});
string codesignFormat = "MMM dd, yyyy 'at' hh:mm:ss tt";
if (DateTime.TryParseExact(normalizedTimestamp, codesignFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
{
return true;
}
return false;
}
/// <summary>
/// Parses an OpenSSL timestamp string into a DateTime object.
/// </summary>
private static bool TryParseOpensslTimestamp(string timestamp, out DateTime dateTime)
{
// As per https://www.ietf.org/rfc/rfc5280.txt, X.509 certificate time fields must be in GMT.
string timezone = timestamp.ExtractTimezone();
if (!string.IsNullOrEmpty(timezone) && timezone.Equals("GMT"))
{
// Normalize single-digit day and hour by adding a leading zero where necessary (e.g., "Feb 1" or "7:" => "Feb 01" or "07:").
string normalizedTimestamp = Regex.Replace(timestamp, @"(?<=\b[A-Za-z]{3}\s)(\d)(?=\s)|(?<=\s)(\d)(?=:)", match =>
{
return "0" + match.Value;
});
// GMT is equivalent to UTC+0
normalizedTimestamp = normalizedTimestamp.Replace(timezone, "+00:00").Trim();
string opensslFormat = "MMM dd HH:mm:ss yyyy zzz";
if (DateTime.TryParseExact(normalizedTimestamp, opensslFormat, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out dateTime))
{
return true;
}
}
dateTime = default;
return false;
}
/// <summary>
/// Extracts the timezone from a timestamp string.
/// </summary>
private static string ExtractTimezone(this string timestamp)
{
var timezoneRegex = new Regex(@"\s(?<timezone>[a-zA-Z]{3,4})");
return timezoneRegex.Match(timestamp).GroupValueOrDefault("timezone");
}
}
}