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