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