Skip to content

Remove Dev Proxy CA certificate when uninstalling for Win #1208

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 12 commits into
base: main
Choose a base branch
from
Open
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
93 changes: 93 additions & 0 deletions dev-proxy/CommandHandlers/CertRemoveCommandHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using DevProxy.Abstractions;
using System.CommandLine;
using System.CommandLine.Invocation;
using System.Diagnostics;
using Titanium.Web.Proxy.Helpers;

namespace DevProxy.CommandHandlers;

public static class CertRemoveCommandHandler
{
public static void RemoveCert(ILogger logger, InvocationContext invocationContext, Option<bool> forceOption)
{
logger.LogTrace("RemoveCert() called");
ArgumentNullException.ThrowIfNull(logger);
ArgumentNullException.ThrowIfNull(invocationContext);
ArgumentNullException.ThrowIfNull(forceOption);

try
{
var isForced = invocationContext.ParseResult.GetValueForOption(forceOption);
if (!isForced)
{
var isConfirmed = PromptConfirmation("Do you want to remove the root certificate", defaultValue: false);
if (!isConfirmed)
{
return;
}
}

logger.LogInformation("Uninstalling the root certificate...");

RemoveTrustedCertificateOnMac();
ProxyEngine.ProxyServer.CertificateManager.RemoveTrustedRootCertificate(machineTrusted: false);

logger.LogInformation("DONE");
}
catch (Exception ex)
{
logger.LogError(ex, "Error removing certificate");
}
finally
{
logger.LogTrace("RemoveCert() finished");
}
}

private static bool PromptConfirmation(string message, bool defaultValue)
{
while (true)
{
Console.Write(message + $" ({(defaultValue ? "Y/n" : "y/N")}): ");
var answer = Console.ReadLine();

if (string.IsNullOrWhiteSpace(answer))
{
return defaultValue;
}
else if (answer.StartsWith("y", StringComparison.OrdinalIgnoreCase))
{
return true;
}
else if (answer.StartsWith("n", StringComparison.OrdinalIgnoreCase))
{
return false;
}
}
}

private static void RemoveTrustedCertificateOnMac()
{
if (!RunTime.IsMac)
{
return;
}

var bashScriptPath = Path.Join(ProxyUtils.AppFolder, "remove-cert.sh");
ProcessStartInfo startInfo = new()
{
FileName = "/bin/bash",
Arguments = bashScriptPath,
UseShellExecute = false,
CreateNoWindow = true,
};

var process = new Process() { StartInfo = startInfo };
process.Start();
process.WaitForExit();
}
}
15 changes: 14 additions & 1 deletion dev-proxy/ProxyHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,8 @@ private static Command CreateCertCommand(ILogger logger)

var sortedCommands = new[]
{
CreateCertEnsureCommand(logger)
CreateCertEnsureCommand(logger),
CreateCertRemoveCommand(logger),
}.OrderByName();

certCommand.AddCommands(sortedCommands);
Expand All @@ -396,6 +397,18 @@ private static Command CreateCertEnsureCommand(ILogger logger)
return certEnsureCommand;
}

private static Command CreateCertRemoveCommand(ILogger logger)
{
var forceOption = new Option<bool>("--force", "Force the root certificate removal");
forceOption.AddAlias("-f");

var certRemoveCommand = new Command("remove", "Remove the certificate from Root Store");
certRemoveCommand.SetHandler((context) => CertRemoveCommandHandler.RemoveCert(logger, context, forceOption));

certRemoveCommand.AddOptions(new[] { forceOption }.OrderByName());
return certRemoveCommand;
}

private static Command CreateJwtCommand()
{
var jwtCommand = new Command("jwt", "Manage JSON Web Tokens");
Expand Down
5 changes: 4 additions & 1 deletion dev-proxy/dev-proxy.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,11 @@
<None Update="devproxy-errors.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="remove-cert.sh">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="toggle-proxy.sh">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="trust-cert.sh">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
Expand Down
25 changes: 25 additions & 0 deletions dev-proxy/remove-cert.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#!/bin/bash
set -e

if [ "$(uname -s)" != "Darwin" ]; then
echo "Error: this shell script should be run on macOS."
exit 1
fi

echo -e "\nRemove the self-signed certificate from your Keychain."

cert_name="Dev Proxy CA"
cert_filename="dev-proxy-ca.pem"

# export cert from keychain to PEM
echo "Exporting '$cert_name' certificate..."
security find-certificate -c "$cert_name" -a -p > "$cert_filename"

# add trusted cert to keychain
echo "Removing Dev Proxy trust settings..."
security remove-trusted-cert "$cert_filename"

# remove exported cert
echo "Cleaning up..."
rm "$cert_filename"
echo -e "\033[0;32mDONE\033[0m\n"
4 changes: 4 additions & 0 deletions install-beta.iss
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#define MyAppVersion "0.28.0-beta.1"
#define MyAppPublisher ".NET Foundation"
#define MyAppURL "https://aka.ms/devproxy"
#define DevProxyExecutable "devproxy-beta.exe"

[Setup]
; NOTE: The value of AppId uniquely identifies this application. Do not use the same AppId value in installers for other applications.
Expand Down Expand Up @@ -45,6 +46,9 @@ Source: ".\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsu
[UninstallDelete]
Type:files;Name:"{app}\rootCert.pfx"

[UninstallRun]
Filename: "{app}\{#DevProxyExecutable}"; Parameters: "cert remove --force"; RunOnceId: "RemoveCert"; Flags: runhidden;

[Code]
procedure RemovePath(Path: string);
var
Expand Down
4 changes: 4 additions & 0 deletions install.iss
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#define MyAppVersion "0.28.0"
#define MyAppPublisher ".NET Foundation"
#define MyAppURL "https://aka.ms/devproxy"
#define DevProxyExecutable "devproxy.exe"

[Setup]
; NOTE: The value of AppId uniquely identifies this application. Do not use the same AppId value in installers for other applications.
Expand Down Expand Up @@ -45,6 +46,9 @@ Source: ".\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsu
[UninstallDelete]
Type:files;Name:"{app}\rootCert.pfx"

[UninstallRun]
Filename: "{app}\{#DevProxyExecutable}"; Parameters: "cert remove --force"; RunOnceId: "RemoveCert"; Flags: runhidden;

[Code]
procedure RemovePath(Path: string);
var
Expand Down