]> andersk Git - openssh.git/blob - packet.c
Import of Niels Provos' 20020312 ssh-complete.diff
[openssh.git] / packet.c
1 /*
2  * Author: Tatu Ylonen <ylo@cs.hut.fi>
3  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4  *                    All rights reserved
5  * This file contains code implementing the packet protocol and communication
6  * with the other side.  This same code is used both on client and server side.
7  *
8  * As far as I am concerned, the code I have written for this software
9  * can be used freely for any purpose.  Any derived versions of this
10  * software must be clearly marked as such, and if the derived work is
11  * incompatible with the protocol description in the RFC file, it must be
12  * called by a name other than "ssh" or "Secure Shell".
13  *
14  *
15  * SSH2 packet format added by Markus Friedl.
16  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
17  *
18  * Redistribution and use in source and binary forms, with or without
19  * modification, are permitted provided that the following conditions
20  * are met:
21  * 1. Redistributions of source code must retain the above copyright
22  *    notice, this list of conditions and the following disclaimer.
23  * 2. Redistributions in binary form must reproduce the above copyright
24  *    notice, this list of conditions and the following disclaimer in the
25  *    documentation and/or other materials provided with the distribution.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
28  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
29  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
30  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
31  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
32  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
33  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
34  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
35  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
36  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37  */
38
39 #include "includes.h"
40 RCSID("$OpenBSD: packet.c,v 1.90 2002/02/27 21:23:13 stevesk Exp $");
41
42 #include "xmalloc.h"
43 #include "buffer.h"
44 #include "packet.h"
45 #include "bufaux.h"
46 #include "crc32.h"
47 #include "getput.h"
48
49 #include "compress.h"
50 #include "deattack.h"
51 #include "channels.h"
52
53 #include "compat.h"
54 #include "ssh1.h"
55 #include "ssh2.h"
56
57 #include "cipher.h"
58 #include "kex.h"
59 #include "mac.h"
60 #include "log.h"
61 #include "canohost.h"
62 #include "misc.h"
63
64 #ifdef PACKET_DEBUG
65 #define DBG(x) x
66 #else
67 #define DBG(x)
68 #endif
69
70 /*
71  * This variable contains the file descriptors used for communicating with
72  * the other side.  connection_in is used for reading; connection_out for
73  * writing.  These can be the same descriptor, in which case it is assumed to
74  * be a socket.
75  */
76 static int connection_in = -1;
77 static int connection_out = -1;
78
79 /* Protocol flags for the remote side. */
80 static u_int remote_protocol_flags = 0;
81
82 /* Encryption context for receiving data.  This is only used for decryption. */
83 static CipherContext receive_context;
84
85 /* Encryption context for sending data.  This is only used for encryption. */
86 static CipherContext send_context;
87
88 /* Buffer for raw input data from the socket. */
89 static Buffer input;
90
91 /* Buffer for raw output data going to the socket. */
92 static Buffer output;
93
94 /* Buffer for the partial outgoing packet being constructed. */
95 static Buffer outgoing_packet;
96
97 /* Buffer for the incoming packet currently being processed. */
98 static Buffer incoming_packet;
99
100 /* Scratch buffer for packet compression/decompression. */
101 static Buffer compression_buffer;
102 static int compression_buffer_ready = 0;
103
104 /* Flag indicating whether packet compression/decompression is enabled. */
105 static int packet_compression = 0;
106
107 /* default maximum packet size */
108 int max_packet_size = 32768;
109
110 /* Flag indicating whether this module has been initialized. */
111 static int initialized = 0;
112
113 /* Set to true if the connection is interactive. */
114 static int interactive_mode = 0;
115
116 /* Session key information for Encryption and MAC */
117 Newkeys *newkeys[MODE_MAX];
118 static u_int32_t read_seqnr = 0;
119 static u_int32_t send_seqnr = 0;
120
121 /* roundup current message to extra_pad bytes */
122 static u_char extra_pad = 0;
123
124 /*
125  * Sets the descriptors used for communication.  Disables encryption until
126  * packet_set_encryption_key is called.
127  */
128 void
129 packet_set_connection(int fd_in, int fd_out)
130 {
131         Cipher *none = cipher_by_name("none");
132         if (none == NULL)
133                 fatal("packet_set_connection: cannot load cipher 'none'");
134         connection_in = fd_in;
135         connection_out = fd_out;
136         cipher_init(&send_context, none, "", 0, NULL, 0, CIPHER_ENCRYPT);
137         cipher_init(&receive_context, none, "", 0, NULL, 0, CIPHER_DECRYPT);
138         newkeys[MODE_IN] = newkeys[MODE_OUT] = NULL;
139         if (!initialized) {
140                 initialized = 1;
141                 buffer_init(&input);
142                 buffer_init(&output);
143                 buffer_init(&outgoing_packet);
144                 buffer_init(&incoming_packet);
145         }
146         /* Kludge: arrange the close function to be called from fatal(). */
147         fatal_add_cleanup((void (*) (void *)) packet_close, NULL);
148 }
149
150 /* Returns 1 if remote host is connected via socket, 0 if not. */
151
152 int
153 packet_connection_is_on_socket(void)
154 {
155         struct sockaddr_storage from, to;
156         socklen_t fromlen, tolen;
157
158         /* filedescriptors in and out are the same, so it's a socket */
159         if (connection_in == connection_out)
160                 return 1;
161         fromlen = sizeof(from);
162         memset(&from, 0, sizeof(from));
163         if (getpeername(connection_in, (struct sockaddr *)&from, &fromlen) < 0)
164                 return 0;
165         tolen = sizeof(to);
166         memset(&to, 0, sizeof(to));
167         if (getpeername(connection_out, (struct sockaddr *)&to, &tolen) < 0)
168                 return 0;
169         if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
170                 return 0;
171         if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
172                 return 0;
173         return 1;
174 }
175
176 /* 
177  * Exports an IV from the CipherContext required to export the key
178  * state back from the unprivileged child to the privileged parent
179  * process.
180  */
181
182 void
183 packet_get_keyiv(int mode, u_char *iv, u_int len)
184 {
185         CipherContext *cc;
186
187         if (mode == MODE_OUT)
188                 cc = &send_context;
189         else
190                 cc = &receive_context;
191
192         cipher_get_keyiv(cc, iv, len);
193 }
194
195 int
196 packet_get_keycontext(int mode, u_char *dat)
197 {
198         int plen;
199         CipherContext *cc;
200         
201         if (mode == MODE_OUT)
202                 cc = &send_context;
203         else
204                 cc = &receive_context;
205
206 #if OPENSSL_VERSION_NUMBER < 0x00907000L
207         plen = sizeof(cc->evp.c);
208 #else
209         plen = cc->evp.cipher->ctx_size;
210 #endif
211
212         if (dat == NULL)
213                 return (plen);
214
215 #if OPENSSL_VERSION_NUMBER < 0x00907000L
216         memcpy(dat, &cc->evp.c, sizeof(cc->evp.c));
217 #else
218         memcpy(dat, &cc->evp.cipher_data, plen);
219 #endif
220         return (plen);
221 }
222
223 void
224 packet_set_keycontext(int mode, u_char *dat)
225 {
226         CipherContext *cc;
227         
228         if (mode == MODE_OUT)
229                 cc = &send_context;
230         else
231                 cc = &receive_context;
232
233 #if OPENSSL_VERSION_NUMBER < 0x00907000L
234         memcpy(&cc->evp.c, dat, sizeof(cc->evp.c));
235 #else
236         memcpy(&cc->evp.cipher_data, dat, cc->evp.cipher->ctx_size);
237 #endif
238 }
239
240 u_int32_t
241 packet_get_seqnr(int mode)
242 {
243         return (mode == MODE_IN ? read_seqnr : send_seqnr);
244 }
245
246 void
247 packet_set_seqnr(int mode, u_int32_t seqnr)
248 {
249         if (mode == MODE_IN)
250                 read_seqnr = seqnr;
251         else if (mode == MODE_OUT)
252                 send_seqnr = seqnr;
253         else
254                 fatal("%s: bad mode %d", __FUNCTION__, mode);
255 }
256
257 /* returns 1 if connection is via ipv4 */
258
259 int
260 packet_connection_is_ipv4(void)
261 {
262         struct sockaddr_storage to;
263         socklen_t tolen = sizeof(to);
264
265         memset(&to, 0, sizeof(to));
266         if (getsockname(connection_out, (struct sockaddr *)&to, &tolen) < 0)
267                 return 0;
268         if (to.ss_family != AF_INET)
269                 return 0;
270         return 1;
271 }
272
273 /* Sets the connection into non-blocking mode. */
274
275 void
276 packet_set_nonblocking(void)
277 {
278         /* Set the socket into non-blocking mode. */
279         if (fcntl(connection_in, F_SETFL, O_NONBLOCK) < 0)
280                 error("fcntl O_NONBLOCK: %.100s", strerror(errno));
281
282         if (connection_out != connection_in) {
283                 if (fcntl(connection_out, F_SETFL, O_NONBLOCK) < 0)
284                         error("fcntl O_NONBLOCK: %.100s", strerror(errno));
285         }
286 }
287
288 /* Returns the socket used for reading. */
289
290 int
291 packet_get_connection_in(void)
292 {
293         return connection_in;
294 }
295
296 /* Returns the descriptor used for writing. */
297
298 int
299 packet_get_connection_out(void)
300 {
301         return connection_out;
302 }
303
304 /* Closes the connection and clears and frees internal data structures. */
305
306 void
307 packet_close(void)
308 {
309         if (!initialized)
310                 return;
311         initialized = 0;
312         if (connection_in == connection_out) {
313                 shutdown(connection_out, SHUT_RDWR);
314                 close(connection_out);
315         } else {
316                 close(connection_in);
317                 close(connection_out);
318         }
319         buffer_free(&input);
320         buffer_free(&output);
321         buffer_free(&outgoing_packet);
322         buffer_free(&incoming_packet);
323         if (compression_buffer_ready) {
324                 buffer_free(&compression_buffer);
325                 buffer_compress_uninit();
326         }
327         cipher_cleanup(&send_context);
328         cipher_cleanup(&receive_context);
329 }
330
331 /* Sets remote side protocol flags. */
332
333 void
334 packet_set_protocol_flags(u_int protocol_flags)
335 {
336         remote_protocol_flags = protocol_flags;
337 }
338
339 /* Returns the remote protocol flags set earlier by the above function. */
340
341 u_int
342 packet_get_protocol_flags(void)
343 {
344         return remote_protocol_flags;
345 }
346
347 /*
348  * Starts packet compression from the next packet on in both directions.
349  * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
350  */
351
352 static void
353 packet_init_compression(void)
354 {
355         if (compression_buffer_ready == 1)
356                 return;
357         compression_buffer_ready = 1;
358         buffer_init(&compression_buffer);
359 }
360
361 void
362 packet_start_compression(int level)
363 {
364         if (packet_compression && !compat20)
365                 fatal("Compression already enabled.");
366         packet_compression = 1;
367         packet_init_compression();
368         buffer_compress_init_send(level);
369         buffer_compress_init_recv();
370 }
371
372 /*
373  * Causes any further packets to be encrypted using the given key.  The same
374  * key is used for both sending and reception.  However, both directions are
375  * encrypted independently of each other.
376  */
377 void
378 packet_set_encryption_key(const u_char *key, u_int keylen,
379     int number)
380 {
381         Cipher *cipher = cipher_by_number(number);
382         if (cipher == NULL)
383                 fatal("packet_set_encryption_key: unknown cipher number %d", number);
384         if (keylen < 20)
385                 fatal("packet_set_encryption_key: keylen too small: %d", keylen);
386         cipher_init(&send_context, cipher, key, keylen, NULL, 0, CIPHER_ENCRYPT);
387         cipher_init(&receive_context, cipher, key, keylen, NULL, 0, CIPHER_DECRYPT);
388 }
389
390 /* Start constructing a packet to send. */
391 void
392 packet_start(u_char type)
393 {
394         u_char buf[9];
395         int len;
396
397         DBG(debug("packet_start[%d]", type));
398         len = compat20 ? 6 : 9;
399         memset(buf, 0, len - 1);
400         buf[len - 1] = type;
401         buffer_clear(&outgoing_packet);
402         buffer_append(&outgoing_packet, buf, len);
403 }
404
405 /* Append payload. */
406 void
407 packet_put_char(int value)
408 {
409         char ch = value;
410         buffer_append(&outgoing_packet, &ch, 1);
411 }
412 void
413 packet_put_int(u_int value)
414 {
415         buffer_put_int(&outgoing_packet, value);
416 }
417 void
418 packet_put_string(const void *buf, u_int len)
419 {
420         buffer_put_string(&outgoing_packet, buf, len);
421 }
422 void
423 packet_put_cstring(const char *str)
424 {
425         buffer_put_cstring(&outgoing_packet, str);
426 }
427 void
428 packet_put_raw(const void *buf, u_int len)
429 {
430         buffer_append(&outgoing_packet, buf, len);
431 }
432 void
433 packet_put_bignum(BIGNUM * value)
434 {
435         buffer_put_bignum(&outgoing_packet, value);
436 }
437 void
438 packet_put_bignum2(BIGNUM * value)
439 {
440         buffer_put_bignum2(&outgoing_packet, value);
441 }
442
443 /*
444  * Finalizes and sends the packet.  If the encryption key has been set,
445  * encrypts the packet before sending.
446  */
447
448 static void
449 packet_send1(void)
450 {
451         u_char buf[8], *cp;
452         int i, padding, len;
453         u_int checksum;
454         u_int32_t rand = 0;
455
456         /*
457          * If using packet compression, compress the payload of the outgoing
458          * packet.
459          */
460         if (packet_compression) {
461                 buffer_clear(&compression_buffer);
462                 /* Skip padding. */
463                 buffer_consume(&outgoing_packet, 8);
464                 /* padding */
465                 buffer_append(&compression_buffer, "\0\0\0\0\0\0\0\0", 8);
466                 buffer_compress(&outgoing_packet, &compression_buffer);
467                 buffer_clear(&outgoing_packet);
468                 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
469                     buffer_len(&compression_buffer));
470         }
471         /* Compute packet length without padding (add checksum, remove padding). */
472         len = buffer_len(&outgoing_packet) + 4 - 8;
473
474         /* Insert padding. Initialized to zero in packet_start1() */
475         padding = 8 - len % 8;
476         if (!send_context.plaintext) {
477                 cp = buffer_ptr(&outgoing_packet);
478                 for (i = 0; i < padding; i++) {
479                         if (i % 4 == 0)
480                                 rand = arc4random();
481                         cp[7 - i] = rand & 0xff;
482                         rand >>= 8;
483                 }
484         }
485         buffer_consume(&outgoing_packet, 8 - padding);
486
487         /* Add check bytes. */
488         checksum = ssh_crc32(buffer_ptr(&outgoing_packet),
489             buffer_len(&outgoing_packet));
490         PUT_32BIT(buf, checksum);
491         buffer_append(&outgoing_packet, buf, 4);
492
493 #ifdef PACKET_DEBUG
494         fprintf(stderr, "packet_send plain: ");
495         buffer_dump(&outgoing_packet);
496 #endif
497
498         /* Append to output. */
499         PUT_32BIT(buf, len);
500         buffer_append(&output, buf, 4);
501         cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
502         cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
503             buffer_len(&outgoing_packet));
504
505 #ifdef PACKET_DEBUG
506         fprintf(stderr, "encrypted: ");
507         buffer_dump(&output);
508 #endif
509
510         buffer_clear(&outgoing_packet);
511
512         /*
513          * Note that the packet is now only buffered in output.  It won\'t be
514          * actually sent until packet_write_wait or packet_write_poll is
515          * called.
516          */
517 }
518
519 void
520 set_newkeys(int mode)
521 {
522         Enc *enc;
523         Mac *mac;
524         Comp *comp;
525         CipherContext *cc;
526         int encrypt;
527
528         debug("newkeys: mode %d", mode);
529
530         if (mode == MODE_OUT) {
531                 cc = &send_context;
532                 encrypt = CIPHER_ENCRYPT;
533         } else {
534                 cc = &receive_context;
535                 encrypt = CIPHER_DECRYPT;
536         }
537         if (newkeys[mode] != NULL) {
538                 debug("newkeys: rekeying");
539                 cipher_cleanup(cc);
540                 enc  = &newkeys[mode]->enc;
541                 mac  = &newkeys[mode]->mac;
542                 comp = &newkeys[mode]->comp;
543                 memset(mac->key, 0, mac->key_len);
544                 xfree(enc->name);
545                 xfree(enc->iv);
546                 xfree(enc->key);
547                 xfree(mac->name);
548                 xfree(mac->key);
549                 xfree(comp->name);
550                 xfree(newkeys[mode]);
551         }
552         newkeys[mode] = kex_get_newkeys(mode);
553         if (newkeys[mode] == NULL)
554                 fatal("newkeys: no keys for mode %d", mode);
555         enc  = &newkeys[mode]->enc;
556         mac  = &newkeys[mode]->mac;
557         comp = &newkeys[mode]->comp;
558         if (mac->md != NULL)
559                 mac->enabled = 1;
560         DBG(debug("cipher_init_context: %d", mode));
561         cipher_init(cc, enc->cipher, enc->key, enc->key_len,
562             enc->iv, enc->block_size, encrypt);
563         /* Deleting the keys does not gain extra security */
564         /* memset(enc->iv,  0, enc->block_size);
565            memset(enc->key, 0, enc->key_len); */
566         if (comp->type != 0 && comp->enabled == 0) {
567                 packet_init_compression();
568                 if (mode == MODE_OUT)
569                         buffer_compress_init_send(6);
570                 else
571                         buffer_compress_init_recv();
572                 comp->enabled = 1;
573         }
574 }
575
576 /*
577  * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
578  */
579 static void
580 packet_send2(void)
581 {
582         u_char type, *cp, *macbuf = NULL;
583         u_char padlen, pad;
584         u_int packet_length = 0;
585         u_int i, len;
586         u_int32_t rand = 0;
587         Enc *enc   = NULL;
588         Mac *mac   = NULL;
589         Comp *comp = NULL;
590         int block_size;
591
592         if (newkeys[MODE_OUT] != NULL) {
593                 enc  = &newkeys[MODE_OUT]->enc;
594                 mac  = &newkeys[MODE_OUT]->mac;
595                 comp = &newkeys[MODE_OUT]->comp;
596         }
597         block_size = enc ? enc->block_size : 8;
598
599         cp = buffer_ptr(&outgoing_packet);
600         type = cp[5];
601
602 #ifdef PACKET_DEBUG
603         fprintf(stderr, "plain:     ");
604         buffer_dump(&outgoing_packet);
605 #endif
606
607         if (comp && comp->enabled) {
608                 len = buffer_len(&outgoing_packet);
609                 /* skip header, compress only payload */
610                 buffer_consume(&outgoing_packet, 5);
611                 buffer_clear(&compression_buffer);
612                 buffer_compress(&outgoing_packet, &compression_buffer);
613                 buffer_clear(&outgoing_packet);
614                 buffer_append(&outgoing_packet, "\0\0\0\0\0", 5);
615                 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
616                     buffer_len(&compression_buffer));
617                 DBG(debug("compression: raw %d compressed %d", len,
618                     buffer_len(&outgoing_packet)));
619         }
620
621         /* sizeof (packet_len + pad_len + payload) */
622         len = buffer_len(&outgoing_packet);
623
624         /*
625          * calc size of padding, alloc space, get random data,
626          * minimum padding is 4 bytes
627          */
628         padlen = block_size - (len % block_size);
629         if (padlen < 4)
630                 padlen += block_size;
631         if (extra_pad) {
632                 /* will wrap if extra_pad+padlen > 255 */
633                 extra_pad  = roundup(extra_pad, block_size);
634                 pad = extra_pad - ((len + padlen) % extra_pad);
635                 debug("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
636                     pad, len, padlen, extra_pad);
637                 padlen += pad;
638                 extra_pad = 0;
639         }
640         cp = buffer_append_space(&outgoing_packet, padlen);
641         if (enc && !send_context.plaintext) {
642                 /* random padding */
643                 for (i = 0; i < padlen; i++) {
644                         if (i % 4 == 0)
645                                 rand = arc4random();
646                         cp[i] = rand & 0xff;
647                         rand >>= 8;
648                 }
649         } else {
650                 /* clear padding */
651                 memset(cp, 0, padlen);
652         }
653         /* packet_length includes payload, padding and padding length field */
654         packet_length = buffer_len(&outgoing_packet) - 4;
655         cp = buffer_ptr(&outgoing_packet);
656         PUT_32BIT(cp, packet_length);
657         cp[4] = padlen;
658         DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
659
660         /* compute MAC over seqnr and packet(length fields, payload, padding) */
661         if (mac && mac->enabled) {
662                 macbuf = mac_compute(mac, send_seqnr,
663                     buffer_ptr(&outgoing_packet),
664                     buffer_len(&outgoing_packet));
665                 DBG(debug("done calc MAC out #%d", send_seqnr));
666         }
667         /* encrypt packet and append to output buffer. */
668         cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
669         cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
670             buffer_len(&outgoing_packet));
671         /* append unencrypted MAC */
672         if (mac && mac->enabled)
673                 buffer_append(&output, (char *)macbuf, mac->mac_len);
674 #ifdef PACKET_DEBUG
675         fprintf(stderr, "encrypted: ");
676         buffer_dump(&output);
677 #endif
678         /* increment sequence number for outgoing packets */
679         if (++send_seqnr == 0)
680                 log("outgoing seqnr wraps around");
681         buffer_clear(&outgoing_packet);
682
683         if (type == SSH2_MSG_NEWKEYS)
684                 set_newkeys(MODE_OUT);
685 }
686
687 void
688 packet_send(void)
689 {
690         if (compat20)
691                 packet_send2();
692         else
693                 packet_send1();
694         DBG(debug("packet_send done"));
695 }
696
697 /*
698  * Waits until a packet has been received, and returns its type.  Note that
699  * no other data is processed until this returns, so this function should not
700  * be used during the interactive session.
701  */
702
703 int
704 packet_read_seqnr(u_int32_t *seqnr_p)
705 {
706         int type, len;
707         fd_set *setp;
708         char buf[8192];
709         DBG(debug("packet_read()"));
710
711         setp = (fd_set *)xmalloc(howmany(connection_in+1, NFDBITS) *
712             sizeof(fd_mask));
713
714         /* Since we are blocking, ensure that all written packets have been sent. */
715         packet_write_wait();
716
717         /* Stay in the loop until we have received a complete packet. */
718         for (;;) {
719                 /* Try to read a packet from the buffer. */
720                 type = packet_read_poll_seqnr(seqnr_p);
721                 if (!compat20 && (
722                     type == SSH_SMSG_SUCCESS
723                     || type == SSH_SMSG_FAILURE
724                     || type == SSH_CMSG_EOF
725                     || type == SSH_CMSG_EXIT_CONFIRMATION))
726                         packet_check_eom();
727                 /* If we got a packet, return it. */
728                 if (type != SSH_MSG_NONE) {
729                         xfree(setp);
730                         return type;
731                 }
732                 /*
733                  * Otherwise, wait for some data to arrive, add it to the
734                  * buffer, and try again.
735                  */
736                 memset(setp, 0, howmany(connection_in + 1, NFDBITS) *
737                     sizeof(fd_mask));
738                 FD_SET(connection_in, setp);
739
740                 /* Wait for some data to arrive. */
741                 while (select(connection_in + 1, setp, NULL, NULL, NULL) == -1 &&
742                     (errno == EAGAIN || errno == EINTR))
743                         ;
744
745                 /* Read data from the socket. */
746                 len = read(connection_in, buf, sizeof(buf));
747                 if (len == 0) {
748                         log("Connection closed by %.200s", get_remote_ipaddr());
749                         fatal_cleanup();
750                 }
751                 if (len < 0)
752                         fatal("Read from socket failed: %.100s", strerror(errno));
753                 /* Append it to the buffer. */
754                 packet_process_incoming(buf, len);
755         }
756         /* NOTREACHED */
757 }
758
759 int
760 packet_read(void)
761 {
762         return packet_read_seqnr(NULL);
763 }
764
765 /*
766  * Waits until a packet has been received, verifies that its type matches
767  * that given, and gives a fatal error and exits if there is a mismatch.
768  */
769
770 void
771 packet_read_expect(int expected_type)
772 {
773         int type;
774
775         type = packet_read();
776         if (type != expected_type)
777                 packet_disconnect("Protocol error: expected packet type %d, got %d",
778                     expected_type, type);
779 }
780
781 /* Checks if a full packet is available in the data received so far via
782  * packet_process_incoming.  If so, reads the packet; otherwise returns
783  * SSH_MSG_NONE.  This does not wait for data from the connection.
784  *
785  * SSH_MSG_DISCONNECT is handled specially here.  Also,
786  * SSH_MSG_IGNORE messages are skipped by this function and are never returned
787  * to higher levels.
788  */
789
790 static int
791 packet_read_poll1(void)
792 {
793         u_int len, padded_len;
794         u_char *cp, type;
795         u_int checksum, stored_checksum;
796
797         /* Check if input size is less than minimum packet size. */
798         if (buffer_len(&input) < 4 + 8)
799                 return SSH_MSG_NONE;
800         /* Get length of incoming packet. */
801         cp = buffer_ptr(&input);
802         len = GET_32BIT(cp);
803         if (len < 1 + 2 + 2 || len > 256 * 1024)
804                 packet_disconnect("Bad packet length %d.", len);
805         padded_len = (len + 8) & ~7;
806
807         /* Check if the packet has been entirely received. */
808         if (buffer_len(&input) < 4 + padded_len)
809                 return SSH_MSG_NONE;
810
811         /* The entire packet is in buffer. */
812
813         /* Consume packet length. */
814         buffer_consume(&input, 4);
815
816         /*
817          * Cryptographic attack detector for ssh
818          * (C)1998 CORE-SDI, Buenos Aires Argentina
819          * Ariel Futoransky(futo@core-sdi.com)
820          */
821         if (!receive_context.plaintext &&
822             detect_attack(buffer_ptr(&input), padded_len, NULL) == DEATTACK_DETECTED)
823                 packet_disconnect("crc32 compensation attack: network attack detected");
824
825         /* Decrypt data to incoming_packet. */
826         buffer_clear(&incoming_packet);
827         cp = buffer_append_space(&incoming_packet, padded_len);
828         cipher_crypt(&receive_context, cp, buffer_ptr(&input), padded_len);
829
830         buffer_consume(&input, padded_len);
831
832 #ifdef PACKET_DEBUG
833         fprintf(stderr, "read_poll plain: ");
834         buffer_dump(&incoming_packet);
835 #endif
836
837         /* Compute packet checksum. */
838         checksum = ssh_crc32(buffer_ptr(&incoming_packet),
839             buffer_len(&incoming_packet) - 4);
840
841         /* Skip padding. */
842         buffer_consume(&incoming_packet, 8 - len % 8);
843
844         /* Test check bytes. */
845         if (len != buffer_len(&incoming_packet))
846                 packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
847                     len, buffer_len(&incoming_packet));
848
849         cp = (u_char *)buffer_ptr(&incoming_packet) + len - 4;
850         stored_checksum = GET_32BIT(cp);
851         if (checksum != stored_checksum)
852                 packet_disconnect("Corrupted check bytes on input.");
853         buffer_consume_end(&incoming_packet, 4);
854
855         if (packet_compression) {
856                 buffer_clear(&compression_buffer);
857                 buffer_uncompress(&incoming_packet, &compression_buffer);
858                 buffer_clear(&incoming_packet);
859                 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
860                     buffer_len(&compression_buffer));
861         }
862         type = buffer_get_char(&incoming_packet);
863         return type;
864 }
865
866 static int
867 packet_read_poll2(u_int32_t *seqnr_p)
868 {
869         static u_int packet_length = 0;
870         u_int padlen, need;
871         u_char *macbuf, *cp, type;
872         int maclen, block_size;
873         Enc *enc   = NULL;
874         Mac *mac   = NULL;
875         Comp *comp = NULL;
876
877         if (newkeys[MODE_IN] != NULL) {
878                 enc  = &newkeys[MODE_IN]->enc;
879                 mac  = &newkeys[MODE_IN]->mac;
880                 comp = &newkeys[MODE_IN]->comp;
881         }
882         maclen = mac && mac->enabled ? mac->mac_len : 0;
883         block_size = enc ? enc->block_size : 8;
884
885         if (packet_length == 0) {
886                 /*
887                  * check if input size is less than the cipher block size,
888                  * decrypt first block and extract length of incoming packet
889                  */
890                 if (buffer_len(&input) < block_size)
891                         return SSH_MSG_NONE;
892                 buffer_clear(&incoming_packet);
893                 cp = buffer_append_space(&incoming_packet, block_size);
894                 cipher_crypt(&receive_context, cp, buffer_ptr(&input),
895                     block_size);
896                 cp = buffer_ptr(&incoming_packet);
897                 packet_length = GET_32BIT(cp);
898                 if (packet_length < 1 + 4 || packet_length > 256 * 1024) {
899                         buffer_dump(&incoming_packet);
900                         packet_disconnect("Bad packet length %d.", packet_length);
901                 }
902                 DBG(debug("input: packet len %d", packet_length+4));
903                 buffer_consume(&input, block_size);
904         }
905         /* we have a partial packet of block_size bytes */
906         need = 4 + packet_length - block_size;
907         DBG(debug("partial packet %d, need %d, maclen %d", block_size,
908             need, maclen));
909         if (need % block_size != 0)
910                 fatal("padding error: need %d block %d mod %d",
911                     need, block_size, need % block_size);
912         /*
913          * check if the entire packet has been received and
914          * decrypt into incoming_packet
915          */
916         if (buffer_len(&input) < need + maclen)
917                 return SSH_MSG_NONE;
918 #ifdef PACKET_DEBUG
919         fprintf(stderr, "read_poll enc/full: ");
920         buffer_dump(&input);
921 #endif
922         cp = buffer_append_space(&incoming_packet, need);
923         cipher_crypt(&receive_context, cp, buffer_ptr(&input), need);
924         buffer_consume(&input, need);
925         /*
926          * compute MAC over seqnr and packet,
927          * increment sequence number for incoming packet
928          */
929         if (mac && mac->enabled) {
930                 macbuf = mac_compute(mac, read_seqnr,
931                     buffer_ptr(&incoming_packet),
932                     buffer_len(&incoming_packet));
933                 if (memcmp(macbuf, buffer_ptr(&input), mac->mac_len) != 0)
934                         packet_disconnect("Corrupted MAC on input.");
935                 DBG(debug("MAC #%d ok", read_seqnr));
936                 buffer_consume(&input, mac->mac_len);
937         }
938         if (seqnr_p != NULL)
939                 *seqnr_p = read_seqnr;
940         if (++read_seqnr == 0)
941                 log("incoming seqnr wraps around");
942
943         /* get padlen */
944         cp = buffer_ptr(&incoming_packet);
945         padlen = cp[4];
946         DBG(debug("input: padlen %d", padlen));
947         if (padlen < 4)
948                 packet_disconnect("Corrupted padlen %d on input.", padlen);
949
950         /* skip packet size + padlen, discard padding */
951         buffer_consume(&incoming_packet, 4 + 1);
952         buffer_consume_end(&incoming_packet, padlen);
953
954         DBG(debug("input: len before de-compress %d", buffer_len(&incoming_packet)));
955         if (comp && comp->enabled) {
956                 buffer_clear(&compression_buffer);
957                 buffer_uncompress(&incoming_packet, &compression_buffer);
958                 buffer_clear(&incoming_packet);
959                 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
960                     buffer_len(&compression_buffer));
961                 DBG(debug("input: len after de-compress %d", buffer_len(&incoming_packet)));
962         }
963         /*
964          * get packet type, implies consume.
965          * return length of payload (without type field)
966          */
967         type = buffer_get_char(&incoming_packet);
968         if (type == SSH2_MSG_NEWKEYS)
969                 set_newkeys(MODE_IN);
970 #ifdef PACKET_DEBUG
971         fprintf(stderr, "read/plain[%d]:\r\n", type);
972         buffer_dump(&incoming_packet);
973 #endif
974         /* reset for next packet */
975         packet_length = 0;
976         return type;
977 }
978
979 int
980 packet_read_poll_seqnr(u_int32_t *seqnr_p)
981 {
982         int reason, seqnr;
983         u_char type;
984         char *msg;
985
986         for (;;) {
987                 if (compat20) {
988                         type = packet_read_poll2(seqnr_p);
989                         if (type)
990                                 DBG(debug("received packet type %d", type));
991                         switch (type) {
992                         case SSH2_MSG_IGNORE:
993                                 break;
994                         case SSH2_MSG_DEBUG:
995                                 packet_get_char();
996                                 msg = packet_get_string(NULL);
997                                 debug("Remote: %.900s", msg);
998                                 xfree(msg);
999                                 msg = packet_get_string(NULL);
1000                                 xfree(msg);
1001                                 break;
1002                         case SSH2_MSG_DISCONNECT:
1003                                 reason = packet_get_int();
1004                                 msg = packet_get_string(NULL);
1005                                 log("Received disconnect from %s: %d: %.400s", get_remote_ipaddr(),
1006                                         reason, msg);
1007                                 xfree(msg);
1008                                 fatal_cleanup();
1009                                 break;
1010                         case SSH2_MSG_UNIMPLEMENTED:
1011                                 seqnr = packet_get_int();
1012                                 debug("Received SSH2_MSG_UNIMPLEMENTED for %d", seqnr);
1013                                 break;
1014                         default:
1015                                 return type;
1016                                 break;
1017                         }
1018                 } else {
1019                         type = packet_read_poll1();
1020                         switch (type) {
1021                         case SSH_MSG_IGNORE:
1022                                 break;
1023                         case SSH_MSG_DEBUG:
1024                                 msg = packet_get_string(NULL);
1025                                 debug("Remote: %.900s", msg);
1026                                 xfree(msg);
1027                                 break;
1028                         case SSH_MSG_DISCONNECT:
1029                                 msg = packet_get_string(NULL);
1030                                 log("Received disconnect from %s: %.400s", get_remote_ipaddr(),
1031                                         msg);
1032                                 fatal_cleanup();
1033                                 xfree(msg);
1034                                 break;
1035                         default:
1036                                 if (type)
1037                                         DBG(debug("received packet type %d", type));
1038                                 return type;
1039                                 break;
1040                         }
1041                 }
1042         }
1043 }
1044
1045 int
1046 packet_read_poll(void)
1047 {
1048         return packet_read_poll_seqnr(NULL);
1049 }
1050
1051 /*
1052  * Buffers the given amount of input characters.  This is intended to be used
1053  * together with packet_read_poll.
1054  */
1055
1056 void
1057 packet_process_incoming(const char *buf, u_int len)
1058 {
1059         buffer_append(&input, buf, len);
1060 }
1061
1062 /* Returns a character from the packet. */
1063
1064 u_int
1065 packet_get_char(void)
1066 {
1067         char ch;
1068         buffer_get(&incoming_packet, &ch, 1);
1069         return (u_char) ch;
1070 }
1071
1072 /* Returns an integer from the packet data. */
1073
1074 u_int
1075 packet_get_int(void)
1076 {
1077         return buffer_get_int(&incoming_packet);
1078 }
1079
1080 /*
1081  * Returns an arbitrary precision integer from the packet data.  The integer
1082  * must have been initialized before this call.
1083  */
1084
1085 void
1086 packet_get_bignum(BIGNUM * value)
1087 {
1088         buffer_get_bignum(&incoming_packet, value);
1089 }
1090
1091 void
1092 packet_get_bignum2(BIGNUM * value)
1093 {
1094         buffer_get_bignum2(&incoming_packet, value);
1095 }
1096
1097 void *
1098 packet_get_raw(int *length_ptr)
1099 {
1100         int bytes = buffer_len(&incoming_packet);
1101         if (length_ptr != NULL)
1102                 *length_ptr = bytes;
1103         return buffer_ptr(&incoming_packet);
1104 }
1105
1106 int
1107 packet_remaining(void)
1108 {
1109         return buffer_len(&incoming_packet);
1110 }
1111
1112 /*
1113  * Returns a string from the packet data.  The string is allocated using
1114  * xmalloc; it is the responsibility of the calling program to free it when
1115  * no longer needed.  The length_ptr argument may be NULL, or point to an
1116  * integer into which the length of the string is stored.
1117  */
1118
1119 void *
1120 packet_get_string(u_int *length_ptr)
1121 {
1122         return buffer_get_string(&incoming_packet, length_ptr);
1123 }
1124
1125 /*
1126  * Sends a diagnostic message from the server to the client.  This message
1127  * can be sent at any time (but not while constructing another message). The
1128  * message is printed immediately, but only if the client is being executed
1129  * in verbose mode.  These messages are primarily intended to ease debugging
1130  * authentication problems.   The length of the formatted message must not
1131  * exceed 1024 bytes.  This will automatically call packet_write_wait.
1132  */
1133
1134 void
1135 packet_send_debug(const char *fmt,...)
1136 {
1137         char buf[1024];
1138         va_list args;
1139
1140         if (compat20 && (datafellows & SSH_BUG_DEBUG))
1141                 return;
1142
1143         va_start(args, fmt);
1144         vsnprintf(buf, sizeof(buf), fmt, args);
1145         va_end(args);
1146
1147         if (compat20) {
1148                 packet_start(SSH2_MSG_DEBUG);
1149                 packet_put_char(0);     /* bool: always display */
1150                 packet_put_cstring(buf);
1151                 packet_put_cstring("");
1152         } else {
1153                 packet_start(SSH_MSG_DEBUG);
1154                 packet_put_cstring(buf);
1155         }
1156         packet_send();
1157         packet_write_wait();
1158 }
1159
1160 /*
1161  * Logs the error plus constructs and sends a disconnect packet, closes the
1162  * connection, and exits.  This function never returns. The error message
1163  * should not contain a newline.  The length of the formatted message must
1164  * not exceed 1024 bytes.
1165  */
1166
1167 void
1168 packet_disconnect(const char *fmt,...)
1169 {
1170         char buf[1024];
1171         va_list args;
1172         static int disconnecting = 0;
1173         if (disconnecting)      /* Guard against recursive invocations. */
1174                 fatal("packet_disconnect called recursively.");
1175         disconnecting = 1;
1176
1177         /*
1178          * Format the message.  Note that the caller must make sure the
1179          * message is of limited size.
1180          */
1181         va_start(args, fmt);
1182         vsnprintf(buf, sizeof(buf), fmt, args);
1183         va_end(args);
1184
1185         /* Send the disconnect message to the other side, and wait for it to get sent. */
1186         if (compat20) {
1187                 packet_start(SSH2_MSG_DISCONNECT);
1188                 packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
1189                 packet_put_cstring(buf);
1190                 packet_put_cstring("");
1191         } else {
1192                 packet_start(SSH_MSG_DISCONNECT);
1193                 packet_put_cstring(buf);
1194         }
1195         packet_send();
1196         packet_write_wait();
1197
1198         /* Stop listening for connections. */
1199         channel_close_all();
1200
1201         /* Close the connection. */
1202         packet_close();
1203
1204         /* Display the error locally and exit. */
1205         log("Disconnecting: %.100s", buf);
1206         fatal_cleanup();
1207 }
1208
1209 /* Checks if there is any buffered output, and tries to write some of the output. */
1210
1211 void
1212 packet_write_poll(void)
1213 {
1214         int len = buffer_len(&output);
1215         if (len > 0) {
1216                 len = write(connection_out, buffer_ptr(&output), len);
1217                 if (len <= 0) {
1218                         if (errno == EAGAIN)
1219                                 return;
1220                         else
1221                                 fatal("Write failed: %.100s", strerror(errno));
1222                 }
1223                 buffer_consume(&output, len);
1224         }
1225 }
1226
1227 /*
1228  * Calls packet_write_poll repeatedly until all pending output data has been
1229  * written.
1230  */
1231
1232 void
1233 packet_write_wait(void)
1234 {
1235         fd_set *setp;
1236
1237         setp = (fd_set *)xmalloc(howmany(connection_out + 1, NFDBITS) *
1238             sizeof(fd_mask));
1239         packet_write_poll();
1240         while (packet_have_data_to_write()) {
1241                 memset(setp, 0, howmany(connection_out + 1, NFDBITS) *
1242                     sizeof(fd_mask));
1243                 FD_SET(connection_out, setp);
1244                 while (select(connection_out + 1, NULL, setp, NULL, NULL) == -1 &&
1245                     (errno == EAGAIN || errno == EINTR))
1246                         ;
1247                 packet_write_poll();
1248         }
1249         xfree(setp);
1250 }
1251
1252 /* Returns true if there is buffered data to write to the connection. */
1253
1254 int
1255 packet_have_data_to_write(void)
1256 {
1257         return buffer_len(&output) != 0;
1258 }
1259
1260 /* Returns true if there is not too much data to write to the connection. */
1261
1262 int
1263 packet_not_very_much_data_to_write(void)
1264 {
1265         if (interactive_mode)
1266                 return buffer_len(&output) < 16384;
1267         else
1268                 return buffer_len(&output) < 128 * 1024;
1269 }
1270
1271 /* Informs that the current session is interactive.  Sets IP flags for that. */
1272
1273 void
1274 packet_set_interactive(int interactive)
1275 {
1276         static int called = 0;
1277 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1278         int lowdelay = IPTOS_LOWDELAY;
1279         int throughput = IPTOS_THROUGHPUT;
1280 #endif
1281
1282         if (called)
1283                 return;
1284         called = 1;
1285
1286         /* Record that we are in interactive mode. */
1287         interactive_mode = interactive;
1288
1289         /* Only set socket options if using a socket.  */
1290         if (!packet_connection_is_on_socket())
1291                 return;
1292         /*
1293          * IPTOS_LOWDELAY and IPTOS_THROUGHPUT are IPv4 only
1294          */
1295         if (interactive) {
1296                 /*
1297                  * Set IP options for an interactive connection.  Use
1298                  * IPTOS_LOWDELAY and TCP_NODELAY.
1299                  */
1300 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1301                 if (packet_connection_is_ipv4()) {
1302                         if (setsockopt(connection_in, IPPROTO_IP, IP_TOS,
1303                             &lowdelay, sizeof(lowdelay)) < 0)
1304                                 error("setsockopt IPTOS_LOWDELAY: %.100s",
1305                                     strerror(errno));
1306                 }
1307 #endif
1308                 set_nodelay(connection_in);
1309         } else if (packet_connection_is_ipv4()) {
1310                 /*
1311                  * Set IP options for a non-interactive connection.  Use
1312                  * IPTOS_THROUGHPUT.
1313                  */
1314 #if defined(IP_TOS) && !defined(IP_TOS_IS_BROKEN)
1315                 if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, &throughput,
1316                     sizeof(throughput)) < 0)
1317                         error("setsockopt IPTOS_THROUGHPUT: %.100s", strerror(errno));
1318 #endif
1319         }
1320 }
1321
1322 /* Returns true if the current connection is interactive. */
1323
1324 int
1325 packet_is_interactive(void)
1326 {
1327         return interactive_mode;
1328 }
1329
1330 int
1331 packet_set_maxsize(int s)
1332 {
1333         static int called = 0;
1334         if (called) {
1335                 log("packet_set_maxsize: called twice: old %d new %d",
1336                     max_packet_size, s);
1337                 return -1;
1338         }
1339         if (s < 4 * 1024 || s > 1024 * 1024) {
1340                 log("packet_set_maxsize: bad size %d", s);
1341                 return -1;
1342         }
1343         called = 1;
1344         debug("packet_set_maxsize: setting to %d", s);
1345         max_packet_size = s;
1346         return s;
1347 }
1348
1349 /* roundup current message to pad bytes */
1350 void
1351 packet_add_padding(u_char pad)
1352 {
1353         extra_pad = pad;
1354 }
1355
1356 /*
1357  * 9.2.  Ignored Data Message
1358  *
1359  *   byte      SSH_MSG_IGNORE
1360  *   string    data
1361  *
1362  * All implementations MUST understand (and ignore) this message at any
1363  * time (after receiving the protocol version). No implementation is
1364  * required to send them. This message can be used as an additional
1365  * protection measure against advanced traffic analysis techniques.
1366  */
1367 void
1368 packet_send_ignore(int nbytes)
1369 {
1370         u_int32_t rand = 0;
1371         int i;
1372
1373         packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1374         packet_put_int(nbytes);
1375         for (i = 0; i < nbytes; i++) {
1376                 if (i % 4 == 0)
1377                         rand = arc4random();
1378                 packet_put_char(rand & 0xff);
1379                 rand >>= 8;
1380         }
1381 }
This page took 0.143132 seconds and 5 git commands to generate.