Skip to content
This repository was archived by the owner on Dec 18, 2018. It is now read-only.

Add "zero config" HTTPS support using local development certificate. #2093

Merged
merged 20 commits into from
Oct 25, 2017
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
59 changes: 31 additions & 28 deletions src/Kestrel.Core/CoreStrings.resx
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema

<!--
Microsoft ResX Schema
Version 2.0

The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.

Example:

... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
Expand All @@ -26,36 +26,36 @@
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>

There are any number of "resheader" rows that contain simple
There are any number of "resheader" rows that contain simple
name/value pairs.

Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.

The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:

Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.

mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.

mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.

mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
Expand Down Expand Up @@ -462,4 +462,7 @@
<data name="Http2ErrorConnectionSpecificHeaderField" xml:space="preserve">
<value>Request headers contain connection-specific header field.</value>
</data>
</root>
<data name="UnableToConfigureHttpsBindings" xml:space="preserve">
<value>Unable to configure default https bindings because no IDefaultHttpsProvider service was provided.</value>
</data>
</root>
68 changes: 56 additions & 12 deletions src/Kestrel.Core/Internal/AddressBinder.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
Expand All @@ -18,10 +18,12 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal
internal class AddressBinder
{
public static async Task BindAsync(IServerAddressesFeature addresses,
List<ListenOptions> listenOptions,
KestrelServerOptions serverOptions,
ILogger logger,
IDefaultHttpsProvider defaultHttpsProvider,
Func<ListenOptions, Task> createBinding)
{
var listenOptions = serverOptions.ListenOptions;
var strategy = CreateStrategy(
listenOptions.ToArray(),
addresses.Addresses.ToArray(),
Expand All @@ -31,7 +33,9 @@ public static async Task BindAsync(IServerAddressesFeature addresses,
{
Addresses = addresses.Addresses,
ListenOptions = listenOptions,
ServerOptions = serverOptions,
Logger = logger,
DefaultHttpsProvider = defaultHttpsProvider ?? UnconfiguredDefaultHttpsProvider.Instance,
CreateBinding = createBinding
};

Expand All @@ -47,7 +51,9 @@ private class AddressBindContext
{
public ICollection<string> Addresses { get; set; }
public List<ListenOptions> ListenOptions { get; set; }
public KestrelServerOptions ServerOptions { get; set; }
public ILogger Logger { get; set; }
public IDefaultHttpsProvider DefaultHttpsProvider { get; set; }

public Func<ListenOptions, Task> CreateBinding { get; set; }
}
Expand Down Expand Up @@ -120,7 +126,7 @@ private static async Task BindEndpointAsync(ListenOptions endpoint, AddressBindC
context.ListenOptions.Add(endpoint);
}

private static async Task BindLocalhostAsync(ServerAddress address, AddressBindContext context)
private static async Task BindLocalhostAsync(ServerAddress address, AddressBindContext context, bool https)
{
if (address.Port == 0)
{
Expand All @@ -131,7 +137,14 @@ private static async Task BindLocalhostAsync(ServerAddress address, AddressBindC

try
{
await BindEndpointAsync(new IPEndPoint(IPAddress.Loopback, address.Port), context).ConfigureAwait(false);
var options = new ListenOptions(new IPEndPoint(IPAddress.Loopback, address.Port));
await BindEndpointAsync(options, context).ConfigureAwait(false);

if (https)
{
options.KestrelServerOptions = context.ServerOptions;
context.DefaultHttpsProvider.ConfigureHttps(options);
}
}
catch (Exception ex) when (!(ex is IOException))
{
Expand All @@ -141,7 +154,14 @@ private static async Task BindLocalhostAsync(ServerAddress address, AddressBindC

try
{
await BindEndpointAsync(new IPEndPoint(IPAddress.IPv6Loopback, address.Port), context).ConfigureAwait(false);
var options = new ListenOptions(new IPEndPoint(IPAddress.IPv6Loopback, address.Port));
await BindEndpointAsync(options, context).ConfigureAwait(false);

if (https)
{
options.KestrelServerOptions = context.ServerOptions;
context.DefaultHttpsProvider.ConfigureHttps(options);
}
}
catch (Exception ex) when (!(ex is IOException))
{
Expand All @@ -162,10 +182,11 @@ private static async Task BindLocalhostAsync(ServerAddress address, AddressBindC
private static async Task BindAddressAsync(string address, AddressBindContext context)
{
var parsedAddress = ServerAddress.FromUrl(address);
var https = false;

if (parsedAddress.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException(CoreStrings.FormatConfigureHttpsFromMethodCall($"{nameof(KestrelServerOptions)}.{nameof(KestrelServerOptions.Listen)}()"));
https = true;
}
else if (!parsedAddress.Scheme.Equals("http", StringComparison.OrdinalIgnoreCase))
{
Expand All @@ -177,20 +198,20 @@ private static async Task BindAddressAsync(string address, AddressBindContext co
throw new InvalidOperationException(CoreStrings.FormatConfigurePathBaseFromMethodCall($"{nameof(IApplicationBuilder)}.UsePathBase()"));
}

ListenOptions options = null;
if (parsedAddress.IsUnixPipe)
{
var endPoint = new ListenOptions(parsedAddress.UnixPipePath);
await BindEndpointAsync(endPoint, context).ConfigureAwait(false);
context.Addresses.Add(endPoint.GetDisplayName());
options = new ListenOptions(parsedAddress.UnixPipePath);
await BindEndpointAsync(options, context).ConfigureAwait(false);
context.Addresses.Add(options.GetDisplayName());
}
else if (string.Equals(parsedAddress.Host, "localhost", StringComparison.OrdinalIgnoreCase))
{
// "localhost" for both IPv4 and IPv6 can't be represented as an IPEndPoint.
await BindLocalhostAsync(parsedAddress, context).ConfigureAwait(false);
await BindLocalhostAsync(parsedAddress, context, https).ConfigureAwait(false);
}
else
{
ListenOptions options;
if (TryCreateIPEndPoint(parsedAddress, out var endpoint))
{
options = new ListenOptions(endpoint);
Expand All @@ -216,6 +237,12 @@ private static async Task BindAddressAsync(string address, AddressBindContext co

context.Addresses.Add(options.GetDisplayName());
}

if (https && options != null)
{
options.KestrelServerOptions = context.ServerOptions;
context.DefaultHttpsProvider.ConfigureHttps(options);
}
}

private interface IStrategy
Expand All @@ -229,7 +256,7 @@ public async Task BindAsync(AddressBindContext context)
{
context.Logger.LogDebug(CoreStrings.BindingToDefaultAddress, Constants.DefaultServerAddress);

await BindLocalhostAsync(ServerAddress.FromUrl(Constants.DefaultServerAddress), context).ConfigureAwait(false);
await BindLocalhostAsync(ServerAddress.FromUrl(Constants.DefaultServerAddress), context, https: false).ConfigureAwait(false);
}
}

Expand Down Expand Up @@ -305,5 +332,22 @@ public virtual async Task BindAsync(AddressBindContext context)
}
}
}

private class UnconfiguredDefaultHttpsProvider : IDefaultHttpsProvider
{
public static readonly UnconfiguredDefaultHttpsProvider Instance = new UnconfiguredDefaultHttpsProvider();

private UnconfiguredDefaultHttpsProvider()
{
}

public void ConfigureHttps(ListenOptions listenOptions)
{
// We have to throw here. If this is called, it's because the user asked for "https" binding but for some
// reason didn't provide a certificate and didn't use the "DefaultHttpsProvider". This means if we no-op,
// we'll silently downgrade to HTTP, which is bad.
throw new InvalidOperationException(CoreStrings.UnableToConfigureHttpsBindings);
}
}
}
}
10 changes: 10 additions & 0 deletions src/Kestrel.Core/Internal/IDefaultHttpsProvider.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal
{
public interface IDefaultHttpsProvider
{
void ConfigureHttps(ListenOptions listenOptions);
}
}
2 changes: 2 additions & 0 deletions src/Kestrel.Core/Internal/KestrelServerOptionsSetup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal
Expand Down
9 changes: 8 additions & 1 deletion src/Kestrel.Core/KestrelServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ public class KestrelServer : IServer
private readonly List<ITransport> _transports = new List<ITransport>();
private readonly Heartbeat _heartbeat;
private readonly IServerAddressesFeature _serverAddresses;
private readonly IDefaultHttpsProvider _defaultHttpsProvider;
private readonly ITransportFactory _transportFactory;

private bool _hasStarted;
Expand All @@ -33,6 +34,12 @@ public KestrelServer(IOptions<KestrelServerOptions> options, ITransportFactory t
{
}

public KestrelServer(IOptions<KestrelServerOptions> options, ITransportFactory transportFactory, ILoggerFactory loggerFactory, IDefaultHttpsProvider defaultHttpsProvider)
: this(transportFactory, CreateServiceContext(options, loggerFactory))
{
_defaultHttpsProvider = defaultHttpsProvider;
}

// For testing
internal KestrelServer(ITransportFactory transportFactory, ServiceContext serviceContext)
{
Expand Down Expand Up @@ -152,7 +159,7 @@ async Task OnBind(ListenOptions endpoint)
await transport.BindAsync().ConfigureAwait(false);
}

await AddressBinder.BindAsync(_serverAddresses, Options.ListenOptions, Trace, OnBind).ConfigureAwait(false);
await AddressBinder.BindAsync(_serverAddresses, Options, Trace, _defaultHttpsProvider, OnBind).ConfigureAwait(false);
}
catch (Exception ex)
{
Expand Down
14 changes: 14 additions & 0 deletions src/Kestrel.Core/Properties/CoreStrings.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src/Kestrel.Https/ListenOptionsHttpsExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
namespace Microsoft.AspNetCore.Hosting
{
/// <summary>
/// Extension methods fro <see cref="ListenOptions"/> that configure Kestrel to use HTTPS for a given endpoint.
/// Extension methods for <see cref="ListenOptions"/> that configure Kestrel to use HTTPS for a given endpoint.
/// </summary>
public static class ListenOptionsHttpsExtensions
{
Expand Down
42 changes: 42 additions & 0 deletions src/Kestrel/Internal/DefaultHttpsProvider.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using Microsoft.AspNetCore.Certificates.Generation;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal;
using Microsoft.Extensions.Logging;

namespace Microsoft.AspNetCore.Server.Kestrel.Internal
{
public class DefaultHttpsProvider : IDefaultHttpsProvider
{
private static readonly CertificateManager _certificateManager = new CertificateManager();

private readonly ILogger<DefaultHttpsProvider> _logger;

public DefaultHttpsProvider(ILogger<DefaultHttpsProvider> logger)
{
_logger = logger;
}

public void ConfigureHttps(ListenOptions listenOptions)
{
var certificate = _certificateManager.ListCertificates(CertificatePurpose.HTTPS, StoreName.My, StoreLocation.CurrentUser, isValid: true)
.FirstOrDefault();
if (certificate != null)
{
_logger.LocatedDevelopmentCertificate(certificate);
listenOptions.UseHttps(certificate);
}
else
{
_logger.UnableToLocateDevelopmentCertificate();
throw new InvalidOperationException(KestrelStrings.HttpsUrlProvidedButNoDevelopmentCertificateFound);
}
}
}
}
Loading