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