1 /**
2 * TLS Channel
3 * 
4 * Copyright:
5 * (C) 2011,2012,2014 Jack Lloyd
6 * (C) 2014-2015 Etienne Cimon
7 *
8 * License:
9 * Botan is released under the Simplified BSD License (see LICENSE.md)
10 */
11 module botan.tls.channel;
12 
13 import botan.constants;
14 static if (BOTAN_HAS_TLS):
15 
16 public import botan.cert.x509.x509cert;
17 public import botan.tls.policy;
18 public import botan.tls.session;
19 public import botan.tls.alert;
20 public import botan.tls.session_manager;
21 public import botan.tls.version_;
22 public import botan.tls.exceptn;
23 public import botan.rng.rng;
24 import core.thread : Thread;
25 import botan.tls.handshake_state;
26 import botan.tls.messages;
27 import botan.tls.heartbeats;
28 import botan.tls.record;
29 import botan.tls.seq_numbers;
30 import botan.utils.rounding;
31 import memutils.dictionarylist;
32 import botan.utils.loadstor;
33 import botan.utils.types;
34 import botan.utils.get_byte;
35 import memutils.hashmap;
36 import std.string : toStringz;
37 import std.algorithm;
38 
39 alias DataWriter = void delegate(in ubyte[]);
40 alias OnClearData = void delegate(in ubyte[]);
41 alias OnAlert = void delegate(in TLSAlert, in ubyte[]);
42 alias OnHandshakeComplete = bool delegate(in TLSSession);
43 
44 /**
45 * Generic interface for TLS endpoint
46 */
47 class TLSChannel
48 {
49 public:
50 
51 	this(DataWriter output_fn,
52 		OnClearData data_cb,
53 		OnAlert alert_cb,
54 		OnHandshakeComplete handshake_cb,
55 		TLSSessionManager session_manager,
56 		RandomNumberGenerator rng,
57 		bool is_datagram,
58 		size_t reserved_io_buffer_size)
59 	{
60 		m_owner = Thread.getThis();
61 		m_handshake_cb = handshake_cb;
62 		m_data_cb = data_cb;
63 		m_alert_cb = alert_cb;
64 		m_output_fn = output_fn;
65 		m_rng = rng;
66 		m_session_manager = session_manager;
67 		/* epoch 0 is plaintext, thus null cipher state */
68 		//m_write_cipher_states[cast(ushort)0] = ConnectionCipherState.init;
69 		//m_read_cipher_states[cast(ushort)0] = ConnectionCipherState.init;
70 		
71 		m_writebuf.reserve(reserved_io_buffer_size);
72 		m_readbuf.reserve(reserved_io_buffer_size);
73 	}
74 
75     /**
76     * Inject TLS traffic received from counterparty
77     * Returns: a hint as the how many more bytes we need to process the
78     *            current record (this may be 0 if on a record boundary)
79     */
80     size_t receivedData(const(ubyte)* input, size_t input_size)
81     {
82         
83         const size_t max_fragment_size = maximumFragmentSize();
84         
85         try
86         {
87             while (!isClosed() && input_size)
88             {
89                 SecureVector!ubyte record;
90                 ulong record_sequence = 0;
91                 RecordType record_type = NO_RECORD;
92                 TLSProtocolVersion record_version;
93 
94                 size_t consumed = 0;
95                 const size_t needed = .readRecord(m_readbuf,
96                                                   input,
97                                                   input_size,
98                                                   m_is_datagram,
99                                                   consumed,
100                                                   record,
101                                                   record_sequence,
102                                                   record_version,
103                                                   record_type,
104                                                   *m_sequence_numbers,
105                                                   &readCipherStateEpoch);
106                 assert(consumed > 0, "Got to eat something");
107                 assert(consumed <= input_size, "Record reader consumed sane amount");
108                 
109                 input += consumed;
110                 input_size -= consumed;
111                 
112                 assert(input_size == 0 || needed == 0, "Got a full record or consumed all input");
113                 
114                 if (input_size == 0 && needed != 0)
115                     return needed; // need more data to complete record
116                 
117                 if (record.length > max_fragment_size)
118                     throw new TLSException(TLSAlert.RECORD_OVERFLOW, "Plaintext record is too large");
119                 if (record_type == HANDSHAKE || record_type == CHANGE_CIPHER_SPEC)
120                 {
121                     if (!m_pending_state)
122                     {
123                         if (record_version.isDatagramProtocol())
124                         {
125                             if (m_sequence_numbers)
126                             {
127 
128                                 /*
129                                 * Might be a peer retransmit under epoch - 1 in which
130                                 * case we must retransmit last flight
131                                 */
132 
133                                 (*m_sequence_numbers).readAccept(record_sequence);
134                                           
135                                 const ushort epoch = record_sequence >> 48;
136                                 
137                                 if (epoch == sequenceNumbers().currentReadEpoch())
138                                 {
139                                     createHandshakeState(record_version);
140                                 }
141                                 else if (epoch == sequenceNumbers().currentReadEpoch() - 1)
142                                 {
143                                     assert(m_active_state, "Have active state here");
144                                     auto rec = unlock(record);
145                                     m_active_state.handshakeIo().addRecord(rec, record_type, record_sequence);
146                                 }
147                             }
148                             else if (record_sequence == 0)
149                             {
150                                 createHandshakeState(record_version);
151                             }
152                         }
153                         else
154                         {
155                             createHandshakeState(record_version);
156                         }
157                         
158                     }
159 
160                     if (m_pending_state)
161                     {
162                         auto rec = unlock(record);
163                         m_pending_state.handshakeIo().addRecord(rec, record_type, record_sequence);
164                         
165                         while (true) {
166                             if (auto pending = *m_pending_state) {
167                                 auto msg = pending.getNextHandshakeMsg();
168                                 
169                                 if (msg.type == HANDSHAKE_NONE) // no full handshake yet
170                                     break;
171 
172                                 processHandshakeMsg(activeState(), pending, msg.type, msg.data);
173                             } else break;
174                         }
175                     }
176                 }
177                 else if (record_type == HEARTBEAT && peerSupportsHeartbeats())
178                 {
179                     if (!activeState())
180                         throw new TLSUnexpectedMessage("Heartbeat sent before handshake done");
181                     
182                     HeartbeatMessage heartbeat = HeartbeatMessage(unlock(record));
183                     
184                     const Vector!ubyte* payload = &heartbeat.payload();
185                     
186                     if (heartbeat.isRequest())
187                     {
188                         if (!pendingState())
189                         {
190                             HeartbeatMessage response = HeartbeatMessage(HeartbeatMessage.RESPONSE, payload.ptr, payload.length);
191                             auto rec = response.contents();
192                             sendRecord(HEARTBEAT, rec);
193                         }
194                     }
195                     else
196                     {
197                         m_alert_cb(TLSAlert(TLSAlert.HEARTBEAT_PAYLOAD), cast(ubyte[])(*payload)[]);
198                     }
199                 }
200                 else if (record_type == APPLICATION_DATA)
201                 {
202                     if (!activeState())
203                         throw new TLSUnexpectedMessage("Application data before handshake done");
204                             
205                     /*
206                     * OpenSSL among others sends empty records in versions
207                     * before TLS v1.1 in order to randomize the IV of the
208                     * following record. Avoid spurious callbacks.
209                     */
210                     if (record.length > 0)
211                         m_data_cb(cast(ubyte[])record[]);
212                 }
213                 else if (record_type == ALERT)
214                 {
215                     TLSAlert alert_msg = TLSAlert(record);
216                     
217                     if (alert_msg.type() == TLSAlert.NO_RENEGOTIATION)
218                     m_pending_state.free();
219                     
220 					if (alert_msg.type() == TLSAlert.CLOSE_NOTIFY)
221 						sendWarningAlert(TLSAlert.CLOSE_NOTIFY); // reply in kind
222 
223 					m_alert_cb(alert_msg, null);
224                     
225                     if (alert_msg.isFatal())
226                     {
227                         if (auto active = activeState()) {
228                             auto entry = &active.serverHello().sessionId();
229                             m_session_manager.removeEntry(*entry);
230                         }
231 						return 0;
232                     }
233                 }
234                 else if (record_type != NO_RECORD)
235                     throw new TLSUnexpectedMessage("Unexpected record type " ~ to!string(record_type) ~ " from counterparty");
236             }
237                         
238             return 0; // on a record boundary
239         }
240         catch(TLSException e)
241         {
242             sendFatalAlert(e.type());
243             throw e;
244         }
245         catch(IntegrityFailure e)
246         {
247             sendFatalAlert(TLSAlert.BAD_RECORD_MAC);
248             throw e;
249         }
250         catch(DecodingError e)
251         {
252             sendFatalAlert(TLSAlert.DECODE_ERROR);
253             throw e;
254         }
255         catch(Exception e)
256         {
257             sendFatalAlert(TLSAlert.INTERNAL_ERROR);
258             throw e;
259         }
260     }
261 
262     /**
263     * Inject TLS traffic received from counterparty
264     * Returns: a hint as the how many more bytes we need to process the
265     *            current record (this may be 0 if on a record boundary)
266     */
267     size_t receivedData(const ref Vector!ubyte buf)
268     {
269         return this.receivedData(buf.ptr, buf.length);
270     }
271 
272     /**
273     * Inject plaintext intended for counterparty
274     * Throws an exception if isActive() is false
275     */
276     void send(const(ubyte)* buf, size_t buf_size)
277     {
278         if (!isActive())
279             throw new TLSClosedException("Data cannot be sent on inactive TLS connection");
280         
281         sendRecordArray(sequenceNumbers().currentWriteEpoch(), APPLICATION_DATA, buf, buf_size);
282     }
283 
284     /**
285     * Inject plaintext intended for counterparty
286     * Throws an exception if isActive() is false
287     */
288     void send(in string str)
289     {
290         this.send(cast(const(ubyte)*)(str.toStringz), str.length);
291     }
292 
293     /**
294     * Inject plaintext intended for counterparty
295     * Throws an exception if isActive() is false
296     */
297     void send(Alloc)(const ref Vector!( char, Alloc ) val)
298     {
299         send(val.ptr, val.length);
300     }
301 
302     /**
303     * Send a TLS alert message. If the alert is fatal, the internal
304     * state (keys, etc) will be reset.
305     *
306     * Params:
307     *  alert = the TLSAlert to send
308     */
309     void sendAlert(in TLSAlert alert)
310     {
311         if (alert.isValid() && !isClosed())
312         {
313             try
314             {
315                 auto rec = alert.serialize();
316                 sendRecord(ALERT, rec);
317             }
318             catch (Exception) { /* swallow it */ }
319         }
320         
321         if (alert.type() == TLSAlert.NO_RENEGOTIATION)
322             m_pending_state.free();
323         
324         if (alert.isFatal()) {
325             if (auto active = activeState()) {
326                 auto entry = &active.serverHello().sessionId();
327                 m_session_manager.removeEntry(*entry);
328             }
329         }
330     }
331 
332     /**
333     * Send a warning alert
334     */
335     void sendWarningAlert(TLSAlertType type) { sendAlert(TLSAlert(type, false)); }
336 
337     /**
338     * Send a fatal alert
339     */
340     void sendFatalAlert(TLSAlertType type) { sendAlert(TLSAlert(type, true)); }
341 
342     /**
343     * Send a close notification alert
344     */
345     void close() { sendWarningAlert(TLSAlert.CLOSE_NOTIFY); }
346 
347     /**
348     * Returns: true iff the connection is active for sending application data
349     */
350     bool isActive() const
351     {
352         return (activeState() !is null);
353     }
354 
355     /**
356     * Returns: true iff the connection has been definitely closed
357     */
358     bool isClosed() const
359     {
360         if (activeState() || pendingState())
361             return false;
362         
363         /*
364         * If no active or pending state, then either we had a connection
365         * and it has been closed, or we are a server which has never
366         * received a connection. This case is detectable by also lacking
367         * m_sequence_numbers
368         */
369         return (*m_sequence_numbers !is null);
370     }
371 
372     /**
373     * Attempt to renegotiate the session
374     * Params:
375     *  force_full_renegotiation = if true, require a full renegotiation,
376     *                                            otherwise allow session resumption
377     */
378     void renegotiate(bool force_full_renegotiation = false)
379     {
380         if (pendingState()) // currently in handshake?
381             return;
382         
383         if (const HandshakeState active = activeState())
384             initiateHandshake(createHandshakeState(active.Version()),
385                                force_full_renegotiation);
386         else
387             throw new Exception("Cannot renegotiate on inactive connection");
388     }
389 
390     /**
391     * Returns: true iff the peer supports heartbeat messages
392     */
393     bool peerSupportsHeartbeats() const
394     {
395         if (const HandshakeState active = activeState())
396             return active.serverHello().supportsHeartbeats();
397         return false;
398     }
399 
400     /**
401     * Returns: true iff we are allowed to send heartbeat messages
402     */
403     bool heartbeatSendingAllowed() const
404     {
405         if (const HandshakeState active = activeState())
406             return active.serverHello().peerCanSendHeartbeats();
407         return false;
408     }
409 
410     /**
411     * Attempt to send a heartbeat message (if negotiated with counterparty)
412     * Params:
413     *  payload = will be echoed back
414     *  payload_size = size of payload in bytes
415     */
416     void heartbeat(const(ubyte)* payload, size_t payload_size)
417     {
418         if (heartbeatSendingAllowed())
419         {
420             HeartbeatMessage heartbeat = HeartbeatMessage(HeartbeatMessage.REQUEST, payload, payload_size);
421             auto rec = heartbeat.contents();
422             sendRecord(HEARTBEAT, rec);
423         }
424     }
425 
426     /**
427     * Attempt to send a heartbeat message (if negotiated with counterparty)
428     */
429     void heartbeat() { heartbeat(null, 0); }
430 
431     /**
432     * Returns: certificate chain of the peer (may be empty)
433     */
434     Vector!X509Certificate peerCertChain() const
435     {
436         if (const HandshakeState active = activeState())
437             return getPeerCertChain(active).dup;
438         return Vector!X509Certificate();
439     }
440 
441     /**
442     * Key material export (RFC 5705)
443     * Params:
444     *  label = a disambiguating label string
445     *  context = a per-association context value
446     *  length = the length of the desired key in bytes
447     * Returns: key of length bytes
448     */
449     const(SymmetricKey) keyMaterialExport(in string label,
450                                    in string context,
451                                    size_t length) const
452     {
453         if (auto active = activeState())
454         {
455             Unique!KDF prf = active.protocolSpecificPrf();
456             
457             const(SecureVector!ubyte)* master_secret = &active.sessionKeys().masterSecret();
458             
459             Vector!ubyte salt;
460             salt ~= label;
461 			salt ~= active.clientHello().randomBytes();
462 			salt ~= active.serverHello().randomBytes();
463 
464             if (context != "")
465             {
466                 size_t context_size = context.length;
467                 if (context_size > 0xFFFF)
468                     throw new Exception("key_material_export context is too long");
469                 salt.pushBack(get_byte(0, cast(ushort) context_size));
470                 salt.pushBack(get_byte(1, cast(ushort) context_size));
471                 salt ~= context;
472             }
473             
474             return SymmetricKey(prf.deriveKey(length, *master_secret, salt));
475         }
476         else
477             throw new Exception("key_material_export connection not active");
478     }
479 
480 	/// Returns the ALPN chosen in the ServerHello with the ALPN extention
481 	const(string) applicationProtocol() const { return m_application_protocol; }
482 
483 	/// Returns the current session ID
484 	const(ubyte[]) sessionId() const {
485 		if (auto active = activeState()) {
486 			return active.serverHello().sessionIdBytes();
487 		}
488 		return null;
489 	}
490 
491     ~this()
492     {
493         resetState();
494     }
495 
496 protected:
497 
498     abstract void processHandshakeMsg(in HandshakeState active_state,
499                                       HandshakeState pending_state,
500                                       HandshakeType type,
501                                       const ref Vector!ubyte contents);
502 
503     abstract void initiateHandshake(HandshakeState state,
504                                     bool force_full_renegotiation);
505 
506     abstract Vector!X509Certificate getPeerCertChain(in HandshakeState state) const;
507 
508     abstract HandshakeState newHandshakeState(HandshakeIO io);
509 
510     HandshakeState createHandshakeState(TLSProtocolVersion _version)
511     {
512         if (pendingState())
513             throw new InternalError("createHandshakeState called during handshake");
514         
515         if (const HandshakeState active = activeState())
516         {
517             TLSProtocolVersion active_version = active.Version();
518             
519             if (active_version.isDatagramProtocol() != _version.isDatagramProtocol())
520                 throw new Exception("Active state using version " ~ active_version.toString() ~
521                                     " cannot change to " ~ _version.toString() ~ " in pending");
522         }
523         
524         if (!m_sequence_numbers)
525         {
526             if (_version.isDatagramProtocol())
527                 m_sequence_numbers = new DatagramSequenceNumbers;
528             else
529                 m_sequence_numbers = new StreamSequenceNumbers;
530         }
531         
532         Unique!HandshakeIO io;
533         if (_version.isDatagramProtocol()) {
534 			// default MTU is IPv6 min MTU minus UDP/IP headers (TODO: make configurable)
535 			const ushort mtu = 1280 - 40 - 8;
536             io = new DatagramHandshakeIO(*m_sequence_numbers, &sendRecordUnderEpoch, mtu);
537         }
538         else {
539             io = new StreamHandshakeIO(&sendRecord);
540 		}
541 
542         m_pending_state = newHandshakeState(io.release());
543         
544         if (auto active = activeState())
545             m_pending_state.setVersion(active.Version());
546         
547         return *m_pending_state;
548     }
549 
550     /**
551     * Perform a handshake timeout check. This does nothing unless
552     * this is a DTLS channel with a pending handshake state, in
553     * which case we check for timeout and potentially retransmit
554     * handshake packets.
555     */
556     bool timeoutCheck() {
557         if (m_pending_state)
558             return m_pending_state.handshakeIo().timeoutCheck();
559         //FIXME: scan cipher suites and remove epochs older than 2*MSL
560         return false;
561     }
562 
563     void activateSession()
564     {
565         std.algorithm.swap(m_active_state, m_pending_state);
566         m_pending_state.free();
567         
568         if (!m_active_state.Version().isDatagramProtocol())
569         {
570             // TLS is easy just remove all but the current state
571             auto current_epoch = sequenceNumbers().currentWriteEpoch();
572 
573             foreach (const ref ushort k, const ref ConnectionCipherState v; m_write_cipher_states) {
574                 if (k != current_epoch) {
575                     v.destroy();
576                     m_write_cipher_states.remove(k);
577                 }
578             }
579             foreach (const ref ushort k, const ref ConnectionCipherState v; m_read_cipher_states) {
580                 if (k != current_epoch) {
581                     v.destroy();
582                     m_write_cipher_states.remove(k);                    
583                 }
584             }
585         }
586     }
587 
588     void changeCipherSpecReader(ConnectionSide side)
589     {
590         auto pending = pendingState();
591         
592         assert(pending && pending.serverHello(), "Have received server hello");
593         
594         if (pending.serverHello().compressionMethod() != NO_COMPRESSION)
595             throw new InternalError("Negotiated unknown compression algorithm");
596         
597         (*m_sequence_numbers).newReadCipherState();
598         
599         const ushort epoch = sequenceNumbers().currentReadEpoch();
600 
601         assert(m_read_cipher_states.get(epoch, ConnectionCipherState.init) is ConnectionCipherState.init, 
602                "No read cipher state currently set for next epoch");
603         
604         // flip side as we are reading
605         ConnectionCipherState read_state = new ConnectionCipherState(pending.Version(),
606                                                                  (side == CLIENT) ? SERVER : CLIENT,
607                                                                  false,
608                                                                  pending.ciphersuite(),
609                                                                  pending.sessionKeys());
610         
611         m_read_cipher_states[epoch] = read_state;
612     }
613 
614     void changeCipherSpecWriter(ConnectionSide side)
615     {
616         auto pending = pendingState();
617         
618         assert(pending && pending.serverHello(), "Have received server hello");
619         
620         if (pending.serverHello().compressionMethod() != NO_COMPRESSION)
621             throw new InternalError("Negotiated unknown compression algorithm");
622         
623         (*m_sequence_numbers).newWriteCipherState();
624         
625         const ushort epoch = sequenceNumbers().currentWriteEpoch();
626         
627         assert(m_write_cipher_states.get(epoch, ConnectionCipherState.init) is ConnectionCipherState.init, "No write cipher state currently set for next epoch");
628         
629         ConnectionCipherState write_state = new ConnectionCipherState(pending.Version(),
630                                                                   side,
631                                                                   true,
632                                                                   pending.ciphersuite(),
633                                                                   pending.sessionKeys());
634         
635         m_write_cipher_states[epoch] = write_state;
636     }
637 
638     /* secure renegotiation handling */
639     void secureRenegotiationCheck(const ClientHello client_hello)
640     {
641         const bool secure_renegotiation = client_hello.secureRenegotiation();
642         
643         if (auto active = activeState())
644         {
645             const bool active_sr = active.clientHello().secureRenegotiation();
646             
647             if (active_sr != secure_renegotiation)
648                 throw new TLSException(TLSAlert.HANDSHAKE_FAILURE, "TLSClient changed its mind about secure renegotiation");
649         }
650         
651         if (secure_renegotiation)
652         {
653             Vector!ubyte data = client_hello.renegotiationInfo();
654             
655             if (data != secureRenegotiationDataForClientHello())
656                 throw new TLSException(TLSAlert.HANDSHAKE_FAILURE, "TLSClient sent bad values for secure renegotiation");
657         }
658     }
659 
660     void secureRenegotiationCheck(const ServerHello server_hello)
661     {
662         const bool secure_renegotiation = server_hello.secureRenegotiation();
663         
664         if (auto active = activeState())
665         {
666             const bool active_sr = active.clientHello().secureRenegotiation();
667             
668             if (active_sr != secure_renegotiation)
669                 throw new TLSException(TLSAlert.HANDSHAKE_FAILURE, "TLSServer changed its mind about secure renegotiation");
670         }
671         
672         if (secure_renegotiation)
673         {
674             const Vector!ubyte data = server_hello.renegotiationInfo();
675             
676             if (data != secureRenegotiationDataForServerHello())
677                 throw new TLSException(TLSAlert.HANDSHAKE_FAILURE, "TLSServer sent bad values for secure renegotiation");
678         }
679     }
680 
681     Vector!ubyte secureRenegotiationDataForClientHello() const
682     {
683         if (auto active = activeState()) {
684 			auto verif_data = active.clientFinished().verifyDataBytes();
685             return Vector!ubyte(verif_data);
686 		}
687         return Vector!ubyte();
688     }
689 
690     Vector!ubyte secureRenegotiationDataForServerHello() const
691     {
692         if (auto active = activeState())
693         {
694 			Vector!ubyte buf = active.clientFinished().verifyDataBytes();
695 			buf ~= active.serverFinished().verifyDataBytes();
696 			return buf.move();
697         }
698         
699         return Vector!ubyte();
700     }
701 
702     /**
703     * Returns: true iff the counterparty supports the secure
704     * renegotiation extensions.
705     */
706     bool secureRenegotiationSupported() const
707     {
708         if (auto active = activeState())
709             return active.serverHello().secureRenegotiation();
710         
711         if (auto pending = pendingState())
712             if (auto hello = pending.serverHello())
713                 return hello.secureRenegotiation();
714         
715         return false;
716     }
717 
718     RandomNumberGenerator rng() { return m_rng; }
719 
720     TLSSessionManager sessionManager() { return m_session_manager; }
721 
722     bool saveSession(in TLSSession session) const { return m_handshake_cb(session); }
723 
724 private:
725 
726     size_t maximumFragmentSize() const
727     {
728         // should we be caching this value?
729         
730         if (auto pending = pendingState())
731             if (auto server_hello = pending.serverHello())
732                 if (size_t frag = server_hello.fragmentSize())
733                     return frag;
734         
735         if (auto active = activeState())
736             if (size_t frag = active.serverHello().fragmentSize())
737                 return frag;
738         
739         return MAX_PLAINTEXT_SIZE;
740     }
741 
742     void sendRecord(ubyte record_type, const ref Vector!ubyte record)
743     {
744 		if (auto seq = sequenceNumbers())
745 	        sendRecordArray(seq.currentWriteEpoch(), record_type, record.ptr, record.length);
746     }
747 
748     void sendRecordUnderEpoch(ushort epoch, ubyte record_type, const ref Vector!ubyte record)
749     {
750         sendRecordArray(epoch, record_type, record.ptr, record.length);
751     }
752 
753     void sendRecordArray(ushort epoch, ubyte type, const(ubyte)* input, size_t length)
754     {
755         if (length == 0)
756             return;
757         /*
758         * If using CBC mode without an explicit IV (TLS v1.0),
759         * send a single ubyte of plaintext to randomize the (implicit) IV of
760         * the following main block. If using a stream cipher, or TLS v1.1
761         * or higher, this isn't necessary.
762         *
763         * An empty record also works but apparently some implementations do
764         * not like this (https://bugzilla.mozilla.org/show_bug.cgi?id=665814)
765         *
766         * See http://www.openssl.org/~bodo/tls-cbc.txt for background.
767         */
768         
769         auto cipher_state = cast(ConnectionCipherState)writeCipherStateEpoch(epoch);
770         
771         if (type == APPLICATION_DATA && cipher_state.cbcWithoutExplicitIv())
772         {
773             writeRecord(cipher_state, epoch, type, input, 1);
774             input += 1;
775             length -= 1;
776         }
777         
778         const size_t max_fragment_size = maximumFragmentSize();
779         
780         while (length)
781         {
782             const size_t sending = std.algorithm.min(length, max_fragment_size);
783             writeRecord(cipher_state, epoch, type, input, sending);
784             
785             input += sending;
786             length -= sending;
787         }
788     }
789 
790     void writeRecord(ConnectionCipherState cipher_state, ushort epoch, ubyte record_type, const(ubyte)* input, size_t length)
791     {
792         assert(m_pending_state || m_active_state, "Some connection state exists");
793         
794         TLSProtocolVersion record_version = (m_pending_state) ? (m_pending_state.Version()) : (m_active_state.Version());
795         
796         .writeRecord(m_writebuf,
797                      record_type,
798                      input,
799                      length,
800                      record_version,
801                      (*m_sequence_numbers).nextWriteSequence(epoch),
802                      cipher_state,
803                      m_rng);
804         
805         m_output_fn(cast(ubyte[]) m_writebuf[]);
806     }
807 
808     const(ConnectionSequenceNumbers) sequenceNumbers() const
809     {
810         assert(m_sequence_numbers, "Have a sequence numbers object");
811         return *m_sequence_numbers;
812     }
813 
814     const(ConnectionCipherState) readCipherStateEpoch(ushort epoch) const
815     {
816         auto state = m_read_cipher_states.get(epoch, ConnectionCipherState.init);
817         
818         assert(state !is ConnectionCipherState.init || epoch == 0, "Have a cipher state for the specified epoch");
819         
820         return state;
821     }
822 
823     const(ConnectionCipherState) writeCipherStateEpoch(ushort epoch) const
824     {
825         auto state = m_write_cipher_states.get(epoch, ConnectionCipherState.init);
826         
827         assert(state !is ConnectionCipherState.init || epoch == 0, "Have a cipher state for the specified epoch");
828         
829         return state;
830     }
831 
832     protected void resetState()
833     {
834         m_active_state.free();
835         m_pending_state.free();
836         m_readbuf.destroy();
837 		m_writebuf.destroy();
838         foreach (const ref k, const ref v; m_write_cipher_states)
839         {
840             v.destroy();
841         }
842         m_write_cipher_states.clear();
843         foreach (const ref k, const ref v; m_read_cipher_states)
844         {
845             v.destroy();
846         }
847         m_read_cipher_states.clear();
848     }
849 
850     const(HandshakeState) activeState() const { return *m_active_state; }
851 
852     const(HandshakeState) pendingState() const { return *m_pending_state; }
853 
854 	Thread m_owner;
855 	package string m_application_protocol;
856     bool m_is_datagram;
857 
858     /* callbacks */
859     OnHandshakeComplete m_handshake_cb;
860     OnClearData m_data_cb;
861     OnAlert m_alert_cb;
862     DataWriter m_output_fn;
863 
864     /* external state */
865     RandomNumberGenerator m_rng;
866     package TLSSessionManager m_session_manager; // fixme: package protection for switchContext, use protected: method instead
867 
868     /* sequence number state */
869     Unique!ConnectionSequenceNumbers m_sequence_numbers;
870 
871     /* pending and active connection states */
872     Unique!HandshakeState m_active_state;
873     Unique!HandshakeState m_pending_state;
874 
875     /* cipher states for each epoch */
876     HashMap!(ushort, ConnectionCipherState) m_write_cipher_states;
877     HashMap!(ushort, ConnectionCipherState) m_read_cipher_states;
878 
879     /* I/O buffers */
880     SecureVector!ubyte m_writebuf;
881     SecureVector!ubyte m_readbuf;
882 }