-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathSslStreamPal.Unix.cs
281 lines (240 loc) · 12.1 KB
/
SslStreamPal.Unix.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Diagnostics;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Win32.SafeHandles;
namespace System.Net.Security
{
internal static class SslStreamPal
{
public static Exception GetException(SecurityStatusPal status)
{
return status.Exception ?? new Interop.OpenSsl.SslException((int)status.ErrorCode);
}
internal const bool StartMutualAuthAsAnonymous = false;
internal const bool CanEncryptEmptyMessage = false;
public static void VerifyPackageInfo()
{
}
public static SecurityStatusPal SelectApplicationProtocol(
SafeFreeCredentials? credentialsHandle,
SafeDeleteSslContext? context,
SslAuthenticationOptions sslAuthenticationOptions,
ReadOnlySpan<byte> clientProtocols)
{
throw new PlatformNotSupportedException(nameof(SelectApplicationProtocol));
}
#pragma warning disable IDE0060
public static ProtocolToken AcceptSecurityContext(
ref SafeFreeCredentials? credential,
ref SafeDeleteSslContext? context,
ReadOnlySpan<byte> inputBuffer,
out int consumed,
SslAuthenticationOptions sslAuthenticationOptions)
{
return HandshakeInternal(ref context, inputBuffer, out consumed, sslAuthenticationOptions);
}
public static ProtocolToken InitializeSecurityContext(
ref SafeFreeCredentials? credential,
ref SafeDeleteSslContext? context,
string? _ /*targetName*/,
ReadOnlySpan<byte> inputBuffer,
out int consumed,
SslAuthenticationOptions sslAuthenticationOptions)
{
return HandshakeInternal(ref context, inputBuffer, out consumed, sslAuthenticationOptions);
}
public static SafeFreeCredentials? AcquireCredentialsHandle(SslAuthenticationOptions _1, bool _2)
{
return null;
}
public static ProtocolToken EncryptMessage(SafeDeleteSslContext securityContext, ReadOnlyMemory<byte> input, int _ /*headerSize*/, int _1 /*trailerSize*/)
{
ProtocolToken token = default;
token.RentBuffer = true;
try
{
Interop.Ssl.SslErrorCode errorCode = Interop.OpenSsl.Encrypt((SafeSslHandle)securityContext, input.Span, ref token);
token.Status = MapNativeErrorCode(errorCode);
}
catch (Exception ex)
{
token.Status = new SecurityStatusPal(SecurityStatusPalErrorCode.InternalError, ex);
}
return token;
}
public static SecurityStatusPal DecryptMessage(SafeDeleteSslContext securityContext, Span<byte> buffer, out int offset, out int count)
{
offset = 0;
count = 0;
try
{
int resultSize = Interop.OpenSsl.Decrypt((SafeSslHandle)securityContext, buffer, out Interop.Ssl.SslErrorCode errorCode);
SecurityStatusPal retVal = MapNativeErrorCode(errorCode);
if (retVal.ErrorCode == SecurityStatusPalErrorCode.OK ||
retVal.ErrorCode == SecurityStatusPalErrorCode.Renegotiate)
{
count = resultSize;
}
return retVal;
}
catch (Exception ex)
{
return new SecurityStatusPal(SecurityStatusPalErrorCode.InternalError, ex);
}
}
private static SecurityStatusPal MapNativeErrorCode(Interop.Ssl.SslErrorCode errorCode) =>
errorCode switch
{
Interop.Ssl.SslErrorCode.SSL_ERROR_RENEGOTIATE => new SecurityStatusPal(SecurityStatusPalErrorCode.Renegotiate),
Interop.Ssl.SslErrorCode.SSL_ERROR_ZERO_RETURN => new SecurityStatusPal(SecurityStatusPalErrorCode.ContextExpired),
Interop.Ssl.SslErrorCode.SSL_ERROR_WANT_X509_LOOKUP => new SecurityStatusPal(SecurityStatusPalErrorCode.CredentialsNeeded),
Interop.Ssl.SslErrorCode.SSL_ERROR_NONE or
Interop.Ssl.SslErrorCode.SSL_ERROR_WANT_READ => new SecurityStatusPal(SecurityStatusPalErrorCode.OK),
_ => new SecurityStatusPal(SecurityStatusPalErrorCode.InternalError, new Interop.OpenSsl.SslException((int)errorCode))
};
public static ChannelBinding? QueryContextChannelBinding(SafeDeleteSslContext securityContext, ChannelBindingKind attribute)
{
ChannelBinding? bindingHandle;
if (attribute == ChannelBindingKind.Endpoint)
{
bindingHandle = EndpointChannelBindingToken.Build(securityContext);
if (bindingHandle == null)
{
throw Interop.OpenSsl.CreateSslException(SR.net_ssl_invalid_certificate);
}
}
else
{
bindingHandle = Interop.OpenSsl.QueryChannelBinding(
(SafeSslHandle)securityContext,
attribute);
}
return bindingHandle;
}
public static ProtocolToken Renegotiate(
ref SafeFreeCredentials? credentialsHandle,
ref SafeDeleteSslContext context,
SslAuthenticationOptions sslAuthenticationOptions)
{
SecurityStatusPal status = Interop.OpenSsl.SslRenegotiate((SafeSslHandle)context, out _);
if (status.ErrorCode != SecurityStatusPalErrorCode.OK)
{
return default;
}
return HandshakeInternal(ref context!, null, out _, sslAuthenticationOptions);
}
public static void QueryContextStreamSizes(SafeDeleteContext? _ /*securityContext*/, out StreamSizes streamSizes)
{
streamSizes = StreamSizes.Default;
}
public static void QueryContextConnectionInfo(SafeDeleteSslContext securityContext, ref SslConnectionInfo connectionInfo)
{
connectionInfo.UpdateSslConnectionInfo((SafeSslHandle)securityContext);
}
public static bool TryUpdateClintCertificate(
SafeFreeCredentials? _,
SafeDeleteSslContext? context,
SslAuthenticationOptions sslAuthenticationOptions)
{
Interop.OpenSsl.UpdateClientCertificate((SafeSslHandle)context!, sslAuthenticationOptions);
return true;
}
private static ProtocolToken HandshakeInternal(ref SafeDeleteSslContext? context,
ReadOnlySpan<byte> inputBuffer, out int consumed, SslAuthenticationOptions sslAuthenticationOptions)
{
ProtocolToken token = default;
token.RentBuffer = true;
consumed = 0;
try
{
if ((null == context) || context.IsInvalid)
{
context = Interop.OpenSsl.AllocateSslHandle(sslAuthenticationOptions);
}
SecurityStatusPalErrorCode errorCode = Interop.OpenSsl.DoSslHandshake((SafeSslHandle)context, inputBuffer, ref token);
consumed = inputBuffer.Length;
if (errorCode == SecurityStatusPalErrorCode.CredentialsNeeded)
{
// this should happen only for clients
Debug.Assert(sslAuthenticationOptions.IsClient);
// if we don't have a client certificate ready, bubble up so
// that the certificate selection routine runs again. This
// happens if the first call to LocalCertificateSelectionCallback
// returns null.
if (sslAuthenticationOptions.CertificateContext == null)
{
token.Status = new SecurityStatusPal(SecurityStatusPalErrorCode.CredentialsNeeded);
return token;
}
// set the cert and continue
TryUpdateClintCertificate(null, context, sslAuthenticationOptions);
errorCode = Interop.OpenSsl.DoSslHandshake((SafeSslHandle)context, ReadOnlySpan<byte>.Empty, ref token);
}
// sometimes during renegotiation processing message does not yield new output.
// That seems to be flaw in OpenSSL state machine and we have workaround to peek it and try it again.
if (token.Size == 0 && Interop.Ssl.IsSslRenegotiatePending((SafeSslHandle)context))
{
errorCode = Interop.OpenSsl.DoSslHandshake((SafeSslHandle)context, ReadOnlySpan<byte>.Empty, ref token);
}
// When the handshake is done, and the context is server, check if the alpnHandle target was set to null during ALPN.
// If it was, then that indicates ALPN failed, send failure.
// We have this workaround, as openssl supports terminating handshake only from version 1.1.0,
// whereas ALPN is supported from version 1.0.2.
SafeSslHandle sslContext = (SafeSslHandle)context;
if (errorCode == SecurityStatusPalErrorCode.OK && sslAuthenticationOptions.IsServer
&& sslAuthenticationOptions.ApplicationProtocols != null && sslAuthenticationOptions.ApplicationProtocols.Count != 0
&& sslContext.AlpnHandle.IsAllocated && sslContext.AlpnHandle.Target == null)
{
token.Status = new SecurityStatusPal(SecurityStatusPalErrorCode.InternalError, Interop.OpenSsl.CreateSslException(SR.net_alpn_failed));
return token;
}
token.Status = new SecurityStatusPal(errorCode);
}
catch (Exception exc)
{
token.Status = new SecurityStatusPal(SecurityStatusPalErrorCode.InternalError, exc);
}
return token;
}
public static SecurityStatusPal ApplyAlertToken(SafeDeleteContext? securityContext, TlsAlertType alertType, TlsAlertMessage alertMessage)
{
// There doesn't seem to be an exposed API for writing an alert,
// the API seems to assume that all alerts are generated internally by
// SSLHandshake.
return new SecurityStatusPal(SecurityStatusPalErrorCode.OK);
}
#pragma warning restore IDE0060
public static SecurityStatusPal ApplyShutdownToken(SafeDeleteSslContext context)
{
// Unset the quiet shutdown option initially configured.
Interop.Ssl.SslSetQuietShutdown((SafeSslHandle)context, 0);
int status = Interop.Ssl.SslShutdown((SafeSslHandle)context);
if (status == 0)
{
// Call SSL_shutdown again for a bi-directional shutdown.
status = Interop.Ssl.SslShutdown((SafeSslHandle)context);
}
if (status == 1)
return new SecurityStatusPal(SecurityStatusPalErrorCode.OK);
Interop.Ssl.SslErrorCode code = Interop.Ssl.SslGetError((SafeSslHandle)context, status);
if (code == Interop.Ssl.SslErrorCode.SSL_ERROR_WANT_READ ||
code == Interop.Ssl.SslErrorCode.SSL_ERROR_WANT_WRITE)
{
return new SecurityStatusPal(SecurityStatusPalErrorCode.OK);
}
else if (code == Interop.Ssl.SslErrorCode.SSL_ERROR_SSL)
{
// OpenSSL failure occurred. The error queue contains more details, when building the exception the queue will be cleared.
return new SecurityStatusPal(SecurityStatusPalErrorCode.InternalError, Interop.Crypto.CreateOpenSslCryptographicException());
}
else
{
return new SecurityStatusPal(SecurityStatusPalErrorCode.InternalError, new Interop.OpenSsl.SslException((int)code));
}
}
}
}