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

using Org.BouncyCastle.Utilities;

namespace Org.BouncyCastle.Crypto.Tls
{
    public abstract class AbstractTlsServer
        :   AbstractTlsPeer, TlsServer
    {
        protected TlsCipherFactory mCipherFactory;

        protected TlsServerContext mContext;

        protected ProtocolVersion mClientVersion;
        protected int[] mOfferedCipherSuites;
        protected byte[] mOfferedCompressionMethods;
        protected IDictionary mClientExtensions;

        protected bool mEncryptThenMacOffered;
        protected short mMaxFragmentLengthOffered;
        protected bool mTruncatedHMacOffered;
        protected IList mSupportedSignatureAlgorithms;
        protected bool mEccCipherSuitesOffered;
        protected int[] mNamedCurves;
        protected byte[] mClientECPointFormats, mServerECPointFormats;

        protected ProtocolVersion mServerVersion;
        protected int mSelectedCipherSuite;
        protected byte mSelectedCompressionMethod;
        protected IDictionary mServerExtensions;

        public AbstractTlsServer()
            :   this(new DefaultTlsCipherFactory())
        {
        }

        public AbstractTlsServer(TlsCipherFactory cipherFactory)
        {
            this.mCipherFactory = cipherFactory;
        }

        protected virtual bool AllowEncryptThenMac
        {
            get { return true; }
        }

        protected virtual bool AllowTruncatedHMac
        {
            get { return false; }
        }

        protected virtual IDictionary CheckServerExtensions()
        {
            return this.mServerExtensions = TlsExtensionsUtilities.EnsureExtensionsInitialised(this.mServerExtensions);
        }

        protected abstract int[] GetCipherSuites();

        protected byte[] GetCompressionMethods()
        {
            return new byte[] { CompressionMethod.cls_null };
        }

        protected virtual ProtocolVersion MaximumVersion
        {
            get { return ProtocolVersion.TLSv11; }
        }

        protected virtual ProtocolVersion MinimumVersion
        {
            get { return ProtocolVersion.TLSv10; }
        }

        protected virtual bool SupportsClientEccCapabilities(int[] namedCurves, byte[] ecPointFormats)
        {
            // NOTE: BC supports all the current set of point formats so we don't check them here

            if (namedCurves == null)
            {
                /*
                 * RFC 4492 4. A client that proposes ECC cipher suites may choose not to include these
                 * extensions. In this case, the server is free to choose any one of the elliptic curves
                 * or point formats [...].
                 */
                return TlsEccUtilities.HasAnySupportedNamedCurves();
            }

            for (int i = 0; i < namedCurves.Length; ++i)
            {
                int namedCurve = namedCurves[i];
                if (NamedCurve.IsValid(namedCurve)
                    && (!NamedCurve.RefersToASpecificNamedCurve(namedCurve) || TlsEccUtilities.IsSupportedNamedCurve(namedCurve)))
                {
                    return true;
                }
            }

            return false;
        }

        public virtual void Init(TlsServerContext context)
        {
            this.mContext = context;
        }

        public virtual void NotifyClientVersion(ProtocolVersion clientVersion)
        {
            this.mClientVersion = clientVersion;
        }

        public virtual void NotifyOfferedCipherSuites(int[] offeredCipherSuites)
        {
            this.mOfferedCipherSuites = offeredCipherSuites;
            this.mEccCipherSuitesOffered = TlsEccUtilities.ContainsEccCipherSuites(this.mOfferedCipherSuites);
        }

        public virtual void NotifyOfferedCompressionMethods(byte[] offeredCompressionMethods)
        {
            this.mOfferedCompressionMethods = offeredCompressionMethods;
        }

        public virtual void ProcessClientExtensions(IDictionary clientExtensions)
        {
            this.mClientExtensions = clientExtensions;

            if (clientExtensions != null)
            {
                this.mEncryptThenMacOffered = TlsExtensionsUtilities.HasEncryptThenMacExtension(clientExtensions);
                this.mMaxFragmentLengthOffered = TlsExtensionsUtilities.GetMaxFragmentLengthExtension(clientExtensions);
                this.mTruncatedHMacOffered = TlsExtensionsUtilities.HasTruncatedHMacExtension(clientExtensions);

                this.mSupportedSignatureAlgorithms = TlsUtilities.GetSignatureAlgorithmsExtension(clientExtensions);
                if (this.mSupportedSignatureAlgorithms != null)
                {
                    /*
                     * 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(mClientVersion))
                        throw new TlsFatalAlert(AlertDescription.illegal_parameter);
                }

                this.mNamedCurves = TlsEccUtilities.GetSupportedEllipticCurvesExtension(clientExtensions);
                this.mClientECPointFormats = TlsEccUtilities.GetSupportedPointFormatsExtension(clientExtensions);
            }

            /*
             * RFC 4429 4. The client MUST NOT include these extensions in the ClientHello message if it
             * does not propose any ECC cipher suites.
             */
            if (!this.mEccCipherSuitesOffered && (this.mNamedCurves != null || this.mClientECPointFormats != null))
                throw new TlsFatalAlert(AlertDescription.illegal_parameter);
        }

        public virtual ProtocolVersion GetServerVersion()
        {
            if (MinimumVersion.IsEqualOrEarlierVersionOf(mClientVersion))
            {
                ProtocolVersion maximumVersion = MaximumVersion;
                if (mClientVersion.IsEqualOrEarlierVersionOf(maximumVersion))
                {
                    return mServerVersion = mClientVersion;
                }
                if (mClientVersion.IsLaterVersionOf(maximumVersion))
                {
                    return mServerVersion = maximumVersion;
                }
            }
            throw new TlsFatalAlert(AlertDescription.protocol_version);
        }

        public virtual int GetSelectedCipherSuite()
        {
            /*
             * TODO RFC 5246 7.4.3. In order to negotiate correctly, the server MUST check any candidate
             * cipher suites against the "signature_algorithms" extension before selecting them. This is
             * somewhat inelegant but is a compromise designed to minimize changes to the original
             * cipher suite design.
             */

            /*
             * RFC 4429 5.1. A server that receives a ClientHello containing one or both of these
             * extensions MUST use the client's enumerated capabilities to guide its selection of an
             * appropriate cipher suite. One of the proposed ECC cipher suites must be negotiated only
             * if the server can successfully complete the handshake while using the curves and point
             * formats supported by the client [...].
             */
            bool eccCipherSuitesEnabled = SupportsClientEccCapabilities(this.mNamedCurves, this.mClientECPointFormats);

            int[] cipherSuites = GetCipherSuites();
            for (int i = 0; i < cipherSuites.Length; ++i)
            {
                int cipherSuite = cipherSuites[i];

                if (Arrays.Contains(this.mOfferedCipherSuites, cipherSuite)
                    && (eccCipherSuitesEnabled || !TlsEccUtilities.IsEccCipherSuite(cipherSuite))
                    && TlsUtilities.IsValidCipherSuiteForVersion(cipherSuite, mServerVersion))
                {
                    return this.mSelectedCipherSuite = cipherSuite;
                }
            }
            throw new TlsFatalAlert(AlertDescription.handshake_failure);
        }

        public virtual byte GetSelectedCompressionMethod()
        {
            byte[] compressionMethods = GetCompressionMethods();
            for (int i = 0; i < compressionMethods.Length; ++i)
            {
                if (Arrays.Contains(mOfferedCompressionMethods, compressionMethods[i]))
                {
                    return this.mSelectedCompressionMethod = compressionMethods[i];
                }
            }
            throw new TlsFatalAlert(AlertDescription.handshake_failure);
        }

        // IDictionary is (Int32 -> byte[])
        public virtual IDictionary GetServerExtensions()
        {
            if (this.mEncryptThenMacOffered && AllowEncryptThenMac)
            {
                /*
                 * draft-ietf-tls-encrypt-then-mac-03 3. If a server receives an encrypt-then-MAC
                 * request extension from a client and then selects a stream or AEAD cipher suite, it
                 * MUST NOT send an encrypt-then-MAC response extension back to the client.
                 */
                if (TlsUtilities.IsBlockCipherSuite(this.mSelectedCipherSuite))
                {
                    TlsExtensionsUtilities.AddEncryptThenMacExtension(CheckServerExtensions());
                }
            }

            if (this.mMaxFragmentLengthOffered >= 0
                && TlsUtilities.IsValidUint8(mMaxFragmentLengthOffered)
                && MaxFragmentLength.IsValid((byte)mMaxFragmentLengthOffered))
            {
                TlsExtensionsUtilities.AddMaxFragmentLengthExtension(CheckServerExtensions(), (byte)mMaxFragmentLengthOffered);
            }

            if (this.mTruncatedHMacOffered && AllowTruncatedHMac)
            {
                TlsExtensionsUtilities.AddTruncatedHMacExtension(CheckServerExtensions());
            }

            if (this.mClientECPointFormats != null && TlsEccUtilities.IsEccCipherSuite(this.mSelectedCipherSuite))
            {
                /*
                 * RFC 4492 5.2. A server that selects an ECC cipher suite in response to a ClientHello
                 * message including a Supported Point Formats Extension appends this extension (along
                 * with others) to its ServerHello message, enumerating the point formats it can parse.
                 */
                this.mServerECPointFormats = new byte[]{ ECPointFormat.uncompressed,
                    ECPointFormat.ansiX962_compressed_prime, ECPointFormat.ansiX962_compressed_char2, };

                TlsEccUtilities.AddSupportedPointFormatsExtension(CheckServerExtensions(), mServerECPointFormats);
            }

            return mServerExtensions;
        }

        public virtual IList GetServerSupplementalData()
        {
            return null;
        }

        public abstract TlsCredentials GetCredentials();

        public virtual CertificateStatus GetCertificateStatus()
        {
            return null;
        }

        public abstract TlsKeyExchange GetKeyExchange();

        public virtual CertificateRequest GetCertificateRequest()
        {
            return null;
        }

        public virtual void ProcessClientSupplementalData(IList clientSupplementalData)
        {
            if (clientSupplementalData != null)
                throw new TlsFatalAlert(AlertDescription.unexpected_message);
        }

        public virtual void NotifyClientCertificate(Certificate clientCertificate)
        {
            throw new TlsFatalAlert(AlertDescription.internal_error);
        }

        public override TlsCompression GetCompression()
        {
            switch (mSelectedCompressionMethod)
            {
            case CompressionMethod.cls_null:
                return new TlsNullCompression();

            default:
                /*
                 * Note: internal error here; we selected the compression method, so if we now can't
                 * produce an implementation, we shouldn't have chosen it!
                 */
                throw new TlsFatalAlert(AlertDescription.internal_error);
            }
        }

        public virtual NewSessionTicket GetNewSessionTicket()
        {
            /*
             * RFC 5077 3.3. If the server determines that it does not want to include a ticket after it
             * has included the SessionTicket extension in the ServerHello, then it sends a zero-length
             * ticket in the NewSessionTicket handshake message.
             */
            return new NewSessionTicket(0L, TlsUtilities.EmptyBytes);
        }
    }
}