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

Commit 8c4bdbc

Browse files
Cesar Blum Silveiraanalogrelay
Cesar Blum Silveira
authored andcommitted
Add "zero config" HTTPS support using local development certificate. (#2093)
1 parent c3ba875 commit 8c4bdbc

17 files changed

+422
-62
lines changed

src/Kestrel.Core/CoreStrings.resx

Lines changed: 31 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,17 @@
11
<?xml version="1.0" encoding="utf-8"?>
22
<root>
3-
<!--
4-
Microsoft ResX Schema
5-
3+
<!--
4+
Microsoft ResX Schema
5+
66
Version 2.0
7-
8-
The primary goals of this format is to allow a simple XML format
9-
that is mostly human readable. The generation and parsing of the
10-
various data types are done through the TypeConverter classes
7+
8+
The primary goals of this format is to allow a simple XML format
9+
that is mostly human readable. The generation and parsing of the
10+
various data types are done through the TypeConverter classes
1111
associated with the data types.
12-
12+
1313
Example:
14-
14+
1515
... ado.net/XML headers & schema ...
1616
<resheader name="resmimetype">text/microsoft-resx</resheader>
1717
<resheader name="version">2.0</resheader>
@@ -26,36 +26,36 @@
2626
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
2727
<comment>This is a comment</comment>
2828
</data>
29-
30-
There are any number of "resheader" rows that contain simple
29+
30+
There are any number of "resheader" rows that contain simple
3131
name/value pairs.
32-
33-
Each data row contains a name, and value. The row also contains a
34-
type or mimetype. Type corresponds to a .NET class that support
35-
text/value conversion through the TypeConverter architecture.
36-
Classes that don't support this are serialized and stored with the
32+
33+
Each data row contains a name, and value. The row also contains a
34+
type or mimetype. Type corresponds to a .NET class that support
35+
text/value conversion through the TypeConverter architecture.
36+
Classes that don't support this are serialized and stored with the
3737
mimetype set.
38-
39-
The mimetype is used for serialized objects, and tells the
40-
ResXResourceReader how to depersist the object. This is currently not
38+
39+
The mimetype is used for serialized objects, and tells the
40+
ResXResourceReader how to depersist the object. This is currently not
4141
extensible. For a given mimetype the value must be set accordingly:
42-
43-
Note - application/x-microsoft.net.object.binary.base64 is the format
44-
that the ResXResourceWriter will generate, however the reader can
42+
43+
Note - application/x-microsoft.net.object.binary.base64 is the format
44+
that the ResXResourceWriter will generate, however the reader can
4545
read any of the formats listed below.
46-
46+
4747
mimetype: application/x-microsoft.net.object.binary.base64
48-
value : The object must be serialized with
48+
value : The object must be serialized with
4949
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
5050
: and then encoded with base64 encoding.
51-
51+
5252
mimetype: application/x-microsoft.net.object.soap.base64
53-
value : The object must be serialized with
53+
value : The object must be serialized with
5454
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
5555
: and then encoded with base64 encoding.
5656
5757
mimetype: application/x-microsoft.net.object.bytearray.base64
58-
value : The object must be serialized into a byte array
58+
value : The object must be serialized into a byte array
5959
: using a System.ComponentModel.TypeConverter
6060
: and then encoded with base64 encoding.
6161
-->
@@ -462,4 +462,7 @@
462462
<data name="Http2ErrorConnectionSpecificHeaderField" xml:space="preserve">
463463
<value>Request headers contain connection-specific header field.</value>
464464
</data>
465-
</root>
465+
<data name="UnableToConfigureHttpsBindings" xml:space="preserve">
466+
<value>Unable to configure default https bindings because no IDefaultHttpsProvider service was provided.</value>
467+
</data>
468+
</root>

src/Kestrel.Core/Internal/AddressBinder.cs

Lines changed: 56 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Copyright (c) .NET Foundation. All rights reserved.
1+
// Copyright (c) .NET Foundation. All rights reserved.
22
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
33

44
using System;
@@ -18,10 +18,12 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal
1818
internal class AddressBinder
1919
{
2020
public static async Task BindAsync(IServerAddressesFeature addresses,
21-
List<ListenOptions> listenOptions,
21+
KestrelServerOptions serverOptions,
2222
ILogger logger,
23+
IDefaultHttpsProvider defaultHttpsProvider,
2324
Func<ListenOptions, Task> createBinding)
2425
{
26+
var listenOptions = serverOptions.ListenOptions;
2527
var strategy = CreateStrategy(
2628
listenOptions.ToArray(),
2729
addresses.Addresses.ToArray(),
@@ -31,7 +33,9 @@ public static async Task BindAsync(IServerAddressesFeature addresses,
3133
{
3234
Addresses = addresses.Addresses,
3335
ListenOptions = listenOptions,
36+
ServerOptions = serverOptions,
3437
Logger = logger,
38+
DefaultHttpsProvider = defaultHttpsProvider ?? UnconfiguredDefaultHttpsProvider.Instance,
3539
CreateBinding = createBinding
3640
};
3741

@@ -47,7 +51,9 @@ private class AddressBindContext
4751
{
4852
public ICollection<string> Addresses { get; set; }
4953
public List<ListenOptions> ListenOptions { get; set; }
54+
public KestrelServerOptions ServerOptions { get; set; }
5055
public ILogger Logger { get; set; }
56+
public IDefaultHttpsProvider DefaultHttpsProvider { get; set; }
5157

5258
public Func<ListenOptions, Task> CreateBinding { get; set; }
5359
}
@@ -120,7 +126,7 @@ private static async Task BindEndpointAsync(ListenOptions endpoint, AddressBindC
120126
context.ListenOptions.Add(endpoint);
121127
}
122128

123-
private static async Task BindLocalhostAsync(ServerAddress address, AddressBindContext context)
129+
private static async Task BindLocalhostAsync(ServerAddress address, AddressBindContext context, bool https)
124130
{
125131
if (address.Port == 0)
126132
{
@@ -131,7 +137,14 @@ private static async Task BindLocalhostAsync(ServerAddress address, AddressBindC
131137

132138
try
133139
{
134-
await BindEndpointAsync(new IPEndPoint(IPAddress.Loopback, address.Port), context).ConfigureAwait(false);
140+
var options = new ListenOptions(new IPEndPoint(IPAddress.Loopback, address.Port));
141+
await BindEndpointAsync(options, context).ConfigureAwait(false);
142+
143+
if (https)
144+
{
145+
options.KestrelServerOptions = context.ServerOptions;
146+
context.DefaultHttpsProvider.ConfigureHttps(options);
147+
}
135148
}
136149
catch (Exception ex) when (!(ex is IOException))
137150
{
@@ -141,7 +154,14 @@ private static async Task BindLocalhostAsync(ServerAddress address, AddressBindC
141154

142155
try
143156
{
144-
await BindEndpointAsync(new IPEndPoint(IPAddress.IPv6Loopback, address.Port), context).ConfigureAwait(false);
157+
var options = new ListenOptions(new IPEndPoint(IPAddress.IPv6Loopback, address.Port));
158+
await BindEndpointAsync(options, context).ConfigureAwait(false);
159+
160+
if (https)
161+
{
162+
options.KestrelServerOptions = context.ServerOptions;
163+
context.DefaultHttpsProvider.ConfigureHttps(options);
164+
}
145165
}
146166
catch (Exception ex) when (!(ex is IOException))
147167
{
@@ -162,10 +182,11 @@ private static async Task BindLocalhostAsync(ServerAddress address, AddressBindC
162182
private static async Task BindAddressAsync(string address, AddressBindContext context)
163183
{
164184
var parsedAddress = ServerAddress.FromUrl(address);
185+
var https = false;
165186

166187
if (parsedAddress.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
167188
{
168-
throw new InvalidOperationException(CoreStrings.FormatConfigureHttpsFromMethodCall($"{nameof(KestrelServerOptions)}.{nameof(KestrelServerOptions.Listen)}()"));
189+
https = true;
169190
}
170191
else if (!parsedAddress.Scheme.Equals("http", StringComparison.OrdinalIgnoreCase))
171192
{
@@ -177,20 +198,20 @@ private static async Task BindAddressAsync(string address, AddressBindContext co
177198
throw new InvalidOperationException(CoreStrings.FormatConfigurePathBaseFromMethodCall($"{nameof(IApplicationBuilder)}.UsePathBase()"));
178199
}
179200

201+
ListenOptions options = null;
180202
if (parsedAddress.IsUnixPipe)
181203
{
182-
var endPoint = new ListenOptions(parsedAddress.UnixPipePath);
183-
await BindEndpointAsync(endPoint, context).ConfigureAwait(false);
184-
context.Addresses.Add(endPoint.GetDisplayName());
204+
options = new ListenOptions(parsedAddress.UnixPipePath);
205+
await BindEndpointAsync(options, context).ConfigureAwait(false);
206+
context.Addresses.Add(options.GetDisplayName());
185207
}
186208
else if (string.Equals(parsedAddress.Host, "localhost", StringComparison.OrdinalIgnoreCase))
187209
{
188210
// "localhost" for both IPv4 and IPv6 can't be represented as an IPEndPoint.
189-
await BindLocalhostAsync(parsedAddress, context).ConfigureAwait(false);
211+
await BindLocalhostAsync(parsedAddress, context, https).ConfigureAwait(false);
190212
}
191213
else
192214
{
193-
ListenOptions options;
194215
if (TryCreateIPEndPoint(parsedAddress, out var endpoint))
195216
{
196217
options = new ListenOptions(endpoint);
@@ -216,6 +237,12 @@ private static async Task BindAddressAsync(string address, AddressBindContext co
216237

217238
context.Addresses.Add(options.GetDisplayName());
218239
}
240+
241+
if (https && options != null)
242+
{
243+
options.KestrelServerOptions = context.ServerOptions;
244+
context.DefaultHttpsProvider.ConfigureHttps(options);
245+
}
219246
}
220247

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

232-
await BindLocalhostAsync(ServerAddress.FromUrl(Constants.DefaultServerAddress), context).ConfigureAwait(false);
259+
await BindLocalhostAsync(ServerAddress.FromUrl(Constants.DefaultServerAddress), context, https: false).ConfigureAwait(false);
233260
}
234261
}
235262

@@ -305,5 +332,22 @@ public virtual async Task BindAsync(AddressBindContext context)
305332
}
306333
}
307334
}
335+
336+
private class UnconfiguredDefaultHttpsProvider : IDefaultHttpsProvider
337+
{
338+
public static readonly UnconfiguredDefaultHttpsProvider Instance = new UnconfiguredDefaultHttpsProvider();
339+
340+
private UnconfiguredDefaultHttpsProvider()
341+
{
342+
}
343+
344+
public void ConfigureHttps(ListenOptions listenOptions)
345+
{
346+
// We have to throw here. If this is called, it's because the user asked for "https" binding but for some
347+
// reason didn't provide a certificate and didn't use the "DefaultHttpsProvider". This means if we no-op,
348+
// we'll silently downgrade to HTTP, which is bad.
349+
throw new InvalidOperationException(CoreStrings.UnableToConfigureHttpsBindings);
350+
}
351+
}
308352
}
309353
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
// Copyright (c) .NET Foundation. All rights reserved.
2+
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
3+
4+
namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal
5+
{
6+
public interface IDefaultHttpsProvider
7+
{
8+
void ConfigureHttps(ListenOptions listenOptions);
9+
}
10+
}

src/Kestrel.Core/Internal/KestrelServerOptionsSetup.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
33

44
using System;
5+
using Microsoft.AspNetCore.Hosting.Server.Features;
6+
using Microsoft.Extensions.DependencyInjection;
57
using Microsoft.Extensions.Options;
68

79
namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal

src/Kestrel.Core/KestrelServer.cs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ public class KestrelServer : IServer
2222
private readonly List<ITransport> _transports = new List<ITransport>();
2323
private readonly Heartbeat _heartbeat;
2424
private readonly IServerAddressesFeature _serverAddresses;
25+
private readonly IDefaultHttpsProvider _defaultHttpsProvider;
2526
private readonly ITransportFactory _transportFactory;
2627

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

37+
public KestrelServer(IOptions<KestrelServerOptions> options, ITransportFactory transportFactory, ILoggerFactory loggerFactory, IDefaultHttpsProvider defaultHttpsProvider)
38+
: this(transportFactory, CreateServiceContext(options, loggerFactory))
39+
{
40+
_defaultHttpsProvider = defaultHttpsProvider;
41+
}
42+
3643
// For testing
3744
internal KestrelServer(ITransportFactory transportFactory, ServiceContext serviceContext)
3845
{
@@ -152,7 +159,7 @@ async Task OnBind(ListenOptions endpoint)
152159
await transport.BindAsync().ConfigureAwait(false);
153160
}
154161

155-
await AddressBinder.BindAsync(_serverAddresses, Options.ListenOptions, Trace, OnBind).ConfigureAwait(false);
162+
await AddressBinder.BindAsync(_serverAddresses, Options, Trace, _defaultHttpsProvider, OnBind).ConfigureAwait(false);
156163
}
157164
catch (Exception ex)
158165
{

src/Kestrel.Core/Properties/CoreStrings.Designer.cs

Lines changed: 14 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/Kestrel.Https/ListenOptionsHttpsExtensions.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
namespace Microsoft.AspNetCore.Hosting
1313
{
1414
/// <summary>
15-
/// Extension methods fro <see cref="ListenOptions"/> that configure Kestrel to use HTTPS for a given endpoint.
15+
/// Extension methods for <see cref="ListenOptions"/> that configure Kestrel to use HTTPS for a given endpoint.
1616
/// </summary>
1717
public static class ListenOptionsHttpsExtensions
1818
{
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// Copyright (c) .NET Foundation. All rights reserved.
2+
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
3+
4+
using System;
5+
using System.Linq;
6+
using System.Security.Cryptography.X509Certificates;
7+
using Microsoft.AspNetCore.Certificates.Generation;
8+
using Microsoft.AspNetCore.Hosting;
9+
using Microsoft.AspNetCore.Server.Kestrel.Core;
10+
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal;
11+
using Microsoft.Extensions.Logging;
12+
13+
namespace Microsoft.AspNetCore.Server.Kestrel.Internal
14+
{
15+
public class DefaultHttpsProvider : IDefaultHttpsProvider
16+
{
17+
private static readonly CertificateManager _certificateManager = new CertificateManager();
18+
19+
private readonly ILogger<DefaultHttpsProvider> _logger;
20+
21+
public DefaultHttpsProvider(ILogger<DefaultHttpsProvider> logger)
22+
{
23+
_logger = logger;
24+
}
25+
26+
public void ConfigureHttps(ListenOptions listenOptions)
27+
{
28+
var certificate = _certificateManager.ListCertificates(CertificatePurpose.HTTPS, StoreName.My, StoreLocation.CurrentUser, isValid: true)
29+
.FirstOrDefault();
30+
if (certificate != null)
31+
{
32+
_logger.LocatedDevelopmentCertificate(certificate);
33+
listenOptions.UseHttps(certificate);
34+
}
35+
else
36+
{
37+
_logger.UnableToLocateDevelopmentCertificate();
38+
throw new InvalidOperationException(KestrelStrings.HttpsUrlProvidedButNoDevelopmentCertificateFound);
39+
}
40+
}
41+
}
42+
}

0 commit comments

Comments
 (0)