1 // Transport Security Layer (TLS)
2 // Copyright (c) 2003-2004 Carlos Guzman Alvarez
3 // Copyright (C) 2006 Novell, Inc (http://www.novell.com)
5 // Permission is hereby granted, free of charge, to any person obtaining
6 // a copy of this software and associated documentation files (the
7 // "Software"), to deal in the Software without restriction, including
8 // without limitation the rights to use, copy, modify, merge, publish,
9 // distribute, sublicense, and/or sell copies of the Software, and to
10 // permit persons to whom the Software is furnished to do so, subject to
11 // the following conditions:
13 // The above copyright notice and this permission notice shall be
14 // included in all copies or substantial portions of the Software.
16 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27 using System.Collections;
28 using System.Security.Cryptography;
29 using System.Security.Cryptography.X509Certificates;
31 using Mono.Security.Cryptography;
32 using Mono.Security.Protocol.Tls.Handshake;
34 namespace Mono.Security.Protocol.Tls
36 internal abstract class Context
38 #region Internal Constants
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;
50 private SecurityProtocolType securityProtocol;
53 private byte[] sessionId;
56 private SecurityCompressionType compressionMethod;
58 // Information sent and request by the server in the Handshake protocol
59 private TlsServerSettings serverSettings;
61 // Client configuration
62 private TlsClientSettings clientSettings;
64 // Cipher suite information
65 private SecurityParameters current;
66 private SecurityParameters negotiating;
67 private SecurityParameters read;
68 private SecurityParameters write;
69 private CipherSuiteCollection supportedCiphers;
71 // Last handshake message received
72 private HandshakeType lastHandshakeMsg;
74 // Handshake negotiation state
75 private HandshakeState handshakeState;
78 private bool abbreviatedHandshake;
79 private bool receivedConnectionEnd;
80 private bool sentConnectionEnd;
81 private bool protocolNegotiated;
84 private ulong writeSequenceNumber;
85 private ulong readSequenceNumber;
88 private byte[] clientRandom;
89 private byte[] serverRandom;
90 private byte[] randomCS;
91 private byte[] randomSC;
94 private byte[] masterSecret;
95 private byte[] clientWriteKey;
96 private byte[] serverWriteKey;
97 private byte[] clientWriteIV;
98 private byte[] serverWriteIV;
101 private TlsStream handshakeMessages;
103 // Secure Random generator
104 private RandomNumberGenerator random;
107 private RecordProtocol recordProtocol;
113 public bool AbbreviatedHandshake
115 get { return abbreviatedHandshake; }
116 set { abbreviatedHandshake = value; }
119 public bool ProtocolNegotiated
121 get { return this.protocolNegotiated; }
122 set { this.protocolNegotiated = value; }
125 public bool ChangeCipherSpecDone { get; set; }
127 public SecurityProtocolType SecurityProtocol
131 if ((this.securityProtocol & SecurityProtocolType.Tls) == SecurityProtocolType.Tls ||
132 (this.securityProtocol & SecurityProtocolType.Default) == SecurityProtocolType.Default)
134 return SecurityProtocolType.Tls;
138 if ((this.securityProtocol & SecurityProtocolType.Ssl3) == SecurityProtocolType.Ssl3)
140 return SecurityProtocolType.Ssl3;
144 throw new NotSupportedException("Unsupported security protocol type");
147 set { this.securityProtocol = value; }
150 public SecurityProtocolType SecurityProtocolFlags
152 get { return this.securityProtocol; }
155 public short Protocol
159 switch (this.SecurityProtocol)
161 case SecurityProtocolType.Tls:
162 case SecurityProtocolType.Default:
163 return Context.TLS1_PROTOCOL_CODE;
165 case SecurityProtocolType.Ssl3:
166 return Context.SSL3_PROTOCOL_CODE;
168 case SecurityProtocolType.Ssl2:
170 throw new NotSupportedException("Unsupported security protocol type");
175 public byte[] SessionId
177 get { return this.sessionId; }
178 set { this.sessionId = value; }
181 public SecurityCompressionType CompressionMethod
183 get { return this.compressionMethod; }
184 set { this.compressionMethod = value; }
187 public TlsServerSettings ServerSettings
189 get { return this.serverSettings; }
192 public TlsClientSettings ClientSettings
194 get { return this.clientSettings; }
197 public HandshakeType LastHandshakeMsg
199 get { return this.lastHandshakeMsg; }
200 set { this.lastHandshakeMsg = value; }
203 public HandshakeState HandshakeState
205 get { return this.handshakeState; }
206 set { this.handshakeState = value; }
209 public bool ReceivedConnectionEnd
211 get { return this.receivedConnectionEnd; }
212 set { this.receivedConnectionEnd = value; }
215 public bool SentConnectionEnd
217 get { return this.sentConnectionEnd; }
218 set { this.sentConnectionEnd = value; }
221 public CipherSuiteCollection SupportedCiphers
223 get { return supportedCiphers; }
224 set { supportedCiphers = value; }
227 public TlsStream HandshakeMessages
229 get { return this.handshakeMessages; }
232 public ulong WriteSequenceNumber
234 get { return this.writeSequenceNumber; }
235 set { this.writeSequenceNumber = value; }
238 public ulong ReadSequenceNumber
240 get { return this.readSequenceNumber; }
241 set { this.readSequenceNumber = value; }
244 public byte[] ClientRandom
246 get { return this.clientRandom; }
247 set { this.clientRandom = value; }
250 public byte[] ServerRandom
252 get { return this.serverRandom; }
253 set { this.serverRandom = value; }
256 public byte[] RandomCS
258 get { return this.randomCS; }
259 set { this.randomCS = value; }
262 public byte[] RandomSC
264 get { return this.randomSC; }
265 set { this.randomSC = value; }
268 public byte[] MasterSecret
270 get { return this.masterSecret; }
271 set { this.masterSecret = value; }
274 public byte[] ClientWriteKey
276 get { return this.clientWriteKey; }
277 set { this.clientWriteKey = value; }
280 public byte[] ServerWriteKey
282 get { return this.serverWriteKey; }
283 set { this.serverWriteKey = value; }
286 public byte[] ClientWriteIV
288 get { return this.clientWriteIV; }
289 set { this.clientWriteIV = value; }
292 public byte[] ServerWriteIV
294 get { return this.serverWriteIV; }
295 set { this.serverWriteIV = value; }
298 public RecordProtocol RecordProtocol
300 get { return this.recordProtocol; }
301 set { this.recordProtocol = value; }
308 public Context(SecurityProtocolType securityProtocolType)
310 this.SecurityProtocol = securityProtocolType;
311 this.compressionMethod = SecurityCompressionType.None;
312 this.serverSettings = new TlsServerSettings();
313 this.clientSettings = new TlsClientSettings();
314 this.handshakeMessages = new TlsStream();
315 this.sessionId = null;
316 this.handshakeState = HandshakeState.None;
317 this.random = RandomNumberGenerator.Create();
324 public int GetUnixTime()
326 DateTime now = DateTime.UtcNow;
328 return (int)((now.Ticks - UNIX_BASE_TICKS) / TimeSpan.TicksPerSecond);
331 public byte[] GetSecureRandomBytes(int count)
333 byte[] secureBytes = new byte[count];
335 this.random.GetNonZeroBytes(secureBytes);
340 public virtual void Clear()
342 this.compressionMethod = SecurityCompressionType.None;
343 this.serverSettings = new TlsServerSettings();
344 this.clientSettings = new TlsClientSettings();
345 this.handshakeMessages = new TlsStream();
346 this.sessionId = null;
347 this.handshakeState = HandshakeState.None;
352 public virtual void ClearKeyInfo()
354 // Clear Master Secret
355 if (masterSecret != null) {
356 Array.Clear (masterSecret, 0, masterSecret.Length);
360 // Clear client and server random
361 if (clientRandom != null) {
362 Array.Clear (clientRandom, 0, clientRandom.Length);
365 if (serverRandom != null) {
366 Array.Clear (serverRandom, 0, serverRandom.Length);
369 if (randomCS != null) {
370 Array.Clear (randomCS, 0, randomCS.Length);
373 if (randomSC != null) {
374 Array.Clear (randomSC, 0, randomSC.Length);
379 if (clientWriteKey != null) {
380 Array.Clear (clientWriteKey, 0, clientWriteKey.Length);
381 clientWriteKey = null;
383 if (clientWriteIV != null) {
384 Array.Clear (clientWriteIV, 0, clientWriteIV.Length);
385 clientWriteIV = null;
389 if (serverWriteKey != null) {
390 Array.Clear (serverWriteKey, 0, serverWriteKey.Length);
391 serverWriteKey = null;
393 if (serverWriteIV != null) {
394 Array.Clear (serverWriteIV, 0, serverWriteIV.Length);
395 serverWriteIV = null;
398 // Reset handshake messages
399 this.handshakeMessages.Reset();
401 // Clear MAC keys if protocol is different than Ssl3
402 // SSLv3 needs them inside Mono.Security.Protocol.Tls.SslCipherSuite.Compute[Client|Server]RecordMAC
403 if (this.securityProtocol != SecurityProtocolType.Ssl3)
405 // this.clientWriteMAC = null;
406 // this.serverWriteMAC = null;
410 public SecurityProtocolType DecodeProtocolCode (short code, bool allowFallback = false)
414 case Context.TLS1_PROTOCOL_CODE:
415 return SecurityProtocolType.Tls;
417 case Context.SSL3_PROTOCOL_CODE:
418 return SecurityProtocolType.Ssl3;
421 // if allowed we'll continue using TLS (1.0) even if the other side is capable of using a newer
422 // version of the TLS protocol
423 if (allowFallback && (code > (short) Context.TLS1_PROTOCOL_CODE))
424 return SecurityProtocolType.Tls;
425 throw new NotSupportedException("Unsupported security protocol type");
429 public void ChangeProtocol(short protocol)
431 SecurityProtocolType protocolType = this.DecodeProtocolCode(protocol);
433 if ((protocolType & this.SecurityProtocolFlags) == protocolType ||
434 (this.SecurityProtocolFlags & SecurityProtocolType.Default) == SecurityProtocolType.Default)
436 this.SecurityProtocol = protocolType;
437 this.SupportedCiphers = CipherSuiteFactory.GetSupportedCiphers ((this is ServerContext), protocolType);
441 throw new TlsException(AlertDescription.ProtocolVersion, "Incorrect protocol version received from server");
446 public SecurityParameters Current
451 current = new SecurityParameters ();
452 if (current.Cipher != null)
453 current.Cipher.Context = this;
458 public SecurityParameters Negotiating
462 if (negotiating == null)
463 negotiating = new SecurityParameters ();
464 if (negotiating.Cipher != null)
465 negotiating.Cipher.Context = this;
470 public SecurityParameters Read
475 public SecurityParameters Write
477 get { return write; }
480 public void StartSwitchingSecurityParameters (bool client)
483 // everything we write from now on is encrypted
485 // but we still read with the older cipher until we
486 // receive the ChangeCipherSpec message
489 // everything we read from now on is encrypted
491 // but we still write with the older cipher until we
492 // receive the ChangeCipherSpec message
495 current = negotiating;
498 public void EndSwitchingSecurityParameters (bool client)
500 SecurityParameters temp;
503 // we now read with the new, negotiated, security parameters
507 // we now write with the new, negotiated, security parameters
510 // so we clear the old one (last reference)
514 // and are now ready for a future renegotiation