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