Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

#nullable enable

using System.Diagnostics;
using System.Text;

namespace Microsoft.AspNetCore.Certificates.Generation;

internal static class CertificateManagerProcessRunner

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

subjective nit: this class could be just called ProcessRunner as its more or less general purpose utility

Suggested change
internal static class CertificateManagerProcessRunner
internal static class ProcessRunner

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It makes sense, but as we are unlikely to repurpose this helper for anything else in release/10.0, I'll keep the existing name to get this in faster (but I admit that I agree ProcessRunner is a better name)

{
internal static ProcessExecutionResult Run(ProcessStartInfo processInfo)
Comment thread
adamsitnik marked this conversation as resolved.
Resolved
{
using var process = Process.Start(processInfo)
?? throw new InvalidOperationException($"Failed to start process '{processInfo.FileName}'.");
Comment thread
Youssef1313 marked this conversation as resolved.
Resolved

StringBuilder? outBuilder = null;
StringBuilder? errBuilder = null;
if (processInfo.RedirectStandardOutput)
{
process.OutputDataReceived += (_, e) =>
{
if (e.Data is not null)
{
(outBuilder ??= new()).AppendLine(e.Data);
}
};

process.BeginOutputReadLine();
}
Comment thread
Youssef1313 marked this conversation as resolved.
Resolved

if (processInfo.RedirectStandardError)
{
process.ErrorDataReceived += (_, e) =>
{
if (e.Data is not null)
{
(errBuilder ??= new()).AppendLine(e.Data);
}
};

process.BeginErrorReadLine();
}

process.WaitForExit();

return new ProcessExecutionResult(process.ExitCode, outBuilder?.ToString() ?? string.Empty, errBuilder?.ToString() ?? string.Empty);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: we could delay the allocation of both strings to the moment where the properties are being requested for the first time, so in case exit code == 0, they are not allocated.

Since this is just a backport and the previous version was already allocating this memory, it's just something to consider, not a must have

}

internal static int RunAndDiscardOutput(ProcessStartInfo processInfo)
{
using var process = Process.Start(processInfo)
?? throw new InvalidOperationException($"Failed to start process '{processInfo.FileName}'.");

if (processInfo.RedirectStandardOutput)
{
process.OutputDataReceived += static (_, _) => { };
process.BeginOutputReadLine();
}

if (processInfo.RedirectStandardError)
{
process.ErrorDataReceived += static (_, _) => { };
process.BeginErrorReadLine();
}

process.WaitForExit();
return process.ExitCode;
}
}

internal readonly record struct ProcessExecutionResult(int ExitCode, string StandardOutput, string StandardError);
36 changes: 13 additions & 23 deletions src/Shared/CertificateGeneration/MacOSCertificateManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -156,17 +156,17 @@ public override TrustLevel GetTrustLevel(X509Certificate2 certificate)
// We can't guarantee that the temp file is in a directory with sensible permissions, but we're not exporting the private key
ExportCertificate(certificate, tmpFile, includePrivateKey: false, password: null, CertificateKeyExportFormat.Pem);

using var checkTrustProcess = Process.Start(new ProcessStartInfo(
var checkTrustProcessStartInfo = new ProcessStartInfo(
MacOSVerifyCertificateCommandLine,
string.Format(CultureInfo.InvariantCulture, MacOSVerifyCertificateCommandLineArgumentsFormat, tmpFile))
{
RedirectStandardOutput = true,
// Do this to avoid showing output to the console when the cert is not trusted. It is trivial to export
// the cert and replicate the command to see details.
RedirectStandardError = true,
});
checkTrustProcess!.WaitForExit();
return checkTrustProcess.ExitCode == 0 ? TrustLevel.Full : TrustLevel.None;
};

return CertificateManagerProcessRunner.RunAndDiscardOutput(checkTrustProcessStartInfo) == 0 ? TrustLevel.Full : TrustLevel.None;
}
finally
{
Expand Down Expand Up @@ -254,18 +254,13 @@ private static void RemoveCertificateFromKeychain(string keychain, X509Certifica
Log.MacOSRemoveCertificateFromKeyChainStart(keychain, GetDescription(certificate));
}

using (var process = Process.Start(processInfo))
var processOutput = CertificateManagerProcessRunner.Run(processInfo);
if (processOutput.ExitCode != 0)
{
var output = process!.StandardOutput.ReadToEnd() + process.StandardError.ReadToEnd();
process.WaitForExit();
Log.MacOSRemoveCertificateFromKeyChainError(processOutput.ExitCode);
throw new InvalidOperationException($@"There was an error removing the certificate with thumbprint '{certificate.Thumbprint}'.

if (process.ExitCode != 0)
{
Log.MacOSRemoveCertificateFromKeyChainError(process.ExitCode);
throw new InvalidOperationException($@"There was an error removing the certificate with thumbprint '{certificate.Thumbprint}'.

{output}");
}
{processOutput.StandardOutput}{processOutput.StandardError}");
}

Log.MacOSRemoveCertificateFromKeyChainEnd();
Expand Down Expand Up @@ -355,16 +350,11 @@ private static void SaveCertificateToUserKeychain(X509Certificate2 certificate)
Log.MacOSAddCertificateToKeyChainStart(MacOSUserKeychain, GetDescription(certificate));
}

using (var process = Process.Start(processInfo))
var processOutput = CertificateManagerProcessRunner.Run(processInfo);
if (processOutput.ExitCode != 0)
{
var output = process!.StandardOutput.ReadToEnd() + process.StandardError.ReadToEnd();
process.WaitForExit();

if (process.ExitCode != 0)
{
Log.MacOSAddCertificateToKeyChainError(process.ExitCode, output);
throw new InvalidOperationException("Failed to add the certificate to the keychain. Are you running in a non-interactive session perhaps?");
}
Log.MacOSAddCertificateToKeyChainError(processOutput.ExitCode, processOutput.StandardOutput + processOutput.StandardError);
throw new InvalidOperationException("Failed to add the certificate to the keychain. Are you running in a non-interactive session perhaps?");
}

Log.MacOSAddCertificateToKeyChainEnd();
Expand Down
34 changes: 10 additions & 24 deletions src/Shared/CertificateGeneration/UnixCertificateManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -691,9 +691,7 @@ private static bool TrustCertificateInWindowsStore(X509Certificate2 certificate)
RedirectStandardError = true,
};

using var process = Process.Start(startInfo)!;
process.WaitForExit();
return process.ExitCode == 0;
return CertificateManagerProcessRunner.RunAndDiscardOutput(startInfo) == 0;
}

/// <remarks>
Expand All @@ -714,9 +712,7 @@ private static bool IsCertificateInNssDb(string nickname, NssDb nssDb)

try
{
using var process = Process.Start(startInfo)!;
process.WaitForExit();
return process.ExitCode == 0;
return CertificateManagerProcessRunner.RunAndDiscardOutput(startInfo) == 0;
}
catch (Exception ex)
{
Expand All @@ -743,9 +739,7 @@ private static bool TryAddCertificateToNssDb(string certificatePath, string nick

try
{
using var process = Process.Start(startInfo)!;
process.WaitForExit();
return process.ExitCode == 0;
return CertificateManagerProcessRunner.RunAndDiscardOutput(startInfo) == 0;
}
catch (Exception ex)
{
Expand All @@ -767,9 +761,7 @@ private static bool TryRemoveCertificateFromNssDb(string nickname, NssDb nssDb)

try
{
using var process = Process.Start(startInfo)!;
process.WaitForExit();
if (process.ExitCode == 0)
if (CertificateManagerProcessRunner.RunAndDiscardOutput(startInfo) == 0)
{
return true;
}
Expand Down Expand Up @@ -939,17 +931,14 @@ private static bool TryGetOpenSslDirectory([NotNullWhen(true)] out string? openS
RedirectStandardError = true
};

using var process = Process.Start(processInfo);
var stdout = process!.StandardOutput.ReadToEnd();

process.WaitForExit();
if (process.ExitCode != 0)
var processOutput = CertificateManagerProcessRunner.Run(processInfo);
if (processOutput.ExitCode != 0)
{
Log.UnixOpenSslVersionFailed();
return false;
}

var match = OpenSslVersionRegex.Match(stdout);
var match = OpenSslVersionRegex.Match(processOutput.StandardOutput);
if (!match.Success)
{
Log.UnixOpenSslVersionParsingFailed();
Expand Down Expand Up @@ -983,17 +972,14 @@ private static bool TryGetOpenSslHash(string certificatePath, [NotNullWhen(true)
RedirectStandardError = true
};

using var process = Process.Start(processInfo);
var stdout = process!.StandardOutput.ReadToEnd();

process.WaitForExit();
if (process.ExitCode != 0)
var processOutput = CertificateManagerProcessRunner.Run(processInfo);
if (processOutput.ExitCode != 0)
{
Log.UnixOpenSslHashFailed(certificatePath);
return false;
}

hash = stdout.Trim();
hash = processOutput.StandardOutput.Trim();
return true;
}
catch (Exception ex)
Expand Down
Loading