1 /* Copyright (c) 2004-2008, 2010, Sara Golemon <sarag@libssh2.org>
2  * Copyright (c) 2009-2014 by Daniel Stenberg
3  * Copyright (c) 2010 Simon Josefsson
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms,
7  * with or without modification, are permitted provided
8  * that the following conditions are met:
9  *
10  *   Redistributions of source code must retain the above
11  *   copyright notice, this list of conditions and the
12  *   following disclaimer.
13  *
14  *   Redistributions in binary form must reproduce the above
15  *   copyright notice, this list of conditions and the following
16  *   disclaimer in the documentation and/or other materials
17  *   provided with the distribution.
18  *
19  *   Neither the name of the copyright holder nor the names
20  *   of any other contributors may be used to endorse or
21  *   promote products derived from this software without
22  *   specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
25  * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
26  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
27  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
29  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
31  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
32  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
34  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
35  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
36  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
37  * OF SUCH DAMAGE.
38  */
39 
40 #ifndef LIBSSH2_PRIV_H
41 #define LIBSSH2_PRIV_H 1
42 
43 #define LIBSSH2_LIBRARY
44 #include "libssh2_config.h"
45 
46 #ifdef HAVE_WINDOWS_H
47 #ifndef WIN32_LEAN_AND_MEAN
48 #define WIN32_LEAN_AND_MEAN
49 #endif
50 #include <windows.h>
51 #undef WIN32_LEAN_AND_MEAN
52 #endif
53 
54 #ifdef HAVE_WS2TCPIP_H
55 #include <ws2tcpip.h>
56 #endif
57 
58 #include <stdio.h>
59 #include <time.h>
60 
61 /* The following CPP block should really only be in session.c and packet.c.
62    However, AIX have #define's for 'events' and 'revents' and we are using
63    those names in libssh2.h, so we need to include the AIX headers first, to
64    make sure all code is compiled with consistent names of these fields.
65    While arguable the best would to change libssh2.h to use other names, that
66    would break backwards compatibility.
67 */
68 #ifdef HAVE_POLL
69 # include <poll.h>
70 #else
71 # if defined(HAVE_SELECT) && !defined(WIN32)
72 # ifdef HAVE_SYS_SELECT_H
73 # include <sys/select.h>
74 # else
75 # include <sys/time.h>
76 # include <sys/types.h>
77 # endif
78 # endif
79 #endif
80 
81 /* Needed for struct iovec on some platforms */
82 #ifdef HAVE_SYS_UIO_H
83 #include <sys/uio.h>
84 #endif
85 
86 #ifdef HAVE_SYS_SOCKET_H
87 # include <sys/socket.h>
88 #endif
89 #ifdef HAVE_SYS_IOCTL_H
90 # include <sys/ioctl.h>
91 #endif
92 #ifdef HAVE_INTTYPES_H
93 #include <inttypes.h>
94 #endif
95 
96 #include "libssh2.h"
97 #include "libssh2_publickey.h"
98 #include "libssh2_sftp.h"
99 #include "misc.h" /* for the linked list stuff */
100 
101 #ifndef FALSE
102 #define FALSE 0
103 #endif
104 #ifndef TRUE
105 #define TRUE 1
106 #endif
107 
108 #ifdef _MSC_VER
109 /* "inline" keyword is valid only with C++ engine! */
110 #define inline __inline
111 #endif
112 
113 /* Provide iovec / writev on WIN32 platform. */
114 #ifdef WIN32
115 
116 struct iovec {
117     size_t iov_len;
118     void *iov_base;
119 };
120 
writev(int sock,struct iovec * iov,int nvecs)121 static inline int writev(int sock, struct iovec *iov, int nvecs)
122 {
123     DWORD ret;
124     if(WSASend(sock, (LPWSABUF)iov, nvecs, &ret, 0, NULL, NULL) == 0) {
125         return ret;
126     }
127     return -1;
128 }
129 
130 #endif /* WIN32 */
131 
132 #ifdef __OS400__
133 /* Force parameter type. */
134 #define send(s, b, l, f)    send((s), (unsigned char *) (b), (l), (f))
135 #endif
136 
137 #include "crypto.h"
138 
139 #ifdef HAVE_WINSOCK2_H
140 
141 #include <winsock2.h>
142 #include <ws2tcpip.h>
143 
144 #endif
145 
146 #ifndef SIZE_MAX
147 #if _WIN64
148 #define SIZE_MAX 0xFFFFFFFFFFFFFFFF
149 #else
150 #define SIZE_MAX 0xFFFFFFFF
151 #endif
152 #endif
153 
154 #ifndef UINT_MAX
155 #define UINT_MAX 0xFFFFFFFF
156 #endif
157 
158 /* RFC4253 section 6.1 Maximum Packet Length says:
159  *
160  * "All implementations MUST be able to process packets with
161  * uncompressed payload length of 32768 bytes or less and
162  * total packet size of 35000 bytes or less (including length,
163  * padding length, payload, padding, and MAC.)."
164  */
165 #define MAX_SSH_PACKET_LEN 35000
166 #define MAX_SHA_DIGEST_LEN SHA512_DIGEST_LENGTH
167 
168 #define LIBSSH2_ALLOC(session, count) \
169   session->alloc((count), &(session)->abstract)
170 #define LIBSSH2_CALLOC(session, count) _libssh2_calloc(session, count)
171 #define LIBSSH2_REALLOC(session, ptr, count) \
172  ((ptr) ? session->realloc((ptr), (count), &(session)->abstract) : \
173  session->alloc((count), &(session)->abstract))
174 #define LIBSSH2_FREE(session, ptr) \
175  session->free((ptr), &(session)->abstract)
176 #define LIBSSH2_IGNORE(session, data, datalen) \
177  session->ssh_msg_ignore((session), (data), (datalen), &(session)->abstract)
178 #define LIBSSH2_DEBUG(session, always_display, message, message_len, \
179                       language, language_len)    \
180     session->ssh_msg_debug((session), (always_display), (message), \
181                            (message_len), (language), (language_len), \
182                            &(session)->abstract)
183 #define LIBSSH2_DISCONNECT(session, reason, message, message_len, \
184                            language, language_len)                \
185     session->ssh_msg_disconnect((session), (reason), (message),   \
186                                 (message_len), (language), (language_len), \
187                                 &(session)->abstract)
188 
189 #define LIBSSH2_MACERROR(session, data, datalen)         \
190     session->macerror((session), (data), (datalen), &(session)->abstract)
191 #define LIBSSH2_X11_OPEN(channel, shost, sport)          \
192     channel->session->x11(((channel)->session), (channel), \
193                           (shost), (sport), (&(channel)->session->abstract))
194 
195 #define LIBSSH2_CHANNEL_CLOSE(session, channel)          \
196     channel->close_cb((session), &(session)->abstract, \
197                       (channel), &(channel)->abstract)
198 
199 #define LIBSSH2_SEND_FD(session, fd, buffer, length, flags) \
200     (session->send)(fd, buffer, length, flags, &session->abstract)
201 #define LIBSSH2_RECV_FD(session, fd, buffer, length, flags) \
202     (session->recv)(fd, buffer, length, flags, &session->abstract)
203 
204 #define LIBSSH2_SEND(session, buffer, length, flags)  \
205     LIBSSH2_SEND_FD(session, session->socket_fd, buffer, length, flags)
206 #define LIBSSH2_RECV(session, buffer, length, flags)                    \
207     LIBSSH2_RECV_FD(session, session->socket_fd, buffer, length, flags)
208 
209 typedef struct _LIBSSH2_KEX_METHOD LIBSSH2_KEX_METHOD;
210 typedef struct _LIBSSH2_HOSTKEY_METHOD LIBSSH2_HOSTKEY_METHOD;
211 typedef struct _LIBSSH2_CRYPT_METHOD LIBSSH2_CRYPT_METHOD;
212 typedef struct _LIBSSH2_COMP_METHOD LIBSSH2_COMP_METHOD;
213 
214 typedef struct _LIBSSH2_PACKET LIBSSH2_PACKET;
215 
216 typedef enum
217 {
218     libssh2_NB_state_idle = 0,
219     libssh2_NB_state_allocated,
220     libssh2_NB_state_created,
221     libssh2_NB_state_sent,
222     libssh2_NB_state_sent1,
223     libssh2_NB_state_sent2,
224     libssh2_NB_state_sent3,
225     libssh2_NB_state_sent4,
226     libssh2_NB_state_sent5,
227     libssh2_NB_state_sent6,
228     libssh2_NB_state_sent7,
229     libssh2_NB_state_jump1,
230     libssh2_NB_state_jump2,
231     libssh2_NB_state_jump3,
232     libssh2_NB_state_jump4,
233     libssh2_NB_state_jump5,
234     libssh2_NB_state_end
235 } libssh2_nonblocking_states;
236 
237 typedef struct packet_require_state_t
238 {
239     libssh2_nonblocking_states state;
240     time_t start;
241 } packet_require_state_t;
242 
243 typedef struct packet_requirev_state_t
244 {
245     time_t start;
246 } packet_requirev_state_t;
247 
248 typedef struct kmdhgGPshakex_state_t
249 {
250     libssh2_nonblocking_states state;
251     unsigned char *e_packet;
252     unsigned char *s_packet;
253     unsigned char *tmp;
254     unsigned char h_sig_comp[MAX_SHA_DIGEST_LEN];
255     unsigned char c;
256     size_t e_packet_len;
257     size_t s_packet_len;
258     size_t tmp_len;
259     _libssh2_bn_ctx *ctx;
260     _libssh2_dh_ctx x;
261     _libssh2_bn *e;
262     _libssh2_bn *f;
263     _libssh2_bn *k;
264     unsigned char *f_value;
265     unsigned char *k_value;
266     unsigned char *h_sig;
267     size_t f_value_len;
268     size_t k_value_len;
269     size_t h_sig_len;
270     void *exchange_hash;
271     packet_require_state_t req_state;
272     libssh2_nonblocking_states burn_state;
273 } kmdhgGPshakex_state_t;
274 
275 typedef struct key_exchange_state_low_t
276 {
277     libssh2_nonblocking_states state;
278     packet_require_state_t req_state;
279     kmdhgGPshakex_state_t exchange_state;
280     _libssh2_bn *p;             /* SSH2 defined value (p_value) */
281     _libssh2_bn *g;             /* SSH2 defined value (2) */
282     unsigned char request[256]; /* Must fit EC_MAX_POINT_LEN + data */
283     unsigned char *data;
284     size_t request_len;
285     size_t data_len;
286     _libssh2_ec_key *private_key;   /* SSH2 ecdh private key */
287     unsigned char *public_key_oct;  /* SSH2 ecdh public key octal value */
288     size_t public_key_oct_len;      /* SSH2 ecdh public key octal value
289                                        length */
290     unsigned char *curve25519_public_key; /* curve25519 public key, 32
291                                              bytes */
292     unsigned char *curve25519_private_key; /* curve25519 private key, 32
293                                               bytes */
294 } key_exchange_state_low_t;
295 
296 typedef struct key_exchange_state_t
297 {
298     libssh2_nonblocking_states state;
299     packet_require_state_t req_state;
300     key_exchange_state_low_t key_state_low;
301     unsigned char *data;
302     size_t data_len;
303     unsigned char *oldlocal;
304     size_t oldlocal_len;
305 } key_exchange_state_t;
306 
307 #define FwdNotReq "Forward not requested"
308 
309 typedef struct packet_queue_listener_state_t
310 {
311     libssh2_nonblocking_states state;
312     unsigned char packet[17 + (sizeof(FwdNotReq) - 1)];
313     unsigned char *host;
314     unsigned char *shost;
315     uint32_t sender_channel;
316     uint32_t initial_window_size;
317     uint32_t packet_size;
318     uint32_t port;
319     uint32_t sport;
320     uint32_t host_len;
321     uint32_t shost_len;
322     LIBSSH2_CHANNEL *channel;
323 } packet_queue_listener_state_t;
324 
325 #define X11FwdUnAvil "X11 Forward Unavailable"
326 
327 typedef struct packet_x11_open_state_t
328 {
329     libssh2_nonblocking_states state;
330     unsigned char packet[17 + (sizeof(X11FwdUnAvil) - 1)];
331     unsigned char *shost;
332     uint32_t sender_channel;
333     uint32_t initial_window_size;
334     uint32_t packet_size;
335     uint32_t sport;
336     uint32_t shost_len;
337     LIBSSH2_CHANNEL *channel;
338 } packet_x11_open_state_t;
339 
340 struct _LIBSSH2_PACKET
341 {
342     struct list_node node; /* linked list header */
343 
344     /* the raw unencrypted payload */
345     unsigned char *data;
346     size_t data_len;
347 
348     /* Where to start reading data from,
349      * used for channel data that's been partially consumed */
350     size_t data_head;
351 };
352 
353 typedef struct _libssh2_channel_data
354 {
355     /* Identifier */
356     uint32_t id;
357 
358     /* Limits and restrictions */
359     uint32_t window_size_initial, window_size, packet_size;
360 
361     /* Set to 1 when CHANNEL_CLOSE / CHANNEL_EOF sent/received */
362     char close, eof, extended_data_ignore_mode;
363 } libssh2_channel_data;
364 
365 struct _LIBSSH2_CHANNEL
366 {
367     struct list_node node;
368 
369     unsigned char *channel_type;
370     unsigned channel_type_len;
371 
372     /* channel's program exit status */
373     int exit_status;
374 
375     /* channel's program exit signal (without the SIG prefix) */
376     char *exit_signal;
377 
378     libssh2_channel_data local, remote;
379     /* Amount of bytes to be refunded to receive window (but not yet sent) */
380     uint32_t adjust_queue;
381     /* Data immediately available for reading */
382     uint32_t read_avail;
383 
384     LIBSSH2_SESSION *session;
385 
386     void *abstract;
387       LIBSSH2_CHANNEL_CLOSE_FUNC((*close_cb));
388 
389     /* State variables used in libssh2_channel_setenv_ex() */
390     libssh2_nonblocking_states setenv_state;
391     unsigned char *setenv_packet;
392     size_t setenv_packet_len;
393     unsigned char setenv_local_channel[4];
394     packet_requirev_state_t setenv_packet_requirev_state;
395 
396     /* State variables used in libssh2_channel_request_pty_ex()
397        libssh2_channel_request_pty_size_ex() */
398     libssh2_nonblocking_states reqPTY_state;
399     unsigned char reqPTY_packet[41 + 256];
400     size_t reqPTY_packet_len;
401     unsigned char reqPTY_local_channel[4];
402     packet_requirev_state_t reqPTY_packet_requirev_state;
403 
404     /* State variables used in libssh2_channel_x11_req_ex() */
405     libssh2_nonblocking_states reqX11_state;
406     unsigned char *reqX11_packet;
407     size_t reqX11_packet_len;
408     unsigned char reqX11_local_channel[4];
409     packet_requirev_state_t reqX11_packet_requirev_state;
410 
411     /* State variables used in libssh2_channel_process_startup() */
412     libssh2_nonblocking_states process_state;
413     unsigned char *process_packet;
414     size_t process_packet_len;
415     unsigned char process_local_channel[4];
416     packet_requirev_state_t process_packet_requirev_state;
417 
418     /* State variables used in libssh2_channel_flush_ex() */
419     libssh2_nonblocking_states flush_state;
420     size_t flush_refund_bytes;
421     size_t flush_flush_bytes;
422 
423     /* State variables used in libssh2_channel_receive_window_adjust() */
424     libssh2_nonblocking_states adjust_state;
425     unsigned char adjust_adjust[9];     /* packet_type(1) + channel(4) +
426                                            adjustment(4) */
427 
428     /* State variables used in libssh2_channel_read_ex() */
429     libssh2_nonblocking_states read_state;
430 
431     uint32_t read_local_id;
432 
433     /* State variables used in libssh2_channel_write_ex() */
434     libssh2_nonblocking_states write_state;
435     unsigned char write_packet[13];
436     size_t write_packet_len;
437     size_t write_bufwrite;
438 
439     /* State variables used in libssh2_channel_close() */
440     libssh2_nonblocking_states close_state;
441     unsigned char close_packet[5];
442 
443     /* State variables used in libssh2_channel_wait_closedeof() */
444     libssh2_nonblocking_states wait_eof_state;
445 
446     /* State variables used in libssh2_channel_wait_closed() */
447     libssh2_nonblocking_states wait_closed_state;
448 
449     /* State variables used in libssh2_channel_free() */
450     libssh2_nonblocking_states free_state;
451 
452     /* State variables used in libssh2_channel_handle_extended_data2() */
453     libssh2_nonblocking_states extData2_state;
454 
455 };
456 
457 struct _LIBSSH2_LISTENER
458 {
459     struct list_node node; /* linked list header */
460 
461     LIBSSH2_SESSION *session;
462 
463     char *host;
464     int port;
465 
466     /* a list of CHANNELs for this listener */
467     struct list_head queue;
468 
469     int queue_size;
470     int queue_maxsize;
471 
472     /* State variables used in libssh2_channel_forward_cancel() */
473     libssh2_nonblocking_states chanFwdCncl_state;
474     unsigned char *chanFwdCncl_data;
475     size_t chanFwdCncl_data_len;
476 };
477 
478 typedef struct _libssh2_endpoint_data
479 {
480     unsigned char *banner;
481 
482     unsigned char *kexinit;
483     size_t kexinit_len;
484 
485     const LIBSSH2_CRYPT_METHOD *crypt;
486     void *crypt_abstract;
487 
488     const struct _LIBSSH2_MAC_METHOD *mac;
489     uint32_t seqno;
490     void *mac_abstract;
491 
492     const LIBSSH2_COMP_METHOD *comp;
493     void *comp_abstract;
494 
495     /* Method Preferences -- NULL yields "load order" */
496     char *crypt_prefs;
497     char *mac_prefs;
498     char *comp_prefs;
499     char *lang_prefs;
500 } libssh2_endpoint_data;
501 
502 #define PACKETBUFSIZE (1024*16)
503 
504 struct transportpacket
505 {
506     /* ------------- for incoming data --------------- */
507     unsigned char buf[PACKETBUFSIZE];
508     unsigned char init[5];  /* first 5 bytes of the incoming data stream,
509                                still encrypted */
510     size_t writeidx;        /* at what array index we do the next write into
511                                the buffer */
512     size_t readidx;         /* at what array index we do the next read from
513                                the buffer */
514     uint32_t packet_length; /* the most recent packet_length as read from the
515                                network data */
516     uint8_t padding_length; /* the most recent padding_length as read from the
517                                network data */
518     size_t data_num;        /* How much of the total package that has been read
519                                so far. */
520     size_t total_num;       /* How much a total package is supposed to be, in
521                                number of bytes. A full package is
522                                packet_length + padding_length + 4 +
523                                mac_length. */
524     unsigned char *payload; /* this is a pointer to a LIBSSH2_ALLOC()
525                                area to which we write decrypted data */
526     unsigned char *wptr;    /* write pointer into the payload to where we
527                                are currently writing decrypted data */
528 
529     /* ------------- for outgoing data --------------- */
530     unsigned char outbuf[MAX_SSH_PACKET_LEN]; /* area for the outgoing data */
531 
532     int ototal_num;         /* size of outbuf in number of bytes */
533     const unsigned char *odata; /* original pointer to the data */
534     size_t olen;            /* original size of the data we stored in
535                                outbuf */
536     size_t osent;           /* number of bytes already sent */
537 };
538 
539 struct _LIBSSH2_PUBLICKEY
540 {
541     LIBSSH2_CHANNEL *channel;
542     uint32_t version;
543 
544     /* State variables used in libssh2_publickey_packet_receive() */
545     libssh2_nonblocking_states receive_state;
546     unsigned char *receive_packet;
547     size_t receive_packet_len;
548 
549     /* State variables used in libssh2_publickey_add_ex() */
550     libssh2_nonblocking_states add_state;
551     unsigned char *add_packet;
552     unsigned char *add_s;
553 
554     /* State variables used in libssh2_publickey_remove_ex() */
555     libssh2_nonblocking_states remove_state;
556     unsigned char *remove_packet;
557     unsigned char *remove_s;
558 
559     /* State variables used in libssh2_publickey_list_fetch() */
560     libssh2_nonblocking_states listFetch_state;
561     unsigned char *listFetch_s;
562     unsigned char listFetch_buffer[12];
563     unsigned char *listFetch_data;
564     size_t listFetch_data_len;
565 };
566 
567 #define LIBSSH2_SCP_RESPONSE_BUFLEN     256
568 
569 struct flags {
570     int sigpipe;  /* LIBSSH2_FLAG_SIGPIPE */
571     int compress; /* LIBSSH2_FLAG_COMPRESS */
572 };
573 
574 struct _LIBSSH2_SESSION
575 {
576     /* Memory management callbacks */
577     void *abstract;
578       LIBSSH2_ALLOC_FUNC((*alloc));
579       LIBSSH2_REALLOC_FUNC((*realloc));
580       LIBSSH2_FREE_FUNC((*free));
581 
582     /* Other callbacks */
583       LIBSSH2_IGNORE_FUNC((*ssh_msg_ignore));
584       LIBSSH2_DEBUG_FUNC((*ssh_msg_debug));
585       LIBSSH2_DISCONNECT_FUNC((*ssh_msg_disconnect));
586       LIBSSH2_MACERROR_FUNC((*macerror));
587       LIBSSH2_X11_OPEN_FUNC((*x11));
588       LIBSSH2_SEND_FUNC((*send));
589       LIBSSH2_RECV_FUNC((*recv));
590 
591     /* Method preferences -- NULL yields "load order" */
592     char *kex_prefs;
593     char *hostkey_prefs;
594 
595     int state;
596 
597     /* Flag options */
598     struct flags flag;
599 
600     /* Agreed Key Exchange Method */
601     const LIBSSH2_KEX_METHOD *kex;
602     unsigned int burn_optimistic_kexinit:1;
603 
604     unsigned char *session_id;
605     uint32_t session_id_len;
606 
607     /* this is set to TRUE if a blocking API behavior is requested */
608     int api_block_mode;
609 
610     /* Timeout used when blocking API behavior is active */
611     long api_timeout;
612 
613     /* Server's public key */
614     const LIBSSH2_HOSTKEY_METHOD *hostkey;
615     void *server_hostkey_abstract;
616 
617     /* Either set with libssh2_session_hostkey() (for server mode)
618      * Or read from server in (eg) KEXDH_INIT (for client mode)
619      */
620     unsigned char *server_hostkey;
621     uint32_t server_hostkey_len;
622 #if LIBSSH2_MD5
623     unsigned char server_hostkey_md5[MD5_DIGEST_LENGTH];
624     int server_hostkey_md5_valid;
625 #endif                          /* ! LIBSSH2_MD5 */
626     unsigned char server_hostkey_sha1[SHA_DIGEST_LENGTH];
627     int server_hostkey_sha1_valid;
628 
629     unsigned char server_hostkey_sha256[SHA256_DIGEST_LENGTH];
630     int server_hostkey_sha256_valid;
631 
632     /* (remote as source of data -- packet_read ) */
633     libssh2_endpoint_data remote;
634 
635     /* (local as source of data -- packet_write ) */
636     libssh2_endpoint_data local;
637 
638     /* Inbound Data linked list -- Sometimes the packet that comes in isn't the
639        packet we're ready for */
640     struct list_head packets;
641 
642     /* Active connection channels */
643     struct list_head channels;
644 
645     uint32_t next_channel;
646 
647     struct list_head listeners; /* list of LIBSSH2_LISTENER structs */
648 
649     /* Actual I/O socket */
650     libssh2_socket_t socket_fd;
651     int socket_state;
652     int socket_block_directions;
653     int socket_prev_blockstate; /* stores the state of the socket blockiness
654                                    when libssh2_session_startup() is called */
655 
656     /* Error tracking */
657     const char *err_msg;
658     int err_code;
659     int err_flags;
660 
661     /* struct members for packet-level reading */
662     struct transportpacket packet;
663 #ifdef LIBSSH2DEBUG
664     int showmask;               /* what debug/trace messages to display */
665     libssh2_trace_handler_func tracehandler; /* callback to display trace
666                                                 messages */
667     void *tracehandler_context; /* context for the trace handler */
668 #endif
669 
670     /* State variables used in libssh2_banner_send() */
671     libssh2_nonblocking_states banner_TxRx_state;
672     char banner_TxRx_banner[256];
673     ssize_t banner_TxRx_total_send;
674 
675     /* State variables used in libssh2_kexinit() */
676     libssh2_nonblocking_states kexinit_state;
677     unsigned char *kexinit_data;
678     size_t kexinit_data_len;
679 
680     /* State variables used in libssh2_session_startup() */
681     libssh2_nonblocking_states startup_state;
682     unsigned char *startup_data;
683     size_t startup_data_len;
684     unsigned char startup_service[sizeof("ssh-userauth") + 5 - 1];
685     size_t startup_service_length;
686     packet_require_state_t startup_req_state;
687     key_exchange_state_t startup_key_state;
688 
689     /* State variables used in libssh2_session_free() */
690     libssh2_nonblocking_states free_state;
691 
692     /* State variables used in libssh2_session_disconnect_ex() */
693     libssh2_nonblocking_states disconnect_state;
694     unsigned char disconnect_data[256 + 13];
695     size_t disconnect_data_len;
696 
697     /* State variables used in libssh2_packet_read() */
698     libssh2_nonblocking_states readPack_state;
699     int readPack_encrypted;
700 
701     /* State variables used in libssh2_userauth_list() */
702     libssh2_nonblocking_states userauth_list_state;
703     unsigned char *userauth_list_data;
704     size_t userauth_list_data_len;
705     packet_requirev_state_t userauth_list_packet_requirev_state;
706 
707     /* State variables used in libssh2_userauth_password_ex() */
708     libssh2_nonblocking_states userauth_pswd_state;
709     unsigned char *userauth_pswd_data;
710     unsigned char userauth_pswd_data0;
711     size_t userauth_pswd_data_len;
712     char *userauth_pswd_newpw;
713     int userauth_pswd_newpw_len;
714     packet_requirev_state_t userauth_pswd_packet_requirev_state;
715 
716     /* State variables used in libssh2_userauth_hostbased_fromfile_ex() */
717     libssh2_nonblocking_states userauth_host_state;
718     unsigned char *userauth_host_data;
719     size_t userauth_host_data_len;
720     unsigned char *userauth_host_packet;
721     size_t userauth_host_packet_len;
722     unsigned char *userauth_host_method;
723     size_t userauth_host_method_len;
724     unsigned char *userauth_host_s;
725     packet_requirev_state_t userauth_host_packet_requirev_state;
726 
727     /* State variables used in libssh2_userauth_publickey_fromfile_ex() */
728     libssh2_nonblocking_states userauth_pblc_state;
729     unsigned char *userauth_pblc_data;
730     size_t userauth_pblc_data_len;
731     unsigned char *userauth_pblc_packet;
732     size_t userauth_pblc_packet_len;
733     unsigned char *userauth_pblc_method;
734     size_t userauth_pblc_method_len;
735     unsigned char *userauth_pblc_s;
736     unsigned char *userauth_pblc_b;
737     packet_requirev_state_t userauth_pblc_packet_requirev_state;
738 
739     /* State variables used in libssh2_userauth_keyboard_interactive_ex() */
740     libssh2_nonblocking_states userauth_kybd_state;
741     unsigned char *userauth_kybd_data;
742     size_t userauth_kybd_data_len;
743     unsigned char *userauth_kybd_packet;
744     size_t userauth_kybd_packet_len;
745     unsigned int userauth_kybd_auth_name_len;
746     char *userauth_kybd_auth_name;
747     unsigned userauth_kybd_auth_instruction_len;
748     char *userauth_kybd_auth_instruction;
749     unsigned int userauth_kybd_num_prompts;
750     int userauth_kybd_auth_failure;
751     LIBSSH2_USERAUTH_KBDINT_PROMPT *userauth_kybd_prompts;
752     LIBSSH2_USERAUTH_KBDINT_RESPONSE *userauth_kybd_responses;
753     packet_requirev_state_t userauth_kybd_packet_requirev_state;
754 
755     /* State variables used in libssh2_channel_open_ex() */
756     libssh2_nonblocking_states open_state;
757     packet_requirev_state_t open_packet_requirev_state;
758     LIBSSH2_CHANNEL *open_channel;
759     unsigned char *open_packet;
760     size_t open_packet_len;
761     unsigned char *open_data;
762     size_t open_data_len;
763     uint32_t open_local_channel;
764 
765     /* State variables used in libssh2_channel_direct_tcpip_ex() */
766     libssh2_nonblocking_states direct_state;
767     unsigned char *direct_message;
768     size_t direct_host_len;
769     size_t direct_shost_len;
770     size_t direct_message_len;
771 
772     /* State variables used in libssh2_channel_forward_listen_ex() */
773     libssh2_nonblocking_states fwdLstn_state;
774     unsigned char *fwdLstn_packet;
775     uint32_t fwdLstn_host_len;
776     uint32_t fwdLstn_packet_len;
777     packet_requirev_state_t fwdLstn_packet_requirev_state;
778 
779     /* State variables used in libssh2_publickey_init() */
780     libssh2_nonblocking_states pkeyInit_state;
781     LIBSSH2_PUBLICKEY *pkeyInit_pkey;
782     LIBSSH2_CHANNEL *pkeyInit_channel;
783     unsigned char *pkeyInit_data;
784     size_t pkeyInit_data_len;
785     /* 19 = packet_len(4) + version_len(4) + "version"(7) + version_num(4) */
786     unsigned char pkeyInit_buffer[19];
787     size_t pkeyInit_buffer_sent; /* how much of buffer that has been sent */
788 
789     /* State variables used in libssh2_packet_add() */
790     libssh2_nonblocking_states packAdd_state;
791     LIBSSH2_CHANNEL *packAdd_channelp; /* keeper of the channel during EAGAIN
792                                           states */
793     packet_queue_listener_state_t packAdd_Qlstn_state;
794     packet_x11_open_state_t packAdd_x11open_state;
795 
796     /* State variables used in fullpacket() */
797     libssh2_nonblocking_states fullpacket_state;
798     int fullpacket_macstate;
799     size_t fullpacket_payload_len;
800     int fullpacket_packet_type;
801 
802     /* State variables used in libssh2_sftp_init() */
803     libssh2_nonblocking_states sftpInit_state;
804     LIBSSH2_SFTP *sftpInit_sftp;
805     LIBSSH2_CHANNEL *sftpInit_channel;
806     unsigned char sftpInit_buffer[9];   /* sftp_header(5){excludes request_id}
807                                            + version_id(4) */
808     int sftpInit_sent; /* number of bytes from the buffer that have been
809                           sent */
810 
811     /* State variables used in libssh2_scp_recv() / libssh_scp_recv2() */
812     libssh2_nonblocking_states scpRecv_state;
813     unsigned char *scpRecv_command;
814     size_t scpRecv_command_len;
815     unsigned char scpRecv_response[LIBSSH2_SCP_RESPONSE_BUFLEN];
816     size_t scpRecv_response_len;
817     long scpRecv_mode;
818 #if defined(HAVE_LONGLONG) && defined(HAVE_STRTOLL)
819     /* we have the type and we can parse such numbers */
820     long long scpRecv_size;
821 #define scpsize_strtol strtoll
822 #elif defined(HAVE_STRTOI64)
823     __int64 scpRecv_size;
824 #define scpsize_strtol _strtoi64
825 #else
826     long scpRecv_size;
827 #define scpsize_strtol strtol
828 #endif
829     long scpRecv_mtime;
830     long scpRecv_atime;
831     LIBSSH2_CHANNEL *scpRecv_channel;
832 
833     /* State variables used in libssh2_scp_send_ex() */
834     libssh2_nonblocking_states scpSend_state;
835     unsigned char *scpSend_command;
836     size_t scpSend_command_len;
837     unsigned char scpSend_response[LIBSSH2_SCP_RESPONSE_BUFLEN];
838     size_t scpSend_response_len;
839     LIBSSH2_CHANNEL *scpSend_channel;
840 
841     /* Keepalive variables used by keepalive.c. */
842     int keepalive_interval;
843     int keepalive_want_reply;
844     time_t keepalive_last_sent;
845 };
846 
847 /* session.state bits */
848 #define LIBSSH2_STATE_EXCHANGING_KEYS   0x00000001
849 #define LIBSSH2_STATE_NEWKEYS           0x00000002
850 #define LIBSSH2_STATE_AUTHENTICATED     0x00000004
851 #define LIBSSH2_STATE_KEX_ACTIVE        0x00000008
852 
853 /* session.flag helpers */
854 #ifdef MSG_NOSIGNAL
855 #define LIBSSH2_SOCKET_SEND_FLAGS(session)              \
856     (((session)->flag.sigpipe) ? 0 : MSG_NOSIGNAL)
857 #define LIBSSH2_SOCKET_RECV_FLAGS(session)              \
858     (((session)->flag.sigpipe) ? 0 : MSG_NOSIGNAL)
859 #else
860 /* If MSG_NOSIGNAL isn't defined we're SOL on blocking SIGPIPE */
861 #define LIBSSH2_SOCKET_SEND_FLAGS(session)      0
862 #define LIBSSH2_SOCKET_RECV_FLAGS(session)      0
863 #endif
864 
865 /* --------- */
866 
867 /* libssh2 extensible ssh api, ultimately I'd like to allow loading additional
868    methods via .so/.dll */
869 
870 struct _LIBSSH2_KEX_METHOD
871 {
872     const char *name;
873 
874     /* Key exchange, populates session->* and returns 0 on success, non-0 on
875        error */
876     int (*exchange_keys) (LIBSSH2_SESSION * session,
877                           key_exchange_state_low_t * key_state);
878 
879     long flags;
880 };
881 
882 struct _LIBSSH2_HOSTKEY_METHOD
883 {
884     const char *name;
885     unsigned long hash_len;
886 
887     int (*init) (LIBSSH2_SESSION * session, const unsigned char *hostkey_data,
888                  size_t hostkey_data_len, void **abstract);
889     int (*initPEM) (LIBSSH2_SESSION * session, const char *privkeyfile,
890                     unsigned const char *passphrase, void **abstract);
891     int (*initPEMFromMemory) (LIBSSH2_SESSION * session,
892                               const char *privkeyfiledata,
893                               size_t privkeyfiledata_len,
894                               unsigned const char *passphrase,
895                               void **abstract);
896     int (*sig_verify) (LIBSSH2_SESSION * session, const unsigned char *sig,
897                        size_t sig_len, const unsigned char *m,
898                        size_t m_len, void **abstract);
899     int (*signv) (LIBSSH2_SESSION * session, unsigned char **signature,
900                   size_t *signature_len, int veccount,
901                   const struct iovec datavec[], void **abstract);
902     int (*encrypt) (LIBSSH2_SESSION * session, unsigned char **dst,
903                     size_t *dst_len, const unsigned char *src,
904                     size_t src_len, void **abstract);
905     int (*dtor) (LIBSSH2_SESSION * session, void **abstract);
906 };
907 
908 struct _LIBSSH2_CRYPT_METHOD
909 {
910     const char *name;
911     const char *pem_annotation;
912 
913     int blocksize;
914 
915     /* iv and key sizes (-1 for variable length) */
916     int iv_len;
917     int secret_len;
918 
919     long flags;
920 
921     int (*init) (LIBSSH2_SESSION * session,
922                  const LIBSSH2_CRYPT_METHOD * method, unsigned char *iv,
923                  int *free_iv, unsigned char *secret, int *free_secret,
924                  int encrypt, void **abstract);
925     int (*crypt) (LIBSSH2_SESSION * session, unsigned char *block,
926                   size_t blocksize, void **abstract);
927     int (*dtor) (LIBSSH2_SESSION * session, void **abstract);
928 
929       _libssh2_cipher_type(algo);
930 };
931 
932 struct _LIBSSH2_COMP_METHOD
933 {
934     const char *name;
935     int compress; /* 1 if it does compress, 0 if it doesn't */
936     int use_in_auth; /* 1 if compression should be used in userauth */
937     int (*init) (LIBSSH2_SESSION *session, int compress, void **abstract);
938     int (*comp) (LIBSSH2_SESSION *session,
939                  unsigned char *dest,
940                  size_t *dest_len,
941                  const unsigned char *src,
942                  size_t src_len,
943                  void **abstract);
944     int (*decomp) (LIBSSH2_SESSION *session,
945                    unsigned char **dest,
946                    size_t *dest_len,
947                    size_t payload_limit,
948                    const unsigned char *src,
949                    size_t src_len,
950                    void **abstract);
951     int (*dtor) (LIBSSH2_SESSION * session, int compress, void **abstract);
952 };
953 
954 #ifdef LIBSSH2DEBUG
955 void _libssh2_debug(LIBSSH2_SESSION * session, int context, const char *format,
956                     ...);
957 #else
958 #if (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) ||     \
959     defined(__GNUC__)
960 /* C99 supported and also by older GCC */
961 #define _libssh2_debug(x,y,z,...) do {} while (0)
962 #else
963 /* no gcc and not C99, do static and hopefully inline */
964 static inline void
_libssh2_debug(LIBSSH2_SESSION * session,int context,const char * format,...)965 _libssh2_debug(LIBSSH2_SESSION * session, int context, const char *format, ...)
966 {
967     (void)session;
968     (void)context;
969     (void)format;
970 }
971 #endif
972 #endif
973 
974 #define LIBSSH2_SOCKET_UNKNOWN                   1
975 #define LIBSSH2_SOCKET_CONNECTED                 0
976 #define LIBSSH2_SOCKET_DISCONNECTED             -1
977 
978 /* Initial packet state, prior to MAC check */
979 #define LIBSSH2_MAC_UNCONFIRMED                  1
980 /* When MAC type is "none" (proto initiation phase) all packets are deemed
981    "confirmed" */
982 #define LIBSSH2_MAC_CONFIRMED                    0
983 /* Something very bad is going on */
984 #define LIBSSH2_MAC_INVALID                     -1
985 
986 /* Flags for _libssh2_error_flags */
987 /* Error message is allocated on the heap */
988 #define LIBSSH2_ERR_FLAG_DUP                     1
989 
990 /* SSH Packet Types -- Defined by internet draft */
991 /* Transport Layer */
992 #define SSH_MSG_DISCONNECT                          1
993 #define SSH_MSG_IGNORE                              2
994 #define SSH_MSG_UNIMPLEMENTED                       3
995 #define SSH_MSG_DEBUG                               4
996 #define SSH_MSG_SERVICE_REQUEST                     5
997 #define SSH_MSG_SERVICE_ACCEPT                      6
998 
999 #define SSH_MSG_KEXINIT                             20
1000 #define SSH_MSG_NEWKEYS                             21
1001 
1002 /* diffie-hellman-group1-sha1 */
1003 #define SSH_MSG_KEXDH_INIT                          30
1004 #define SSH_MSG_KEXDH_REPLY                         31
1005 
1006 /* diffie-hellman-group-exchange-sha1 and
1007    diffie-hellman-group-exchange-sha256 */
1008 #define SSH_MSG_KEX_DH_GEX_REQUEST_OLD              30
1009 #define SSH_MSG_KEX_DH_GEX_REQUEST                  34
1010 #define SSH_MSG_KEX_DH_GEX_GROUP                    31
1011 #define SSH_MSG_KEX_DH_GEX_INIT                     32
1012 #define SSH_MSG_KEX_DH_GEX_REPLY                    33
1013 
1014 /* ecdh */
1015 #define SSH2_MSG_KEX_ECDH_INIT                      30
1016 #define SSH2_MSG_KEX_ECDH_REPLY                     31
1017 
1018 /* User Authentication */
1019 #define SSH_MSG_USERAUTH_REQUEST                    50
1020 #define SSH_MSG_USERAUTH_FAILURE                    51
1021 #define SSH_MSG_USERAUTH_SUCCESS                    52
1022 #define SSH_MSG_USERAUTH_BANNER                     53
1023 
1024 /* "public key" method */
1025 #define SSH_MSG_USERAUTH_PK_OK                      60
1026 /* "password" method */
1027 #define SSH_MSG_USERAUTH_PASSWD_CHANGEREQ           60
1028 /* "keyboard-interactive" method */
1029 #define SSH_MSG_USERAUTH_INFO_REQUEST               60
1030 #define SSH_MSG_USERAUTH_INFO_RESPONSE              61
1031 
1032 /* Channels */
1033 #define SSH_MSG_GLOBAL_REQUEST                      80
1034 #define SSH_MSG_REQUEST_SUCCESS                     81
1035 #define SSH_MSG_REQUEST_FAILURE                     82
1036 
1037 #define SSH_MSG_CHANNEL_OPEN                        90
1038 #define SSH_MSG_CHANNEL_OPEN_CONFIRMATION           91
1039 #define SSH_MSG_CHANNEL_OPEN_FAILURE                92
1040 #define SSH_MSG_CHANNEL_WINDOW_ADJUST               93
1041 #define SSH_MSG_CHANNEL_DATA                        94
1042 #define SSH_MSG_CHANNEL_EXTENDED_DATA               95
1043 #define SSH_MSG_CHANNEL_EOF                         96
1044 #define SSH_MSG_CHANNEL_CLOSE                       97
1045 #define SSH_MSG_CHANNEL_REQUEST                     98
1046 #define SSH_MSG_CHANNEL_SUCCESS                     99
1047 #define SSH_MSG_CHANNEL_FAILURE                     100
1048 
1049 /* Error codes returned in SSH_MSG_CHANNEL_OPEN_FAILURE message
1050    (see RFC4254) */
1051 #define SSH_OPEN_ADMINISTRATIVELY_PROHIBITED 1
1052 #define SSH_OPEN_CONNECT_FAILED              2
1053 #define SSH_OPEN_UNKNOWN_CHANNELTYPE         3
1054 #define SSH_OPEN_RESOURCE_SHORTAGE           4
1055 
1056 ssize_t _libssh2_recv(libssh2_socket_t socket, void *buffer,
1057                       size_t length, int flags, void **abstract);
1058 ssize_t _libssh2_send(libssh2_socket_t socket, const void *buffer,
1059                       size_t length, int flags, void **abstract);
1060 
1061 #define LIBSSH2_READ_TIMEOUT 60 /* generic timeout in seconds used when
1062                                    waiting for more data to arrive */
1063 
1064 
1065 int _libssh2_kex_exchange(LIBSSH2_SESSION * session, int reexchange,
1066                           key_exchange_state_t * state);
1067 
1068 /* Let crypt.c/hostkey.c expose their method structs */
1069 const LIBSSH2_CRYPT_METHOD **libssh2_crypt_methods(void);
1070 const LIBSSH2_HOSTKEY_METHOD **libssh2_hostkey_methods(void);
1071 
1072 /* misc.c */
1073 int _libssh2_bcrypt_pbkdf(const char *pass,
1074                           size_t passlen,
1075                           const uint8_t *salt,
1076                           size_t saltlen,
1077                           uint8_t *key,
1078                           size_t keylen,
1079                           unsigned int rounds);
1080 
1081 /* pem.c */
1082 int _libssh2_pem_parse(LIBSSH2_SESSION * session,
1083                        const char *headerbegin,
1084                        const char *headerend,
1085                        const unsigned char *passphrase,
1086                        FILE * fp, unsigned char **data, unsigned int *datalen);
1087 int _libssh2_pem_parse_memory(LIBSSH2_SESSION * session,
1088                               const char *headerbegin,
1089                               const char *headerend,
1090                               const char *filedata, size_t filedata_len,
1091                               unsigned char **data, unsigned int *datalen);
1092  /* OpenSSL keys */
1093 int
1094 _libssh2_openssh_pem_parse(LIBSSH2_SESSION * session,
1095                            const unsigned char *passphrase,
1096                            FILE * fp, struct string_buf **decrypted_buf);
1097 int
1098 _libssh2_openssh_pem_parse_memory(LIBSSH2_SESSION * session,
1099                                   const unsigned char *passphrase,
1100                                   const char *filedata, size_t filedata_len,
1101                                   struct string_buf **decrypted_buf);
1102 
1103 int _libssh2_pem_decode_sequence(unsigned char **data, unsigned int *datalen);
1104 int _libssh2_pem_decode_integer(unsigned char **data, unsigned int *datalen,
1105                                 unsigned char **i, unsigned int *ilen);
1106 
1107 /* global.c */
1108 void _libssh2_init_if_needed(void);
1109 
1110 
1111 #define ARRAY_SIZE(a) (sizeof ((a)) / sizeof ((a)[0]))
1112 
1113 /* define to output the libssh2_int64_t type in a *printf() */
1114 #if defined(__BORLANDC__) || defined(_MSC_VER) || defined(__MINGW32__)
1115 #define LIBSSH2_INT64_T_FORMAT "I64d"
1116 #else
1117 #define LIBSSH2_INT64_T_FORMAT "lld"
1118 #endif
1119 
1120 /* In Windows the default file mode is text but an application can override it.
1121 Therefore we specify it explicitly. https://github.com/curl/curl/pull/258
1122 */
1123 #if defined(WIN32) || defined(MSDOS)
1124 #define FOPEN_READTEXT "rt"
1125 #define FOPEN_WRITETEXT "wt"
1126 #define FOPEN_APPENDTEXT "at"
1127 #elif defined(__CYGWIN__)
1128 /* Cygwin has specific behavior we need to address when WIN32 is not defined.
1129 https://cygwin.com/cygwin-ug-net/using-textbinary.html
1130 For write we want our output to have line endings of LF and be compatible with
1131 other Cygwin utilities. For read we want to handle input that may have line
1132 endings either CRLF or LF so 't' is appropriate.
1133 */
1134 #define FOPEN_READTEXT "rt"
1135 #define FOPEN_WRITETEXT "w"
1136 #define FOPEN_APPENDTEXT "a"
1137 #else
1138 #define FOPEN_READTEXT "r"
1139 #define FOPEN_WRITETEXT "w"
1140 #define FOPEN_APPENDTEXT "a"
1141 #endif
1142 
1143 #endif /* LIBSSH2_H */
1144