1 /* Copyright (C) 2007 The Written Word, Inc. All rights reserved.
2 * Copyright (C) 2009-2010 by Daniel Stenberg
3 * Author: Daniel Stenberg <daniel@haxx.se>
4 *
5 * Redistribution and use in source and binary forms,
6 * with or without modification, are permitted provided
7 * that the following conditions are met:
8 *
9 * Redistributions of source code must retain the above
10 * copyright notice, this list of conditions and the
11 * following disclaimer.
12 *
13 * Redistributions in binary form must reproduce the above
14 * copyright notice, this list of conditions and the following
15 * disclaimer in the documentation and/or other materials
16 * provided with the distribution.
17 *
18 * Neither the name of the copyright holder nor the names
19 * of any other contributors may be used to endorse or
20 * promote products derived from this software without
21 * specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
24 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
25 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
28 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
29 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
33 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
34 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
35 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
36 * OF SUCH DAMAGE.
37 *
38 * This file handles reading and writing to the SECSH transport layer. RFC4253.
39 */
40
41 #include "libssh2_priv.h"
42 #include <errno.h>
43 #include <fcntl.h>
44 #include <ctype.h>
45 #ifdef LIBSSH2DEBUG
46 #include <stdio.h>
47 #endif
48
49 #include <assert.h>
50
51 #include "transport.h"
52 #include "mac.h"
53
54 #define MAX_BLOCKSIZE 32 /* MUST fit biggest crypto block size we use/get */
55 #define MAX_MACSIZE 64 /* MUST fit biggest MAC length we support */
56
57 #ifdef LIBSSH2DEBUG
58 #define UNPRINTABLE_CHAR '.'
59 static void
debugdump(LIBSSH2_SESSION * session,const char * desc,const unsigned char * ptr,size_t size)60 debugdump(LIBSSH2_SESSION * session,
61 const char *desc, const unsigned char *ptr, size_t size)
62 {
63 size_t i;
64 size_t c;
65 unsigned int width = 0x10;
66 char buffer[256]; /* Must be enough for width*4 + about 30 or so */
67 size_t used;
68 static const char *hex_chars = "0123456789ABCDEF";
69
70 if(!(session->showmask & LIBSSH2_TRACE_TRANS)) {
71 /* not asked for, bail out */
72 return;
73 }
74
75 used = snprintf(buffer, sizeof(buffer), "=> %s (%d bytes)\n",
76 desc, (int) size);
77 if(session->tracehandler)
78 (session->tracehandler)(session, session->tracehandler_context,
79 buffer, used);
80 else
81 fprintf(stderr, "%s", buffer);
82
83 for(i = 0; i < size; i += width) {
84
85 used = snprintf(buffer, sizeof(buffer), "%04lx: ", (long)i);
86
87 /* hex not disabled, show it */
88 for(c = 0; c < width; c++) {
89 if(i + c < size) {
90 buffer[used++] = hex_chars[(ptr[i + c] >> 4) & 0xF];
91 buffer[used++] = hex_chars[ptr[i + c] & 0xF];
92 }
93 else {
94 buffer[used++] = ' ';
95 buffer[used++] = ' ';
96 }
97
98 buffer[used++] = ' ';
99 if((width/2) - 1 == c)
100 buffer[used++] = ' ';
101 }
102
103 buffer[used++] = ':';
104 buffer[used++] = ' ';
105
106 for(c = 0; (c < width) && (i + c < size); c++) {
107 buffer[used++] = isprint(ptr[i + c]) ?
108 ptr[i + c] : UNPRINTABLE_CHAR;
109 }
110 buffer[used++] = '\n';
111 buffer[used] = 0;
112
113 if(session->tracehandler)
114 (session->tracehandler)(session, session->tracehandler_context,
115 buffer, used);
116 else
117 fprintf(stderr, "%s", buffer);
118 }
119 }
120 #else
121 #define debugdump(a,x,y,z)
122 #endif
123
124
125 /* decrypt() decrypts 'len' bytes from 'source' to 'dest'.
126 *
127 * returns 0 on success and negative on failure
128 */
129
130 static int
decrypt(LIBSSH2_SESSION * session,unsigned char * source,unsigned char * dest,int len)131 decrypt(LIBSSH2_SESSION * session, unsigned char *source,
132 unsigned char *dest, int len)
133 {
134 struct transportpacket *p = &session->packet;
135 int blocksize = session->remote.crypt->blocksize;
136
137 /* if we get called with a len that isn't an even number of blocksizes
138 we risk losing those extra bytes */
139 assert((len % blocksize) == 0);
140
141 while(len >= blocksize) {
142 if(session->remote.crypt->crypt(session, source, blocksize,
143 &session->remote.crypt_abstract)) {
144 LIBSSH2_FREE(session, p->payload);
145 return LIBSSH2_ERROR_DECRYPT;
146 }
147
148 /* if the crypt() function would write to a given address it
149 wouldn't have to memcpy() and we could avoid this memcpy()
150 too */
151 memcpy(dest, source, blocksize);
152
153 len -= blocksize; /* less bytes left */
154 dest += blocksize; /* advance write pointer */
155 source += blocksize; /* advance read pointer */
156 }
157 return LIBSSH2_ERROR_NONE; /* all is fine */
158 }
159
160 /*
161 * fullpacket() gets called when a full packet has been received and properly
162 * collected.
163 */
164 static int
fullpacket(LIBSSH2_SESSION * session,int encrypted)165 fullpacket(LIBSSH2_SESSION * session, int encrypted /* 1 or 0 */ )
166 {
167 unsigned char macbuf[MAX_MACSIZE];
168 struct transportpacket *p = &session->packet;
169 int rc;
170 int compressed;
171
172 if(session->fullpacket_state == libssh2_NB_state_idle) {
173 session->fullpacket_macstate = LIBSSH2_MAC_CONFIRMED;
174 session->fullpacket_payload_len = p->packet_length - 1;
175
176 if(encrypted) {
177
178 /* Calculate MAC hash */
179 session->remote.mac->hash(session, macbuf, /* store hash here */
180 session->remote.seqno,
181 p->init, 5,
182 p->payload,
183 session->fullpacket_payload_len,
184 &session->remote.mac_abstract);
185
186 /* Compare the calculated hash with the MAC we just read from
187 * the network. The read one is at the very end of the payload
188 * buffer. Note that 'payload_len' here is the packet_length
189 * field which includes the padding but not the MAC.
190 */
191 if(memcmp(macbuf, p->payload + session->fullpacket_payload_len,
192 session->remote.mac->mac_len)) {
193 session->fullpacket_macstate = LIBSSH2_MAC_INVALID;
194 }
195 }
196
197 session->remote.seqno++;
198
199 /* ignore the padding */
200 session->fullpacket_payload_len -= p->padding_length;
201
202 /* Check for and deal with decompression */
203 compressed =
204 session->local.comp != NULL &&
205 session->local.comp->compress &&
206 ((session->state & LIBSSH2_STATE_AUTHENTICATED) ||
207 session->local.comp->use_in_auth);
208
209 if(compressed && session->remote.comp_abstract) {
210 /*
211 * The buffer for the decompression (remote.comp_abstract) is
212 * initialised in time when it is needed so as long it is NULL we
213 * cannot decompress.
214 */
215
216 unsigned char *data;
217 size_t data_len;
218 rc = session->remote.comp->decomp(session,
219 &data, &data_len,
220 LIBSSH2_PACKET_MAXDECOMP,
221 p->payload,
222 session->fullpacket_payload_len,
223 &session->remote.comp_abstract);
224 LIBSSH2_FREE(session, p->payload);
225 if(rc)
226 return rc;
227
228 p->payload = data;
229 session->fullpacket_payload_len = data_len;
230 }
231
232 session->fullpacket_packet_type = p->payload[0];
233
234 debugdump(session, "libssh2_transport_read() plain",
235 p->payload, session->fullpacket_payload_len);
236
237 session->fullpacket_state = libssh2_NB_state_created;
238 }
239
240 if(session->fullpacket_state == libssh2_NB_state_created) {
241 rc = _libssh2_packet_add(session, p->payload,
242 session->fullpacket_payload_len,
243 session->fullpacket_macstate);
244 if(rc == LIBSSH2_ERROR_EAGAIN)
245 return rc;
246 if(rc) {
247 session->fullpacket_state = libssh2_NB_state_idle;
248 return rc;
249 }
250 }
251
252 session->fullpacket_state = libssh2_NB_state_idle;
253
254 return session->fullpacket_packet_type;
255 }
256
257
258 /*
259 * _libssh2_transport_read
260 *
261 * Collect a packet into the input queue.
262 *
263 * Returns packet type added to input queue (0 if nothing added), or a
264 * negative error number.
265 */
266
267 /*
268 * This function reads the binary stream as specified in chapter 6 of RFC4253
269 * "The Secure Shell (SSH) Transport Layer Protocol"
270 *
271 * DOES NOT call _libssh2_error() for ANY error case.
272 */
_libssh2_transport_read(LIBSSH2_SESSION * session)273 int _libssh2_transport_read(LIBSSH2_SESSION * session)
274 {
275 int rc;
276 struct transportpacket *p = &session->packet;
277 int remainbuf;
278 int remainpack;
279 int numbytes;
280 int numdecrypt;
281 unsigned char block[MAX_BLOCKSIZE];
282 int blocksize;
283 int encrypted = 1;
284
285 /* default clear the bit */
286 session->socket_block_directions &= ~LIBSSH2_SESSION_BLOCK_INBOUND;
287
288 /*
289 * All channels, systems, subsystems, etc eventually make it down here
290 * when looking for more incoming data. If a key exchange is going on
291 * (LIBSSH2_STATE_EXCHANGING_KEYS bit is set) then the remote end will
292 * ONLY send key exchange related traffic. In non-blocking mode, there is
293 * a chance to break out of the kex_exchange function with an EAGAIN
294 * status, and never come back to it. If LIBSSH2_STATE_EXCHANGING_KEYS is
295 * active, then we must redirect to the key exchange. However, if
296 * kex_exchange is active (as in it is the one that calls this execution
297 * of packet_read, then don't redirect, as that would be an infinite loop!
298 */
299
300 if(session->state & LIBSSH2_STATE_EXCHANGING_KEYS &&
301 !(session->state & LIBSSH2_STATE_KEX_ACTIVE)) {
302
303 /* Whoever wants a packet won't get anything until the key re-exchange
304 * is done!
305 */
306 _libssh2_debug(session, LIBSSH2_TRACE_TRANS, "Redirecting into the"
307 " key re-exchange from _libssh2_transport_read");
308 rc = _libssh2_kex_exchange(session, 1, &session->startup_key_state);
309 if(rc)
310 return rc;
311 }
312
313 /*
314 * =============================== NOTE ===============================
315 * I know this is very ugly and not a really good use of "goto", but
316 * this case statement would be even uglier to do it any other way
317 */
318 if(session->readPack_state == libssh2_NB_state_jump1) {
319 session->readPack_state = libssh2_NB_state_idle;
320 encrypted = session->readPack_encrypted;
321 goto libssh2_transport_read_point1;
322 }
323
324 do {
325 if(session->socket_state == LIBSSH2_SOCKET_DISCONNECTED) {
326 return LIBSSH2_ERROR_NONE;
327 }
328
329 if(session->state & LIBSSH2_STATE_NEWKEYS) {
330 blocksize = session->remote.crypt->blocksize;
331 }
332 else {
333 encrypted = 0; /* not encrypted */
334 blocksize = 5; /* not strictly true, but we can use 5 here to
335 make the checks below work fine still */
336 }
337
338 /* read/use a whole big chunk into a temporary area stored in
339 the LIBSSH2_SESSION struct. We will decrypt data from that
340 buffer into the packet buffer so this temp one doesn't have
341 to be able to keep a whole SSH packet, just be large enough
342 so that we can read big chunks from the network layer. */
343
344 /* how much data there is remaining in the buffer to deal with
345 before we should read more from the network */
346 remainbuf = p->writeidx - p->readidx;
347
348 /* if remainbuf turns negative we have a bad internal error */
349 assert(remainbuf >= 0);
350
351 if(remainbuf < blocksize) {
352 /* If we have less than a blocksize left, it is too
353 little data to deal with, read more */
354 ssize_t nread;
355
356 /* move any remainder to the start of the buffer so
357 that we can do a full refill */
358 if(remainbuf) {
359 memmove(p->buf, &p->buf[p->readidx], remainbuf);
360 p->readidx = 0;
361 p->writeidx = remainbuf;
362 }
363 else {
364 /* nothing to move, just zero the indexes */
365 p->readidx = p->writeidx = 0;
366 }
367
368 /* now read a big chunk from the network into the temp buffer */
369 nread =
370 LIBSSH2_RECV(session, &p->buf[remainbuf],
371 PACKETBUFSIZE - remainbuf,
372 LIBSSH2_SOCKET_RECV_FLAGS(session));
373 if(nread <= 0) {
374 /* check if this is due to EAGAIN and return the special
375 return code if so, error out normally otherwise */
376 if((nread < 0) && (nread == -EAGAIN)) {
377 session->socket_block_directions |=
378 LIBSSH2_SESSION_BLOCK_INBOUND;
379 return LIBSSH2_ERROR_EAGAIN;
380 }
381 _libssh2_debug(session, LIBSSH2_TRACE_SOCKET,
382 "Error recving %d bytes (got %d)",
383 PACKETBUFSIZE - remainbuf, -nread);
384 return LIBSSH2_ERROR_SOCKET_RECV;
385 }
386 _libssh2_debug(session, LIBSSH2_TRACE_SOCKET,
387 "Recved %d/%d bytes to %p+%d", nread,
388 PACKETBUFSIZE - remainbuf, p->buf, remainbuf);
389
390 debugdump(session, "libssh2_transport_read() raw",
391 &p->buf[remainbuf], nread);
392 /* advance write pointer */
393 p->writeidx += nread;
394
395 /* update remainbuf counter */
396 remainbuf = p->writeidx - p->readidx;
397 }
398
399 /* how much data to deal with from the buffer */
400 numbytes = remainbuf;
401
402 if(!p->total_num) {
403 size_t total_num;
404
405 /* No payload package area allocated yet. To know the
406 size of this payload, we need to decrypt the first
407 blocksize data. */
408
409 if(numbytes < blocksize) {
410 /* we can't act on anything less than blocksize, but this
411 check is only done for the initial block since once we have
412 got the start of a block we can in fact deal with fractions
413 */
414 session->socket_block_directions |=
415 LIBSSH2_SESSION_BLOCK_INBOUND;
416 return LIBSSH2_ERROR_EAGAIN;
417 }
418
419 if(encrypted) {
420 rc = decrypt(session, &p->buf[p->readidx], block, blocksize);
421 if(rc != LIBSSH2_ERROR_NONE) {
422 return rc;
423 }
424 /* save the first 5 bytes of the decrypted package, to be
425 used in the hash calculation later down. */
426 memcpy(p->init, block, 5);
427 }
428 else {
429 /* the data is plain, just copy it verbatim to
430 the working block buffer */
431 memcpy(block, &p->buf[p->readidx], blocksize);
432 }
433
434 /* advance the read pointer */
435 p->readidx += blocksize;
436
437 /* we now have the initial blocksize bytes decrypted,
438 * and we can extract packet and padding length from it
439 */
440 p->packet_length = _libssh2_ntohu32(block);
441 if(p->packet_length < 1) {
442 return LIBSSH2_ERROR_DECRYPT;
443 }
444 else if(p->packet_length > LIBSSH2_PACKET_MAXPAYLOAD) {
445 return LIBSSH2_ERROR_OUT_OF_BOUNDARY;
446 }
447
448 p->padding_length = block[4];
449 if(p->padding_length > p->packet_length - 1) {
450 return LIBSSH2_ERROR_DECRYPT;
451 }
452
453
454 /* total_num is the number of bytes following the initial
455 (5 bytes) packet length and padding length fields */
456 total_num =
457 p->packet_length - 1 +
458 (encrypted ? session->remote.mac->mac_len : 0);
459
460 /* RFC4253 section 6.1 Maximum Packet Length says:
461 *
462 * "All implementations MUST be able to process
463 * packets with uncompressed payload length of 32768
464 * bytes or less and total packet size of 35000 bytes
465 * or less (including length, padding length, payload,
466 * padding, and MAC.)."
467 */
468 if(total_num > LIBSSH2_PACKET_MAXPAYLOAD) {
469 return LIBSSH2_ERROR_OUT_OF_BOUNDARY;
470 }
471
472 /* Get a packet handle put data into. We get one to
473 hold all data, including padding and MAC. */
474 p->payload = LIBSSH2_ALLOC(session, total_num);
475 if(!p->payload) {
476 return LIBSSH2_ERROR_ALLOC;
477 }
478 p->total_num = total_num;
479 /* init write pointer to start of payload buffer */
480 p->wptr = p->payload;
481
482 if(blocksize > 5) {
483 /* copy the data from index 5 to the end of
484 the blocksize from the temporary buffer to
485 the start of the decrypted buffer */
486 if(blocksize - 5 <= (int) total_num) {
487 memcpy(p->wptr, &block[5], blocksize - 5);
488 p->wptr += blocksize - 5; /* advance write pointer */
489 }
490 else {
491 return LIBSSH2_ERROR_OUT_OF_BOUNDARY;
492 }
493 }
494
495 /* init the data_num field to the number of bytes of
496 the package read so far */
497 p->data_num = p->wptr - p->payload;
498
499 /* we already dealt with a blocksize worth of data */
500 numbytes -= blocksize;
501 }
502
503 /* how much there is left to add to the current payload
504 package */
505 remainpack = p->total_num - p->data_num;
506
507 if(numbytes > remainpack) {
508 /* if we have more data in the buffer than what is going into this
509 particular packet, we limit this round to this packet only */
510 numbytes = remainpack;
511 }
512
513 if(encrypted) {
514 /* At the end of the incoming stream, there is a MAC,
515 and we don't want to decrypt that since we need it
516 "raw". We MUST however decrypt the padding data
517 since it is used for the hash later on. */
518 int skip = session->remote.mac->mac_len;
519
520 /* if what we have plus numbytes is bigger than the
521 total minus the skip margin, we should lower the
522 amount to decrypt even more */
523 if((p->data_num + numbytes) > (p->total_num - skip)) {
524 numdecrypt = (p->total_num - skip) - p->data_num;
525 }
526 else {
527 int frac;
528 numdecrypt = numbytes;
529 frac = numdecrypt % blocksize;
530 if(frac) {
531 /* not an aligned amount of blocks,
532 align it */
533 numdecrypt -= frac;
534 /* and make it no unencrypted data
535 after it */
536 numbytes = 0;
537 }
538 }
539 }
540 else {
541 /* unencrypted data should not be decrypted at all */
542 numdecrypt = 0;
543 }
544
545 /* if there are bytes to decrypt, do that */
546 if(numdecrypt > 0) {
547 /* now decrypt the lot */
548 rc = decrypt(session, &p->buf[p->readidx], p->wptr, numdecrypt);
549 if(rc != LIBSSH2_ERROR_NONE) {
550 p->total_num = 0; /* no packet buffer available */
551 return rc;
552 }
553
554 /* advance the read pointer */
555 p->readidx += numdecrypt;
556 /* advance write pointer */
557 p->wptr += numdecrypt;
558 /* increase data_num */
559 p->data_num += numdecrypt;
560
561 /* bytes left to take care of without decryption */
562 numbytes -= numdecrypt;
563 }
564
565 /* if there are bytes to copy that aren't decrypted, simply
566 copy them as-is to the target buffer */
567 if(numbytes > 0) {
568
569 if(numbytes <= (int)(p->total_num - (p->wptr - p->payload))) {
570 memcpy(p->wptr, &p->buf[p->readidx], numbytes);
571 }
572 else {
573 return LIBSSH2_ERROR_OUT_OF_BOUNDARY;
574 }
575
576 /* advance the read pointer */
577 p->readidx += numbytes;
578 /* advance write pointer */
579 p->wptr += numbytes;
580 /* increase data_num */
581 p->data_num += numbytes;
582 }
583
584 /* now check how much data there's left to read to finish the
585 current packet */
586 remainpack = p->total_num - p->data_num;
587
588 if(!remainpack) {
589 /* we have a full packet */
590 libssh2_transport_read_point1:
591 rc = fullpacket(session, encrypted);
592 if(rc == LIBSSH2_ERROR_EAGAIN) {
593
594 if(session->packAdd_state != libssh2_NB_state_idle) {
595 /* fullpacket only returns LIBSSH2_ERROR_EAGAIN if
596 * libssh2_packet_add returns LIBSSH2_ERROR_EAGAIN. If
597 * that returns LIBSSH2_ERROR_EAGAIN but the packAdd_state
598 * is idle, then the packet has been added to the brigade,
599 * but some immediate action that was taken based on the
600 * packet type (such as key re-exchange) is not yet
601 * complete. Clear the way for a new packet to be read
602 * in.
603 */
604 session->readPack_encrypted = encrypted;
605 session->readPack_state = libssh2_NB_state_jump1;
606 }
607
608 return rc;
609 }
610
611 p->total_num = 0; /* no packet buffer available */
612
613 return rc;
614 }
615 } while(1); /* loop */
616
617 return LIBSSH2_ERROR_SOCKET_RECV; /* we never reach this point */
618 }
619
620 static int
send_existing(LIBSSH2_SESSION * session,const unsigned char * data,size_t data_len,ssize_t * ret)621 send_existing(LIBSSH2_SESSION *session, const unsigned char *data,
622 size_t data_len, ssize_t *ret)
623 {
624 ssize_t rc;
625 ssize_t length;
626 struct transportpacket *p = &session->packet;
627
628 if(!p->olen) {
629 *ret = 0;
630 return LIBSSH2_ERROR_NONE;
631 }
632
633 /* send as much as possible of the existing packet */
634 if((data != p->odata) || (data_len != p->olen)) {
635 /* When we are about to complete the sending of a packet, it is vital
636 that the caller doesn't try to send a new/different packet since
637 we don't add this one up until the previous one has been sent. To
638 make the caller really notice his/hers flaw, we return error for
639 this case */
640 return LIBSSH2_ERROR_BAD_USE;
641 }
642
643 *ret = 1; /* set to make our parent return */
644
645 /* number of bytes left to send */
646 length = p->ototal_num - p->osent;
647
648 rc = LIBSSH2_SEND(session, &p->outbuf[p->osent], length,
649 LIBSSH2_SOCKET_SEND_FLAGS(session));
650 if(rc < 0)
651 _libssh2_debug(session, LIBSSH2_TRACE_SOCKET,
652 "Error sending %d bytes: %d", length, -rc);
653 else {
654 _libssh2_debug(session, LIBSSH2_TRACE_SOCKET,
655 "Sent %d/%d bytes at %p+%d", rc, length, p->outbuf,
656 p->osent);
657 debugdump(session, "libssh2_transport_write send()",
658 &p->outbuf[p->osent], rc);
659 }
660
661 if(rc == length) {
662 /* the remainder of the package was sent */
663 p->ototal_num = 0;
664 p->olen = 0;
665 /* we leave *ret set so that the parent returns as we MUST return back
666 a send success now, so that we don't risk sending EAGAIN later
667 which then would confuse the parent function */
668 return LIBSSH2_ERROR_NONE;
669
670 }
671 else if(rc < 0) {
672 /* nothing was sent */
673 if(rc != -EAGAIN)
674 /* send failure! */
675 return LIBSSH2_ERROR_SOCKET_SEND;
676
677 session->socket_block_directions |= LIBSSH2_SESSION_BLOCK_OUTBOUND;
678 return LIBSSH2_ERROR_EAGAIN;
679 }
680
681 p->osent += rc; /* we sent away this much data */
682
683 return rc < length ? LIBSSH2_ERROR_EAGAIN : LIBSSH2_ERROR_NONE;
684 }
685
686 /*
687 * libssh2_transport_send
688 *
689 * Send a packet, encrypting it and adding a MAC code if necessary
690 * Returns 0 on success, non-zero on failure.
691 *
692 * The data is provided as _two_ data areas that are combined by this
693 * function. The 'data' part is sent immediately before 'data2'. 'data2' may
694 * be set to NULL to only use a single part.
695 *
696 * Returns LIBSSH2_ERROR_EAGAIN if it would block or if the whole packet was
697 * not sent yet. If it does so, the caller should call this function again as
698 * soon as it is likely that more data can be sent, and this function MUST
699 * then be called with the same argument set (same data pointer and same
700 * data_len) until ERROR_NONE or failure is returned.
701 *
702 * This function DOES NOT call _libssh2_error() on any errors.
703 */
_libssh2_transport_send(LIBSSH2_SESSION * session,const unsigned char * data,size_t data_len,const unsigned char * data2,size_t data2_len)704 int _libssh2_transport_send(LIBSSH2_SESSION *session,
705 const unsigned char *data, size_t data_len,
706 const unsigned char *data2, size_t data2_len)
707 {
708 int blocksize =
709 (session->state & LIBSSH2_STATE_NEWKEYS) ?
710 session->local.crypt->blocksize : 8;
711 int padding_length;
712 size_t packet_length;
713 int total_length;
714 #ifdef RANDOM_PADDING
715 int rand_max;
716 int seed = data[0]; /* FIXME: make this random */
717 #endif
718 struct transportpacket *p = &session->packet;
719 int encrypted;
720 int compressed;
721 ssize_t ret;
722 int rc;
723 const unsigned char *orgdata = data;
724 size_t orgdata_len = data_len;
725
726 /*
727 * If the last read operation was interrupted in the middle of a key
728 * exchange, we must complete that key exchange before continuing to write
729 * further data.
730 *
731 * See the similar block in _libssh2_transport_read for more details.
732 */
733 if(session->state & LIBSSH2_STATE_EXCHANGING_KEYS &&
734 !(session->state & LIBSSH2_STATE_KEX_ACTIVE)) {
735 /* Don't write any new packets if we're still in the middle of a key
736 * exchange. */
737 _libssh2_debug(session, LIBSSH2_TRACE_TRANS, "Redirecting into the"
738 " key re-exchange from _libssh2_transport_send");
739 rc = _libssh2_kex_exchange(session, 1, &session->startup_key_state);
740 if(rc)
741 return rc;
742 }
743
744 debugdump(session, "libssh2_transport_write plain", data, data_len);
745 if(data2)
746 debugdump(session, "libssh2_transport_write plain2", data2, data2_len);
747
748 /* FIRST, check if we have a pending write to complete. send_existing
749 only sanity-check data and data_len and not data2 and data2_len!! */
750 rc = send_existing(session, data, data_len, &ret);
751 if(rc)
752 return rc;
753
754 session->socket_block_directions &= ~LIBSSH2_SESSION_BLOCK_OUTBOUND;
755
756 if(ret)
757 /* set by send_existing if data was sent */
758 return rc;
759
760 encrypted = (session->state & LIBSSH2_STATE_NEWKEYS) ? 1 : 0;
761
762 compressed =
763 session->local.comp != NULL &&
764 session->local.comp->compress &&
765 ((session->state & LIBSSH2_STATE_AUTHENTICATED) ||
766 session->local.comp->use_in_auth);
767
768 if(encrypted && compressed) {
769 /* the idea here is that these function must fail if the output gets
770 larger than what fits in the assigned buffer so thus they don't
771 check the input size as we don't know how much it compresses */
772 size_t dest_len = MAX_SSH_PACKET_LEN-5-256;
773 size_t dest2_len = dest_len;
774
775 /* compress directly to the target buffer */
776 rc = session->local.comp->comp(session,
777 &p->outbuf[5], &dest_len,
778 data, data_len,
779 &session->local.comp_abstract);
780 if(rc)
781 return rc; /* compression failure */
782
783 if(data2 && data2_len) {
784 /* compress directly to the target buffer right after where the
785 previous call put data */
786 dest2_len -= dest_len;
787
788 rc = session->local.comp->comp(session,
789 &p->outbuf[5 + dest_len],
790 &dest2_len,
791 data2, data2_len,
792 &session->local.comp_abstract);
793 }
794 else
795 dest2_len = 0;
796 if(rc)
797 return rc; /* compression failure */
798
799 data_len = dest_len + dest2_len; /* use the combined length */
800 }
801 else {
802 if((data_len + data2_len) >= (MAX_SSH_PACKET_LEN-0x100))
803 /* too large packet, return error for this until we make this
804 function split it up and send multiple SSH packets */
805 return LIBSSH2_ERROR_INVAL;
806
807 /* copy the payload data */
808 memcpy(&p->outbuf[5], data, data_len);
809 if(data2 && data2_len)
810 memcpy(&p->outbuf[5 + data_len], data2, data2_len);
811 data_len += data2_len; /* use the combined length */
812 }
813
814
815 /* RFC4253 says: Note that the length of the concatenation of
816 'packet_length', 'padding_length', 'payload', and 'random padding'
817 MUST be a multiple of the cipher block size or 8, whichever is
818 larger. */
819
820 /* Plain math: (4 + 1 + packet_length + padding_length) % blocksize == 0 */
821
822 packet_length = data_len + 1 + 4; /* 1 is for padding_length field
823 4 for the packet_length field */
824
825 /* at this point we have it all except the padding */
826
827 /* first figure out our minimum padding amount to make it an even
828 block size */
829 padding_length = blocksize - (packet_length % blocksize);
830
831 /* if the padding becomes too small we add another blocksize worth
832 of it (taken from the original libssh2 where it didn't have any
833 real explanation) */
834 if(padding_length < 4) {
835 padding_length += blocksize;
836 }
837 #ifdef RANDOM_PADDING
838 /* FIXME: we can add padding here, but that also makes the packets
839 bigger etc */
840
841 /* now we can add 'blocksize' to the padding_length N number of times
842 (to "help thwart traffic analysis") but it must be less than 255 in
843 total */
844 rand_max = (255 - padding_length) / blocksize + 1;
845 padding_length += blocksize * (seed % rand_max);
846 #endif
847
848 packet_length += padding_length;
849
850 /* append the MAC length to the total_length size */
851 total_length =
852 packet_length + (encrypted ? session->local.mac->mac_len : 0);
853
854 /* store packet_length, which is the size of the whole packet except
855 the MAC and the packet_length field itself */
856 _libssh2_htonu32(p->outbuf, packet_length - 4);
857 /* store padding_length */
858 p->outbuf[4] = (unsigned char)padding_length;
859
860 /* fill the padding area with random junk */
861 _libssh2_random(p->outbuf + 5 + data_len, padding_length);
862
863 if(encrypted) {
864 size_t i;
865
866 /* Calculate MAC hash. Put the output at index packet_length,
867 since that size includes the whole packet. The MAC is
868 calculated on the entire unencrypted packet, including all
869 fields except the MAC field itself. */
870 session->local.mac->hash(session, p->outbuf + packet_length,
871 session->local.seqno, p->outbuf,
872 packet_length, NULL, 0,
873 &session->local.mac_abstract);
874
875 /* Encrypt the whole packet data, one block size at a time.
876 The MAC field is not encrypted. */
877 for(i = 0; i < packet_length; i += session->local.crypt->blocksize) {
878 unsigned char *ptr = &p->outbuf[i];
879 if(session->local.crypt->crypt(session, ptr,
880 session->local.crypt->blocksize,
881 &session->local.crypt_abstract))
882 return LIBSSH2_ERROR_ENCRYPT; /* encryption failure */
883 }
884 }
885
886 session->local.seqno++;
887
888 ret = LIBSSH2_SEND(session, p->outbuf, total_length,
889 LIBSSH2_SOCKET_SEND_FLAGS(session));
890 if(ret < 0)
891 _libssh2_debug(session, LIBSSH2_TRACE_SOCKET,
892 "Error sending %d bytes: %d", total_length, -ret);
893 else {
894 _libssh2_debug(session, LIBSSH2_TRACE_SOCKET, "Sent %d/%d bytes at %p",
895 ret, total_length, p->outbuf);
896 debugdump(session, "libssh2_transport_write send()", p->outbuf, ret);
897 }
898
899 if(ret != total_length) {
900 if(ret >= 0 || ret == -EAGAIN) {
901 /* the whole packet could not be sent, save the rest */
902 session->socket_block_directions |= LIBSSH2_SESSION_BLOCK_OUTBOUND;
903 p->odata = orgdata;
904 p->olen = orgdata_len;
905 p->osent = ret <= 0 ? 0 : ret;
906 p->ototal_num = total_length;
907 return LIBSSH2_ERROR_EAGAIN;
908 }
909 return LIBSSH2_ERROR_SOCKET_SEND;
910 }
911
912 /* the whole thing got sent away */
913 p->odata = NULL;
914 p->olen = 0;
915
916 return LIBSSH2_ERROR_NONE; /* all is good */
917 }
918