forked from WalletWasabi/WalletWasabi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MacSignTools.cs
525 lines (437 loc) · 15.6 KB
/
MacSignTools.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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using WalletWasabi.Helpers;
namespace WalletWasabi.Packager;
public static class MacSignTools
{
public static void Sign(ArgsProcessor argsProcessor)
{
if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
throw new NotSupportedException("This signing method is only valid on macOS!");
}
Console.WriteLine("Phase: finding the zip file on desktop which contains the compiled binaries from Windows.");
string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string removableDriveFolder = Tools.GetSingleUsbDrive();
var srcZipFileNamePattern = "WasabiToNotarize-*";
var files = Directory.GetFiles(removableDriveFolder, srcZipFileNamePattern);
if (files.Length != 2)
{
throw new InvalidDataException($"{srcZipFileNamePattern} file missing or there are more! There must be exactly two!");
}
var (appleId, password) = argsProcessor.GetAppleIdAndPassword();
while (string.IsNullOrWhiteSpace(appleId))
{
Console.WriteLine("Enter appleId (email):");
appleId = Console.ReadLine();
}
while (string.IsNullOrWhiteSpace(password))
{
Console.WriteLine("Enter password:");
password = Console.ReadLine();
}
foreach (var zipPath in files)
{
var zipFile = Path.GetFileName(zipPath);
var versionPrefix = Path.GetFileNameWithoutExtension(zipPath).Split('-')[1]; // Example: "WasabiToNotarize-2.0.0.0-arm64.zip or WasabiToNotarize-2.0.0.0.zip ".
var workingDir = Path.Combine(desktopPath, "wasabiTemp");
var dmgPath = Path.Combine(workingDir, "dmg");
var unzippedPath = Path.Combine(workingDir, "unzipped");
var appName = $"{Constants.AppName}.app";
var appPath = Path.Combine(dmgPath, appName);
var appContentsPath = Path.Combine(appPath, "Contents");
var appMacOsPath = Path.Combine(appContentsPath, "MacOS");
var appResPath = Path.Combine(appContentsPath, "Resources");
var appFrameworksPath = Path.Combine(appContentsPath, "Frameworks");
var infoFilePath = Path.Combine(appContentsPath, "Info.plist");
var dmgFileName = zipFile.Replace("WasabiToNotarize", "Wasabi").Replace("zip", "dmg");
var dmgFilePath = Path.Combine(workingDir, dmgFileName);
var dmgUnzippedFilePath = Path.Combine(workingDir, $"Wasabi.tmp.dmg");
var appNotarizeFilePath = Path.Combine(workingDir, $"Wasabi-{versionPrefix}.zip");
var contentsPath = Path.GetFullPath(Path.Combine(Program.PackagerProjectDirectory.Replace("\\", "//"), "Content", "Osx"));
var entitlementsPath = Path.Combine(contentsPath, "entitlements.plist");
var dmgContentsDir = Path.Combine(contentsPath, "Dmg");
var desktopDmgFilePath = Path.Combine(desktopPath, dmgFileName);
var signArguments = $"--sign \"L233B2JQ68\" --verbose --force --options runtime --timestamp";
Console.WriteLine("Phase: creating the working directory.");
if (Directory.Exists(workingDir))
{
DeleteWithChmod(workingDir);
}
if (File.Exists(desktopDmgFilePath))
{
File.Delete(desktopDmgFilePath);
}
Console.WriteLine("Phase: creating the app.");
IoHelpers.EnsureDirectoryExists(appResPath);
IoHelpers.EnsureDirectoryExists(appMacOsPath);
ZipFile.ExtractToDirectory(zipPath, appMacOsPath); // Copy the binaries.
IoHelpers.CopyFilesRecursively(new DirectoryInfo(Path.Combine(contentsPath, "App")), new DirectoryInfo(appPath));
Console.WriteLine("Update the plist file with current information for example with version.");
var lines = File.ReadAllLines(infoFilePath);
string? bundleIdentifier = null;
for (int i = 0; i < lines.Length; i++)
{
string line = lines[i];
if (!line.TrimStart().StartsWith("<key>", StringComparison.InvariantCultureIgnoreCase))
{
continue;
}
if (line.Contains("CFBundleShortVersionString", StringComparison.InvariantCulture) ||
line.Contains("CFBundleVersion", StringComparison.InvariantCulture))
{
lines[i + 1] = lines[i + 1].Replace("?", $"{Version.Parse(versionPrefix).ToString(3)}"); // Apple allow only 3 version tags in plist.
}
else if (line.Contains("CFBundleIdentifier", StringComparison.InvariantCulture))
{
bundleIdentifier = lines[i + 1].Trim().Replace("<string>", "").Replace("</string>", "");
}
}
if (string.IsNullOrWhiteSpace(bundleIdentifier))
{
throw new InvalidDataException("Bundle identifier not found in plist file.");
}
File.Delete(infoFilePath);
File.WriteAllLines(infoFilePath, lines);
using (var process = Process.Start(new ProcessStartInfo
{
FileName = "chmod",
Arguments = $"-R u+rwX,go+rX,go-w \"{appPath}\"",
WorkingDirectory = workingDir
}))
{
WaitProcessToFinish(process, "chmod");
}
var filesToCheck = new[] { entitlementsPath };
foreach (var file in filesToCheck)
{
if (!File.Exists(file))
{
throw new FileNotFoundException($"File missing: {file}");
}
}
Console.WriteLine("Signing the files in app.");
IoHelpers.EnsureDirectoryExists(appResPath);
IoHelpers.EnsureDirectoryExists(appMacOsPath);
var executables = GetExecutables(appPath);
// The main executable needs to be signed last.
var filesToSignInOrder = Directory.GetFiles(appPath, "*.*", SearchOption.AllDirectories)
.OrderBy(file => executables.Contains(file))
.OrderBy(file => new FileInfo(file).Name == "wassabee")
.ToArray();
foreach (var file in executables)
{
using var process = Process.Start(new ProcessStartInfo
{
FileName = "chmod",
Arguments = $"u+x \"{file}\"",
WorkingDirectory = workingDir
});
WaitProcessToFinish(process, "chmod");
}
SignDirectory(filesToSignInOrder, workingDir, signArguments, entitlementsPath);
Console.WriteLine("Phase: verifying the signature.");
Verify(appPath);
Console.WriteLine("Phase: notarize the app.");
// Source: https://blog.frostwire.com/2019/08/27/apple-notarization-the-signature-of-the-binary-is-invalid-one-other-reason-not-explained-in-apple-developer-documentation/
using (var process = Process.Start(new ProcessStartInfo
{
FileName = "ditto",
Arguments = $"-c -k --keepParent \"{appPath}\" \"{appNotarizeFilePath}\"",
WorkingDirectory = workingDir
}))
{
WaitProcessToFinish(process, "ditto");
}
Notarize(appleId, password, appNotarizeFilePath, bundleIdentifier);
Staple(appPath);
using (var process = Process.Start(new ProcessStartInfo
{
FileName = "spctl",
Arguments = $"-a -t exec -vv \"{appPath}\"",
WorkingDirectory = workingDir,
RedirectStandardError = true
}))
{
var nonNullProcess = WaitProcessToFinish(process, "spctl");
string result = nonNullProcess.StandardError.ReadToEnd();
if (!result.Contains(": accepted"))
{
throw new InvalidOperationException(result);
}
}
Console.WriteLine("Phase: creating the dmg.");
if (File.Exists(dmgFilePath))
{
File.Delete(dmgFilePath);
}
Console.WriteLine("Phase: creating dmg.");
IoHelpers.CopyFilesRecursively(new DirectoryInfo(dmgContentsDir), new DirectoryInfo(dmgPath));
File.Copy(Path.Combine(contentsPath, "WasabiLogo.icns"), Path.Combine(dmgPath, ".VolumeIcon.icns"), true);
var temp = Path.Combine(dmgPath, ".DS_Store.dat");
File.Move(temp, Path.Combine(dmgPath, ".DS_Store"), true);
using (var process = Process.Start(new ProcessStartInfo
{
FileName = "ln",
Arguments = "-s /Applications",
WorkingDirectory = dmgPath
}))
{
WaitProcessToFinish(process, "ln");
}
var hdutilCreateArgs = string.Join(
" ",
new string[]
{
"create",
$"\"{dmgUnzippedFilePath}\"",
"-ov",
$"-volname \"Wasabi Wallet\"",
"-fs HFS+",
$"-srcfolder \"{dmgPath}\""
});
using (var process = Process.Start(new ProcessStartInfo
{
FileName = "hdiutil",
Arguments = hdutilCreateArgs,
WorkingDirectory = dmgPath
}))
{
WaitProcessToFinish(process, "hdiutil");
}
var hdutilConvertArgs = string.Join(
" ",
new string[]
{
"convert",
$"\"{dmgUnzippedFilePath}\"",
"-format UDZO",
$"-o \"{dmgFilePath}\""
});
using (var process = Process.Start(new ProcessStartInfo
{
FileName = "hdiutil",
Arguments = hdutilConvertArgs,
WorkingDirectory = dmgPath
}))
{
WaitProcessToFinish(process, "hdiutil");
}
Console.WriteLine("Phase: signing the dmg file.");
SignFile($"{signArguments} --entitlements \"{entitlementsPath}\" \"{dmgFilePath}\"", dmgPath);
Console.WriteLine("Phase: verifying the signature.");
Verify(dmgFilePath);
Console.WriteLine("Phase: notarize dmg");
Notarize(appleId, password, dmgFilePath, bundleIdentifier);
Console.WriteLine("Phase: staple dmp");
Staple(dmgFilePath);
using (var process = Process.Start(new ProcessStartInfo
{
FileName = "spctl",
Arguments = $"-a -t open --context context:primary-signature -v \"{dmgFilePath}\"",
WorkingDirectory = workingDir,
RedirectStandardError = true
}))
{
var nonNullProcess = WaitProcessToFinish(process, "spctl");
string result = nonNullProcess.StandardError.ReadToEnd();
if (!result.Contains(": accepted"))
{
throw new InvalidOperationException(result);
}
}
File.Move(dmgFilePath, desktopDmgFilePath);
DeleteWithChmod(workingDir);
Console.WriteLine("Phase: finish.");
var toRemovableFilePath = Path.Combine(removableDriveFolder, Path.GetFileName(desktopDmgFilePath));
File.Move(desktopDmgFilePath, toRemovableFilePath, true);
if (File.Exists(zipPath))
{
File.Delete(zipPath);
}
}
}
private static Process WaitProcessToFinish(Process? process, string processName)
{
if (process is null)
{
throw new InvalidOperationException($"Could not start ${processName} process.");
}
process.WaitForExit();
return process;
}
private static void Notarize(string appleId, string password, string filePath, string bundleIdentifier)
{
string? uploadId = null;
Console.WriteLine("Start notarizing, uploading file.");
using (var process = Process.Start(new ProcessStartInfo
{
FileName = "xcrun",
Arguments = $"altool --notarize-app -t osx -f \"{filePath}\" --primary-bundle-id \"{bundleIdentifier}\" -u \"{appleId}\" -p \"{password}\" --output-format xml",
RedirectStandardOutput = true,
}))
{
var nonNullProcess = WaitProcessToFinish(process, "xcrum");
string result = nonNullProcess.StandardOutput.ReadToEnd();
if (result.Contains("The software asset has already been uploaded. The upload ID is"))
{
// Example: The software asset has already been uploaded. The upload ID is 7689dc08-d6c8-4783-8d28-33e575f5c967
uploadId = result.Split('"').First(line => line.Contains("The software asset has already been uploaded.")).Split("The upload ID is")[^1].Trim();
}
else if (result.Contains("No errors uploading"))
{
// Example: <key>RequestUUID</key>\n\t\t<string>2a2a164f-2ae7-4293-8357-5d5a5cdd580a</string>
var lines = result.Split('\n');
for (int i = 0; i < lines.Length; i++)
{
string line = lines[i].Trim();
if (!line.TrimStart().StartsWith("<key>", StringComparison.InvariantCultureIgnoreCase))
{
continue;
}
if (line.Contains("<key>RequestUUID</key>", StringComparison.InvariantCulture))
{
uploadId = lines[i + 1].Trim().Replace("<string>", "").Replace("</string>", "");
}
}
}
}
if (uploadId is null)
{
throw new InvalidOperationException("Cannot get uploadId. Notarization failed.");
}
Stopwatch sw = new();
sw.Start();
while (true) // Wait for the notarization.
{
Console.WriteLine($"Checking notarization status. Elapsed time: {sw.Elapsed}");
using var process = Process.Start(new ProcessStartInfo
{
FileName = "xcrun",
Arguments = $"altool --notarization-info \"{uploadId}\" -u \"{appleId}\" -p \"{password}\"",
RedirectStandardError = true,
RedirectStandardOutput = true,
});
var nonNullProcess = WaitProcessToFinish(process, "xcrum");
string result = $"{nonNullProcess.StandardError.ReadToEnd()} {nonNullProcess.StandardOutput.ReadToEnd()}";
if (result.Contains("Status Message: Package Approved"))
{
break;
}
if (result.Contains("Status: in progress"))
{
Thread.Sleep(4000);
continue;
}
if (result.Contains("Could not find the RequestUUID"))
{
Thread.Sleep(4000);
continue;
}
throw new InvalidOperationException(result);
}
}
private static void Staple(string filePath)
{
using var process = Process.Start(new ProcessStartInfo
{
FileName = "xcrun",
Arguments = $"stapler staple \"{filePath}\"",
});
WaitProcessToFinish(process, "xcrum");
}
private static void DeleteWithChmod(string path)
{
using (var process = Process.Start(new ProcessStartInfo
{
FileName = "chmod",
Arguments = $"-R ugo+rwx \"{path}\"",
}))
{
WaitProcessToFinish(process, "chmod");
}
IoHelpers.TryDeleteDirectoryAsync(path).GetAwaiter().GetResult();
}
private static void SignFile(string arguments, string workingDir)
{
using var process = Process.Start(new ProcessStartInfo
{
FileName = "codesign",
Arguments = arguments,
WorkingDirectory = workingDir,
RedirectStandardError = true
});
var nonNullProcess = WaitProcessToFinish(process, "codesign");
var result = nonNullProcess.StandardError.ReadToEnd();
if (result.Contains("code object is not signed at all"))
{
throw new InvalidOperationException(result);
}
if (result.Contains("xcrun: error: invalid active developer path"))
{
throw new InvalidOperationException($"{result}\ntip: run xcode-select --install");
}
Console.WriteLine(result.Trim());
}
private static void Verify(string path)
{
using var process = Process.Start(new ProcessStartInfo
{
FileName = "codesign",
Arguments = $"-dv --verbose=4 \"{path}\"",
RedirectStandardError = true,
});
var nonNullProcess = WaitProcessToFinish(process, "codesign");
string result = nonNullProcess.StandardError.ReadToEnd();
if (!result.Contains("Authority=Developer ID Application: zkSNACKs Ltd."))
{
throw new InvalidOperationException(result);
}
}
private static void SignDirectory(string[] files, string workingDir, string signArguments, string entitlementsPath)
{
// Tor already signed by: The Tor Project, Inc (MADPSAYN6T)
// Wassabee has to be signed at the end. Otherwise codesign will throw a "submodule not signed" error.
foreach (var file in files)
{
var fileName = new FileInfo(file).Name;
if (fileName == ".DS_Store")
{
File.Delete(file);
continue;
}
SignFile($"{signArguments} --entitlements \"{entitlementsPath}\" \"{file}\"", workingDir);
}
}
private static IEnumerable<string> GetExecutables(string appPath)
{
string result = ExecuteBashCommand($"find -H \"{appPath}\" -print0 | xargs -0 file | grep \"Mach-O.* executable\"");
var lines = result.Split("\n").Where(x => !string.IsNullOrWhiteSpace(x));
var files = lines.Select(line => line.Split(":").First());
return files;
}
private static string ExecuteBashCommand(string command)
{
// according to: https://stackoverflow.com/a/15262019/637142
// Thanks to this we will pass everything as one command.
command = command.Replace("\"", "\"\"");
using var process = Process.Start(new ProcessStartInfo
{
FileName = "/bin/bash",
Arguments = $"-c \"{command}\"",
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
CreateNoWindow = true
})
?? throw new InvalidOperationException("Could not start bash process.");
var result = process.StandardOutput.ReadToEnd();
process.WaitForExit();
return result;
}
}