1 /*
2  * Binary packet protocol for SSH-2.
3  */
4 
5 #include <assert.h>
6 
7 #include "putty.h"
8 #include "ssh.h"
9 #include "sshbpp.h"
10 #include "sshcr.h"
11 
12 struct ssh2_bpp_direction {
13     unsigned long sequence;
14     ssh_cipher *cipher;
15     ssh2_mac *mac;
16     bool etm_mode;
17     const ssh_compression_alg *pending_compression;
18 };
19 
20 struct ssh2_bpp_state {
21     int crState;
22     long len, pad, payload, packetlen, maclen, length, maxlen;
23     unsigned char *buf;
24     size_t bufsize;
25     unsigned char *data;
26     unsigned cipherblk;
27     PktIn *pktin;
28     struct DataTransferStats *stats;
29     bool cbc_ignore_workaround;
30 
31     struct ssh2_bpp_direction in, out;
32     /* comp and decomp logically belong in the per-direction
33      * substructure, except that they have different types */
34     ssh_decompressor *in_decomp;
35     ssh_compressor *out_comp;
36 
37     bool is_server;
38     bool pending_newkeys;
39     bool pending_compression, seen_userauth_success;
40     bool enforce_next_packet_is_userauth_success;
41     unsigned nnewkeys;
42     int prev_type;
43 
44     BinaryPacketProtocol bpp;
45 };
46 
47 static void ssh2_bpp_free(BinaryPacketProtocol *bpp);
48 static void ssh2_bpp_handle_input(BinaryPacketProtocol *bpp);
49 static void ssh2_bpp_handle_output(BinaryPacketProtocol *bpp);
50 static PktOut *ssh2_bpp_new_pktout(int type);
51 
52 static const BinaryPacketProtocolVtable ssh2_bpp_vtable = {
53     .free = ssh2_bpp_free,
54     .handle_input = ssh2_bpp_handle_input,
55     .handle_output = ssh2_bpp_handle_output,
56     .new_pktout = ssh2_bpp_new_pktout,
57     .queue_disconnect = ssh2_bpp_queue_disconnect, /* in sshcommon.c */
58     .packet_size_limit = 0xFFFFFFFF, /* no special limit for this bpp */
59 };
60 
ssh2_bpp_new(LogContext * logctx,struct DataTransferStats * stats,bool is_server)61 BinaryPacketProtocol *ssh2_bpp_new(
62     LogContext *logctx, struct DataTransferStats *stats, bool is_server)
63 {
64     struct ssh2_bpp_state *s = snew(struct ssh2_bpp_state);
65     memset(s, 0, sizeof(*s));
66     s->bpp.vt = &ssh2_bpp_vtable;
67     s->bpp.logctx = logctx;
68     s->stats = stats;
69     s->is_server = is_server;
70     ssh_bpp_common_setup(&s->bpp);
71     return &s->bpp;
72 }
73 
ssh2_bpp_free_outgoing_crypto(struct ssh2_bpp_state * s)74 static void ssh2_bpp_free_outgoing_crypto(struct ssh2_bpp_state *s)
75 {
76     /*
77      * We must free the MAC before the cipher, because sometimes the
78      * MAC is not actually separately allocated but just a different
79      * facet of the same object as the cipher, in which case
80      * ssh2_mac_free does nothing and ssh_cipher_free does the actual
81      * freeing. So if we freed the cipher first and then tried to
82      * dereference the MAC's vtable pointer to find out how to free
83      * that too, we'd be accessing freed memory.
84      */
85     if (s->out.mac)
86         ssh2_mac_free(s->out.mac);
87     if (s->out.cipher)
88         ssh_cipher_free(s->out.cipher);
89     if (s->out_comp)
90         ssh_compressor_free(s->out_comp);
91 }
92 
ssh2_bpp_free_incoming_crypto(struct ssh2_bpp_state * s)93 static void ssh2_bpp_free_incoming_crypto(struct ssh2_bpp_state *s)
94 {
95     /* As above, take care to free in.mac before in.cipher */
96     if (s->in.mac)
97         ssh2_mac_free(s->in.mac);
98     if (s->in.cipher)
99         ssh_cipher_free(s->in.cipher);
100     if (s->in_decomp)
101         ssh_decompressor_free(s->in_decomp);
102 }
103 
ssh2_bpp_free(BinaryPacketProtocol * bpp)104 static void ssh2_bpp_free(BinaryPacketProtocol *bpp)
105 {
106     struct ssh2_bpp_state *s = container_of(bpp, struct ssh2_bpp_state, bpp);
107     sfree(s->buf);
108     ssh2_bpp_free_outgoing_crypto(s);
109     ssh2_bpp_free_incoming_crypto(s);
110     sfree(s->pktin);
111     sfree(s);
112 }
113 
ssh2_bpp_new_outgoing_crypto(BinaryPacketProtocol * bpp,const ssh_cipheralg * cipher,const void * ckey,const void * iv,const ssh2_macalg * mac,bool etm_mode,const void * mac_key,const ssh_compression_alg * compression,bool delayed_compression)114 void ssh2_bpp_new_outgoing_crypto(
115     BinaryPacketProtocol *bpp,
116     const ssh_cipheralg *cipher, const void *ckey, const void *iv,
117     const ssh2_macalg *mac, bool etm_mode, const void *mac_key,
118     const ssh_compression_alg *compression, bool delayed_compression)
119 {
120     struct ssh2_bpp_state *s;
121     assert(bpp->vt == &ssh2_bpp_vtable);
122     s = container_of(bpp, struct ssh2_bpp_state, bpp);
123 
124     ssh2_bpp_free_outgoing_crypto(s);
125 
126     if (cipher) {
127         s->out.cipher = ssh_cipher_new(cipher);
128         ssh_cipher_setkey(s->out.cipher, ckey);
129         ssh_cipher_setiv(s->out.cipher, iv);
130 
131         s->cbc_ignore_workaround = (
132             (ssh_cipher_alg(s->out.cipher)->flags & SSH_CIPHER_IS_CBC) &&
133             !(s->bpp.remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE));
134 
135         bpp_logevent("Initialised %s outbound encryption",
136                      ssh_cipher_alg(s->out.cipher)->text_name);
137     } else {
138         s->out.cipher = NULL;
139         s->cbc_ignore_workaround = false;
140     }
141     s->out.etm_mode = etm_mode;
142     if (mac) {
143         s->out.mac = ssh2_mac_new(mac, s->out.cipher);
144         ssh2_mac_setkey(s->out.mac, make_ptrlen(mac_key, mac->keylen));
145 
146         bpp_logevent("Initialised %s outbound MAC algorithm%s%s",
147                      ssh2_mac_text_name(s->out.mac),
148                      etm_mode ? " (in ETM mode)" : "",
149                      (s->out.cipher &&
150                       ssh_cipher_alg(s->out.cipher)->required_mac ?
151                       " (required by cipher)" : ""));
152     } else {
153         s->out.mac = NULL;
154     }
155 
156     if (delayed_compression && !s->seen_userauth_success) {
157         s->out.pending_compression = compression;
158         s->out_comp = NULL;
159 
160         bpp_logevent("Will enable %s compression after user authentication",
161                      s->out.pending_compression->text_name);
162     } else {
163         s->out.pending_compression = NULL;
164 
165         /* 'compression' is always non-NULL, because no compression is
166          * indicated by ssh_comp_none. But this setup call may return a
167          * null out_comp. */
168         s->out_comp = ssh_compressor_new(compression);
169 
170         if (s->out_comp)
171             bpp_logevent("Initialised %s compression",
172                          ssh_compressor_alg(s->out_comp)->text_name);
173     }
174 }
175 
ssh2_bpp_new_incoming_crypto(BinaryPacketProtocol * bpp,const ssh_cipheralg * cipher,const void * ckey,const void * iv,const ssh2_macalg * mac,bool etm_mode,const void * mac_key,const ssh_compression_alg * compression,bool delayed_compression)176 void ssh2_bpp_new_incoming_crypto(
177     BinaryPacketProtocol *bpp,
178     const ssh_cipheralg *cipher, const void *ckey, const void *iv,
179     const ssh2_macalg *mac, bool etm_mode, const void *mac_key,
180     const ssh_compression_alg *compression, bool delayed_compression)
181 {
182     struct ssh2_bpp_state *s;
183     assert(bpp->vt == &ssh2_bpp_vtable);
184     s = container_of(bpp, struct ssh2_bpp_state, bpp);
185 
186     ssh2_bpp_free_incoming_crypto(s);
187 
188     if (cipher) {
189         s->in.cipher = ssh_cipher_new(cipher);
190         ssh_cipher_setkey(s->in.cipher, ckey);
191         ssh_cipher_setiv(s->in.cipher, iv);
192 
193         bpp_logevent("Initialised %s inbound encryption",
194                      ssh_cipher_alg(s->in.cipher)->text_name);
195     } else {
196         s->in.cipher = NULL;
197     }
198     s->in.etm_mode = etm_mode;
199     if (mac) {
200         s->in.mac = ssh2_mac_new(mac, s->in.cipher);
201         ssh2_mac_setkey(s->in.mac, make_ptrlen(mac_key, mac->keylen));
202 
203         bpp_logevent("Initialised %s inbound MAC algorithm%s%s",
204                      ssh2_mac_text_name(s->in.mac),
205                      etm_mode ? " (in ETM mode)" : "",
206                      (s->in.cipher &&
207                       ssh_cipher_alg(s->in.cipher)->required_mac ?
208                       " (required by cipher)" : ""));
209     } else {
210         s->in.mac = NULL;
211     }
212 
213     if (delayed_compression && !s->seen_userauth_success) {
214         s->in.pending_compression = compression;
215         s->in_decomp = NULL;
216 
217         bpp_logevent("Will enable %s decompression after user authentication",
218                      s->in.pending_compression->text_name);
219     } else {
220         s->in.pending_compression = NULL;
221 
222         /* 'compression' is always non-NULL, because no compression is
223          * indicated by ssh_comp_none. But this setup call may return a
224          * null in_decomp. */
225         s->in_decomp = ssh_decompressor_new(compression);
226 
227         if (s->in_decomp)
228             bpp_logevent("Initialised %s decompression",
229                          ssh_decompressor_alg(s->in_decomp)->text_name);
230     }
231 
232     /* Clear the pending_newkeys flag, so that handle_input below will
233      * start consuming the input data again. */
234     s->pending_newkeys = false;
235 
236     /* And schedule a run of handle_input, in case there's already
237      * input data in the queue. */
238     queue_idempotent_callback(&s->bpp.ic_in_raw);
239 }
240 
ssh2_bpp_rekey_inadvisable(BinaryPacketProtocol * bpp)241 bool ssh2_bpp_rekey_inadvisable(BinaryPacketProtocol *bpp)
242 {
243     struct ssh2_bpp_state *s;
244     assert(bpp->vt == &ssh2_bpp_vtable);
245     s = container_of(bpp, struct ssh2_bpp_state, bpp);
246 
247     return s->pending_compression;
248 }
249 
ssh2_bpp_enable_pending_compression(struct ssh2_bpp_state * s)250 static void ssh2_bpp_enable_pending_compression(struct ssh2_bpp_state *s)
251 {
252     BinaryPacketProtocol *bpp = &s->bpp; /* for bpp_logevent */
253 
254     if (s->in.pending_compression) {
255         s->in_decomp = ssh_decompressor_new(s->in.pending_compression);
256         bpp_logevent("Initialised delayed %s decompression",
257                      ssh_decompressor_alg(s->in_decomp)->text_name);
258         s->in.pending_compression = NULL;
259     }
260     if (s->out.pending_compression) {
261         s->out_comp = ssh_compressor_new(s->out.pending_compression);
262         bpp_logevent("Initialised delayed %s compression",
263                      ssh_compressor_alg(s->out_comp)->text_name);
264         s->out.pending_compression = NULL;
265     }
266 }
267 
268 #define BPP_READ(ptr, len) do                                           \
269     {                                                                   \
270         bool success;                                                   \
271         crMaybeWaitUntilV((success = bufchain_try_fetch_consume(        \
272                                s->bpp.in_raw, ptr, len)) ||             \
273                           s->bpp.input_eof);                            \
274         if (!success)                                                   \
275             goto eof;                                                   \
276         ssh_check_frozen(s->bpp.ssh);                                   \
277     } while (0)
278 
279 #define userauth_range(pkttype) ((unsigned)((pkttype) - 50) < 20)
280 
ssh2_bpp_handle_input(BinaryPacketProtocol * bpp)281 static void ssh2_bpp_handle_input(BinaryPacketProtocol *bpp)
282 {
283     struct ssh2_bpp_state *s = container_of(bpp, struct ssh2_bpp_state, bpp);
284 
285     crBegin(s->crState);
286 
287     while (1) {
288         s->maxlen = 0;
289         s->length = 0;
290         if (s->in.cipher)
291             s->cipherblk = ssh_cipher_alg(s->in.cipher)->blksize;
292         else
293             s->cipherblk = 8;
294         if (s->cipherblk < 8)
295             s->cipherblk = 8;
296         s->maclen = s->in.mac ? ssh2_mac_alg(s->in.mac)->len : 0;
297 
298         if (s->in.cipher &&
299             (ssh_cipher_alg(s->in.cipher)->flags & SSH_CIPHER_IS_CBC) &&
300             s->in.mac && !s->in.etm_mode) {
301             /*
302              * When dealing with a CBC-mode cipher, we want to avoid the
303              * possibility of an attacker's tweaking the ciphertext stream
304              * so as to cause us to feed the same block to the block
305              * cipher more than once and thus leak information
306              * (VU#958563).  The way we do this is not to take any
307              * decisions on the basis of anything we've decrypted until
308              * we've verified it with a MAC.  That includes the packet
309              * length, so we just read data and check the MAC repeatedly,
310              * and when the MAC passes, see if the length we've got is
311              * plausible.
312              *
313              * This defence is unnecessary in OpenSSH ETM mode, because
314              * the whole point of ETM mode is that the attacker can't
315              * tweak the ciphertext stream at all without the MAC
316              * detecting it before we decrypt anything.
317              */
318 
319             /*
320              * Make sure we have buffer space for a maximum-size packet.
321              */
322             unsigned buflimit = OUR_V2_PACKETLIMIT + s->maclen;
323             if (s->bufsize < buflimit) {
324                 s->bufsize = buflimit;
325                 s->buf = sresize(s->buf, s->bufsize, unsigned char);
326             }
327 
328             /* Read an amount corresponding to the MAC. */
329             BPP_READ(s->buf, s->maclen);
330 
331             s->packetlen = 0;
332             ssh2_mac_start(s->in.mac);
333             put_uint32(s->in.mac, s->in.sequence);
334 
335             for (;;) { /* Once around this loop per cipher block. */
336                 /* Read another cipher-block's worth, and tack it on to
337                  * the end. */
338                 BPP_READ(s->buf + (s->packetlen + s->maclen), s->cipherblk);
339                 /* Decrypt one more block (a little further back in
340                  * the stream). */
341                 ssh_cipher_decrypt(s->in.cipher,
342                                    s->buf + s->packetlen, s->cipherblk);
343 
344                 /* Feed that block to the MAC. */
345                 put_data(s->in.mac,
346                          s->buf + s->packetlen, s->cipherblk);
347                 s->packetlen += s->cipherblk;
348 
349                 /* See if that gives us a valid packet. */
350                 if (ssh2_mac_verresult(s->in.mac, s->buf + s->packetlen) &&
351                     ((s->len = toint(GET_32BIT_MSB_FIRST(s->buf))) ==
352                      s->packetlen-4))
353                     break;
354                 if (s->packetlen >= (long)OUR_V2_PACKETLIMIT) {
355                     ssh_sw_abort(s->bpp.ssh,
356                                  "No valid incoming packet found");
357                     crStopV;
358                 }
359             }
360             s->maxlen = s->packetlen + s->maclen;
361 
362             /*
363              * Now transfer the data into an output packet.
364              */
365             s->pktin = snew_plus(PktIn, s->maxlen);
366             s->pktin->qnode.prev = s->pktin->qnode.next = NULL;
367             s->pktin->type = 0;
368             s->pktin->qnode.on_free_queue = false;
369             s->data = snew_plus_get_aux(s->pktin);
370             memcpy(s->data, s->buf, s->maxlen);
371         } else if (s->in.mac && s->in.etm_mode) {
372             if (s->bufsize < 4) {
373                 s->bufsize = 4;
374                 s->buf = sresize(s->buf, s->bufsize, unsigned char);
375             }
376 
377             /*
378              * OpenSSH encrypt-then-MAC mode: the packet length is
379              * unencrypted, unless the cipher supports length encryption.
380              */
381             BPP_READ(s->buf, 4);
382 
383             /* Cipher supports length decryption, so do it */
384             if (s->in.cipher && (ssh_cipher_alg(s->in.cipher)->flags &
385                                  SSH_CIPHER_SEPARATE_LENGTH)) {
386                 /* Keep the packet the same though, so the MAC passes */
387                 unsigned char len[4];
388                 memcpy(len, s->buf, 4);
389                 ssh_cipher_decrypt_length(
390                     s->in.cipher, len, 4, s->in.sequence);
391                 s->len = toint(GET_32BIT_MSB_FIRST(len));
392             } else {
393                 s->len = toint(GET_32BIT_MSB_FIRST(s->buf));
394             }
395 
396             /*
397              * _Completely_ silly lengths should be stomped on before they
398              * do us any more damage.
399              */
400             if (s->len < 0 || s->len > (long)OUR_V2_PACKETLIMIT ||
401                 s->len % s->cipherblk != 0) {
402                 ssh_sw_abort(s->bpp.ssh,
403                              "Incoming packet length field was garbled");
404                 crStopV;
405             }
406 
407             /*
408              * So now we can work out the total packet length.
409              */
410             s->packetlen = s->len + 4;
411 
412             /*
413              * Allocate the packet to return, now we know its length.
414              */
415             s->pktin = snew_plus(PktIn, OUR_V2_PACKETLIMIT + s->maclen);
416             s->pktin->qnode.prev = s->pktin->qnode.next = NULL;
417             s->pktin->type = 0;
418             s->pktin->qnode.on_free_queue = false;
419             s->data = snew_plus_get_aux(s->pktin);
420             memcpy(s->data, s->buf, 4);
421 
422             /*
423              * Read the remainder of the packet.
424              */
425             BPP_READ(s->data + 4, s->packetlen + s->maclen - 4);
426 
427             /*
428              * Check the MAC.
429              */
430             if (s->in.mac && !ssh2_mac_verify(
431                     s->in.mac, s->data, s->len + 4, s->in.sequence)) {
432                 ssh_sw_abort(s->bpp.ssh, "Incorrect MAC received on packet");
433                 crStopV;
434             }
435 
436             /* Decrypt everything between the length field and the MAC. */
437             if (s->in.cipher)
438                 ssh_cipher_decrypt(
439                     s->in.cipher, s->data + 4, s->packetlen - 4);
440         } else {
441             if (s->bufsize < s->cipherblk) {
442                 s->bufsize = s->cipherblk;
443                 s->buf = sresize(s->buf, s->bufsize, unsigned char);
444             }
445 
446             /*
447              * Acquire and decrypt the first block of the packet. This will
448              * contain the length and padding details.
449              */
450             BPP_READ(s->buf, s->cipherblk);
451 
452             if (s->in.cipher)
453                 ssh_cipher_decrypt(s->in.cipher, s->buf, s->cipherblk);
454 
455             /*
456              * Now get the length figure.
457              */
458             s->len = toint(GET_32BIT_MSB_FIRST(s->buf));
459 
460             /*
461              * _Completely_ silly lengths should be stomped on before they
462              * do us any more damage.
463              */
464             if (s->len < 0 || s->len > (long)OUR_V2_PACKETLIMIT ||
465                 (s->len + 4) % s->cipherblk != 0) {
466                 ssh_sw_abort(s->bpp.ssh,
467                              "Incoming packet was garbled on decryption");
468                 crStopV;
469             }
470 
471             /*
472              * So now we can work out the total packet length.
473              */
474             s->packetlen = s->len + 4;
475 
476             /*
477              * Allocate the packet to return, now we know its length.
478              */
479             s->maxlen = s->packetlen + s->maclen;
480             s->pktin = snew_plus(PktIn, s->maxlen);
481             s->pktin->qnode.prev = s->pktin->qnode.next = NULL;
482             s->pktin->type = 0;
483             s->pktin->qnode.on_free_queue = false;
484             s->data = snew_plus_get_aux(s->pktin);
485             memcpy(s->data, s->buf, s->cipherblk);
486 
487             /*
488              * Read and decrypt the remainder of the packet.
489              */
490             BPP_READ(s->data + s->cipherblk,
491                      s->packetlen + s->maclen - s->cipherblk);
492 
493             /* Decrypt everything _except_ the MAC. */
494             if (s->in.cipher)
495                 ssh_cipher_decrypt(
496                     s->in.cipher,
497                     s->data + s->cipherblk, s->packetlen - s->cipherblk);
498 
499             /*
500              * Check the MAC.
501              */
502             if (s->in.mac && !ssh2_mac_verify(
503                     s->in.mac, s->data, s->len + 4, s->in.sequence)) {
504                 ssh_sw_abort(s->bpp.ssh, "Incorrect MAC received on packet");
505                 crStopV;
506             }
507         }
508         /* Get and sanity-check the amount of random padding. */
509         s->pad = s->data[4];
510         if (s->pad < 4 || s->len - s->pad < 1) {
511             ssh_sw_abort(s->bpp.ssh,
512                          "Invalid padding length on received packet");
513             crStopV;
514         }
515         /*
516          * This enables us to deduce the payload length.
517          */
518         s->payload = s->len - s->pad - 1;
519 
520         s->length = s->payload + 5;
521 
522         dts_consume(&s->stats->in, s->packetlen);
523 
524         s->pktin->sequence = s->in.sequence++;
525 
526         s->length = s->packetlen - s->pad;
527         assert(s->length >= 0);
528 
529         /*
530          * Decompress packet payload.
531          */
532         {
533             unsigned char *newpayload;
534             int newlen;
535             if (s->in_decomp && ssh_decompressor_decompress(
536                     s->in_decomp, s->data + 5, s->length - 5,
537                     &newpayload, &newlen)) {
538                 if (s->maxlen < newlen + 5) {
539                     PktIn *old_pktin = s->pktin;
540 
541                     s->maxlen = newlen + 5;
542                     s->pktin = snew_plus(PktIn, s->maxlen);
543                     *s->pktin = *old_pktin; /* structure copy */
544                     s->data = snew_plus_get_aux(s->pktin);
545 
546                     smemclr(old_pktin, s->packetlen + s->maclen);
547                     sfree(old_pktin);
548                 }
549                 s->length = 5 + newlen;
550                 memcpy(s->data + 5, newpayload, newlen);
551                 sfree(newpayload);
552             }
553         }
554 
555         /*
556          * Now we can identify the semantic content of the packet,
557          * and also the initial type byte.
558          */
559         if (s->length <= 5) { /* == 5 we hope, but robustness */
560             /*
561              * RFC 4253 doesn't explicitly say that completely empty
562              * packets with no type byte are forbidden. We handle them
563              * here by giving them a type code larger than 0xFF, which
564              * will be picked up at the next layer and trigger
565              * SSH_MSG_UNIMPLEMENTED.
566              */
567             s->pktin->type = SSH_MSG_NO_TYPE_CODE;
568             s->data += 5;
569             s->length = 0;
570         } else {
571             s->pktin->type = s->data[5];
572             s->data += 6;
573             s->length -= 6;
574         }
575         BinarySource_INIT(s->pktin, s->data, s->length);
576 
577         if (s->bpp.logctx) {
578             logblank_t blanks[MAX_BLANKS];
579             int nblanks = ssh2_censor_packet(
580                 s->bpp.pls, s->pktin->type, false,
581                 make_ptrlen(s->data, s->length), blanks);
582             log_packet(s->bpp.logctx, PKT_INCOMING, s->pktin->type,
583                        ssh2_pkt_type(s->bpp.pls->kctx, s->bpp.pls->actx,
584                                      s->pktin->type),
585                        s->data, s->length, nblanks, blanks,
586                        &s->pktin->sequence, 0, NULL);
587         }
588 
589         if (ssh2_bpp_check_unimplemented(&s->bpp, s->pktin)) {
590             sfree(s->pktin);
591             s->pktin = NULL;
592             continue;
593         }
594 
595         s->pktin->qnode.formal_size = get_avail(s->pktin);
596         pq_push(&s->bpp.in_pq, s->pktin);
597 
598         {
599             int type = s->pktin->type;
600             int prev_type = s->prev_type;
601             s->prev_type = type;
602             s->pktin = NULL;
603 
604             if (s->enforce_next_packet_is_userauth_success) {
605                 /* See EXT_INFO handler below */
606                 if (type != SSH2_MSG_USERAUTH_SUCCESS) {
607                     ssh_proto_error(s->bpp.ssh,
608                                     "Remote side sent SSH2_MSG_EXT_INFO "
609                                     "not either preceded by NEWKEYS or "
610                                     "followed by USERAUTH_SUCCESS");
611                     return;
612                 }
613                 s->enforce_next_packet_is_userauth_success = false;
614             }
615 
616             if (type == SSH2_MSG_NEWKEYS) {
617                 if (s->nnewkeys < 2)
618                     s->nnewkeys++;
619                 /*
620                  * Mild layer violation: in this situation we must
621                  * suspend processing of the input byte stream until
622                  * the transport layer has initialised the new keys by
623                  * calling ssh2_bpp_new_incoming_crypto above.
624                  */
625                 s->pending_newkeys = true;
626                 crWaitUntilV(!s->pending_newkeys);
627                 continue;
628             }
629 
630             if (type == SSH2_MSG_USERAUTH_SUCCESS && !s->is_server) {
631                 /*
632                  * Another one: if we were configured with OpenSSH's
633                  * deferred compression which is triggered on receipt
634                  * of USERAUTH_SUCCESS, then this is the moment to
635                  * turn on compression.
636                  */
637                 ssh2_bpp_enable_pending_compression(s);
638 
639                 /*
640                  * Whether or not we were doing delayed compression in
641                  * _this_ set of crypto parameters, we should set a
642                  * flag indicating that we're now authenticated, so
643                  * that a delayed compression method enabled in any
644                  * future rekey will be treated as un-delayed.
645                  */
646                 s->seen_userauth_success = true;
647             }
648 
649             if (type == SSH2_MSG_EXT_INFO) {
650                 /*
651                  * And another: enforce that an incoming EXT_INFO is
652                  * either the message immediately after the initial
653                  * NEWKEYS, or (if we're the client) the one
654                  * immediately before USERAUTH_SUCCESS.
655                  */
656                 if (prev_type == SSH2_MSG_NEWKEYS && s->nnewkeys == 1) {
657                     /* OK - this is right after the first NEWKEYS. */
658                 } else if (s->is_server) {
659                     /* We're the server, so they're the client.
660                      * Clients may not send EXT_INFO at _any_ other
661                      * time. */
662                     ssh_proto_error(s->bpp.ssh,
663                                     "Remote side sent SSH2_MSG_EXT_INFO "
664                                     "that was not immediately after the "
665                                     "initial NEWKEYS");
666                     return;
667                 } else if (s->nnewkeys > 0 && s->seen_userauth_success) {
668                     /* We're the client, so they're the server. In
669                      * that case they may also send EXT_INFO
670                      * immediately before USERAUTH_SUCCESS. Error out
671                      * immediately if this can't _possibly_ be that
672                      * moment (because we haven't even seen NEWKEYS
673                      * yet, or because we've already seen
674                      * USERAUTH_SUCCESS). */
675                     ssh_proto_error(s->bpp.ssh,
676                                     "Remote side sent SSH2_MSG_EXT_INFO "
677                                     "after USERAUTH_SUCCESS");
678                     return;
679                 } else {
680                     /* This _could_ be OK, provided the next packet is
681                      * USERAUTH_SUCCESS. Set a flag to remember to
682                      * fault it if not. */
683                     s->enforce_next_packet_is_userauth_success = true;
684                 }
685             }
686 
687             if (s->pending_compression && userauth_range(type)) {
688                 /*
689                  * Receiving any userauth message at all indicates
690                  * that we're not about to turn on delayed compression
691                  * - either because we just _have_ done, or because
692                  * this message is a USERAUTH_FAILURE or some kind of
693                  * intermediate 'please send more data' continuation
694                  * message. Either way, we turn off the outgoing
695                  * packet blockage for now, and release any queued
696                  * output packets, so that we can make another attempt
697                  * to authenticate. The next userauth packet we send
698                  * will re-block the output direction.
699                  */
700                 s->pending_compression = false;
701                 queue_idempotent_callback(&s->bpp.ic_out_pq);
702             }
703         }
704     }
705 
706   eof:
707     /*
708      * We've seen EOF. But we might have pushed stuff on the outgoing
709      * packet queue first, and that stuff _might_ include a DISCONNECT
710      * message, in which case we'd like to use that as the diagnostic.
711      * So first wait for the queue to have been processed.
712      */
713     crMaybeWaitUntilV(!pq_peek(&s->bpp.in_pq));
714     if (!s->bpp.expect_close) {
715         ssh_remote_error(s->bpp.ssh,
716                          "Remote side unexpectedly closed network connection");
717     } else {
718         ssh_remote_eof(s->bpp.ssh, "Remote side closed network connection");
719     }
720     return;  /* avoid touching s now it's been freed */
721 
722     crFinishV;
723 }
724 
ssh2_bpp_new_pktout(int pkt_type)725 static PktOut *ssh2_bpp_new_pktout(int pkt_type)
726 {
727     PktOut *pkt = ssh_new_packet();
728     pkt->length = 5; /* space for packet length + padding length */
729     pkt->minlen = 0;
730     pkt->type = pkt_type;
731     put_byte(pkt, pkt_type);
732     pkt->prefix = pkt->length;
733     return pkt;
734 }
735 
ssh2_bpp_format_packet_inner(struct ssh2_bpp_state * s,PktOut * pkt)736 static void ssh2_bpp_format_packet_inner(struct ssh2_bpp_state *s, PktOut *pkt)
737 {
738     int origlen, cipherblk, maclen, padding, unencrypted_prefix, i;
739 
740     if (s->bpp.logctx) {
741         ptrlen pktdata = make_ptrlen(pkt->data + pkt->prefix,
742                                      pkt->length - pkt->prefix);
743         logblank_t blanks[MAX_BLANKS];
744         int nblanks = ssh2_censor_packet(
745             s->bpp.pls, pkt->type, true, pktdata, blanks);
746         log_packet(s->bpp.logctx, PKT_OUTGOING, pkt->type,
747                    ssh2_pkt_type(s->bpp.pls->kctx, s->bpp.pls->actx,
748                                  pkt->type),
749                    pktdata.ptr, pktdata.len, nblanks, blanks, &s->out.sequence,
750                    pkt->downstream_id, pkt->additional_log_text);
751     }
752 
753     cipherblk = s->out.cipher ? ssh_cipher_alg(s->out.cipher)->blksize : 8;
754     cipherblk = cipherblk < 8 ? 8 : cipherblk;  /* or 8 if blksize < 8 */
755 
756     if (s->out_comp) {
757         unsigned char *newpayload;
758         int minlen, newlen;
759 
760         /*
761          * Compress packet payload.
762          */
763         minlen = pkt->minlen;
764         if (minlen) {
765             /*
766              * Work out how much compressed data we need (at least) to
767              * make the overall packet length come to pkt->minlen.
768              */
769             if (s->out.mac)
770                 minlen -= ssh2_mac_alg(s->out.mac)->len;
771             minlen -= 8;              /* length field + min padding */
772         }
773 
774         ssh_compressor_compress(s->out_comp, pkt->data + 5, pkt->length - 5,
775                                 &newpayload, &newlen, minlen);
776         pkt->length = 5;
777         put_data(pkt, newpayload, newlen);
778         sfree(newpayload);
779     }
780 
781     /*
782      * Add padding. At least four bytes, and must also bring total
783      * length (minus MAC) up to a multiple of the block size.
784      * If pkt->forcepad is set, make sure the packet is at least that size
785      * after padding.
786      */
787     padding = 4;
788     unencrypted_prefix = (s->out.mac && s->out.etm_mode) ? 4 : 0;
789     padding +=
790         (cipherblk - (pkt->length - unencrypted_prefix + padding) % cipherblk)
791         % cipherblk;
792     assert(padding <= 255);
793     maclen = s->out.mac ? ssh2_mac_alg(s->out.mac)->len : 0;
794     origlen = pkt->length;
795     for (i = 0; i < padding; i++)
796         put_byte(pkt, 0);              /* make space for random padding */
797     random_read(pkt->data + origlen, padding);
798     pkt->data[4] = padding;
799     PUT_32BIT_MSB_FIRST(pkt->data, origlen + padding - 4);
800 
801     /* Encrypt length if the scheme requires it */
802     if (s->out.cipher &&
803         (ssh_cipher_alg(s->out.cipher)->flags & SSH_CIPHER_SEPARATE_LENGTH)) {
804         ssh_cipher_encrypt_length(s->out.cipher, pkt->data, 4,
805                                   s->out.sequence);
806     }
807 
808     put_padding(pkt, maclen, 0);
809 
810     if (s->out.mac && s->out.etm_mode) {
811         /*
812          * OpenSSH-defined encrypt-then-MAC protocol.
813          */
814         if (s->out.cipher)
815             ssh_cipher_encrypt(s->out.cipher,
816                                pkt->data + 4, origlen + padding - 4);
817         ssh2_mac_generate(s->out.mac, pkt->data, origlen + padding,
818                           s->out.sequence);
819     } else {
820         /*
821          * SSH-2 standard protocol.
822          */
823         if (s->out.mac)
824             ssh2_mac_generate(s->out.mac, pkt->data, origlen + padding,
825                               s->out.sequence);
826         if (s->out.cipher)
827             ssh_cipher_encrypt(s->out.cipher, pkt->data, origlen + padding);
828     }
829 
830     s->out.sequence++;       /* whether or not we MACed */
831 
832     dts_consume(&s->stats->out, origlen + padding);
833 }
834 
ssh2_bpp_format_packet(struct ssh2_bpp_state * s,PktOut * pkt)835 static void ssh2_bpp_format_packet(struct ssh2_bpp_state *s, PktOut *pkt)
836 {
837     if (pkt->minlen > 0 && !s->out_comp) {
838         /*
839          * If we've been told to pad the packet out to a given minimum
840          * length, but we're not compressing (and hence can't get the
841          * compression to do the padding by pointlessly opening and
842          * closing zlib blocks), then our other strategy is to precede
843          * this message with an SSH_MSG_IGNORE that makes it up to the
844          * right length.
845          *
846          * A third option in principle, and the most obviously
847          * sensible, would be to set the explicit padding field in the
848          * packet to more than its minimum value. Sadly, that turns
849          * out to break some servers (our institutional memory thinks
850          * Cisco in particular) and so we abandoned that idea shortly
851          * after trying it.
852          */
853 
854         /*
855          * Calculate the length we expect the real packet to have.
856          */
857         int block, length;
858         PktOut *ignore_pkt;
859 
860         block = s->out.cipher ? ssh_cipher_alg(s->out.cipher)->blksize : 0;
861         if (block < 8)
862             block = 8;
863         length = pkt->length;
864         length += 4;       /* minimum 4 byte padding */
865         length += block-1;
866         length -= (length % block);
867         if (s->out.mac)
868             length += ssh2_mac_alg(s->out.mac)->len;
869 
870         if (length < pkt->minlen) {
871             /*
872              * We need an ignore message. Calculate its length.
873              */
874             length = pkt->minlen - length;
875 
876             /*
877              * And work backwards from that to the length of the
878              * contained string.
879              */
880             if (s->out.mac)
881                 length -= ssh2_mac_alg(s->out.mac)->len;
882             length -= 8;               /* length field + min padding */
883             length -= 5;               /* type code + string length prefix */
884 
885             if (length < 0)
886                 length = 0;
887 
888             ignore_pkt = ssh2_bpp_new_pktout(SSH2_MSG_IGNORE);
889             put_uint32(ignore_pkt, length);
890             size_t origlen = ignore_pkt->length;
891             for (size_t i = 0; i < length; i++)
892                 put_byte(ignore_pkt, 0);  /* make space for random padding */
893             random_read(ignore_pkt->data + origlen, length);
894             ssh2_bpp_format_packet_inner(s, ignore_pkt);
895             bufchain_add(s->bpp.out_raw, ignore_pkt->data, ignore_pkt->length);
896             ssh_free_pktout(ignore_pkt);
897         }
898     }
899 
900     ssh2_bpp_format_packet_inner(s, pkt);
901     bufchain_add(s->bpp.out_raw, pkt->data, pkt->length);
902 }
903 
ssh2_bpp_handle_output(BinaryPacketProtocol * bpp)904 static void ssh2_bpp_handle_output(BinaryPacketProtocol *bpp)
905 {
906     struct ssh2_bpp_state *s = container_of(bpp, struct ssh2_bpp_state, bpp);
907     PktOut *pkt;
908     int n_userauth;
909 
910     /*
911      * Count the userauth packets in the queue.
912      */
913     n_userauth = 0;
914     for (pkt = pq_first(&s->bpp.out_pq); pkt != NULL;
915          pkt = pq_next(&s->bpp.out_pq, pkt))
916         if (userauth_range(pkt->type))
917             n_userauth++;
918 
919     if (s->pending_compression && !n_userauth) {
920         /*
921          * We're currently blocked from sending any outgoing packets
922          * until the other end tells us whether we're going to have to
923          * enable compression or not.
924          *
925          * If our end has pushed a userauth packet on the queue, that
926          * must mean it knows that a USERAUTH_SUCCESS is not
927          * immediately forthcoming, so we unblock ourselves and send
928          * up to and including that packet. But in this if statement,
929          * there aren't any, so we're still blocked.
930          */
931         return;
932     }
933 
934     if (s->cbc_ignore_workaround) {
935         /*
936          * When using a CBC-mode cipher in SSH-2, it's necessary to
937          * ensure that an attacker can't provide data to be encrypted
938          * using an IV that they know. We ensure this by inserting an
939          * SSH_MSG_IGNORE if the last cipher block of the previous
940          * packet has already been sent to the network (which we
941          * approximate conservatively by checking if it's vanished
942          * from out_raw).
943          */
944         if (bufchain_size(s->bpp.out_raw) <
945             (ssh_cipher_alg(s->out.cipher)->blksize +
946              ssh2_mac_alg(s->out.mac)->len)) {
947             /*
948              * There's less data in out_raw than the MAC size plus the
949              * cipher block size, which means at least one byte of
950              * that cipher block must already have left. Add an
951              * IGNORE.
952              */
953             pkt = ssh_bpp_new_pktout(&s->bpp, SSH2_MSG_IGNORE);
954             put_stringz(pkt, "");
955             ssh2_bpp_format_packet(s, pkt);
956         }
957     }
958 
959     while ((pkt = pq_pop(&s->bpp.out_pq)) != NULL) {
960         int type = pkt->type;
961 
962         if (userauth_range(type))
963             n_userauth--;
964 
965         ssh2_bpp_format_packet(s, pkt);
966         ssh_free_pktout(pkt);
967 
968         if (n_userauth == 0 && s->out.pending_compression && !s->is_server) {
969             /*
970              * This is the last userauth packet in the queue, so
971              * unless our side decides to send another one in future,
972              * we have to assume will potentially provoke
973              * USERAUTH_SUCCESS. Block (non-userauth) outgoing packets
974              * until we see the reply.
975              */
976             s->pending_compression = true;
977             return;
978         } else if (type == SSH2_MSG_USERAUTH_SUCCESS && s->is_server) {
979             ssh2_bpp_enable_pending_compression(s);
980         }
981     }
982 }
983