5 Author: Tatu Ylonen <ylo@cs.hut.fi>
7 Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
10 Created: Sat Mar 18 02:40:40 1995 ylo
12 This file contains code implementing the packet protocol and communication
13 with the other side. This same code is used both on client and server side.
32 /* This variable contains the file descriptors used for communicating with
33 the other side. connection_in is used for reading; connection_out
34 for writing. These can be the same descriptor, in which case it is
35 assumed to be a socket. */
36 static int connection_in = -1;
37 static int connection_out = -1;
39 /* Cipher type. This value is only used to determine whether to pad the
40 packets with zeroes or random data. */
41 static int cipher_type = SSH_CIPHER_NONE;
43 /* Protocol flags for the remote side. */
44 static unsigned int remote_protocol_flags = 0;
46 /* Encryption context for receiving data. This is only used for decryption. */
47 static CipherContext receive_context;
48 /* Encryption coontext for sending data. This is only used for encryption. */
49 static CipherContext send_context;
51 /* Buffer for raw input data from the socket. */
54 /* Buffer for raw output data going to the socket. */
57 /* Buffer for the partial outgoing packet being constructed. */
58 static Buffer outgoing_packet;
60 /* Buffer for the incoming packet currently being processed. */
61 static Buffer incoming_packet;
63 /* Scratch buffer for packet compression/decompression. */
64 static Buffer compression_buffer;
66 /* Flag indicating whether packet compression/decompression is enabled. */
67 static int packet_compression = 0;
69 /* default maximum packet size */
70 int max_packet_size = 32768;
72 /* Flag indicating whether this module has been initialized. */
73 static int initialized = 0;
75 /* Set to true if the connection is interactive. */
76 static int interactive_mode = 0;
78 /* Sets the descriptors used for communication. Disables encryption until
79 packet_set_encryption_key is called. */
82 packet_set_connection(int fd_in, int fd_out)
84 connection_in = fd_in;
85 connection_out = fd_out;
86 cipher_type = SSH_CIPHER_NONE;
87 cipher_set_key(&send_context, SSH_CIPHER_NONE, (unsigned char *)"", 0, 1);
88 cipher_set_key(&receive_context, SSH_CIPHER_NONE, (unsigned char *)"", 0, 0);
94 buffer_init(&outgoing_packet);
95 buffer_init(&incoming_packet);
98 /* Kludge: arrange the close function to be called from fatal(). */
99 fatal_add_cleanup((void (*)(void *))packet_close, NULL);
102 /* Sets the connection into non-blocking mode. */
105 packet_set_nonblocking()
107 /* Set the socket into non-blocking mode. */
108 if (fcntl(connection_in, F_SETFL, O_NONBLOCK) < 0)
109 error("fcntl O_NONBLOCK: %.100s", strerror(errno));
111 if (connection_out != connection_in)
113 if (fcntl(connection_out, F_SETFL, O_NONBLOCK) < 0)
114 error("fcntl O_NONBLOCK: %.100s", strerror(errno));
118 /* Returns the socket used for reading. */
121 packet_get_connection_in()
123 return connection_in;
126 /* Returns the descriptor used for writing. */
129 packet_get_connection_out()
131 return connection_out;
134 /* Closes the connection and clears and frees internal data structures. */
142 if (connection_in == connection_out)
144 shutdown(connection_out, SHUT_RDWR);
145 close(connection_out);
149 close(connection_in);
150 close(connection_out);
153 buffer_free(&output);
154 buffer_free(&outgoing_packet);
155 buffer_free(&incoming_packet);
156 if (packet_compression)
158 buffer_free(&compression_buffer);
159 buffer_compress_uninit();
163 /* Sets remote side protocol flags. */
166 packet_set_protocol_flags(unsigned int protocol_flags)
168 remote_protocol_flags = protocol_flags;
169 channel_set_options((protocol_flags & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) != 0);
172 /* Returns the remote protocol flags set earlier by the above function. */
175 packet_get_protocol_flags()
177 return remote_protocol_flags;
180 /* Starts packet compression from the next packet on in both directions.
181 Level is compression level 1 (fastest) - 9 (slow, best) as in gzip. */
184 packet_start_compression(int level)
186 if (packet_compression)
187 fatal("Compression already enabled.");
188 packet_compression = 1;
189 buffer_init(&compression_buffer);
190 buffer_compress_init(level);
193 /* Encrypts the given number of bytes, copying from src to dest.
194 bytes is known to be a multiple of 8. */
197 packet_encrypt(CipherContext *cc, void *dest, void *src,
200 cipher_encrypt(cc, dest, src, bytes);
203 /* Decrypts the given number of bytes, copying from src to dest.
204 bytes is known to be a multiple of 8. */
207 packet_decrypt(CipherContext *cc, void *dest, void *src,
212 if ((bytes % 8) != 0)
213 fatal("packet_decrypt: bad ciphertext length %d", bytes);
216 Cryptographic attack detector for ssh - Modifications for packet.c
217 (C)1998 CORE-SDI, Buenos Aires Argentina
218 Ariel Futoransky(futo@core-sdi.com)
222 case SSH_CIPHER_NONE:
226 i = detect_attack(src, bytes, NULL);
230 if (i == DEATTACK_DETECTED)
231 packet_disconnect("crc32 compensation attack: network attack detected");
233 cipher_decrypt(cc, dest, src, bytes);
236 /* Causes any further packets to be encrypted using the given key. The same
237 key is used for both sending and reception. However, both directions
238 are encrypted independently of each other. */
241 packet_set_encryption_key(const unsigned char *key, unsigned int keylen,
244 /* All other ciphers use the same key in both directions for now. */
245 cipher_set_key(&receive_context, cipher, key, keylen, 0);
246 cipher_set_key(&send_context, cipher, key, keylen, 1);
249 /* Starts constructing a packet to send. */
252 packet_start(int type)
256 buffer_clear(&outgoing_packet);
259 buffer_append(&outgoing_packet, buf, 9);
262 /* Appends a character to the packet data. */
265 packet_put_char(int value)
268 buffer_append(&outgoing_packet, &ch, 1);
271 /* Appends an integer to the packet data. */
274 packet_put_int(unsigned int value)
276 buffer_put_int(&outgoing_packet, value);
279 /* Appends a string to packet data. */
282 packet_put_string(const char *buf, unsigned int len)
284 buffer_put_string(&outgoing_packet, buf, len);
287 /* Appends an arbitrary precision integer to packet data. */
290 packet_put_bignum(BIGNUM *value)
292 buffer_put_bignum(&outgoing_packet, value);
295 /* Finalizes and sends the packet. If the encryption key has been set,
296 encrypts the packet before sending. */
303 unsigned int checksum;
306 /* If using packet compression, compress the payload of the outgoing
308 if (packet_compression)
310 buffer_clear(&compression_buffer);
311 buffer_consume(&outgoing_packet, 8); /* Skip padding. */
312 buffer_append(&compression_buffer, "\0\0\0\0\0\0\0\0", 8); /* padding */
313 buffer_compress(&outgoing_packet, &compression_buffer);
314 buffer_clear(&outgoing_packet);
315 buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
316 buffer_len(&compression_buffer));
319 /* Compute packet length without padding (add checksum, remove padding). */
320 len = buffer_len(&outgoing_packet) + 4 - 8;
322 /* Insert padding. */
323 padding = 8 - len % 8;
324 if (cipher_type != SSH_CIPHER_NONE)
326 cp = buffer_ptr(&outgoing_packet);
327 for (i = 0; i < padding; i++) {
330 cp[7 - i] = rand & 0xff;
334 buffer_consume(&outgoing_packet, 8 - padding);
336 /* Add check bytes. */
337 checksum = crc32((unsigned char *)buffer_ptr(&outgoing_packet),
338 buffer_len(&outgoing_packet));
339 PUT_32BIT(buf, checksum);
340 buffer_append(&outgoing_packet, buf, 4);
343 fprintf(stderr, "packet_send plain: ");
344 buffer_dump(&outgoing_packet);
347 /* Append to output. */
349 buffer_append(&output, buf, 4);
350 buffer_append_space(&output, &cp, buffer_len(&outgoing_packet));
351 packet_encrypt(&send_context, cp, buffer_ptr(&outgoing_packet),
352 buffer_len(&outgoing_packet));
355 fprintf(stderr, "encrypted: "); buffer_dump(&output);
358 buffer_clear(&outgoing_packet);
360 /* Note that the packet is now only buffered in output. It won\'t be
361 actually sent until packet_write_wait or packet_write_poll is called. */
364 /* Waits until a packet has been received, and returns its type. Note that
365 no other data is processed until this returns, so this function should
366 not be used during the interactive session. */
369 packet_read(int *payload_len_ptr)
375 /* Since we are blocking, ensure that all written packets have been sent. */
378 /* Stay in the loop until we have received a complete packet. */
381 /* Try to read a packet from the buffer. */
382 type = packet_read_poll(payload_len_ptr);
383 if (type == SSH_SMSG_SUCCESS
384 || type == SSH_SMSG_FAILURE
385 || type == SSH_CMSG_EOF
386 || type == SSH_CMSG_EXIT_CONFIRMATION)
387 packet_integrity_check(*payload_len_ptr, 0, type);
388 /* If we got a packet, return it. */
389 if (type != SSH_MSG_NONE)
391 /* Otherwise, wait for some data to arrive, add it to the buffer,
394 FD_SET(connection_in, &set);
395 /* Wait for some data to arrive. */
396 select(connection_in + 1, &set, NULL, NULL, NULL);
397 /* Read data from the socket. */
398 len = read(connection_in, buf, sizeof(buf));
400 fatal("Connection closed by remote host.");
402 fatal("Read from socket failed: %.100s", strerror(errno));
403 /* Append it to the buffer. */
404 packet_process_incoming(buf, len);
409 /* Waits until a packet has been received, verifies that its type matches
410 that given, and gives a fatal error and exits if there is a mismatch. */
413 packet_read_expect(int *payload_len_ptr, int expected_type)
417 type = packet_read(payload_len_ptr);
418 if (type != expected_type)
419 packet_disconnect("Protocol error: expected packet type %d, got %d",
420 expected_type, type);
423 /* Checks if a full packet is available in the data received so far via
424 packet_process_incoming. If so, reads the packet; otherwise returns
425 SSH_MSG_NONE. This does not wait for data from the connection.
427 SSH_MSG_DISCONNECT is handled specially here. Also,
428 SSH_MSG_IGNORE messages are skipped by this function and are never returned
431 The returned payload_len does include space consumed by:
441 packet_read_poll(int *payload_len_ptr)
443 unsigned int len, padded_len;
446 unsigned int checksum, stored_checksum;
450 /* Check if input size is less than minimum packet size. */
451 if (buffer_len(&input) < 4 + 8)
453 /* Get length of incoming packet. */
454 ucp = (unsigned char *)buffer_ptr(&input);
455 len = GET_32BIT(ucp);
456 if (len < 1 + 2 + 2 || len > 256*1024)
457 packet_disconnect("Bad packet length %d.", len);
458 padded_len = (len + 8) & ~7;
460 /* Check if the packet has been entirely received. */
461 if (buffer_len(&input) < 4 + padded_len)
464 /* The entire packet is in buffer. */
466 /* Consume packet length. */
467 buffer_consume(&input, 4);
469 /* Copy data to incoming_packet. */
470 buffer_clear(&incoming_packet);
471 buffer_append_space(&incoming_packet, &cp, padded_len);
472 packet_decrypt(&receive_context, cp, buffer_ptr(&input), padded_len);
473 buffer_consume(&input, padded_len);
476 fprintf(stderr, "read_poll plain: "); buffer_dump(&incoming_packet);
479 /* Compute packet checksum. */
480 checksum = crc32((unsigned char *)buffer_ptr(&incoming_packet),
481 buffer_len(&incoming_packet) - 4);
484 buffer_consume(&incoming_packet, 8 - len % 8);
486 /* Test check bytes. */
488 if (len != buffer_len(&incoming_packet))
489 packet_disconnect("packet_read_poll: len %d != buffer_len %d.",
490 len, buffer_len(&incoming_packet));
492 ucp = (unsigned char *)buffer_ptr(&incoming_packet) + len - 4;
493 stored_checksum = GET_32BIT(ucp);
494 if (checksum != stored_checksum)
495 packet_disconnect("Corrupted check bytes on input.");
496 buffer_consume_end(&incoming_packet, 4);
498 /* If using packet compression, decompress the packet. */
499 if (packet_compression)
501 buffer_clear(&compression_buffer);
502 buffer_uncompress(&incoming_packet, &compression_buffer);
503 buffer_clear(&incoming_packet);
504 buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
505 buffer_len(&compression_buffer));
508 /* Get packet type. */
509 buffer_get(&incoming_packet, &buf[0], 1);
511 /* Return length of payload (without type field). */
512 *payload_len_ptr = buffer_len(&incoming_packet);
514 /* Handle disconnect message. */
515 if ((unsigned char)buf[0] == SSH_MSG_DISCONNECT)
516 fatal("%.900s", packet_get_string(NULL));
518 /* Ignore ignore messages. */
519 if ((unsigned char)buf[0] == SSH_MSG_IGNORE)
522 /* Send debug messages as debugging output. */
523 if ((unsigned char)buf[0] == SSH_MSG_DEBUG)
525 debug("Remote: %.900s", packet_get_string(NULL));
530 return (unsigned char)buf[0];
533 /* Buffers the given amount of input characters. This is intended to be
534 used together with packet_read_poll. */
537 packet_process_incoming(const char *buf, unsigned int len)
539 buffer_append(&input, buf, len);
542 /* Returns a character from the packet. */
548 buffer_get(&incoming_packet, &ch, 1);
549 return (unsigned char)ch;
552 /* Returns an integer from the packet data. */
557 return buffer_get_int(&incoming_packet);
560 /* Returns an arbitrary precision integer from the packet data. The integer
561 must have been initialized before this call. */
564 packet_get_bignum(BIGNUM *value, int *length_ptr)
566 *length_ptr = buffer_get_bignum(&incoming_packet, value);
569 /* Returns a string from the packet data. The string is allocated using
570 xmalloc; it is the responsibility of the calling program to free it when
571 no longer needed. The length_ptr argument may be NULL, or point to an
572 integer into which the length of the string is stored. */
575 *packet_get_string(unsigned int *length_ptr)
577 return buffer_get_string(&incoming_packet, length_ptr);
580 /* Sends a diagnostic message from the server to the client. This message
581 can be sent at any time (but not while constructing another message).
582 The message is printed immediately, but only if the client is being
583 executed in verbose mode. These messages are primarily intended to
584 ease debugging authentication problems. The length of the formatted
585 message must not exceed 1024 bytes. This will automatically call
586 packet_write_wait. */
589 packet_send_debug(const char *fmt, ...)
595 vsnprintf(buf, sizeof(buf), fmt, args);
598 packet_start(SSH_MSG_DEBUG);
599 packet_put_string(buf, strlen(buf));
604 /* Logs the error plus constructs and sends a disconnect
605 packet, closes the connection, and exits. This function never returns.
606 The error message should not contain a newline. The length of the
607 formatted message must not exceed 1024 bytes. */
610 packet_disconnect(const char *fmt, ...)
614 static int disconnecting = 0;
615 if (disconnecting) /* Guard against recursive invocations. */
616 fatal("packet_disconnect called recursively.");
619 /* Format the message. Note that the caller must make sure the message
620 is of limited size. */
622 vsnprintf(buf, sizeof(buf), fmt, args);
625 /* Send the disconnect message to the other side, and wait for it to get
627 packet_start(SSH_MSG_DISCONNECT);
628 packet_put_string(buf, strlen(buf));
632 /* Stop listening for connections. */
633 channel_stop_listening();
635 /* Close the connection. */
638 /* Display the error locally and exit. */
639 fatal("Local: %.100s", buf);
642 /* Checks if there is any buffered output, and tries to write some of the
648 int len = buffer_len(&output);
651 len = write(connection_out, buffer_ptr(&output), len);
656 fatal("Write failed: %.100s", strerror(errno));
658 buffer_consume(&output, len);
662 /* Calls packet_write_poll repeatedly until all pending output data has
669 while (packet_have_data_to_write())
673 FD_SET(connection_out, &set);
674 select(connection_out + 1, NULL, &set, NULL, NULL);
679 /* Returns true if there is buffered data to write to the connection. */
682 packet_have_data_to_write()
684 return buffer_len(&output) != 0;
687 /* Returns true if there is not too much data to write to the connection. */
690 packet_not_very_much_data_to_write()
692 if (interactive_mode)
693 return buffer_len(&output) < 16384;
695 return buffer_len(&output) < 128*1024;
698 /* Informs that the current session is interactive. Sets IP flags for that. */
701 packet_set_interactive(int interactive, int keepalives)
705 /* Record that we are in interactive mode. */
706 interactive_mode = interactive;
708 /* Only set socket options if using a socket (as indicated by the descriptors
710 if (connection_in != connection_out)
715 /* Set keepalives if requested. */
716 if (setsockopt(connection_in, SOL_SOCKET, SO_KEEPALIVE, (void *)&on,
718 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
723 /* Set IP options for an interactive connection. Use IPTOS_LOWDELAY
725 int lowdelay = IPTOS_LOWDELAY;
726 if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, (void *)&lowdelay,
727 sizeof(lowdelay)) < 0)
728 error("setsockopt IPTOS_LOWDELAY: %.100s", strerror(errno));
729 if (setsockopt(connection_in, IPPROTO_TCP, TCP_NODELAY, (void *)&on,
731 error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
735 /* Set IP options for a non-interactive connection. Use
737 int throughput = IPTOS_THROUGHPUT;
738 if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, (void *)&throughput,
739 sizeof(throughput)) < 0)
740 error("setsockopt IPTOS_THROUGHPUT: %.100s", strerror(errno));
744 /* Returns true if the current connection is interactive. */
747 packet_is_interactive()
749 return interactive_mode;
753 packet_set_maxsize(int s)
755 static int called = 0;
757 log("packet_set_maxsize: called twice: old %d new %d", max_packet_size, s);
760 if (s < 4*1024 || s > 1024*1024) {
761 log("packet_set_maxsize: bad size %d", s);
764 log("packet_set_maxsize: setting to %d", s);