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