summary refs log tree commit diff
path: root/crypto/src/tls/AbstractTlsClient.cs
blob: 8d9d9de3d19fa59fbf45eb02f5e1b425bcb76989 (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
using System;
using System.Collections;
using System.IO;

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 m_supportedGroups;
        protected IList m_supportedSignatureAlgorithms;
        protected IList 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 GetNamedGroupRoles()
        {
            IList namedGroupRoles = TlsUtilities.GetNamedGroupRoles(GetCipherSuites());
            IList sigAlgs = m_supportedSignatureAlgorithms, 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 serverExtensions, int extensionType)
        {
            byte[] extensionData = TlsUtilities.GetExtensionData(serverExtensions, extensionType);
            if (extensionData != null && !AllowUnexpectedServerExtension(extensionType, extensionData))
                throw new TlsFatalAlert(AlertDescription.illegal_parameter);
        }

        /// <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 GetCertificateAuthorities()
        {
            return null;
        }

        protected virtual IList GetProtocolNames()
        {
            return null;
        }

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

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

        protected virtual IList 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"/> of <see cref="Int32"/>. See <see cref="NamedGroup"/> for group constants.
        /// </returns>
        protected virtual IList GetSupportedGroups(IList namedGroupRoles)
        {
            TlsCrypto crypto = Crypto;
            IList supportedGroups = Platform.CreateArrayList();

            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 GetSupportedSignatureAlgorithms()
        {
            return TlsUtilities.GetDefaultSupportedSignatureAlgorithms(m_context);
        }

        protected virtual IList GetSupportedSignatureAlgorithmsCert()
        {
            return null;
        }

        protected virtual IList GetTrustedCAIndication()
        {
            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 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 GetClientExtensions()
        {
            IDictionary clientExtensions = Platform.CreateHashtable();

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

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

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

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

            if (offeringTlsV13Plus)
            {
                IList 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);

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

                IList 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))
            {
                IList supportedSigAlgs = GetSupportedSignatureAlgorithms();
                if (null != supportedSigAlgs && supportedSigAlgs.Count > 0)
                {
                    this.m_supportedSignatureAlgorithms = supportedSigAlgs;

                    TlsExtensionsUtilities.AddSignatureAlgorithmsExtension(clientExtensions, supportedSigAlgs);
                }

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

                    TlsExtensionsUtilities.AddSignatureAlgorithmsCertExtension(clientExtensions, supportedSigAlgsCert);
                }
            }

            IList namedGroupRoles = GetNamedGroupRoles();

            IList 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 });
                }
            }

            return clientExtensions;
        }

        public virtual IList 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]);
        }

        /// <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 ProcessServerExtensions(IDictionary 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 serverSupplementalData)
        {
            if (serverSupplementalData != null)
                throw new TlsFatalAlert(AlertDescription.unexpected_message);
        }

        public abstract TlsAuthentication GetAuthentication();

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

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