镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content
3 changes: 0 additions & 3 deletions src/libraries/Common/tests/System/Net/Configuration.Http.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,6 @@ public static partial class Http
public static string TLSv11RemoteServer => GetValue("DOTNET_TEST_HTTPHOST_TLS11", "https://www.ssllabs.com:10302/");
public static string TLSv12RemoteServer => GetValue("DOTNET_TEST_HTTPHOST_TLS12", "https://www.ssllabs.com:10303/");

public static string ExpiredCertRemoteServer => GetValue("DOTNET_TEST_HTTPHOST_EXPIREDCERT", "https://expired.badssl.com/");
public static string WrongHostNameCertRemoteServer => GetValue("DOTNET_TEST_HTTPHOST_WRONGHOSTNAME", "https://wrong.host.badssl.com/");
public static string SelfSignedCertRemoteServer => GetValue("DOTNET_TEST_HTTPHOST_SELFSIGNEDCERT", "https://self-signed.badssl.com/");
public static string RevokedCertRemoteServer => GetValue("DOTNET_TEST_HTTPHOST_REVOKEDCERT", "https://revoked.badssl.com/");

public static string EchoClientCertificateRemoteServer => GetValue("DOTNET_TEST_HTTPHOST_ECHOCLIENTCERT", "https://corefx-net-tls.azurewebsites.net/EchoClientCertificate.ashx");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,19 @@
using System.Net.Security;
using System.Net.Test.Common;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Microsoft.DotNet.XUnitExtensions;
using Xunit;
using Xunit.Abstractions;

namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;

#if WINHTTPHANDLER_TEST
using HttpClientHandler = System.Net.Http.WinHttpClientHandler;
#endif

public abstract class HttpClientHandler_DangerousAcceptAllCertificatesValidator_Test : HttpClientHandlerTestBase
{
private static bool ClientSupportsDHECipherSuites => (!PlatformDetection.IsWindows || PlatformDetection.IsWindows10Version1607OrGreater);

public HttpClientHandler_DangerousAcceptAllCertificatesValidator_Test(ITestOutputHelper output) : base(output) { }

#if !WINHTTPHANDLER_TEST
Expand Down Expand Up @@ -86,22 +82,30 @@ await TestHelper.WhenAllCompletedOrAnyFailed(
}
}

public static readonly object[][] InvalidCertificateServers =
[Theory]
[InlineData(true, false)]
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(true, true)]
public async Task InvalidCertificates_CertificateValidationDisabled_Succeeds(bool expired, bool wrongHostName)
{
new object[] { Configuration.Http.ExpiredCertRemoteServer },
new object[] { Configuration.Http.SelfSignedCertRemoteServer },
new object[] { Configuration.Http.WrongHostNameCertRemoteServer },
};
using X509Certificate2 certificate = TestHelper.CreateServerSelfSignedCertificate(
name: wrongHostName ? "not-localhost" : "localhost", expired: expired);

[OuterLoop]
[ConditionalTheory(nameof(ClientSupportsDHECipherSuites))]
[MemberData(nameof(InvalidCertificateServers))]
public async Task InvalidCertificateServers_CertificateValidationDisabled_Succeeds(string url)
{
using (HttpClientHandler handler = CreateHttpClientHandler(allowAllCertificates: true))
using (HttpClient client = CreateHttpClient(handler))
{
(await client.GetAsync(url)).Dispose();
await LoopbackServerFactory.CreateClientAndServerAsync(async uri =>
{
using HttpResponseMessage response = await client.GetAsync(new UriBuilder(uri) { Host = "localhost" }.Uri);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}, server => server.HandleRequestAsync(),
options: new GenericLoopbackOptions
{
UseSsl = true,
Certificate = certificate,
SslProtocols = SslProtocols.None,
});
}
}
}
Expand Down

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ public static IEnumerable<object[]> GetAsync_AllowedSSLVersion_Succeeds_MemberDa
public async Task GetAsync_AllowedSSLVersion_Succeeds(SslProtocols acceptedProtocol, bool requestOnlyThisProtocol)
{
int count = 0;
using (HttpClientHandler handler = CreateHttpClientHandler())
using (HttpClientHandler handler = CreateHttpClientHandler(allowTlsResume: false))
using (HttpClient client = CreateHttpClient(handler))
{
handler.ServerCertificateCustomValidationCallback =
Expand Down
39 changes: 25 additions & 14 deletions src/libraries/Common/tests/System/Net/Http/LoopbackServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,7 @@ public static string GetConnectionCloseResponse(HttpStatusCode statusCode = Http

public class Options : GenericLoopbackOptions
{
public bool AllowTlsResume { get; set; } = true;
public bool WebSocketEndpoint { get; set; } = false;
public Func<Stream, Stream> StreamWrapper { get; set; }
public string Username { get; set; }
Expand Down Expand Up @@ -477,25 +478,35 @@ public static async Task<Connection> CreateAsync(SocketWrapper socket, Stream st
if (httpOptions.UseSsl)
{
var sslStream = new SslStream(stream, false, delegate { return true; });
#if !NETFRAMEWORK
SslServerAuthenticationOptions sslOptions = new SslServerAuthenticationOptions()
try
{
EnabledSslProtocols = httpOptions.SslProtocols,
ServerCertificateContext = httpOptions.CertificateContext ?? SslStreamCertificateContext.Create(Configuration.Certificates.GetServerCertificate(), null),
ClientCertificateRequired = true,
};
#if !NETFRAMEWORK
SslServerAuthenticationOptions sslOptions = new SslServerAuthenticationOptions()
{
AllowTlsResume = httpOptions.AllowTlsResume,
EnabledSslProtocols = httpOptions.SslProtocols,
ServerCertificateContext = httpOptions.CertificateContext ?? SslStreamCertificateContext.Create(Configuration.Certificates.GetServerCertificate(), null),
ClientCertificateRequired = true,
};

await sslStream.AuthenticateAsServerAsync(sslOptions, default).ConfigureAwait(false);
await sslStream.AuthenticateAsServerAsync(sslOptions, default).ConfigureAwait(false);
#else
using (X509Certificate2 cert = httpOptions.Certificate ?? Configuration.Certificates.GetServerCertificate())
using (X509Certificate2 cert = httpOptions.Certificate ?? Configuration.Certificates.GetServerCertificate())
{
await sslStream.AuthenticateAsServerAsync(
cert,
clientCertificateRequired: true, // allowed but not required
enabledSslProtocols: httpOptions.SslProtocols,
checkCertificateRevocation: false).ConfigureAwait(false);
}
#endif
}
catch
{
await sslStream.AuthenticateAsServerAsync(
cert,
clientCertificateRequired: true, // allowed but not required
enabledSslProtocols: httpOptions.SslProtocols,
checkCertificateRevocation: false).ConfigureAwait(false);
sslStream.Dispose();
throw;
}
#endif

stream = sslStream;
}

Expand Down
30 changes: 23 additions & 7 deletions src/libraries/Common/tests/System/Net/Http/TestHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -109,17 +109,20 @@ public static byte[] GenerateRandomContent(int size)
return data;
}

public static X509Certificate2 CreateServerSelfSignedCertificate(string name = "localhost")
public static X509Certificate2 CreateServerSelfSignedCertificate(string name = "localhost", bool expired = false)
=> CreateServerCertificate(null, name, expired);

public static X509Certificate2 CreateServerCertificate(X509Certificate2 issuerCertificate, string name = "localhost", bool expired = false)
{
using (RSA root = RSA.Create())
using (RSA key = RSA.Create())
{
CertificateRequest req = new CertificateRequest(
$"CN={name}",
root,
key,
HashAlgorithmName.SHA256,
RSASignaturePadding.Pkcs1);

req.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true));
req.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, true));
req.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(req.PublicKey, false));
req.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DataEncipherment, false));
req.CertificateExtensions.Add(
Expand All @@ -136,13 +139,26 @@ public static X509Certificate2 CreateServerSelfSignedCertificate(string name = "
builder.AddIpAddress(IPAddress.IPv6Loopback);
req.CertificateExtensions.Add(builder.Build());

DateTimeOffset start = DateTimeOffset.UtcNow.AddMinutes(-5);
DateTimeOffset start = expired ? DateTimeOffset.UtcNow.AddMonths(-2) : DateTimeOffset.UtcNow.AddMinutes(-5);
DateTimeOffset end = start.AddMonths(1);

X509Certificate2 cert = req.CreateSelfSigned(start, end);
X509Certificate2 cert;
if (issuerCertificate is null)
{
cert = req.CreateSelfSigned(start, end);
}
else
{
using X509Certificate2 publicCertificate = req.Create(issuerCertificate, start, end, Guid.NewGuid().ToByteArray());
cert = publicCertificate.CopyWithPrivateKey(key);
}

if (PlatformDetection.IsWindows)
{
cert = X509CertificateLoader.LoadPkcs12(cert.Export(X509ContentType.Pfx), (string?)null);
using (cert)
{
return X509CertificateLoader.LoadPkcs12(cert.Export(X509ContentType.Pfx), (string?)null);
}
}

return cert;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,73 @@
using System.ComponentModel;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.DotNet.RemoteExecutor;
using Microsoft.DotNet.XUnitExtensions;
using Xunit;

namespace System.Diagnostics.Tests
{
public partial class ProcessTests
{
private static bool IsNotNanoServerNotServerCoreAndRemoteExecutorSupported =>
PlatformDetection.IsNotWindowsNanoServer &&
PlatformDetection.IsNotWindowsServerCore &&
RemoteExecutor.IsSupported;

[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern int MessageBoxW(IntPtr hWnd, string lpText, string lpCaption, uint uType);

[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr FindWindowW(string? lpClassName, string? lpWindowName);

// Creates a visible top-level window with a known title.
// Shows a MessageBox on a background thread, waits until the window is visible via FindWindowW,
// then signals the parent via stdout and blocks until killed by the parent.
private static int CreateMainWindowWithTitle()
{
// MessageBoxW blocks the current thread until the user closes the message box
Thread t = new Thread(() => MessageBoxW(IntPtr.Zero, string.Empty, "Test Main Window", 0 /* MB_OK */));
t.IsBackground = true;
t.Start();

// Spin until the MessageBox window is actually visible before signaling the parent.
SpinWait.SpinUntil(() => FindWindowW(null, "Test Main Window") != IntPtr.Zero);

// Signal the parent that the window is ready.
Console.WriteLine("ready");

// Block until the parent kills this process.
Thread.Sleep(Timeout.Infinite);
return RemoteExecutor.SuccessExitCode;
}

[ConditionalFact(typeof(ProcessTests), nameof(IsNotNanoServerNotServerCoreAndRemoteExecutorSupported))]
[OuterLoop("Pops UI")]
[PlatformSpecific(TestPlatforms.Windows)]
public async Task MainWindowHandle_And_Title_GetWithGui_ShouldRefresh_Windows()
{
using Process process = CreateProcess(CreateMainWindowWithTitle);
process.StartInfo.RedirectStandardOutput = true;
process.Start();

try
{
// Wait for child to signal that its window is ready.
Assert.Equal("ready", await process.StandardOutput.ReadLineAsync());

process.Refresh();
Assert.NotEqual(IntPtr.Zero, process.MainWindowHandle);
Assert.Equal("Test Main Window", process.MainWindowTitle);
}
finally
{
process.Kill();
process.WaitForExit();
}
}

private string WriteScriptFile(string directory, string name, int returnValue)
{
string filename = Path.Combine(directory, name);
Expand Down
70 changes: 0 additions & 70 deletions src/libraries/System.Diagnostics.Process/tests/ProcessTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1817,76 +1817,6 @@ public void MainWindowHandle_GetNotStarted_ThrowsInvalidOperationException()
Assert.Throws<InvalidOperationException>(() => process.MainWindowHandle);
}

[ConditionalFact(typeof(PlatformDetection),
nameof(PlatformDetection.IsNotWindowsNanoServer), // it needs Notepad
nameof(PlatformDetection.IsNotWindowsServerCore))] // explained in https://github.com/dotnet/runtime/pull/44972
[OuterLoop("Pops UI")]
[PlatformSpecific(TestPlatforms.Windows)]
public void MainWindowHandle_GetWithGui_ShouldRefresh_Windows()
{
const string ExePath = "notepad.exe";
Assert.True(IsProgramInstalled(ExePath), "Notepad is not installed");

using (Process process = Process.Start(ExePath))
{
try
{
for (int attempt = 0; attempt < 50; ++attempt)
{
process.Refresh();
if (process.MainWindowHandle != IntPtr.Zero)
{
break;
}

Thread.Sleep(100);
}

Assert.NotEqual(IntPtr.Zero, process.MainWindowHandle);
}
finally
{
process.Kill();
Assert.True(process.WaitForExit(WaitInMS));
}
}
}

[ConditionalFact(typeof(PlatformDetection),
nameof(PlatformDetection.IsNotWindowsNanoServer), // it needs Notepad
nameof(PlatformDetection.IsNotWindowsServerCore))] // explained in https://github.com/dotnet/runtime/pull/44972
[OuterLoop("Pops UI")]
[PlatformSpecific(TestPlatforms.Windows)]
public void MainWindowTitle_GetWithGui_ShouldRefresh_Windows()
{
const string ExePath = "notepad.exe";
Assert.True(IsProgramInstalled(ExePath), "Notepad is not installed");

using (Process process = Process.Start(new ProcessStartInfo(ExePath)))
{
try
{
for (int attempt = 0; attempt < 50; ++attempt)
{
process.Refresh();
if (process.MainWindowTitle != string.Empty)
{
break;
}

Thread.Sleep(100);
}

Assert.NotEqual(string.Empty, process.MainWindowTitle);
}
finally
{
process.Kill();
Assert.True(process.WaitForExit(WaitInMS));
}
}
}

[Fact]
[SkipOnPlatform(TestPlatforms.iOS | TestPlatforms.tvOS, "libproc is not supported on iOS/tvOS")]
public void RefreshResetsAllRefreshableFields()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ public abstract partial class HttpClientHandlerTestBase : FileCleanupTestBase
{
protected static bool IsWinHttpHandler => true;

protected static WinHttpClientHandler CreateHttpClientHandler(Version useVersion = null, bool allowAllCertificates = true)
// WinHTTP owns TLS and does not expose SslStream's resumption setting.
protected static WinHttpClientHandler CreateHttpClientHandler(Version useVersion = null, bool allowAllCertificates = true, bool allowTlsResume = true)
{
useVersion ??= HttpVersion.Version11;

Expand All @@ -26,8 +27,11 @@ protected static WinHttpClientHandler CreateHttpClientHandler(Version useVersion

protected WinHttpClientHandler CreateHttpClientHandler() => CreateHttpClientHandler(UseVersion);

protected static WinHttpClientHandler CreateHttpClientHandler(string useVersionString) =>
CreateHttpClientHandler(Version.Parse(useVersionString));
protected WinHttpClientHandler CreateHttpClientHandler(bool allowTlsResume) =>
CreateHttpClientHandler(UseVersion, allowTlsResume: allowTlsResume);

protected static WinHttpClientHandler CreateHttpClientHandler(string useVersionString, bool allowTlsResume = true) =>
CreateHttpClientHandler(Version.Parse(useVersionString), allowTlsResume: allowTlsResume);

protected static HttpRequestMessage CreateRequest(HttpMethod method, Uri uri, Version version, bool exactVersion = false) =>
new HttpRequestMessage(method, uri)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -667,7 +667,7 @@ public async Task ServerCertificateCustomValidationCallback_Succeeds()
HttpRequestMessage? callbackRequest = null;
int invocationCount = 0;

var httpClientHandler = CreateHttpClientHandler();
var httpClientHandler = CreateHttpClientHandler(allowTlsResume: false);
httpClientHandler.ServerCertificateCustomValidationCallback = (request, _, _, _) =>
{
callbackRequest = request;
Expand Down
Loading
Loading