Welcome to mirror list, hosted at ThFree Co, Russian Federation.

TlsSocket.cs « Mono.Security.Protocol.Tls « Mono.Security « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: dce8206a683ff707dd5f0308f39ef194b23c5a7e (plain)
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
/* Transport Security Layer (TLS)
 * Copyright (c) 2003 Carlos Guzmán Álvarez
 * 
 * Permission is hereby granted, free of charge, to any person 
 * obtaining a copy of this software and associated documentation 
 * files (the "Software"), to deal in the Software without restriction, 
 * including without limitation the rights to use, copy, modify, merge, 
 * publish, distribute, sublicense, and/or sell copies of the Software, 
 * and to permit persons to whom the Software is furnished to do so, 
 * subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included 
 * in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 * DEALINGS IN THE SOFTWARE.
 */

using System;
using System.IO;
using System.Net;
using System.Collections;
using System.Net.Sockets;
using System.Security.Cryptography;

using Mono.Security.Protocol.Tls;
using Mono.Security.Protocol.Tls.Alerts;
using Mono.Security.Protocol.Tls.Handshake;
using Mono.Security.Protocol.Tls.Handshake.Client;

namespace Mono.Security.Protocol.Tls
{
	public sealed class TlsSocket : Socket
	{
		#region FIELDS

		private TlsSession		session;
		private BufferedStream	inputBuffer;

		#endregion

		#region PROPERTIES

		internal TlsSession Session
		{
			get { return this.session; }
		}

		internal BufferedStream InputBuffer
		{
			get { return this.inputBuffer; }
		}

		#endregion

		#region CONSTRUCTORS

		private TlsSocket(
				AddressFamily	addressFamily,
				SocketType		socketType,
				ProtocolType	protocolType
				) : base(addressFamily, socketType, protocolType)
		{
			this.inputBuffer = new BufferedStream(new MemoryStream());
		}

		public TlsSocket(
			TlsSession		session,
			AddressFamily	addressFamily,
			SocketType		socketType,
			ProtocolType	protocolType
			) : this(addressFamily, socketType, protocolType)
		{
			this.session = session;
		}

		#endregion

		#region REPLACED_METHODS

		public new void Close()
		{
			this.resetBuffer();
			base.Close();
			if (this.session.State != TlsSessionState.Closing &&
				this.session.State != TlsSessionState.Closed)
			{
				this.session.Close();
			}
		}

		public new int Receive(byte[] buffer)
		{
			return this.Receive(buffer, 0, buffer != null ? buffer.Length : 0, SocketFlags.None);
		}
						
		public new int Receive(byte[] buffer, SocketFlags socketFlags)
		{
			return this.Receive(buffer, 0, buffer != null ? buffer.Length : 0, socketFlags);
		}

		public new int Receive(byte[] buffer, int size, SocketFlags socketFlags)
		{
			return this.Receive(buffer, 0, size, socketFlags);
		}

		public new int Receive(byte[] buffer, int offset, int size, SocketFlags socketFlags)
		{
			if (!this.session.IsSecure)
			{
				return base.Receive(buffer, offset, size, socketFlags);
			}
			
			// If actual buffer is full readed reset it
			if (this.inputBuffer.Position == this.inputBuffer.Length)
			{
				this.resetBuffer();
			}

			// Check if we have space in the middle buffer
			// if not Read next TLS record and update the inputBuffer
			while ((this.inputBuffer.Length - this.inputBuffer.Position) < size)
			{
				// Read next record and write it into the inputBuffer
				long	position	= this.inputBuffer.Position;					
				byte[]	record		= this.receiveRecord();

				if (record.Length > 0)
				{
					// Write new data to the inputBuffer
					this.inputBuffer.Seek(0, SeekOrigin.End);
					this.inputBuffer.Write(record, 0, record.Length);

					// Restore buffer position
					this.inputBuffer.Seek(position, SeekOrigin.Begin);
				}

				if (base.Available == 0)
				{
					break;
				}
			}

			return this.inputBuffer.Read(buffer, offset, size);
		}

		public new int Send(byte[] buffer)
		{
			return this.Send(buffer, 0, buffer != null ? buffer.Length : 0, SocketFlags.None);
		}
						
		public new int Send(byte[] buffer, SocketFlags socketFlags)
		{
			return this.Send(buffer, 0, buffer != null ? buffer.Length : 0, socketFlags);
		}

		public new int Send(byte[] buffer, int size, SocketFlags socketFlags)
		{
			return this.Send(buffer, 0, size, socketFlags);
		}

		public new int Send(byte[] buffer, int offset, int size, SocketFlags socketFlags)
		{
			if (!this.session.IsSecure)
			{
				return base.Send(buffer, offset, size, socketFlags);
			}

			// Send the buffer as a TLS record
			byte[] recordData = new byte[size];
			System.Array.Copy(buffer, offset, recordData, 0, size);

			return this.sendRecord(TlsContentType.ApplicationData, recordData);
		}

		#endregion

		#region TLS_RECORD_METHODS

		private byte[] receiveRecord()
		{
			if (this.session.Context.ConnectionEnd)
			{
				throw this.session.CreateException("The session is finished and it's no longer valid.");
			}
			
			TlsContentType	contentType	= (TlsContentType)this.ReadByte();
			TlsProtocol		protocol	= (TlsProtocol)this.ReadShort();
			short			length		= this.ReadShort();
			
			// Read Record data
			int		received	= 0;
			byte[]	buffer		= new byte[length];						
			while (received != length)
			{
				received += base.Receive(
					buffer, received, buffer.Length - received, SocketFlags.None);
			}

			TlsStream message = new TlsStream(buffer);
		
			// Check that the message has a valid protocol version
			if (protocol != this.session.Context.Protocol)
			{
				throw session.CreateException("Invalid protocol version on message received from server");
			}

			// Decrypt message contents if needed
			if (contentType == TlsContentType.Alert && length == 2)
			{
			}
			else
			{
				if (session.Context.IsActual &&
					contentType != TlsContentType.ChangeCipherSpec)
				{
					message = this.decryptRecordFragment(
						contentType, 
						protocol,
						message.ToArray());
				}
			}

			byte[] result = message.ToArray();

			// Process record
			switch (contentType)
			{
				case TlsContentType.Alert:
					this.processAlert((TlsAlertLevel)message.ReadByte(),
						(TlsAlertDescription)message.ReadByte());
					break;

				case TlsContentType.ChangeCipherSpec:
					// Reset sequence numbers
					this.session.Context.ReadSequenceNumber = 0;
					break;

				case TlsContentType.ApplicationData:
					break;

				case TlsContentType.Handshake:
					while (!message.EOF)
					{
						this.processHandshakeMessage(message);
					}
					// Update handshakes of current messages
					this.session.Context.HandshakeMessages.Write(message.ToArray());
					break;

				default:
					throw session.CreateException("Unknown record received from server.");
			}

			return result;
		}

		#endregion

		#region TLS_CRYPTO_METHODS

		private byte[] encryptRecordFragment(TlsContentType contentType, byte[] fragment)
		{
			// Calculate message MAC
			byte[] mac	= this.session.Context.Cipher.ComputeClientRecordMAC(contentType, fragment);

			// Encrypt the message
			byte[] ecr = this.session.Context.Cipher.EncryptRecord(fragment, mac);

			// Set new IV
			if (this.session.Context.Cipher.CipherMode == CipherMode.CBC)
			{
				byte[] iv = new byte[this.session.Context.Cipher.IvSize];
				System.Array.Copy(ecr, ecr.Length - iv.Length, iv, 0, iv.Length);
				this.session.Context.Cipher.UpdateClientCipherIV(iv);
			}

			// Update sequence number
			this.session.Context.WriteSequenceNumber++;

			return ecr;
		}

		private TlsStream decryptRecordFragment(TlsContentType contentType, 
			TlsProtocol protocol,
			byte[] fragment)
		{
			byte[]	dcrFragment	= null;
			byte[]	dcrMAC		= null;

			// Decrypt message
			this.session.Context.Cipher.DecryptRecord(fragment, ref dcrFragment, ref dcrMAC);

			// Set new IV
			if (this.session.Context.Cipher.CipherMode == CipherMode.CBC)
			{
				byte[] iv = new byte[session.Context.Cipher.IvSize];
				System.Array.Copy(fragment, fragment.Length - iv.Length, iv, 0, iv.Length);
				this.session.Context.Cipher.UpdateServerCipherIV(iv);
			}
			
			// Check MAC code
			byte[] mac = this.session.Context.Cipher.ComputeServerRecordMAC(contentType, dcrFragment);

			// Check that the mac is correct
			if (mac.Length != dcrMAC.Length)
			{
				throw new TlsException("Invalid MAC received from server.");
			}
			for (int i = 0; i < mac.Length; i++)
			{
				if (mac[i] != dcrMAC[i])
				{
					throw new TlsException("Invalid MAC received from server.");
				}
			}

			// Update sequence number
			this.session.Context.ReadSequenceNumber++;

			return new TlsStream(dcrFragment);
		}

		#endregion

		#region TLS_SEND_METHODS

		internal int SendAlert(TlsAlert alert)
		{			
			// Write record
			int bytesSent = this.sendRecord(TlsContentType.Alert, alert.ToArray());

			// Update session
			alert.UpdateSession();

			// Reset message contents
			alert.Reset();

			return bytesSent;
		}

		private int sendRecord(TlsHandshakeType type)
		{
			TlsHandshakeMessage msg = createClientHandshakeMessage(type);
			
			// Write record
			int bytesSent = this.sendRecord(msg.ContentType, msg.EncodeMessage());

			// Update session
			msg.UpdateSession();

			// Reset message contents
			msg.Reset();

			return bytesSent;
		}

		private int sendChangeCipherSpec()
		{
			// Send Change Cipher Spec message
			int bytesSent = this.sendRecord(TlsContentType.ChangeCipherSpec, new byte[] {1});

			// Reset sequence numbers
			this.session.Context.WriteSequenceNumber = 0;

			// Make the pending state to be the current state
			this.session.Context.IsActual = true;

			// Send Finished message
			bytesSent += this.sendRecord(TlsHandshakeType.Finished);

			return bytesSent;
		}
		
		private int sendRecord(TlsContentType contentType, byte[] recordData)
		{
			if (this.session.Context.ConnectionEnd)
			{
				throw this.session.CreateException("The session is finished and it's no longer valid.");
			}

			int			bytesSent = 0;
			byte[][]	fragments = fragmentData(recordData);
			for (int i = 0; i < fragments.Length; i++)
			{
				byte[] fragment = fragments[i];

				if (this.session.Context.IsActual)
				{
					// Encrypt fragment
					fragment = this.encryptRecordFragment(contentType, fragment);
				}

				// Write tls message
				TlsStream record = new TlsStream();
				record.Write((byte)contentType);
				record.Write((short)this.session.Context.Protocol);
				record.Write((short)fragment.Length);
				record.Write(fragment);

				// Write record
				bytesSent += base.Send(record.ToArray());

				// Reset record data
				record.Reset();
			}

			return bytesSent;
		}

		private byte[][] fragmentData(byte[] messageData)
		{
			ArrayList d = new ArrayList();
			
			int	position = 0;

			while (position < messageData.Length)
			{
				short	fragmentLength = 0;
				byte[]	fragmentData;
				if ((messageData.Length - position) > TlsSessionContext.MAX_FRAGMENT_SIZE)
				{
					fragmentLength = TlsSessionContext.MAX_FRAGMENT_SIZE;
				}
				else
				{
					fragmentLength = (short)(messageData.Length - position);
				}
				fragmentData = new byte[fragmentLength];

				System.Array.Copy(messageData, position, fragmentData, 0, fragmentLength);

				d.Add(fragmentData);

				position += fragmentLength;
			}

			byte[][] result = new byte[d.Count][];
			for (int i = 0; i < d.Count; i++)
			{
				result[i] = (byte[])d[i];
			}

			return result;
		}

		#endregion

		#region MESSAGE_PROCESSING

		private void processHandshakeMessage(TlsStream handMsg)
		{
			TlsHandshakeType	handshakeType	= (TlsHandshakeType)handMsg.ReadByte();
			TlsHandshakeMessage	message			= null;

			// Read message length
			int length = handMsg.ReadInt24();

			// Read message data
			byte[] data = new byte[length];
			handMsg.Read(data, 0, length);

			// Create and process the server message
			message = this.createServerHandshakeMessage(handshakeType, data);

			// Update session
			if (message != null)
			{
				message.UpdateSession();
			}
		}

		private void processAlert(TlsAlertLevel alertLevel, TlsAlertDescription alertDesc)
		{
			switch (alertLevel)
			{
				case TlsAlertLevel.Fatal:
					throw this.session.CreateException(alertLevel, alertDesc);					

				case TlsAlertLevel.Warning:
				default:
				switch (alertDesc)
				{
					case TlsAlertDescription.CloseNotify:
						this.session.Context.ConnectionEnd = true;
						break;

					default:
						this.session.RaiseWarningAlert(alertLevel, alertDesc);
						break;
				}
				break;
			}
		}

		#endregion

		#region MISC_METHODS

		private void resetBuffer()
		{
			this.inputBuffer.SetLength(0);
			this.inputBuffer.Position = 0;
		}

		private byte ReadByte()
		{
			byte[] b = new byte[1];
			base.Receive(b);

			return b[0];
		}

		private short ReadShort()
		{
			byte[] b = new byte[2];
			base.Receive(b);

			short val = BitConverter.ToInt16(b, 0);

			return System.Net.IPAddress.HostToNetworkOrder(val);
		}

		#endregion

		#region HANDSHAKE_METHODS

		/*
			Client											Server

			ClientHello                 -------->
															ServerHello
															Certificate*
															ServerKeyExchange*
															CertificateRequest*
										<--------			ServerHelloDone
			Certificate*
			ClientKeyExchange
			CertificateVerify*
			[ChangeCipherSpec]
			Finished                    -------->
															[ChangeCipherSpec]
										<--------           Finished
			Application Data            <------->			Application Data

					Fig. 1 - Message flow for a full handshake		
		*/

		internal void DoHandshake()
		{
			// Reset isSecure field
			this.session.IsSecure = false;

			// Send client hello
			this.sendRecord(TlsHandshakeType.ClientHello);

			// Read server response
			while (!this.session.Context.HelloDone)
			{
				// Read next record
				this.receiveRecord();
			}
			
			// Send client certificate if requested
			if (this.session.Context.ServerSettings.CertificateRequest)
			{
				this.sendRecord(TlsHandshakeType.Certificate);
			}

			// Send Client Key Exchange
			this.sendRecord(TlsHandshakeType.ClientKeyExchange);

			// Now initialize session cipher with the generated keys
			this.session.Context.Cipher.InitializeCipher();

			// Send certificate verify if requested
			if (this.session.Context.ServerSettings.CertificateRequest)
			{
				this.sendRecord(TlsHandshakeType.CertificateVerify);
			}

			// Send Cipher Spec protocol
			this.sendChangeCipherSpec();			
			
			// Read Cipher Spec protocol
			this.receiveRecord();

			// Read server finished
			if (!this.session.Context.HandshakeFinished)
			{
				this.receiveRecord();
			}

			// Clear Key Info
			this.session.Context.ClearKeyInfo();

			// Set isSecure
			this.session.IsSecure = true;
		}
		
		private TlsHandshakeMessage createClientHandshakeMessage(TlsHandshakeType type)
		{
			switch (type)
			{
				case TlsHandshakeType.ClientHello:
					return new TlsClientHello(session);

				case TlsHandshakeType.Certificate:
					return new TlsClientCertificate(session);

				case TlsHandshakeType.ClientKeyExchange:
					return new TlsClientKeyExchange(session);

				case TlsHandshakeType.CertificateVerify:
					return new TlsClientCertificateVerify(session);

				case TlsHandshakeType.Finished:
					return new TlsClientFinished(session);

				default:
					throw new InvalidOperationException("Unknown client handshake message type: " + type.ToString() );
			}
		}

		private TlsHandshakeMessage createServerHandshakeMessage(TlsHandshakeType type, byte[] buffer)
		{
			switch (type)
			{
				case TlsHandshakeType.HelloRequest:
					this.sendRecord(TlsHandshakeType.ClientHello);
					return null;

				case TlsHandshakeType.ServerHello:
					return new TlsServerHello(session, buffer);

				case TlsHandshakeType.Certificate:
					return new TlsServerCertificate(session, buffer);

				case TlsHandshakeType.ServerKeyExchange:
					return new TlsServerKeyExchange(session, buffer);

				case TlsHandshakeType.CertificateRequest:
					return new TlsServerCertificateRequest(session, buffer);

				case TlsHandshakeType.ServerHelloDone:
					return new TlsServerHelloDone(session, buffer);

				case TlsHandshakeType.Finished:
					return new TlsServerFinished(session, buffer);

				default:
					throw this.session.CreateException("Unknown server handshake message received ({0})", type.ToString());
			}
		}

		#endregion
	}
}