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