File: RecordProtocol.cs

package info (click to toggle)
mono 1.2.2.1-1etch1
  • links: PTS
  • area: main
  • in suites: etch
  • size: 142,720 kB
  • ctags: 256,408
  • sloc: cs: 1,495,736; ansic: 249,442; sh: 18,327; xml: 12,463; makefile: 5,046; perl: 1,248; asm: 635; yacc: 285; sql: 7
file content (979 lines) | stat: -rw-r--r-- 23,641 bytes parent folder | download | duplicates (2)
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
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez
// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
//
// 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.Collections;
using System.IO;
using System.Threading;

using Mono.Security.Protocol.Tls.Handshake;

namespace Mono.Security.Protocol.Tls
{
	internal abstract class RecordProtocol
	{
		#region Fields

		protected Stream	innerStream;
		protected Context	context;

		#endregion

		#region Properties

		public Context Context
		{
			get { return this.context; }
			set { this.context = value; }
		}

		#endregion

		#region Constructors

		public RecordProtocol(Stream innerStream, Context context)
		{
			this.innerStream			= innerStream;
			this.context				= context;
			this.context.RecordProtocol = this;
		}

		#endregion

		#region Abstract Methods

		public virtual void SendRecord(HandshakeType type)
		{

			IAsyncResult ar = this.BeginSendRecord(type, null, null);

			this.EndSendRecord(ar);

		}

		protected abstract void ProcessHandshakeMessage(TlsStream handMsg);

		protected virtual void ProcessChangeCipherSpec ()
		{
			Context ctx = this.Context;

			// Reset sequence numbers
			ctx.ReadSequenceNumber = 0;

			if (ctx is ClientContext) {
				ctx.EndSwitchingSecurityParameters (true);
			} else {
				ctx.StartSwitchingSecurityParameters (false);
			}
		}

		public virtual HandshakeMessage GetMessage(HandshakeType type)
		{
			throw new NotSupportedException();
		}

		#endregion

		#region Receive Record Async Result
		private class ReceiveRecordAsyncResult : IAsyncResult
		{
			private object locker = new object ();
			private AsyncCallback _userCallback;
			private object _userState;
			private Exception _asyncException;
			private ManualResetEvent handle;
			private byte[] _resultingBuffer;
			private Stream _record;
			private bool completed;

			private byte[] _initialBuffer;

			public ReceiveRecordAsyncResult(AsyncCallback userCallback, object userState, byte[] initialBuffer, Stream record)
			{
				_userCallback = userCallback;
				_userState = userState;
				_initialBuffer = initialBuffer;
				_record = record;
			}

			public Stream Record
			{
				get { return _record; }
			}

			public byte[] ResultingBuffer
			{
				get { return _resultingBuffer; }
			}

			public byte[] InitialBuffer
			{
				get { return _initialBuffer; }
			}

			public object AsyncState
			{
				get { return _userState; }
			}

			public Exception AsyncException
			{
				get { return _asyncException; }
			}

			public bool CompletedWithError
			{
				get {
					if (!IsCompleted)
						return false; // Perhaps throw InvalidOperationExcetion?

					return null != _asyncException;
				}
			}

			public WaitHandle AsyncWaitHandle
			{
				get {
					lock (locker) {
						if (handle == null)
							handle = new ManualResetEvent (completed);
					}
					return handle;
				}
				
			}

			public bool CompletedSynchronously
			{
				get { return false; }
			}

			public bool IsCompleted
			{
				get {
					lock (locker) {
						return completed;
					}
				}
			}

			private void SetComplete(Exception ex, byte[] resultingBuffer)
			{
				lock (locker) {
					if (completed)
						return;

					completed = true;
					_asyncException = ex;
					_resultingBuffer = resultingBuffer;
					if (handle != null)
						handle.Set ();

					if (_userCallback != null)
						_userCallback.BeginInvoke (this, null, null);
				}
			}

			public void SetComplete(Exception ex)
			{
				SetComplete(ex, null);
			}

			public void SetComplete(byte[] resultingBuffer)
			{
				SetComplete(null, resultingBuffer);
			}

			public void SetComplete()
			{
				SetComplete(null, null);
			}
		}
		#endregion

		#region Receive Record Async Result
		private class SendRecordAsyncResult : IAsyncResult
		{
			private object locker = new object ();
			private AsyncCallback _userCallback;
			private object _userState;
			private Exception _asyncException;
			private ManualResetEvent handle;
			private HandshakeMessage _message;
			private bool completed;

			public SendRecordAsyncResult(AsyncCallback userCallback, object userState, HandshakeMessage message)
			{
				_userCallback = userCallback;
				_userState = userState;
				_message = message;
			}

			public HandshakeMessage Message
			{
				get { return _message; }
			}

			public object AsyncState
			{
				get { return _userState; }
			}

			public Exception AsyncException
			{
				get { return _asyncException; }
			}

			public bool CompletedWithError
			{
				get {
					if (!IsCompleted)
						return false; // Perhaps throw InvalidOperationExcetion?

					return null != _asyncException;
				}
			}

			public WaitHandle AsyncWaitHandle
			{
				get {
					lock (locker) {
						if (handle == null)
							handle = new ManualResetEvent (completed);
					}
					return handle;
				}
				
			}

			public bool CompletedSynchronously
			{
				get { return false; }
			}

			public bool IsCompleted
			{
				get {
					lock (locker) {
						return completed;
					}
				}
			}

			public void SetComplete(Exception ex)
			{
				lock (locker) {
					if (completed)
						return;

					completed = true;
					if (handle != null)
						handle.Set ();

					if (_userCallback != null)
						_userCallback.BeginInvoke (this, null, null);

					_asyncException = ex;
				}
			}

			public void SetComplete()
			{
				SetComplete(null);
			}
		}
		#endregion

		#region Reveive Record Methods

		public IAsyncResult BeginReceiveRecord(Stream record, AsyncCallback callback, object state)
		{
			if (this.context.ConnectionEnd)
			{
				throw new TlsException(
					AlertDescription.InternalError,
					"The session is finished and it's no longer valid.");
			}

			byte[] recordTypeBuffer = new byte[1];

			ReceiveRecordAsyncResult internalResult = new ReceiveRecordAsyncResult(callback, state, recordTypeBuffer, record);

			record.BeginRead(internalResult.InitialBuffer, 0, internalResult.InitialBuffer.Length, new AsyncCallback(InternalReceiveRecordCallback), internalResult);

			return internalResult;
		}

		private void InternalReceiveRecordCallback(IAsyncResult asyncResult)
		{
			ReceiveRecordAsyncResult internalResult = asyncResult.AsyncState as ReceiveRecordAsyncResult;
			Stream record = internalResult.Record;

			try
			{
				
				int bytesRead = internalResult.Record.EndRead(asyncResult);

				//We're at the end of the stream. Time to bail.
				if (bytesRead == 0)
				{
					internalResult.SetComplete((byte[])null);
					return;
				}

				// Try to read the Record Content Type
				int type = internalResult.InitialBuffer[0];

				// Set last handshake message received to None
				this.context.LastHandshakeMsg = HandshakeType.ClientHello;

				ContentType	contentType	= (ContentType)type;
				byte[] buffer = this.ReadRecordBuffer(type, record);
				if (buffer == null)
				{
					// record incomplete (at the moment)
					internalResult.SetComplete((byte[])null);
					return;
				}

				// Decrypt message contents if needed
				if (contentType == ContentType.Alert && buffer.Length == 2)
				{
				}
				else if ((this.Context.Read != null) && (this.Context.Read.Cipher != null))
				{
					buffer = this.decryptRecordFragment (contentType, buffer);
					DebugHelper.WriteLine ("Decrypted record data", buffer);
				}

				// Process record
				switch (contentType)
				{
					case ContentType.Alert:
						this.ProcessAlert((AlertLevel)buffer [0], (AlertDescription)buffer [1]);
						if (record.CanSeek) 
						{
							// don't reprocess that memory block
							record.SetLength (0); 
						}
						buffer = null;
						break;

					case ContentType.ChangeCipherSpec:
						this.ProcessChangeCipherSpec();
						break;

					case ContentType.ApplicationData:
						break;

					case ContentType.Handshake:
						TlsStream message = new TlsStream (buffer);
						while (!message.EOF)
						{
							this.ProcessHandshakeMessage(message);
						}
						break;

					case (ContentType)0x80:
						this.context.HandshakeMessages.Write (buffer);
						break;

					default:
						throw new TlsException(
							AlertDescription.UnexpectedMessage,
							"Unknown record received from server.");
				}

				internalResult.SetComplete(buffer);
			}
			catch (Exception ex)
			{
				internalResult.SetComplete(ex);
			}

		}

		public byte[] EndReceiveRecord(IAsyncResult asyncResult)
		{
			ReceiveRecordAsyncResult internalResult = asyncResult as ReceiveRecordAsyncResult;

			if (null == internalResult)
				throw new ArgumentException("Either the provided async result is null or was not created by this RecordProtocol.");

			if (!internalResult.IsCompleted)
				internalResult.AsyncWaitHandle.WaitOne();

			if (internalResult.CompletedWithError)
				throw internalResult.AsyncException;
			else
				return internalResult.ResultingBuffer;
		}

		public byte[] ReceiveRecord(Stream record)
		{

			IAsyncResult ar = this.BeginReceiveRecord(record, null, null);
			return this.EndReceiveRecord(ar);

		}

		private byte[] ReadRecordBuffer (int contentType, Stream record)
		{
			switch (contentType)
			{
				case 0x80:
					return this.ReadClientHelloV2(record);

				default:
					if (!Enum.IsDefined(typeof(ContentType), (ContentType)contentType))
					{
						throw new TlsException(AlertDescription.DecodeError);
					}
					return this.ReadStandardRecordBuffer(record);
			}
		}

		private byte[] ReadClientHelloV2 (Stream record)
		{
			int msgLength = record.ReadByte ();
			// process further only if the whole record is available
			if (record.CanSeek && (msgLength + 1 > record.Length)) 
			{
				return null;
			}

			byte[] message = new byte[msgLength];
			record.Read (message, 0, msgLength);

			int msgType		= message [0];
			if (msgType != 1)
			{
				throw new TlsException(AlertDescription.DecodeError);
			}
			int protocol = (message [1] << 8 | message [2]);
			int cipherSpecLength = (message [3] << 8 | message [4]);
			int sessionIdLength = (message [5] << 8 | message [6]);
			int challengeLength = (message [7] << 8 | message [8]);
			int length = (challengeLength > 32) ? 32 : challengeLength;

			// Read CipherSpecs
			byte[] cipherSpecV2 = new byte[cipherSpecLength];
			Buffer.BlockCopy (message, 9, cipherSpecV2, 0, cipherSpecLength);

			// Read session ID
			byte[] sessionId = new byte[sessionIdLength];
			Buffer.BlockCopy (message, 9 + cipherSpecLength, sessionId, 0, sessionIdLength);

			// Read challenge ID
			byte[] challenge = new byte[challengeLength];
			Buffer.BlockCopy (message, 9 + cipherSpecLength + sessionIdLength, challenge, 0, challengeLength);
		
			if (challengeLength < 16 || cipherSpecLength == 0 || (cipherSpecLength % 3) != 0)
			{
				throw new TlsException(AlertDescription.DecodeError);
			}

			// Updated the Session ID
			if (sessionId.Length > 0)
			{
				this.context.SessionId = sessionId;
			}

			// Update the protocol version
			this.Context.ChangeProtocol((short)protocol);

			// Select the Cipher suite
			this.ProcessCipherSpecV2Buffer(this.Context.SecurityProtocol, cipherSpecV2);

			// Updated the Client Random
			this.context.ClientRandom = new byte [32]; // Always 32
			// 1. if challenge is bigger than 32 bytes only use the last 32 bytes
			// 2. right justify (0) challenge in ClientRandom if less than 32
			Buffer.BlockCopy (challenge, challenge.Length - length, this.context.ClientRandom, 32 - length, length);

			// Set 
			this.context.LastHandshakeMsg = HandshakeType.ClientHello;
			this.context.ProtocolNegotiated = true;

			return message;
		}

		private byte[] ReadStandardRecordBuffer (Stream record)
		{
			byte[] header = new byte[4];
			if (record.Read (header, 0, 4) != 4)
				throw new TlsException ("buffer underrun");
			
			short protocol = (short)((header [0] << 8) | header [1]);
			short length = (short)((header [2] << 8) | header [3]);

			// process further only if the whole record is available
			// note: the first 5 bytes aren't part of the length
			if (record.CanSeek && (length + 5 > record.Length)) 
			{
				return null;
			}
			
			// Read Record data
			int	totalReceived = 0;
			byte[]	buffer		= new byte[length];
			while (totalReceived != length)
			{
				int justReceived = record.Read(buffer, totalReceived, buffer.Length - totalReceived);

				//Make sure we get some data so we don't end up in an infinite loop here before shutdown.
				if (0 == justReceived)
				{
					throw new TlsException(AlertDescription.CloseNotify, "Received 0 bytes from stream. It must be closed.");
				}

				totalReceived += justReceived;
			}

			// Check that the message has a valid protocol version
			if (protocol != this.context.Protocol && this.context.ProtocolNegotiated)
			{
				throw new TlsException(
					AlertDescription.ProtocolVersion, "Invalid protocol version on message received");
			}

			DebugHelper.WriteLine("Record data", buffer);

			return buffer;
		}

		private void ProcessAlert(AlertLevel alertLevel, AlertDescription alertDesc)
		{
			switch (alertLevel)
			{
				case AlertLevel.Fatal:
					throw new TlsException(alertLevel, alertDesc);

				case AlertLevel.Warning:
				default:
				switch (alertDesc)
				{
					case AlertDescription.CloseNotify:
						this.context.ConnectionEnd = true;
						break;
				}
				break;
			}
		}

		#endregion

		#region Send Alert Methods

		public void SendAlert(AlertDescription description)
		{
			this.SendAlert(new Alert(description));
		}

		public void SendAlert(
			AlertLevel			level, 
			AlertDescription	description)
		{
			this.SendAlert(new Alert(level, description));
		}

		public void SendAlert(Alert alert)
		{
			AlertLevel level;
			AlertDescription description;
			bool close;

			if (alert == null) {
				DebugHelper.WriteLine(">>>> Write Alert NULL");
				level = AlertLevel.Fatal;
				description = AlertDescription.InternalError;
				close = true;
			} else {
				DebugHelper.WriteLine(">>>> Write Alert ({0}|{1})", alert.Description, alert.Message);
				level = alert.Level;
				description = alert.Description;
				close = alert.IsCloseNotify;
			}

			// Write record
			this.SendRecord (ContentType.Alert, new byte[2] { (byte) level, (byte) description });

			if (close)
			{
				this.context.ConnectionEnd = true;
			}
		}

		#endregion

		#region Send Record Methods

		public void SendChangeCipherSpec()
		{
			DebugHelper.WriteLine(">>>> Write Change Cipher Spec");

			// Send Change Cipher Spec message with the current cipher
			// or as plain text if this is the initial negotiation
			this.SendRecord(ContentType.ChangeCipherSpec, new byte[] {1});

			Context ctx = this.context;

			// Reset sequence numbers
			ctx.WriteSequenceNumber = 0;

			// all further data sent will be encrypted with the negotiated
			// security parameters (now the current parameters)
			if (ctx is ClientContext) {
				ctx.StartSwitchingSecurityParameters (true);
			} else {
				ctx.EndSwitchingSecurityParameters (false);
			}
		}

		public IAsyncResult BeginSendRecord(HandshakeType handshakeType, AsyncCallback callback, object state)
		{
			HandshakeMessage msg = this.GetMessage(handshakeType);

			msg.Process();

			DebugHelper.WriteLine(">>>> Write handshake record ({0}|{1})", context.Protocol, msg.ContentType);

			SendRecordAsyncResult internalResult = new SendRecordAsyncResult(callback, state, msg);

			this.BeginSendRecord(msg.ContentType, msg.EncodeMessage(), new AsyncCallback(InternalSendRecordCallback), internalResult);

			return internalResult;
		}

		private void InternalSendRecordCallback(IAsyncResult ar)
		{
			SendRecordAsyncResult internalResult = ar.AsyncState as SendRecordAsyncResult;
			
			try
			{
				this.EndSendRecord(ar);

				// Update session
				internalResult.Message.Update();

				// Reset message contents
				internalResult.Message.Reset();

				internalResult.SetComplete();
			}
			catch (Exception ex)
			{
				internalResult.SetComplete(ex);
			}
		}

		public IAsyncResult BeginSendRecord(ContentType contentType, byte[] recordData, AsyncCallback callback, object state)
		{
			if (this.context.ConnectionEnd)
			{
				throw new TlsException(
					AlertDescription.InternalError,
					"The session is finished and it's no longer valid.");
			}

			byte[] record = this.EncodeRecord(contentType, recordData);

			return this.innerStream.BeginWrite(record, 0, record.Length, callback, state);
		}

		public void EndSendRecord(IAsyncResult asyncResult)
		{
			if (asyncResult is SendRecordAsyncResult)
			{
				SendRecordAsyncResult internalResult = asyncResult as SendRecordAsyncResult;
				if (!internalResult.IsCompleted)
					internalResult.AsyncWaitHandle.WaitOne();
				if (internalResult.CompletedWithError)
					throw internalResult.AsyncException;
			}
			else
			{
				this.innerStream.EndWrite(asyncResult);
			}
		}

		public void SendRecord(ContentType contentType, byte[] recordData)
		{
			IAsyncResult ar = this.BeginSendRecord(contentType, recordData, null, null);

			this.EndSendRecord(ar);
		}

		public byte[] EncodeRecord(ContentType contentType, byte[] recordData)
		{
			return this.EncodeRecord(
				contentType,
				recordData,
				0,
				recordData.Length);
		}

		public byte[] EncodeRecord(
			ContentType	contentType, 
			byte[]		recordData,
			int			offset,
			int			count)
		{
			if (this.context.ConnectionEnd)
			{
				throw new TlsException(
					AlertDescription.InternalError,
					"The session is finished and it's no longer valid.");
			}

			TlsStream record = new TlsStream();

			int	position = offset;

			while (position < ( offset + count ))
			{
				short	fragmentLength = 0;
				byte[]	fragment;

				if ((count + offset - position) > Context.MAX_FRAGMENT_SIZE)
				{
					fragmentLength = Context.MAX_FRAGMENT_SIZE;
				}
				else
				{
					fragmentLength = (short)(count + offset - position);
				}

				// Fill the fragment data
				fragment = new byte[fragmentLength];
				Buffer.BlockCopy(recordData, position, fragment, 0, fragmentLength);

				if ((this.Context.Write != null) && (this.Context.Write.Cipher != null))
				{
					// Encrypt fragment
					fragment = this.encryptRecordFragment (contentType, fragment);
				}

				// Write tls message
				record.Write((byte)contentType);
				record.Write(this.context.Protocol);
				record.Write((short)fragment.Length);
				record.Write(fragment);

				DebugHelper.WriteLine("Record data", fragment);

				// Update buffer position
				position += fragmentLength;
			}

			return record.ToArray();
		}
		
		#endregion

		#region Cryptography Methods

		private byte[] encryptRecordFragment(
			ContentType	contentType, 
			byte[]		fragment)
		{
			byte[] mac	= null;

			// Calculate message MAC
			if (this.Context is ClientContext)
			{
				mac = this.context.Write.Cipher.ComputeClientRecordMAC(contentType, fragment);
			}	
			else
			{
				mac = this.context.Write.Cipher.ComputeServerRecordMAC (contentType, fragment);
			}

			DebugHelper.WriteLine(">>>> Record MAC", mac);

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

			// Update sequence number
			this.context.WriteSequenceNumber++;

			return ecr;
		}

		private byte[] decryptRecordFragment(
			ContentType	contentType, 
			byte[]		fragment)
		{
			byte[]	dcrFragment		= null;
			byte[]	dcrMAC			= null;

			try
			{
				this.context.Read.Cipher.DecryptRecord (fragment, out dcrFragment, out dcrMAC);
			}
			catch
			{
				if (this.context is ServerContext)
				{
					this.Context.RecordProtocol.SendAlert(AlertDescription.DecryptionFailed);
				}

				throw;
			}
			
			// Generate record MAC
			byte[] mac = null;

			if (this.Context is ClientContext)
			{
				mac = this.context.Read.Cipher.ComputeServerRecordMAC(contentType, dcrFragment);
			}
			else
			{
				mac = this.context.Read.Cipher.ComputeClientRecordMAC (contentType, dcrFragment);
			}

			DebugHelper.WriteLine(">>>> Record MAC", mac);

			// Check record MAC
			if (!Compare (mac, dcrMAC))
			{
				throw new TlsException(AlertDescription.BadRecordMAC, "Bad record MAC");
			}

			// Update sequence number
			this.context.ReadSequenceNumber++;

			return dcrFragment;
		}

		private bool Compare (byte[] array1, byte[] array2)
		{
			if (array1 == null)
				return (array2 == null);
			if (array2 == null)
				return false;
			if (array1.Length != array2.Length)
				return false;
			for (int i = 0; i < array1.Length; i++) {
				if (array1[i] != array2[i])
					return false;
			}
			return true;
		}

		#endregion

		#region CipherSpecV2 processing

		private void ProcessCipherSpecV2Buffer (SecurityProtocolType protocol, byte[] buffer)
		{
			TlsStream codes = new TlsStream(buffer);

			string prefix = (protocol == SecurityProtocolType.Ssl3) ? "SSL_" : "TLS_";

			while (codes.Position < codes.Length)
			{
				byte check = codes.ReadByte();

				if (check == 0)
				{
					// SSL/TLS cipher spec
					short code = codes.ReadInt16();	
					int index = this.Context.SupportedCiphers.IndexOf(code);
					if (index != -1)
					{
						this.Context.Negotiating.Cipher = this.Context.SupportedCiphers[index];
						break;
					}
				}
				else
				{
					byte[] tmp = new byte[2];
					codes.Read(tmp, 0, tmp.Length);

					int tmpCode = ((check & 0xff) << 16) | ((tmp[0] & 0xff) << 8) | (tmp[1] & 0xff);
					CipherSuite cipher = this.MapV2CipherCode(prefix, tmpCode);

					if (cipher != null)
					{
						this.Context.Negotiating.Cipher = cipher;
						break;
					}
				}
			}

			if (this.Context.Negotiating == null)
			{
				throw new TlsException(AlertDescription.InsuficientSecurity, "Insuficient Security");
			}
		}

		private CipherSuite MapV2CipherCode(string prefix, int code)
		{
			try
			{
				switch (code)
				{
					case 65664:
						// TLS_RC4_128_WITH_MD5
						return this.Context.SupportedCiphers[prefix + "RSA_WITH_RC4_128_MD5"];
					
					case 131200:
						// TLS_RC4_128_EXPORT40_WITH_MD5
						return this.Context.SupportedCiphers[prefix + "RSA_EXPORT_WITH_RC4_40_MD5"];
					
					case 196736:
						// TLS_RC2_CBC_128_CBC_WITH_MD5
						return this.Context.SupportedCiphers[prefix + "RSA_EXPORT_WITH_RC2_CBC_40_MD5"];
					
					case 262272:
						// TLS_RC2_CBC_128_CBC_EXPORT40_WITH_MD5
						return this.Context.SupportedCiphers[prefix + "RSA_EXPORT_WITH_RC2_CBC_40_MD5"];
					
					case 327808:
						// TLS_IDEA_128_CBC_WITH_MD5
						return null;
					
					case 393280:
						// TLS_DES_64_CBC_WITH_MD5
						return null;

					case 458944:
						// TLS_DES_192_EDE3_CBC_WITH_MD5
						return null;

					default:
						return null;
				}
			}
			catch
			{
				return null;
			}
		}

		#endregion
	}
}