summary refs log tree commit diff
path: root/crypto/src/tls/AbstractTlsClient.cs
blob: 5645e1c1378e702d999692934c0aa9def339262d (plain) (blame)
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
using System;
using System.Collections.Generic;
using System.IO;

using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Tls.Crypto;
using Org.BouncyCastle.Utilities;

namespace Org.BouncyCastle.Tls
{
    /// <summary>Base class for a TLS client.</summary>
    public abstract class AbstractTlsClient
        : AbstractTlsPeer, TlsClient
    {
        protected TlsClientContext m_context;
        protected ProtocolVersion[] m_protocolVersions;
        protected int[] m_cipherSuites;

        protected IList<int> m_supportedGroups;
        protected IList<SignatureAndHashAlgorithm> m_supportedSignatureAlgorithms;
        protected IList<SignatureAndHashAlgorithm> m_supportedSignatureAlgorithmsCert;

        protected AbstractTlsClient(TlsCrypto crypto)
            : base(crypto)
        {
        }

        /// <exception cref="IOException"/>
        protected virtual bool AllowUnexpectedServerExtension(int extensionType, byte[] extensionData)
        {
            switch (extensionType)
            {
            case ExtensionType.supported_groups:
                /*
                 * Exception added based on field reports that some servers do send this, although the
                 * Supported Elliptic Curves Extension is clearly intended to be client-only. If
                 * present, we still require that it is a valid EllipticCurveList.
                 */
                TlsExtensionsUtilities.ReadSupportedGroupsExtension(extensionData);
                return true;

            case ExtensionType.ec_point_formats:
                /*
                 * Exception added based on field reports that some servers send this even when they
                 * didn't negotiate an ECC cipher suite. If present, we still require that it is a valid
                 * ECPointFormatList.
                 */
                TlsExtensionsUtilities.ReadSupportedPointFormatsExtension(extensionData);
                return true;

            default:
                return false;
            }
        }

        protected virtual IList<int> GetNamedGroupRoles()
        {
            var namedGroupRoles = TlsUtilities.GetNamedGroupRoles(GetCipherSuites());
            var sigAlgs = m_supportedSignatureAlgorithms;
            var sigAlgsCert = m_supportedSignatureAlgorithmsCert;

            if ((null == sigAlgs || TlsUtilities.ContainsAnySignatureAlgorithm(sigAlgs, SignatureAlgorithm.ecdsa)) ||
                (null != sigAlgsCert && TlsUtilities.ContainsAnySignatureAlgorithm(sigAlgsCert, SignatureAlgorithm.ecdsa)))
            {
                TlsUtilities.AddToSet(namedGroupRoles, NamedGroupRole.ecdsa);
            }

            return namedGroupRoles;
        }

        /// <exception cref="IOException"/>
        protected virtual void CheckForUnexpectedServerExtension(IDictionary<int, byte[]> serverExtensions,
            int extensionType)
        {
            byte[] extensionData = TlsUtilities.GetExtensionData(serverExtensions, extensionType);
            if (extensionData != null && !AllowUnexpectedServerExtension(extensionType, extensionData))
                throw new TlsFatalAlert(AlertDescription.illegal_parameter);
        }

        /// <summary>RFC 9146 DTLS connection ID.</summary>
        /// <remarks>
        /// The default <see cref="GetClientExtensions"/> implementation calls this to get the connection_id extension
        /// the client will send. As future communication doesn't include the connection IDs length, this should either
        /// be fixed-length or include the connection ID's length. (see explanation in RFC 9146 4. "cid:")
        /// </remarks>
        /// <returns>The connection ID to use.</returns>
        protected virtual byte[] GetNewConnectionID() => null;

        /// <exception cref="IOException"/>
        public virtual TlsPskIdentity GetPskIdentity()
        {
            return null;
        }

        /// <exception cref="IOException"/>
        public virtual TlsSrpIdentity GetSrpIdentity()
        {
            return null;
        }

        public virtual TlsDHGroupVerifier GetDHGroupVerifier()
        {
            return new DefaultTlsDHGroupVerifier();
        }

        public virtual TlsSrpConfigVerifier GetSrpConfigVerifier()
        {
            return new DefaultTlsSrpConfigVerifier();
        }

        protected virtual IList<X509Name> GetCertificateAuthorities()
        {
            return null;
        }

        protected virtual IList<ProtocolName> GetProtocolNames()
        {
            return null;
        }

        protected virtual CertificateStatusRequest GetCertificateStatusRequest()
        {
            return new CertificateStatusRequest(CertificateStatusType.ocsp, new OcspStatusRequest(null, null));
        }

        /// <returns>an <see cref="IList{T}"/> of <see cref="CertificateStatusRequestItemV2"/> (or null).</returns>
        protected virtual IList<CertificateStatusRequestItemV2> GetMultiCertStatusRequest()
        {
            return null;
        }

        protected virtual IList<ServerName> GetSniServerNames()
        {
            return null;
        }

        /// <summary>The default <see cref="GetClientExtensions"/> implementation calls this to determine which named
        /// groups to include in the supported_groups extension for the ClientHello.</summary>
        /// <param name="namedGroupRoles">The <see cref="NamedGroupRole">named group roles</see> for which there should
        /// be at least one supported group. By default this is inferred from the offered cipher suites and signature
        /// algorithms.</param>
        /// <returns>an <see cref="IList{T}"/> of <see cref="Int32"/>. See <see cref="NamedGroup"/> for group constants.
        /// </returns>
        protected virtual IList<int> GetSupportedGroups(IList<int> namedGroupRoles)
        {
            TlsCrypto crypto = Crypto;
            var supportedGroups = new List<int>();

            if (namedGroupRoles.Contains(NamedGroupRole.ecdh))
            {
                TlsUtilities.AddIfSupported(supportedGroups, crypto,
                    new int[]{ NamedGroup.x25519, NamedGroup.x448 });
            }

            if (namedGroupRoles.Contains(NamedGroupRole.ecdh) ||
                namedGroupRoles.Contains(NamedGroupRole.ecdsa))
            {
                TlsUtilities.AddIfSupported(supportedGroups, crypto,
                    new int[]{ NamedGroup.secp256r1, NamedGroup.secp384r1 });
            }

            if (namedGroupRoles.Contains(NamedGroupRole.dh))
            {
                TlsUtilities.AddIfSupported(supportedGroups, crypto,
                    new int[]{ NamedGroup.ffdhe2048, NamedGroup.ffdhe3072, NamedGroup.ffdhe4096 });
            }

            return supportedGroups;
        }

        protected virtual IList<SignatureAndHashAlgorithm> GetSupportedSignatureAlgorithms()
        {
            return TlsUtilities.GetDefaultSupportedSignatureAlgorithms(m_context);
        }

        protected virtual IList<SignatureAndHashAlgorithm> GetSupportedSignatureAlgorithmsCert()
        {
            return null;
        }

        protected virtual IList<TrustedAuthority> GetTrustedCAIndication()
        {
            return null;
        }

        protected virtual short[] GetAllowedClientCertificateTypes()
        {
            return null;
        }

        protected virtual short[] GetAllowedServerCertificateTypes()
        {
            return null;
        }

        public virtual void Init(TlsClientContext context)
        {
            this.m_context = context;

            this.m_protocolVersions = GetSupportedVersions();
            this.m_cipherSuites = GetSupportedCipherSuites();
        }

        public override ProtocolVersion[] GetProtocolVersions()
        {
            return m_protocolVersions;
        }

        public override int[] GetCipherSuites()
        {
            return m_cipherSuites;
        }

        /// <exception cref="IOException"/>
        public override void NotifyHandshakeBeginning()
        {
            base.NotifyHandshakeBeginning();

            this.m_supportedGroups = null;
            this.m_supportedSignatureAlgorithms = null;
            this.m_supportedSignatureAlgorithmsCert = null;
        }

        public virtual TlsSession GetSessionToResume()
        {
            return null;
        }

        public virtual IList<TlsPskExternal> GetExternalPsks()
        {
            return null;
        }

        public virtual bool IsFallback()
        {
            /*
             * RFC 7507 4. The TLS_FALLBACK_SCSV cipher suite value is meant for use by clients that
             * repeat a connection attempt with a downgraded protocol (perform a "fallback retry") in
             * order to work around interoperability problems with legacy servers.
             */
            return false;
        }

        /// <exception cref="IOException"/>
        public virtual IDictionary<int, byte[]> GetClientExtensions()
        {
            var clientExtensions = new Dictionary<int, byte[]>();

            bool offeringTlsV13Plus = false;
            bool offeringPreTlsV13 = false;
            bool offeringDtlsV12 = false;
            {
                ProtocolVersion[] supportedVersions = GetProtocolVersions();
                for (int i = 0; i < supportedVersions.Length; ++i)
                {
                    var supportedVersion = supportedVersions[i];
                    if (TlsUtilities.IsTlsV13(supportedVersion))
                    {
                        offeringTlsV13Plus = true;
                    }
                    else
                    {
                        offeringPreTlsV13 = true;
                    }

                    offeringDtlsV12 |= ProtocolVersion.DTLSv12.Equals(supportedVersion);
                }
            }

            var protocolNames = GetProtocolNames();
            if (protocolNames != null)
            {
                TlsExtensionsUtilities.AddAlpnExtensionClient(clientExtensions, protocolNames);
            }

            var sniServerNames = GetSniServerNames();
            if (sniServerNames != null)
            {
                TlsExtensionsUtilities.AddServerNameExtensionClient(clientExtensions, sniServerNames);
            }

            CertificateStatusRequest statusRequest = GetCertificateStatusRequest();
            if (statusRequest != null)
            {
                TlsExtensionsUtilities.AddStatusRequestExtension(clientExtensions, statusRequest);
            }

            if (offeringTlsV13Plus)
            {
                var certificateAuthorities = GetCertificateAuthorities();
                if (certificateAuthorities != null)
                {
                    TlsExtensionsUtilities.AddCertificateAuthoritiesExtension(clientExtensions, certificateAuthorities);
                }
            }

            if (offeringPreTlsV13)
            {
                // TODO Shouldn't add if no offered cipher suite uses a block cipher?
                TlsExtensionsUtilities.AddEncryptThenMacExtension(clientExtensions);

                var statusRequestV2 = GetMultiCertStatusRequest();
                if (statusRequestV2 != null)
                {
                    TlsExtensionsUtilities.AddStatusRequestV2Extension(clientExtensions, statusRequestV2);
                }

                var trustedCAKeys = GetTrustedCAIndication();
                if (trustedCAKeys != null)
                {
                    TlsExtensionsUtilities.AddTrustedCAKeysExtensionClient(clientExtensions, trustedCAKeys);
                }
            }

            ProtocolVersion clientVersion = m_context.ClientVersion;

            /*
             * RFC 5246 7.4.1.4.1. Note: this extension is not meaningful for TLS versions prior to 1.2.
             * Clients MUST NOT offer it if they are offering prior versions.
             */
            if (TlsUtilities.IsSignatureAlgorithmsExtensionAllowed(clientVersion))
            {
                var supportedSigAlgs = GetSupportedSignatureAlgorithms();
                if (null != supportedSigAlgs && supportedSigAlgs.Count > 0)
                {
                    this.m_supportedSignatureAlgorithms = supportedSigAlgs;

                    TlsExtensionsUtilities.AddSignatureAlgorithmsExtension(clientExtensions, supportedSigAlgs);
                }

                var supportedSigAlgsCert = GetSupportedSignatureAlgorithmsCert();
                if (null != supportedSigAlgsCert && supportedSigAlgsCert.Count > 0)
                {
                    this.m_supportedSignatureAlgorithmsCert = supportedSigAlgsCert;

                    TlsExtensionsUtilities.AddSignatureAlgorithmsCertExtension(clientExtensions, supportedSigAlgsCert);
                }
            }

            var namedGroupRoles = GetNamedGroupRoles();

            var supportedGroups = GetSupportedGroups(namedGroupRoles);
            if (supportedGroups != null && supportedGroups.Count > 0)
            {
                this.m_supportedGroups = supportedGroups;

                TlsExtensionsUtilities.AddSupportedGroupsExtension(clientExtensions, supportedGroups);
            }

            if (offeringPreTlsV13)
            {
                if (namedGroupRoles.Contains(NamedGroupRole.ecdh) ||
                    namedGroupRoles.Contains(NamedGroupRole.ecdsa))
                {
                    TlsExtensionsUtilities.AddSupportedPointFormatsExtension(clientExtensions,
                        new short[]{ ECPointFormat.uncompressed });
                }
            }

            {
                /*
                 * RFC 7250 4.1. If the client has no remaining certificate types to send in the client hello, other
                 * than the default X.509 type, it MUST omit the client_certificate_type extension [..].
                 */
                short[] clientCertTypes = GetAllowedClientCertificateTypes();
                if (clientCertTypes != null &&
                    TlsUtilities.ContainsNot(clientCertTypes, 0, clientCertTypes.Length, CertificateType.X509))
                {
                    TlsExtensionsUtilities.AddClientCertificateTypeExtensionClient(clientExtensions, clientCertTypes);
                }
            }

            {
                /*
                 * RFC 7250 4.1. If the client has no remaining certificate types to send in the client hello, other than
                 * the default X.509 certificate type, it MUST omit the entire server_certificate_type extension [..].
                 */
                short[] serverCertTypes = GetAllowedServerCertificateTypes();
                if (serverCertTypes != null &&
                    TlsUtilities.ContainsNot(serverCertTypes, 0, serverCertTypes.Length, CertificateType.X509))
                {
                    TlsExtensionsUtilities.AddServerCertificateTypeExtensionClient(clientExtensions, serverCertTypes);
                }
            }

            if (offeringDtlsV12)
            {
                /*
                 * RFC 9146 3. When a DTLS session is resumed or renegotiated, the "connection_id" extension is
                 * negotiated afresh.
                 */
                var clientConnectionID = GetNewConnectionID();
                if (clientConnectionID != null)
                {
                    TlsExtensionsUtilities.AddConnectionIDExtension(clientExtensions, clientConnectionID);
                }
            }

            return clientExtensions;
        }

        public virtual IList<int> GetEarlyKeyShareGroups()
        {
            /*
             * RFC 8446 4.2.8. Each KeyShareEntry value MUST correspond to a group offered in the
             * "supported_groups" extension and MUST appear in the same order. However, the values MAY
             * be a non-contiguous subset of the "supported_groups" extension and MAY omit the most
             * preferred groups.
             */

            if (null == m_supportedGroups || m_supportedGroups.Count < 1)
                return null;

            if (m_supportedGroups.Contains(NamedGroup.x25519))
                return TlsUtilities.VectorOfOne(NamedGroup.x25519);

            if (m_supportedGroups.Contains(NamedGroup.secp256r1))
                return TlsUtilities.VectorOfOne(NamedGroup.secp256r1);

            return TlsUtilities.VectorOfOne(m_supportedGroups[0]);
        }

        public virtual bool ShouldUseCompatibilityMode()
        {
            return true;
        }

        /// <exception cref="IOException"/>
        public virtual void NotifyServerVersion(ProtocolVersion serverVersion)
        {
        }

        public virtual void NotifySessionToResume(TlsSession session)
        {
        }

        public virtual void NotifySessionID(byte[] sessionID)
        {
        }

        public virtual void NotifySelectedCipherSuite(int selectedCipherSuite)
        {
        }

        /// <exception cref="IOException"/>
        public virtual void NotifySelectedPsk(TlsPsk selectedPsk)
        {
        }

        /// <exception cref="IOException"/>
        public virtual void ProcessServerExtensions(IDictionary<int, byte[]> serverExtensions)
        {
            if (null == serverExtensions)
                return;

            SecurityParameters securityParameters = m_context.SecurityParameters;
            bool isTlsV13 = TlsUtilities.IsTlsV13(securityParameters.NegotiatedVersion);

            if (isTlsV13)
            {
                /*
                 * NOTE: From TLS 1.3 the protocol classes are strict about what extensions can appear.
                 */
            }
            else
            {
                /*
                 * RFC 5246 7.4.1.4.1. Servers MUST NOT send this extension.
                 */
                CheckForUnexpectedServerExtension(serverExtensions, ExtensionType.signature_algorithms);
                CheckForUnexpectedServerExtension(serverExtensions, ExtensionType.signature_algorithms_cert);

                CheckForUnexpectedServerExtension(serverExtensions, ExtensionType.supported_groups);

                int selectedCipherSuite = securityParameters.CipherSuite;

                if (TlsEccUtilities.IsEccCipherSuite(selectedCipherSuite))
                {
                    // We only support uncompressed format, this is just to validate the extension, if present.
                    TlsExtensionsUtilities.GetSupportedPointFormatsExtension(serverExtensions);
                }
                else
                {
                    CheckForUnexpectedServerExtension(serverExtensions, ExtensionType.ec_point_formats);
                }

                /*
                 * RFC 7685 3. The server MUST NOT echo the extension.
                 */
                CheckForUnexpectedServerExtension(serverExtensions, ExtensionType.padding);
            }
        }

        /// <exception cref="IOException"/>
        public virtual void ProcessServerSupplementalData(IList<SupplementalDataEntry> serverSupplementalData)
        {
            if (serverSupplementalData != null)
                throw new TlsFatalAlert(AlertDescription.unexpected_message);
        }

        public abstract TlsAuthentication GetAuthentication();

        /// <exception cref="IOException"/>
        public virtual IList<SupplementalDataEntry> GetClientSupplementalData()
        {
            return null;
        }

        /// <exception cref="IOException"/>
        public virtual void NotifyNewSessionTicket(NewSessionTicket newSessionTicket)
        {
        }
    }
}