2004-04-21 Carlos Guzman Alvarez <carlosga@telefonica.net>
[mono.git] / mcs / class / Mono.Security / Mono.Security.Protocol.Tls / Context.cs
1 /* Transport Security Layer (TLS)
2  * Copyright (c) 2003-2004 Carlos Guzman Alvarez
3  * 
4  * Permission is hereby granted, free of charge, to any person 
5  * obtaining a copy of this software and associated documentation 
6  * files (the "Software"), to deal in the Software without restriction, 
7  * including without limitation the rights to use, copy, modify, merge, 
8  * publish, distribute, sublicense, and/or sell copies of the Software, 
9  * and to permit persons to whom the Software is furnished to do so, 
10  * subject to the following conditions:
11  * 
12  * The above copyright notice and this permission notice shall be included 
13  * in all copies or substantial portions of the Software.
14  * 
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
16  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 
17  * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
18  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 
19  * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
20  * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
22  * DEALINGS IN THE SOFTWARE.
23  */
24
25 using System;
26 using System.Text;
27 using System.Collections;
28 using System.Security.Cryptography;
29 using System.Security.Cryptography.X509Certificates;
30
31 using Mono.Security.Cryptography;
32 using Mono.Security.Protocol.Tls.Handshake;
33
34 namespace Mono.Security.Protocol.Tls
35 {
36         internal abstract class Context
37         {
38                 #region Internal Constants
39
40                 internal const short MAX_FRAGMENT_SIZE  = 16384; // 2^14
41                 internal const short TLS1_PROTOCOL_CODE = (0x03 << 8) | 0x01;
42                 internal const short SSL3_PROTOCOL_CODE = (0x03 << 8) | 0x00;
43                 internal const long  UNIX_BASE_TICKS    = 621355968000000000;
44
45                 #endregion
46
47                 #region Fields
48                 
49                 // Protocol version
50                 private SecurityProtocolType securityProtocol;
51                 
52                 // Sesison ID
53                 private byte[] sessionId;
54
55                 // Compression method
56                 private SecurityCompressionType compressionMethod;
57
58                 // Information sent and request by the server in the Handshake protocol
59                 private TlsServerSettings serverSettings;
60
61                 // Client configuration
62                 private TlsClientSettings clientSettings;
63
64                 // Cipher suite information
65                 private CipherSuite                             cipher;
66                 private CipherSuiteCollection   supportedCiphers;
67
68                 // Last handshake message received
69                 private HandshakeType lastHandshakeMsg;
70
71                 // Handshake negotiation state
72                 private HandshakeState handshakeState;
73
74                 // Misc
75                 private bool    isActual;
76                 private bool    connectionEnd;
77                 private bool    protocolNegotiated;
78                 
79                 // Sequence numbers
80                 private long    writeSequenceNumber;
81                 private long    readSequenceNumber;
82
83                 // Random data
84                 private byte[]  clientRandom;
85                 private byte[]  serverRandom;
86                 private byte[]  randomCS;
87                 private byte[]  randomSC;
88
89                 // Key information
90                 private byte[]  masterSecret;
91                 private byte[]  clientWriteMAC;
92                 private byte[]  serverWriteMAC;
93                 private byte[]  clientWriteKey;
94                 private byte[]  serverWriteKey;
95                 private byte[]  clientWriteIV;
96                 private byte[]  serverWriteIV;
97                 
98                 // Handshake hashes
99                 private TlsStream handshakeMessages;
100                 
101                 // Secure Random generator              
102                 private RandomNumberGenerator random;
103
104                 // Record protocol
105                 private RecordProtocol recordProtocol;
106
107                 #endregion
108
109                 #region Properties
110
111                 public bool     ProtocolNegotiated
112                 {
113                         get { return this.protocolNegotiated; }
114                         set { this.protocolNegotiated = value; }
115                 }
116
117                 public SecurityProtocolType SecurityProtocol
118                 {
119                         get 
120                         {
121                                 if ((this.securityProtocol & SecurityProtocolType.Tls) == SecurityProtocolType.Tls ||   
122                                         (this.securityProtocol & SecurityProtocolType.Default) == SecurityProtocolType.Default)
123                                 {
124                                         return SecurityProtocolType.Tls;
125                                 }
126                                 else
127                                 {
128                                         if ((this.securityProtocol & SecurityProtocolType.Ssl3) == SecurityProtocolType.Ssl3)
129                                         {
130                                                 return SecurityProtocolType.Ssl3;
131                                         }
132                                 }
133
134                                 throw new NotSupportedException("Unsupported security protocol type");
135                         }
136
137                         set { this.securityProtocol = value; }
138                 }
139
140                 public SecurityProtocolType SecurityProtocolFlags
141                 {
142                         get { return this.securityProtocol; }
143                 }
144
145                 public short Protocol
146                 {
147                         get 
148                         { 
149                                 switch (this.SecurityProtocol)
150                                 {
151                                         case SecurityProtocolType.Tls:
152                                         case SecurityProtocolType.Default:
153                                                 return Context.TLS1_PROTOCOL_CODE;
154
155                                         case SecurityProtocolType.Ssl3:
156                                                 return Context.SSL3_PROTOCOL_CODE;
157
158                                         case SecurityProtocolType.Ssl2:
159                                         default:
160                                                 throw new NotSupportedException("Unsupported security protocol type");
161                                 }
162                         }
163                 }
164
165                 public byte[] SessionId
166                 {
167                         get { return this.sessionId; }
168                         set { this.sessionId = value; }
169                 }
170
171                 public SecurityCompressionType CompressionMethod
172                 {
173                         get { return this.compressionMethod; }
174                         set { this.compressionMethod = value; }
175                 }
176
177                 public TlsServerSettings ServerSettings
178                 {
179                         get { return this.serverSettings; }
180                         set { this.serverSettings = value; }
181                 }
182
183                 public TlsClientSettings ClientSettings
184                 {
185                         get { return this.clientSettings; }
186                         set { this.clientSettings = value; }
187                 }
188
189                 public bool     IsActual
190                 {
191                         get { return this.isActual; }
192                         set { this.isActual = value; }
193                 }
194
195                 public HandshakeType LastHandshakeMsg
196                 {
197                         get { return this.lastHandshakeMsg; }
198                         set { this.lastHandshakeMsg = value; }
199                 }
200
201                 public  HandshakeState HandshakeState
202                 {
203                         get { return this.handshakeState; }
204                         set { this.handshakeState = value; }
205                 }
206
207                 public bool ConnectionEnd
208                 {
209                         get { return this.connectionEnd; }
210                         set { this.connectionEnd = value; }
211                 }
212
213                 public CipherSuite Cipher
214                 {
215                         get { return this.cipher; }
216                         set 
217                         { 
218                                 this.cipher                     = value; 
219                                 this.cipher.Context = this;
220                         }
221                 }
222
223                 public CipherSuiteCollection SupportedCiphers
224                 {
225                         get { return supportedCiphers; }
226                         set { supportedCiphers = value; }
227                 }
228
229                 public TlsStream HandshakeMessages
230                 {
231                         get { return this.handshakeMessages; }
232                 }
233
234                 public long WriteSequenceNumber
235                 {
236                         get { return this.writeSequenceNumber; }
237                         set { this.writeSequenceNumber = value; }
238                 }
239
240                 public long ReadSequenceNumber
241                 {
242                         get { return this.readSequenceNumber; }
243                         set { this.readSequenceNumber = value; }
244                 }
245
246                 public byte[] ClientRandom
247                 {
248                         get { return this.clientRandom; }
249                         set { this.clientRandom = value; }
250                 }
251
252                 public byte[] ServerRandom
253                 {
254                         get { return this.serverRandom; }
255                         set { this.serverRandom = value; }
256                 }
257
258                 public byte[] RandomCS
259                 {
260                         get { return this.randomCS; }
261                         set { this.randomCS = value; }
262                 }
263
264                 public byte[] RandomSC
265                 {
266                         get { return this.randomSC; }
267                         set { this.randomSC = value; }
268                 }
269
270                 public byte[] MasterSecret
271                 {
272                         get { return this.masterSecret; }
273                         set { this.masterSecret = value; }
274                 }
275
276                 public byte[] ClientWriteMAC
277                 {
278                         get { return this.clientWriteMAC; }
279                         set { this.clientWriteMAC = value; }
280                 }
281
282                 public byte[] ServerWriteMAC
283                 {
284                         get { return this.serverWriteMAC; }
285                         set { this.serverWriteMAC = value; }
286                 }
287
288                 public byte[] ClientWriteKey
289                 {
290                         get { return this.clientWriteKey; }
291                         set { this.clientWriteKey = value; }
292                 }
293
294                 public byte[] ServerWriteKey
295                 {
296                         get { return this.serverWriteKey; }
297                         set { this.serverWriteKey = value; }
298                 }
299
300                 public byte[] ClientWriteIV
301                 {
302                         get { return this.clientWriteIV; }
303                         set { this.clientWriteIV = value; }
304                 }
305
306                 public byte[] ServerWriteIV
307                 {
308                         get { return this.serverWriteIV; }
309                         set { this.serverWriteIV = value; }
310                 }
311
312                 public RecordProtocol RecordProtocol
313                 {
314                         get { return this.recordProtocol; }
315                         set { this.recordProtocol = value; }
316                 }
317
318                 #endregion
319
320                 #region Constructors
321
322                 public Context(SecurityProtocolType securityProtocolType)
323                 {
324                         this.SecurityProtocol   = securityProtocolType;
325                         this.compressionMethod  = SecurityCompressionType.None;
326                         this.serverSettings             = new TlsServerSettings();
327                         this.clientSettings             = new TlsClientSettings();
328                         this.handshakeMessages  = new TlsStream();
329                         this.sessionId                  = null;
330                         this.handshakeState             = HandshakeState.None;
331                         this.random                             = RandomNumberGenerator.Create();
332                 }
333
334                 #endregion
335
336                 #region Methods
337                 
338                 public int GetUnixTime()
339                 {
340                         DateTime now = DateTime.UtcNow;
341                                                                                                                                                      
342                         return (int)(now.Ticks - UNIX_BASE_TICKS / TimeSpan.TicksPerSecond);
343                 }
344
345                 public byte[] GetSecureRandomBytes(int count)
346                 {
347                         byte[] secureBytes = new byte[count];
348
349                         this.random.GetNonZeroBytes(secureBytes);
350                         
351                         return secureBytes;
352                 }
353
354                 public virtual void Clear()
355                 {
356                         this.compressionMethod  = SecurityCompressionType.None;
357                         this.serverSettings             = new TlsServerSettings();
358                         this.clientSettings             = new TlsClientSettings();
359                         this.handshakeMessages  = new TlsStream();
360                         this.sessionId                  = null;
361                         this.handshakeState             = HandshakeState.None;
362
363                         this.ClearKeyInfo();
364                 }
365
366                 public virtual void ClearKeyInfo()
367                 {
368                         // Clear Master Secret
369                         this.masterSecret       = null;
370
371                         // Clear client and server random
372                         this.clientRandom       = null;
373                         this.serverRandom       = null;
374                         this.randomCS           = null;
375                         this.randomSC           = null;
376
377                         // Clear client keys
378                         this.clientWriteKey     = null;
379                         this.clientWriteIV      = null;
380                         
381                         // Clear server keys
382                         this.serverWriteKey     = null;
383                         this.serverWriteIV      = null;
384
385                         // Reset handshake messages
386                         this.handshakeMessages.Reset();
387
388                         // Clear MAC keys if protocol is different than Ssl3
389                         if (this.securityProtocol != SecurityProtocolType.Ssl3)
390                         {
391                                 this.clientWriteMAC = null;
392                                 this.serverWriteMAC = null;
393                         }
394                 }
395
396                 public SecurityProtocolType DecodeProtocolCode(short code)
397                 {
398                         switch (code)
399                         {
400                                 case Context.TLS1_PROTOCOL_CODE:
401                                         return SecurityProtocolType.Tls;
402
403                                 case Context.SSL3_PROTOCOL_CODE:
404                                         return SecurityProtocolType.Ssl3;
405
406                                 default:
407                                         throw new NotSupportedException("Unsupported security protocol type");
408                         }
409                 }
410
411                 #endregion
412         }
413 }