17 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
18 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
19 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
20 #define SSH1_CMSG_USER 4 /* 0x4 */
21 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
22 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
23 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
24 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
25 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
26 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
27 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
28 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
29 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
30 #define SSH1_SMSG_FAILURE 15 /* 0xf */
31 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
32 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
33 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
34 #define SSH1_CMSG_EOF 19 /* 0x13 */
35 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
36 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
37 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
38 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
39 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
40 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
41 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
42 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
43 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
44 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
45 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
46 #define SSH1_MSG_IGNORE 32 /* 0x20 */
47 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
48 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
49 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
50 #define SSH1_MSG_DEBUG 36 /* 0x24 */
51 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
52 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
53 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
54 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
55 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
56 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
57 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
59 #define SSH1_AUTH_TIS 5 /* 0x5 */
60 #define SSH1_AUTH_CCARD 16 /* 0x10 */
62 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
63 /* Mask for protoflags we will echo back to server if seen */
64 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
66 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
67 #define SSH2_MSG_IGNORE 2 /* 0x2 */
68 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
69 #define SSH2_MSG_DEBUG 4 /* 0x4 */
70 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
71 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
72 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
73 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
74 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
75 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
76 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
77 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
78 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
79 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
80 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
81 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
82 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
83 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
84 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
85 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
86 #define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */
87 #define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */
88 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
89 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
90 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
91 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
92 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
93 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
94 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
95 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
96 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
97 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
98 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
99 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
100 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
101 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
104 * Packet type contexts, so that ssh2_pkt_type can correctly decode
105 * the ambiguous type numbers back into the correct type strings.
107 #define SSH2_PKTCTX_DHGROUP1 0x0001
108 #define SSH2_PKTCTX_DHGEX 0x0002
109 #define SSH2_PKTCTX_PUBLICKEY 0x0010
110 #define SSH2_PKTCTX_PASSWORD 0x0020
111 #define SSH2_PKTCTX_KBDINTER 0x0040
112 #define SSH2_PKTCTX_AUTH_MASK 0x00F0
114 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
115 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
116 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
117 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
118 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
119 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
120 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
121 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
122 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
123 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
124 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
125 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
126 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
127 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
128 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
130 static const char *const ssh2_disconnect_reasons[] = {
132 "SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT",
133 "SSH_DISCONNECT_PROTOCOL_ERROR",
134 "SSH_DISCONNECT_KEY_EXCHANGE_FAILED",
135 "SSH_DISCONNECT_HOST_AUTHENTICATION_FAILED",
136 "SSH_DISCONNECT_MAC_ERROR",
137 "SSH_DISCONNECT_COMPRESSION_ERROR",
138 "SSH_DISCONNECT_SERVICE_NOT_AVAILABLE",
139 "SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED",
140 "SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE",
141 "SSH_DISCONNECT_CONNECTION_LOST",
142 "SSH_DISCONNECT_BY_APPLICATION",
143 "SSH_DISCONNECT_TOO_MANY_CONNECTIONS",
144 "SSH_DISCONNECT_AUTH_CANCELLED_BY_USER",
145 "SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE",
146 "SSH_DISCONNECT_ILLEGAL_USER_NAME",
149 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
150 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
151 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
152 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
154 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
157 * Various remote-bug flags.
159 #define BUG_CHOKES_ON_SSH1_IGNORE 1
160 #define BUG_SSH2_HMAC 2
161 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
162 #define BUG_CHOKES_ON_RSA 8
163 #define BUG_SSH2_RSA_PADDING 16
164 #define BUG_SSH2_DERIVEKEY 32
165 #define BUG_SSH2_DH_GEX 64
167 #define translate(x) if (type == x) return #x
168 #define translatec(x,ctx) if (type == x && (pkt_ctx & ctx)) return #x
169 static char *ssh1_pkt_type(int type)
171 translate(SSH1_MSG_DISCONNECT);
172 translate(SSH1_SMSG_PUBLIC_KEY);
173 translate(SSH1_CMSG_SESSION_KEY);
174 translate(SSH1_CMSG_USER);
175 translate(SSH1_CMSG_AUTH_RSA);
176 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
177 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
178 translate(SSH1_CMSG_AUTH_PASSWORD);
179 translate(SSH1_CMSG_REQUEST_PTY);
180 translate(SSH1_CMSG_WINDOW_SIZE);
181 translate(SSH1_CMSG_EXEC_SHELL);
182 translate(SSH1_CMSG_EXEC_CMD);
183 translate(SSH1_SMSG_SUCCESS);
184 translate(SSH1_SMSG_FAILURE);
185 translate(SSH1_CMSG_STDIN_DATA);
186 translate(SSH1_SMSG_STDOUT_DATA);
187 translate(SSH1_SMSG_STDERR_DATA);
188 translate(SSH1_CMSG_EOF);
189 translate(SSH1_SMSG_EXIT_STATUS);
190 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
191 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
192 translate(SSH1_MSG_CHANNEL_DATA);
193 translate(SSH1_MSG_CHANNEL_CLOSE);
194 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
195 translate(SSH1_SMSG_X11_OPEN);
196 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
197 translate(SSH1_MSG_PORT_OPEN);
198 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
199 translate(SSH1_SMSG_AGENT_OPEN);
200 translate(SSH1_MSG_IGNORE);
201 translate(SSH1_CMSG_EXIT_CONFIRMATION);
202 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
203 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
204 translate(SSH1_MSG_DEBUG);
205 translate(SSH1_CMSG_REQUEST_COMPRESSION);
206 translate(SSH1_CMSG_AUTH_TIS);
207 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
208 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
209 translate(SSH1_CMSG_AUTH_CCARD);
210 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
211 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
214 static char *ssh2_pkt_type(int pkt_ctx, int type)
216 translate(SSH2_MSG_DISCONNECT);
217 translate(SSH2_MSG_IGNORE);
218 translate(SSH2_MSG_UNIMPLEMENTED);
219 translate(SSH2_MSG_DEBUG);
220 translate(SSH2_MSG_SERVICE_REQUEST);
221 translate(SSH2_MSG_SERVICE_ACCEPT);
222 translate(SSH2_MSG_KEXINIT);
223 translate(SSH2_MSG_NEWKEYS);
224 translatec(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP1);
225 translatec(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP1);
226 translatec(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
227 translatec(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
228 translatec(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
229 translatec(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
230 translate(SSH2_MSG_USERAUTH_REQUEST);
231 translate(SSH2_MSG_USERAUTH_FAILURE);
232 translate(SSH2_MSG_USERAUTH_SUCCESS);
233 translate(SSH2_MSG_USERAUTH_BANNER);
234 translatec(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
235 translatec(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
236 translatec(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
237 translatec(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
238 translate(SSH2_MSG_GLOBAL_REQUEST);
239 translate(SSH2_MSG_REQUEST_SUCCESS);
240 translate(SSH2_MSG_REQUEST_FAILURE);
241 translate(SSH2_MSG_CHANNEL_OPEN);
242 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
243 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
244 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
245 translate(SSH2_MSG_CHANNEL_DATA);
246 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
247 translate(SSH2_MSG_CHANNEL_EOF);
248 translate(SSH2_MSG_CHANNEL_CLOSE);
249 translate(SSH2_MSG_CHANNEL_REQUEST);
250 translate(SSH2_MSG_CHANNEL_SUCCESS);
251 translate(SSH2_MSG_CHANNEL_FAILURE);
257 #define GET_32BIT(cp) \
258 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
259 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
260 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
261 ((unsigned long)(unsigned char)(cp)[3]))
263 #define PUT_32BIT(cp, value) { \
264 (cp)[0] = (unsigned char)((value) >> 24); \
265 (cp)[1] = (unsigned char)((value) >> 16); \
266 (cp)[2] = (unsigned char)((value) >> 8); \
267 (cp)[3] = (unsigned char)(value); }
269 enum { PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM };
271 /* Coroutine mechanics for the sillier bits of the code */
272 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
275 if (!ssh->t) ssh->t = smalloc(sizeof(struct t)); \
277 #define crFinish(z) } *crLine = 0; return (z); }
278 #define crFinishV } *crLine = 0; return; }
279 #define crReturn(z) \
281 *crLine =__LINE__; return (z); case __LINE__:;\
285 *crLine=__LINE__; return; case __LINE__:;\
287 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
288 #define crStopV do{ *crLine = 0; return; }while(0)
289 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
290 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
292 typedef struct ssh_tag *Ssh;
294 static void ssh2_pkt_init(Ssh, int pkt_type);
295 static void ssh2_pkt_addbool(Ssh, unsigned char value);
296 static void ssh2_pkt_adduint32(Ssh, unsigned long value);
297 static void ssh2_pkt_addstring_start(Ssh);
298 static void ssh2_pkt_addstring_str(Ssh, char *data);
299 static void ssh2_pkt_addstring_data(Ssh, char *data, int len);
300 static void ssh2_pkt_addstring(Ssh, char *data);
301 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
302 static void ssh2_pkt_addmp(Ssh, Bignum b);
303 static int ssh2_pkt_construct(Ssh);
304 static void ssh2_pkt_send(Ssh);
307 * Buffer management constants. There are several of these for
308 * various different purposes:
310 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
311 * on a local data stream before we throttle the whole SSH
312 * connection (in SSH1 only). Throttling the whole connection is
313 * pretty drastic so we set this high in the hope it won't
316 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
317 * on the SSH connection itself before we defensively throttle
318 * _all_ local data streams. This is pretty drastic too (though
319 * thankfully unlikely in SSH2 since the window mechanism should
320 * ensure that the server never has any need to throttle its end
321 * of the connection), so we set this high as well.
323 * - OUR_V2_WINSIZE is the maximum window size we present on SSH2
327 #define SSH1_BUFFER_LIMIT 32768
328 #define SSH_MAX_BACKLOG 32768
329 #define OUR_V2_WINSIZE 16384
331 const static struct ssh_kex *kex_algs[] = {
332 &ssh_diffiehellman_gex,
336 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
338 static void *nullmac_make_context(void)
342 static void nullmac_free_context(void *handle)
345 static void nullmac_key(void *handle, unsigned char *key)
348 static void nullmac_generate(void *handle, unsigned char *blk, int len,
352 static int nullmac_verify(void *handle, unsigned char *blk, int len,
357 const static struct ssh_mac ssh_mac_none = {
358 nullmac_make_context, nullmac_free_context, nullmac_key,
359 nullmac_generate, nullmac_verify, "none", 0
361 const static struct ssh_mac *macs[] = {
362 &ssh_sha1, &ssh_md5, &ssh_mac_none
364 const static struct ssh_mac *buggymacs[] = {
365 &ssh_sha1_buggy, &ssh_md5, &ssh_mac_none
368 static void *ssh_comp_none_init(void)
372 static void ssh_comp_none_cleanup(void *handle)
375 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
376 unsigned char **outblock, int *outlen)
380 static int ssh_comp_none_disable(void *handle)
384 const static struct ssh_compress ssh_comp_none = {
386 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
387 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
388 ssh_comp_none_disable, NULL
390 extern const struct ssh_compress ssh_zlib;
391 const static struct ssh_compress *compressions[] = {
392 &ssh_zlib, &ssh_comp_none
395 enum { /* channel types */
400 CHAN_SOCKDATA_DORMANT /* one the remote hasn't confirmed */
404 * 2-3-4 tree storing channels.
407 Ssh ssh; /* pointer back to main context */
408 unsigned remoteid, localid;
411 * In SSH1, this value contains four bits:
413 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
414 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
415 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
416 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
418 * A channel is completely finished with when all four bits are set.
422 struct ssh1_data_channel {
425 struct ssh2_data_channel {
427 unsigned remwindow, remmaxpkt;
432 struct ssh_agent_channel {
433 unsigned char *message;
434 unsigned char msglen[4];
435 int lensofar, totallen;
437 struct ssh_x11_channel {
440 struct ssh_pfd_channel {
447 * 2-3-4 tree storing remote->local port forwardings. SSH 1 and SSH
448 * 2 use this structure in different ways, reflecting SSH 2's
449 * altogether saner approach to port forwarding.
451 * In SSH 1, you arrange a remote forwarding by sending the server
452 * the remote port number, and the local destination host:port.
453 * When a connection comes in, the server sends you back that
454 * host:port pair, and you connect to it. This is a ready-made
455 * security hole if you're not on the ball: a malicious server
456 * could send you back _any_ host:port pair, so if you trustingly
457 * connect to the address it gives you then you've just opened the
458 * entire inside of your corporate network just by connecting
459 * through it to a dodgy SSH server. Hence, we must store a list of
460 * host:port pairs we _are_ trying to forward to, and reject a
461 * connection request from the server if it's not in the list.
463 * In SSH 2, each side of the connection minds its own business and
464 * doesn't send unnecessary information to the other. You arrange a
465 * remote forwarding by sending the server just the remote port
466 * number. When a connection comes in, the server tells you which
467 * of its ports was connected to; and _you_ have to remember what
468 * local host:port pair went with that port number.
470 * Hence: in SSH 1 this structure stores host:port pairs we intend
471 * to allow connections to, and is indexed by those host:port
472 * pairs. In SSH 2 it stores a mapping from source port to
473 * destination host:port pair, and is indexed by source port.
475 struct ssh_rportfwd {
476 unsigned sport, dport;
489 static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt);
490 static void ssh2_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt);
491 static void ssh_size(void *handle, int width, int height);
492 static void ssh_special(void *handle, Telnet_Special);
493 static int ssh2_try_send(struct ssh_channel *c);
494 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
495 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
496 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin);
497 static int ssh_sendbuffer(void *handle);
499 struct rdpkt1_state_tag {
500 long len, pad, biglen, to_read;
501 unsigned long realcrc, gotcrc;
507 struct rdpkt2_state_tag {
508 long len, pad, payload, packetlen, maclen;
511 unsigned long incoming_sequence;
515 const struct plug_function_table *fn;
516 /* the above field _must_ be first in the structure */
518 SHA_State exhash, exhashbase;
525 unsigned char session_key[32];
527 int v1_remote_protoflags;
528 int v1_local_protoflags;
529 int agentfwd_enabled;
532 const struct ssh_cipher *cipher;
535 const struct ssh2_cipher *cscipher, *sccipher;
536 void *cs_cipher_ctx, *sc_cipher_ctx;
537 const struct ssh_mac *csmac, *scmac;
538 void *cs_mac_ctx, *sc_mac_ctx;
539 const struct ssh_compress *cscomp, *sccomp;
540 void *cs_comp_ctx, *sc_comp_ctx;
541 const struct ssh_kex *kex;
542 const struct ssh_signkey *hostkey;
543 unsigned char v2_session_id[20];
549 int echoing, editing;
553 int term_width, term_height;
555 tree234 *channels; /* indexed by local id */
556 struct ssh_channel *mainchan; /* primary session channel */
563 SSH_STATE_BEFORE_SIZE,
569 int size_needed, eof_needed;
572 struct Packet pktout;
573 unsigned char *deferred_send_data;
574 int deferred_len, deferred_size;
577 * Gross hack: pscp will try to start SFTP but fall back to
578 * scp1 if that fails. This variable is the means by which
579 * scp.c can reach into the SSH code and find out which one it
585 * Used for username and password input.
587 char *userpass_input_buffer;
588 int userpass_input_buflen;
589 int userpass_input_bufpos;
590 int userpass_input_echo;
592 char *portfwd_strptr;
598 int v1_throttle_count;
601 int v1_stdout_throttling;
602 int v2_outgoing_sequence;
604 int ssh1_rdpkt_crstate;
605 int ssh2_rdpkt_crstate;
606 int do_ssh_init_crstate;
607 int ssh_gotdata_crstate;
608 int ssh1_protocol_crstate;
609 int do_ssh1_login_crstate;
610 int do_ssh2_transport_crstate;
611 int do_ssh2_authconn_crstate;
613 void *do_ssh_init_state;
614 void *do_ssh1_login_state;
615 void *do_ssh2_transport_state;
616 void *do_ssh2_authconn_state;
618 struct rdpkt1_state_tag rdpkt1_state;
619 struct rdpkt2_state_tag rdpkt2_state;
621 void (*protocol) (Ssh ssh, unsigned char *in, int inlen, int ispkt);
622 int (*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
625 * We maintain a full _copy_ of a Config structure here, not
626 * merely a pointer to it. That way, when we're passed a new
627 * one for reconfiguration, we can check the differences and
628 * potentially reconfigure port forwardings etc in mid-session.
633 #define logevent(s) logevent(ssh->frontend, s)
635 /* logevent, only printf-formatted. */
636 static void logeventf(Ssh ssh, char *fmt, ...)
642 buf = dupvprintf(fmt, ap);
648 #define bombout(msg) ( ssh->state = SSH_STATE_CLOSED, \
649 (ssh->s ? sk_close(ssh->s), ssh->s = NULL : 0), \
650 logeventf msg, connection_fatal msg )
652 static int ssh_channelcmp(void *av, void *bv)
654 struct ssh_channel *a = (struct ssh_channel *) av;
655 struct ssh_channel *b = (struct ssh_channel *) bv;
656 if (a->localid < b->localid)
658 if (a->localid > b->localid)
662 static int ssh_channelfind(void *av, void *bv)
664 unsigned *a = (unsigned *) av;
665 struct ssh_channel *b = (struct ssh_channel *) bv;
673 static int ssh_rportcmp_ssh1(void *av, void *bv)
675 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
676 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
678 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
679 return i < 0 ? -1 : +1;
680 if (a->dport > b->dport)
682 if (a->dport < b->dport)
687 static int ssh_rportcmp_ssh2(void *av, void *bv)
689 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
690 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
692 if (a->sport > b->sport)
694 if (a->sport < b->sport)
699 static int alloc_channel_id(Ssh ssh)
701 const unsigned CHANNEL_NUMBER_OFFSET = 256;
702 unsigned low, high, mid;
704 struct ssh_channel *c;
707 * First-fit allocation of channel numbers: always pick the
708 * lowest unused one. To do this, binary-search using the
709 * counted B-tree to find the largest channel ID which is in a
710 * contiguous sequence from the beginning. (Precisely
711 * everything in that sequence must have ID equal to its tree
712 * index plus CHANNEL_NUMBER_OFFSET.)
714 tsize = count234(ssh->channels);
718 while (high - low > 1) {
719 mid = (high + low) / 2;
720 c = index234(ssh->channels, mid);
721 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
722 low = mid; /* this one is fine */
724 high = mid; /* this one is past it */
727 * Now low points to either -1, or the tree index of the
728 * largest ID in the initial sequence.
731 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
732 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
734 return low + 1 + CHANNEL_NUMBER_OFFSET;
737 static void c_write(Ssh ssh, char *buf, int len)
739 if ((flags & FLAG_STDERR)) {
741 for (i = 0; i < len; i++)
743 fputc(buf[i], stderr);
746 from_backend(ssh->frontend, 1, buf, len);
749 static void c_write_untrusted(Ssh ssh, char *buf, int len)
752 for (i = 0; i < len; i++) {
754 c_write(ssh, "\r\n", 2);
755 else if ((buf[i] & 0x60) || (buf[i] == '\r'))
756 c_write(ssh, buf + i, 1);
760 static void c_write_str(Ssh ssh, char *buf)
762 c_write(ssh, buf, strlen(buf));
766 * Collect incoming data in the incoming packet buffer.
767 * Decipher and verify the packet when it is completely read.
768 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
769 * Update the *data and *datalen variables.
770 * Return the additional nr of bytes needed, or 0 when
771 * a complete packet is available.
773 static int ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
775 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
777 crBegin(ssh->ssh1_rdpkt_crstate);
782 ssh->pktin.length = 0;
784 for (st->i = st->len = 0; st->i < 4; st->i++) {
785 while ((*datalen) == 0)
787 st->len = (st->len << 8) + **data;
788 (*data)++, (*datalen)--;
791 st->pad = 8 - (st->len % 8);
792 st->biglen = st->len + st->pad;
793 ssh->pktin.length = st->len - 5;
795 if (ssh->pktin.maxlen < st->biglen) {
796 ssh->pktin.maxlen = st->biglen;
797 ssh->pktin.data = srealloc(ssh->pktin.data, st->biglen + APIEXTRA);
800 st->to_read = st->biglen;
801 st->p = ssh->pktin.data;
802 while (st->to_read > 0) {
803 st->chunk = st->to_read;
804 while ((*datalen) == 0)
805 crReturn(st->to_read);
806 if (st->chunk > (*datalen))
807 st->chunk = (*datalen);
808 memcpy(st->p, *data, st->chunk);
810 *datalen -= st->chunk;
812 st->to_read -= st->chunk;
815 if (ssh->cipher && detect_attack(ssh->crcda_ctx, ssh->pktin.data,
817 bombout((ssh,"Network attack (CRC compensation) detected!"));
822 ssh->cipher->decrypt(ssh->v1_cipher_ctx, ssh->pktin.data, st->biglen);
824 st->realcrc = crc32(ssh->pktin.data, st->biglen - 4);
825 st->gotcrc = GET_32BIT(ssh->pktin.data + st->biglen - 4);
826 if (st->gotcrc != st->realcrc) {
827 bombout((ssh,"Incorrect CRC received on packet"));
831 ssh->pktin.body = ssh->pktin.data + st->pad + 1;
833 if (ssh->v1_compressing) {
834 unsigned char *decompblk;
836 zlib_decompress_block(ssh->sc_comp_ctx,
837 ssh->pktin.body - 1, ssh->pktin.length + 1,
838 &decompblk, &decomplen);
840 if (ssh->pktin.maxlen < st->pad + decomplen) {
841 ssh->pktin.maxlen = st->pad + decomplen;
842 ssh->pktin.data = srealloc(ssh->pktin.data,
843 ssh->pktin.maxlen + APIEXTRA);
844 ssh->pktin.body = ssh->pktin.data + st->pad + 1;
847 memcpy(ssh->pktin.body - 1, decompblk, decomplen);
849 ssh->pktin.length = decomplen - 1;
852 ssh->pktin.type = ssh->pktin.body[-1];
855 log_packet(ssh->logctx,
856 PKT_INCOMING, ssh->pktin.type,
857 ssh1_pkt_type(ssh->pktin.type),
858 ssh->pktin.body, ssh->pktin.length);
860 if (ssh->pktin.type == SSH1_SMSG_STDOUT_DATA ||
861 ssh->pktin.type == SSH1_SMSG_STDERR_DATA ||
862 ssh->pktin.type == SSH1_MSG_DEBUG ||
863 ssh->pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE ||
864 ssh->pktin.type == SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
865 long stringlen = GET_32BIT(ssh->pktin.body);
866 if (stringlen + 4 != ssh->pktin.length) {
867 bombout((ssh,"Received data packet with bogus string length"));
872 if (ssh->pktin.type == SSH1_MSG_DEBUG) {
873 /* log debug message */
875 int stringlen = GET_32BIT(ssh->pktin.body);
876 strcpy(buf, "Remote debug message: ");
879 memcpy(buf + 8, ssh->pktin.body + 4, stringlen);
880 buf[8 + stringlen] = '\0';
883 } else if (ssh->pktin.type == SSH1_MSG_IGNORE) {
888 if (ssh->pktin.type == SSH1_MSG_DISCONNECT) {
889 /* log reason code in disconnect message */
891 unsigned msglen = GET_32BIT(ssh->pktin.body);
893 strcpy(buf, "Remote sent disconnect: ");
894 nowlen = strlen(buf);
895 if (msglen > sizeof(buf) - nowlen - 1)
896 msglen = sizeof(buf) - nowlen - 1;
897 memcpy(buf + nowlen, ssh->pktin.body + 4, msglen);
898 buf[nowlen + msglen] = '\0';
899 /* logevent(buf); (this is now done within the bombout macro) */
900 bombout((ssh,"Server sent disconnect message:\n\"%s\"", buf+nowlen));
907 static int ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
909 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
911 crBegin(ssh->ssh2_rdpkt_crstate);
915 ssh->pktin.length = 0;
917 st->cipherblk = ssh->sccipher->blksize;
920 if (st->cipherblk < 8)
923 if (ssh->pktin.maxlen < st->cipherblk) {
924 ssh->pktin.maxlen = st->cipherblk;
925 ssh->pktin.data = srealloc(ssh->pktin.data, st->cipherblk + APIEXTRA);
929 * Acquire and decrypt the first block of the packet. This will
930 * contain the length and padding details.
932 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
933 while ((*datalen) == 0)
934 crReturn(st->cipherblk - st->i);
935 ssh->pktin.data[st->i] = *(*data)++;
940 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
941 ssh->pktin.data, st->cipherblk);
944 * Now get the length and padding figures.
946 st->len = GET_32BIT(ssh->pktin.data);
947 st->pad = ssh->pktin.data[4];
950 * _Completely_ silly lengths should be stomped on before they
951 * do us any more damage.
953 if (st->len < 0 || st->pad < 0 || st->len + st->pad < 0) {
954 bombout((ssh,"Incoming packet was garbled on decryption"));
959 * This enables us to deduce the payload length.
961 st->payload = st->len - st->pad - 1;
963 ssh->pktin.length = st->payload + 5;
966 * So now we can work out the total packet length.
968 st->packetlen = st->len + 4;
969 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
972 * Adjust memory allocation if packet is too big.
974 if (ssh->pktin.maxlen < st->packetlen + st->maclen) {
975 ssh->pktin.maxlen = st->packetlen + st->maclen;
976 ssh->pktin.data = srealloc(ssh->pktin.data,
977 ssh->pktin.maxlen + APIEXTRA);
981 * Read and decrypt the remainder of the packet.
983 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
985 while ((*datalen) == 0)
986 crReturn(st->packetlen + st->maclen - st->i);
987 ssh->pktin.data[st->i] = *(*data)++;
990 /* Decrypt everything _except_ the MAC. */
992 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
993 ssh->pktin.data + st->cipherblk,
994 st->packetlen - st->cipherblk);
1000 && !ssh->scmac->verify(ssh->sc_mac_ctx, ssh->pktin.data, st->len + 4,
1001 st->incoming_sequence)) {
1002 bombout((ssh,"Incorrect MAC received on packet"));
1005 st->incoming_sequence++; /* whether or not we MACed */
1008 * Decompress packet payload.
1011 unsigned char *newpayload;
1014 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1015 ssh->pktin.data + 5, ssh->pktin.length - 5,
1016 &newpayload, &newlen)) {
1017 if (ssh->pktin.maxlen < newlen + 5) {
1018 ssh->pktin.maxlen = newlen + 5;
1019 ssh->pktin.data = srealloc(ssh->pktin.data,
1020 ssh->pktin.maxlen + APIEXTRA);
1022 ssh->pktin.length = 5 + newlen;
1023 memcpy(ssh->pktin.data + 5, newpayload, newlen);
1028 ssh->pktin.savedpos = 6;
1029 ssh->pktin.type = ssh->pktin.data[5];
1032 log_packet(ssh->logctx, PKT_INCOMING, ssh->pktin.type,
1033 ssh2_pkt_type(ssh->pkt_ctx, ssh->pktin.type),
1034 ssh->pktin.data+6, ssh->pktin.length-6);
1036 switch (ssh->pktin.type) {
1038 * These packets we must handle instantly.
1040 case SSH2_MSG_DISCONNECT:
1042 /* log reason code in disconnect message */
1045 int reason = GET_32BIT(ssh->pktin.data + 6);
1046 unsigned msglen = GET_32BIT(ssh->pktin.data + 10);
1048 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
1049 buf = dupprintf("Received disconnect message (%s)",
1050 ssh2_disconnect_reasons[reason]);
1052 buf = dupprintf("Received disconnect message (unknown"
1053 " type %d)", reason);
1057 buf = dupprintf("Disconnection message text: %n%.*s",
1058 &nowlen, msglen, ssh->pktin.data + 14);
1060 bombout((ssh,"Server sent disconnect message\ntype %d (%s):\n\"%s\"",
1062 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
1063 ssh2_disconnect_reasons[reason] : "unknown",
1069 case SSH2_MSG_IGNORE:
1071 case SSH2_MSG_DEBUG:
1073 /* log the debug message */
1075 /* int display = ssh->pktin.body[6]; */
1076 int stringlen = GET_32BIT(ssh->pktin.data+7);
1078 strcpy(buf, "Remote debug message: ");
1079 prefix = strlen(buf);
1080 if (stringlen > (int)(sizeof(buf)-prefix-1))
1081 stringlen = sizeof(buf)-prefix-1;
1082 memcpy(buf + prefix, ssh->pktin.data + 11, stringlen);
1083 buf[prefix + stringlen] = '\0';
1086 goto next_packet; /* FIXME: print the debug message */
1089 * These packets we need do nothing about here.
1091 case SSH2_MSG_UNIMPLEMENTED:
1092 case SSH2_MSG_SERVICE_REQUEST:
1093 case SSH2_MSG_SERVICE_ACCEPT:
1094 case SSH2_MSG_KEXINIT:
1095 case SSH2_MSG_NEWKEYS:
1096 case SSH2_MSG_KEXDH_INIT:
1097 case SSH2_MSG_KEXDH_REPLY:
1098 /* case SSH2_MSG_KEX_DH_GEX_REQUEST: duplicate case value */
1099 /* case SSH2_MSG_KEX_DH_GEX_GROUP: duplicate case value */
1100 case SSH2_MSG_KEX_DH_GEX_INIT:
1101 case SSH2_MSG_KEX_DH_GEX_REPLY:
1102 case SSH2_MSG_USERAUTH_REQUEST:
1103 case SSH2_MSG_USERAUTH_FAILURE:
1104 case SSH2_MSG_USERAUTH_SUCCESS:
1105 case SSH2_MSG_USERAUTH_BANNER:
1106 case SSH2_MSG_USERAUTH_PK_OK:
1107 /* case SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ: duplicate case value */
1108 /* case SSH2_MSG_USERAUTH_INFO_REQUEST: duplicate case value */
1109 case SSH2_MSG_USERAUTH_INFO_RESPONSE:
1110 case SSH2_MSG_GLOBAL_REQUEST:
1111 case SSH2_MSG_REQUEST_SUCCESS:
1112 case SSH2_MSG_REQUEST_FAILURE:
1113 case SSH2_MSG_CHANNEL_OPEN:
1114 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
1115 case SSH2_MSG_CHANNEL_OPEN_FAILURE:
1116 case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
1117 case SSH2_MSG_CHANNEL_DATA:
1118 case SSH2_MSG_CHANNEL_EXTENDED_DATA:
1119 case SSH2_MSG_CHANNEL_EOF:
1120 case SSH2_MSG_CHANNEL_CLOSE:
1121 case SSH2_MSG_CHANNEL_REQUEST:
1122 case SSH2_MSG_CHANNEL_SUCCESS:
1123 case SSH2_MSG_CHANNEL_FAILURE:
1127 * For anything else we send SSH2_MSG_UNIMPLEMENTED.
1130 ssh2_pkt_init(ssh, SSH2_MSG_UNIMPLEMENTED);
1131 ssh2_pkt_adduint32(ssh, st->incoming_sequence - 1);
1139 static void ssh1_pktout_size(Ssh ssh, int len)
1143 len += 5; /* type and CRC */
1144 pad = 8 - (len % 8);
1147 ssh->pktout.length = len - 5;
1148 if (ssh->pktout.maxlen < biglen) {
1149 ssh->pktout.maxlen = biglen;
1151 /* Allocate enough buffer space for extra block
1152 * for MS CryptEncrypt() */
1153 ssh->pktout.data = srealloc(ssh->pktout.data, biglen + 12);
1155 ssh->pktout.data = srealloc(ssh->pktout.data, biglen + 4);
1158 ssh->pktout.body = ssh->pktout.data + 4 + pad + 1;
1161 static void s_wrpkt_start(Ssh ssh, int type, int len)
1163 ssh1_pktout_size(ssh, len);
1164 ssh->pktout.type = type;
1167 static int s_wrpkt_prepare(Ssh ssh)
1169 int pad, len, biglen, i;
1172 ssh->pktout.body[-1] = ssh->pktout.type;
1175 log_packet(ssh->logctx, PKT_OUTGOING, ssh->pktout.type,
1176 ssh1_pkt_type(ssh->pktout.type),
1177 ssh->pktout.body, ssh->pktout.length);
1179 if (ssh->v1_compressing) {
1180 unsigned char *compblk;
1182 zlib_compress_block(ssh->cs_comp_ctx,
1183 ssh->pktout.body - 1, ssh->pktout.length + 1,
1184 &compblk, &complen);
1185 ssh1_pktout_size(ssh, complen - 1);
1186 memcpy(ssh->pktout.body - 1, compblk, complen);
1190 len = ssh->pktout.length + 5; /* type and CRC */
1191 pad = 8 - (len % 8);
1194 for (i = 0; i < pad; i++)
1195 ssh->pktout.data[i + 4] = random_byte();
1196 crc = crc32(ssh->pktout.data + 4, biglen - 4);
1197 PUT_32BIT(ssh->pktout.data + biglen, crc);
1198 PUT_32BIT(ssh->pktout.data, len);
1201 ssh->cipher->encrypt(ssh->v1_cipher_ctx, ssh->pktout.data + 4, biglen);
1206 static void s_wrpkt(Ssh ssh)
1209 len = s_wrpkt_prepare(ssh);
1210 backlog = sk_write(ssh->s, (char *)ssh->pktout.data, len);
1211 if (backlog > SSH_MAX_BACKLOG)
1212 ssh_throttle_all(ssh, 1, backlog);
1215 static void s_wrpkt_defer(Ssh ssh)
1218 len = s_wrpkt_prepare(ssh);
1219 if (ssh->deferred_len + len > ssh->deferred_size) {
1220 ssh->deferred_size = ssh->deferred_len + len + 128;
1221 ssh->deferred_send_data = srealloc(ssh->deferred_send_data,
1222 ssh->deferred_size);
1224 memcpy(ssh->deferred_send_data + ssh->deferred_len, ssh->pktout.data, len);
1225 ssh->deferred_len += len;
1229 * Construct a packet with the specified contents.
1231 static void construct_packet(Ssh ssh, int pkttype, va_list ap1, va_list ap2)
1233 unsigned char *p, *argp, argchar;
1234 unsigned long argint;
1235 int pktlen, argtype, arglen;
1239 while ((argtype = va_arg(ap1, int)) != PKT_END) {
1242 (void) va_arg(ap1, int);
1246 (void) va_arg(ap1, int);
1250 (void) va_arg(ap1, unsigned char *);
1251 arglen = va_arg(ap1, int);
1255 argp = va_arg(ap1, unsigned char *);
1256 arglen = strlen((char *)argp);
1257 pktlen += 4 + arglen;
1260 bn = va_arg(ap1, Bignum);
1261 pktlen += ssh1_bignum_length(bn);
1268 s_wrpkt_start(ssh, pkttype, pktlen);
1269 p = ssh->pktout.body;
1271 while ((argtype = va_arg(ap2, int)) != PKT_END) {
1274 argint = va_arg(ap2, int);
1275 PUT_32BIT(p, argint);
1279 argchar = (unsigned char) va_arg(ap2, int);
1284 argp = va_arg(ap2, unsigned char *);
1285 arglen = va_arg(ap2, int);
1286 memcpy(p, argp, arglen);
1290 argp = va_arg(ap2, unsigned char *);
1291 arglen = strlen((char *)argp);
1292 PUT_32BIT(p, arglen);
1293 memcpy(p + 4, argp, arglen);
1297 bn = va_arg(ap2, Bignum);
1298 p += ssh1_write_bignum(p, bn);
1304 static void send_packet(Ssh ssh, int pkttype, ...)
1307 va_start(ap1, pkttype);
1308 va_start(ap2, pkttype);
1309 construct_packet(ssh, pkttype, ap1, ap2);
1313 static void defer_packet(Ssh ssh, int pkttype, ...)
1316 va_start(ap1, pkttype);
1317 va_start(ap2, pkttype);
1318 construct_packet(ssh, pkttype, ap1, ap2);
1322 static int ssh_versioncmp(char *a, char *b)
1325 unsigned long av, bv;
1327 av = strtoul(a, &ae, 10);
1328 bv = strtoul(b, &be, 10);
1330 return (av < bv ? -1 : +1);
1335 av = strtoul(ae, &ae, 10);
1336 bv = strtoul(be, &be, 10);
1338 return (av < bv ? -1 : +1);
1343 * Utility routines for putting an SSH-protocol `string' and
1344 * `uint32' into a SHA state.
1347 static void sha_string(SHA_State * s, void *str, int len)
1349 unsigned char lenblk[4];
1350 PUT_32BIT(lenblk, len);
1351 SHA_Bytes(s, lenblk, 4);
1352 SHA_Bytes(s, str, len);
1355 static void sha_uint32(SHA_State * s, unsigned i)
1357 unsigned char intblk[4];
1358 PUT_32BIT(intblk, i);
1359 SHA_Bytes(s, intblk, 4);
1363 * SSH2 packet construction functions.
1365 static void ssh2_pkt_ensure(Ssh ssh, int length)
1367 if (ssh->pktout.maxlen < length) {
1368 ssh->pktout.maxlen = length + 256;
1369 ssh->pktout.data = srealloc(ssh->pktout.data,
1370 ssh->pktout.maxlen + APIEXTRA);
1371 if (!ssh->pktout.data)
1372 fatalbox("Out of memory");
1375 static void ssh2_pkt_adddata(Ssh ssh, void *data, int len)
1377 ssh->pktout.length += len;
1378 ssh2_pkt_ensure(ssh, ssh->pktout.length);
1379 memcpy(ssh->pktout.data + ssh->pktout.length - len, data, len);
1381 static void ssh2_pkt_addbyte(Ssh ssh, unsigned char byte)
1383 ssh2_pkt_adddata(ssh, &byte, 1);
1385 static void ssh2_pkt_init(Ssh ssh, int pkt_type)
1387 ssh->pktout.length = 5;
1388 ssh2_pkt_addbyte(ssh, (unsigned char) pkt_type);
1390 static void ssh2_pkt_addbool(Ssh ssh, unsigned char value)
1392 ssh2_pkt_adddata(ssh, &value, 1);
1394 static void ssh2_pkt_adduint32(Ssh ssh, unsigned long value)
1397 PUT_32BIT(x, value);
1398 ssh2_pkt_adddata(ssh, x, 4);
1400 static void ssh2_pkt_addstring_start(Ssh ssh)
1402 ssh2_pkt_adduint32(ssh, 0);
1403 ssh->pktout.savedpos = ssh->pktout.length;
1405 static void ssh2_pkt_addstring_str(Ssh ssh, char *data)
1407 ssh2_pkt_adddata(ssh, data, strlen(data));
1408 PUT_32BIT(ssh->pktout.data + ssh->pktout.savedpos - 4,
1409 ssh->pktout.length - ssh->pktout.savedpos);
1411 static void ssh2_pkt_addstring_data(Ssh ssh, char *data, int len)
1413 ssh2_pkt_adddata(ssh, data, len);
1414 PUT_32BIT(ssh->pktout.data + ssh->pktout.savedpos - 4,
1415 ssh->pktout.length - ssh->pktout.savedpos);
1417 static void ssh2_pkt_addstring(Ssh ssh, char *data)
1419 ssh2_pkt_addstring_start(ssh);
1420 ssh2_pkt_addstring_str(ssh, data);
1422 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
1425 int i, n = (bignum_bitcount(b) + 7) / 8;
1428 fatalbox("out of memory");
1430 for (i = 1; i <= n; i++)
1431 p[i] = bignum_byte(b, n - i);
1433 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1435 memmove(p, p + i, n + 1 - i);
1439 static void ssh2_pkt_addmp(Ssh ssh, Bignum b)
1443 p = ssh2_mpint_fmt(b, &len);
1444 ssh2_pkt_addstring_start(ssh);
1445 ssh2_pkt_addstring_data(ssh, (char *)p, len);
1450 * Construct an SSH2 final-form packet: compress it, encrypt it,
1451 * put the MAC on it. Final packet, ready to be sent, is stored in
1452 * ssh->pktout.data. Total length is returned.
1454 static int ssh2_pkt_construct(Ssh ssh)
1456 int cipherblk, maclen, padding, i;
1459 log_packet(ssh->logctx, PKT_OUTGOING, ssh->pktout.data[5],
1460 ssh2_pkt_type(ssh->pkt_ctx, ssh->pktout.data[5]),
1461 ssh->pktout.data + 6, ssh->pktout.length - 6);
1464 * Compress packet payload.
1467 unsigned char *newpayload;
1470 ssh->cscomp->compress(ssh->cs_comp_ctx, ssh->pktout.data + 5,
1471 ssh->pktout.length - 5,
1472 &newpayload, &newlen)) {
1473 ssh->pktout.length = 5;
1474 ssh2_pkt_adddata(ssh, newpayload, newlen);
1480 * Add padding. At least four bytes, and must also bring total
1481 * length (minus MAC) up to a multiple of the block size.
1483 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
1484 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1487 (cipherblk - (ssh->pktout.length + padding) % cipherblk) % cipherblk;
1488 maclen = ssh->csmac ? ssh->csmac->len : 0;
1489 ssh2_pkt_ensure(ssh, ssh->pktout.length + padding + maclen);
1490 ssh->pktout.data[4] = padding;
1491 for (i = 0; i < padding; i++)
1492 ssh->pktout.data[ssh->pktout.length + i] = random_byte();
1493 PUT_32BIT(ssh->pktout.data, ssh->pktout.length + padding - 4);
1495 ssh->csmac->generate(ssh->cs_mac_ctx, ssh->pktout.data,
1496 ssh->pktout.length + padding,
1497 ssh->v2_outgoing_sequence);
1498 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
1501 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
1502 ssh->pktout.data, ssh->pktout.length + padding);
1504 /* Ready-to-send packet starts at ssh->pktout.data. We return length. */
1505 return ssh->pktout.length + padding + maclen;
1509 * Construct and send an SSH2 packet immediately.
1511 static void ssh2_pkt_send(Ssh ssh)
1515 len = ssh2_pkt_construct(ssh);
1516 backlog = sk_write(ssh->s, (char *)ssh->pktout.data, len);
1517 if (backlog > SSH_MAX_BACKLOG)
1518 ssh_throttle_all(ssh, 1, backlog);
1522 * Construct an SSH2 packet and add it to a deferred data block.
1523 * Useful for sending multiple packets in a single sk_write() call,
1524 * to prevent a traffic-analysing listener from being able to work
1525 * out the length of any particular packet (such as the password
1528 * Note that because SSH2 sequence-numbers its packets, this can
1529 * NOT be used as an m4-style `defer' allowing packets to be
1530 * constructed in one order and sent in another.
1532 static void ssh2_pkt_defer(Ssh ssh)
1534 int len = ssh2_pkt_construct(ssh);
1535 if (ssh->deferred_len + len > ssh->deferred_size) {
1536 ssh->deferred_size = ssh->deferred_len + len + 128;
1537 ssh->deferred_send_data = srealloc(ssh->deferred_send_data,
1538 ssh->deferred_size);
1540 memcpy(ssh->deferred_send_data + ssh->deferred_len, ssh->pktout.data, len);
1541 ssh->deferred_len += len;
1545 * Send the whole deferred data block constructed by
1546 * ssh2_pkt_defer() or SSH1's defer_packet().
1548 static void ssh_pkt_defersend(Ssh ssh)
1551 backlog = sk_write(ssh->s, (char *)ssh->deferred_send_data,
1553 ssh->deferred_len = ssh->deferred_size = 0;
1554 sfree(ssh->deferred_send_data);
1555 ssh->deferred_send_data = NULL;
1556 if (backlog > SSH_MAX_BACKLOG)
1557 ssh_throttle_all(ssh, 1, backlog);
1561 void bndebug(char *string, Bignum b)
1565 p = ssh2_mpint_fmt(b, &len);
1566 debug(("%s", string));
1567 for (i = 0; i < len; i++)
1568 debug((" %02x", p[i]));
1574 static void sha_mpint(SHA_State * s, Bignum b)
1578 p = ssh2_mpint_fmt(b, &len);
1579 sha_string(s, p, len);
1584 * SSH2 packet decode functions.
1586 static unsigned long ssh2_pkt_getuint32(Ssh ssh)
1588 unsigned long value;
1589 if (ssh->pktin.length - ssh->pktin.savedpos < 4)
1590 return 0; /* arrgh, no way to decline (FIXME?) */
1591 value = GET_32BIT(ssh->pktin.data + ssh->pktin.savedpos);
1592 ssh->pktin.savedpos += 4;
1595 static int ssh2_pkt_getbool(Ssh ssh)
1597 unsigned long value;
1598 if (ssh->pktin.length - ssh->pktin.savedpos < 1)
1599 return 0; /* arrgh, no way to decline (FIXME?) */
1600 value = ssh->pktin.data[ssh->pktin.savedpos] != 0;
1601 ssh->pktin.savedpos++;
1604 static void ssh2_pkt_getstring(Ssh ssh, char **p, int *length)
1609 if (ssh->pktin.length - ssh->pktin.savedpos < 4)
1611 len = GET_32BIT(ssh->pktin.data + ssh->pktin.savedpos);
1615 ssh->pktin.savedpos += 4;
1616 if (ssh->pktin.length - ssh->pktin.savedpos < *length)
1618 *p = (char *)(ssh->pktin.data + ssh->pktin.savedpos);
1619 ssh->pktin.savedpos += *length;
1621 static Bignum ssh2_pkt_getmp(Ssh ssh)
1627 ssh2_pkt_getstring(ssh, &p, &length);
1631 bombout((ssh,"internal error: Can't handle negative mpints"));
1634 b = bignum_from_bytes((unsigned char *)p, length);
1639 * Helper function to add an SSH2 signature blob to a packet.
1640 * Expects to be shown the public key blob as well as the signature
1641 * blob. Normally works just like ssh2_pkt_addstring, but will
1642 * fiddle with the signature packet if necessary for
1643 * BUG_SSH2_RSA_PADDING.
1645 static void ssh2_add_sigblob(Ssh ssh, void *pkblob_v, int pkblob_len,
1646 void *sigblob_v, int sigblob_len)
1648 unsigned char *pkblob = (unsigned char *)pkblob_v;
1649 unsigned char *sigblob = (unsigned char *)sigblob_v;
1651 /* dmemdump(pkblob, pkblob_len); */
1652 /* dmemdump(sigblob, sigblob_len); */
1655 * See if this is in fact an ssh-rsa signature and a buggy
1656 * server; otherwise we can just do this the easy way.
1658 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) &&
1659 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
1660 int pos, len, siglen;
1663 * Find the byte length of the modulus.
1666 pos = 4+7; /* skip over "ssh-rsa" */
1667 pos += 4 + GET_32BIT(pkblob+pos); /* skip over exponent */
1668 len = GET_32BIT(pkblob+pos); /* find length of modulus */
1669 pos += 4; /* find modulus itself */
1670 while (len > 0 && pkblob[pos] == 0)
1672 /* debug(("modulus length is %d\n", len)); */
1675 * Now find the signature integer.
1677 pos = 4+7; /* skip over "ssh-rsa" */
1678 siglen = GET_32BIT(sigblob+pos);
1679 /* debug(("signature length is %d\n", siglen)); */
1681 if (len != siglen) {
1682 unsigned char newlen[4];
1683 ssh2_pkt_addstring_start(ssh);
1684 ssh2_pkt_addstring_data(ssh, (char *)sigblob, pos);
1685 /* dmemdump(sigblob, pos); */
1686 pos += 4; /* point to start of actual sig */
1687 PUT_32BIT(newlen, len);
1688 ssh2_pkt_addstring_data(ssh, (char *)newlen, 4);
1689 /* dmemdump(newlen, 4); */
1691 while (len-- > siglen) {
1692 ssh2_pkt_addstring_data(ssh, (char *)newlen, 1);
1693 /* dmemdump(newlen, 1); */
1695 ssh2_pkt_addstring_data(ssh, (char *)(sigblob+pos), siglen);
1696 /* dmemdump(sigblob+pos, siglen); */
1700 /* Otherwise fall through and do it the easy way. */
1703 ssh2_pkt_addstring_start(ssh);
1704 ssh2_pkt_addstring_data(ssh, (char *)sigblob, sigblob_len);
1708 * Examine the remote side's version string and compare it against
1709 * a list of known buggy implementations.
1711 static void ssh_detect_bugs(Ssh ssh, char *vstring)
1713 char *imp; /* pointer to implementation part */
1715 imp += strcspn(imp, "-");
1717 imp += strcspn(imp, "-");
1720 ssh->remote_bugs = 0;
1722 if (ssh->cfg.sshbug_ignore1 == BUG_ON ||
1723 (ssh->cfg.sshbug_ignore1 == BUG_AUTO &&
1724 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
1725 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
1726 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25")))) {
1728 * These versions don't support SSH1_MSG_IGNORE, so we have
1729 * to use a different defence against password length
1732 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
1733 logevent("We believe remote version has SSH1 ignore bug");
1736 if (ssh->cfg.sshbug_plainpw1 == BUG_ON ||
1737 (ssh->cfg.sshbug_plainpw1 == BUG_AUTO &&
1738 (!strcmp(imp, "Cisco-1.25")))) {
1740 * These versions need a plain password sent; they can't
1741 * handle having a null and a random length of data after
1744 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
1745 logevent("We believe remote version needs a plain SSH1 password");
1748 if (ssh->cfg.sshbug_rsa1 == BUG_ON ||
1749 (ssh->cfg.sshbug_rsa1 == BUG_AUTO &&
1750 (!strcmp(imp, "Cisco-1.25")))) {
1752 * These versions apparently have no clue whatever about
1753 * RSA authentication and will panic and die if they see
1754 * an AUTH_RSA message.
1756 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
1757 logevent("We believe remote version can't handle RSA authentication");
1760 if (ssh->cfg.sshbug_hmac2 == BUG_ON ||
1761 (ssh->cfg.sshbug_hmac2 == BUG_AUTO &&
1762 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
1763 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
1764 wc_match("2.1 *", imp)))) {
1766 * These versions have the HMAC bug.
1768 ssh->remote_bugs |= BUG_SSH2_HMAC;
1769 logevent("We believe remote version has SSH2 HMAC bug");
1772 if (ssh->cfg.sshbug_derivekey2 == BUG_ON ||
1773 (ssh->cfg.sshbug_derivekey2 == BUG_AUTO &&
1774 (wc_match("2.0.0*", imp) || wc_match("2.0.1[01]*", imp) ))) {
1776 * These versions have the key-derivation bug (failing to
1777 * include the literal shared secret in the hashes that
1778 * generate the keys).
1780 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
1781 logevent("We believe remote version has SSH2 key-derivation bug");
1784 if (ssh->cfg.sshbug_rsapad2 == BUG_ON ||
1785 (ssh->cfg.sshbug_rsapad2 == BUG_AUTO &&
1786 (wc_match("OpenSSH_2.[5-9]*", imp) ||
1787 wc_match("OpenSSH_3.[0-2]*", imp)))) {
1789 * These versions have the SSH2 RSA padding bug.
1791 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
1792 logevent("We believe remote version has SSH2 RSA padding bug");
1795 if (ssh->cfg.sshbug_dhgex2 == BUG_ON) {
1797 * User specified the SSH2 DH GEX bug.
1799 ssh->remote_bugs |= BUG_SSH2_DH_GEX;
1800 logevent("We believe remote version has SSH2 DH group exchange bug");
1804 static int do_ssh_init(Ssh ssh, unsigned char c)
1806 struct do_ssh_init_state {
1814 crState(do_ssh_init_state);
1816 crBegin(ssh->do_ssh_init_crstate);
1818 /* Search for the string "SSH-" in the input. */
1821 static const int transS[] = { 1, 2, 2, 1 };
1822 static const int transH[] = { 0, 0, 3, 0 };
1823 static const int transminus[] = { 0, 0, 0, -1 };
1825 s->i = transS[s->i];
1827 s->i = transH[s->i];
1829 s->i = transminus[s->i];
1834 crReturn(1); /* get another character */
1838 s->vstring = smalloc(s->vstrsize);
1839 strcpy(s->vstring, "SSH-");
1843 crReturn(1); /* get another char */
1844 if (s->vslen >= s->vstrsize - 1) {
1846 s->vstring = srealloc(s->vstring, s->vstrsize);
1848 s->vstring[s->vslen++] = c;
1851 s->version[s->i] = '\0';
1853 } else if (s->i < sizeof(s->version) - 1)
1854 s->version[s->i++] = c;
1855 } else if (c == '\012')
1859 ssh->agentfwd_enabled = FALSE;
1860 ssh->rdpkt2_state.incoming_sequence = 0;
1862 s->vstring[s->vslen] = 0;
1863 s->vstring[strcspn(s->vstring, "\r\n")] = '\0';/* remove EOL chars */
1866 vlog = smalloc(20 + s->vslen);
1867 sprintf(vlog, "Server version: %s", s->vstring);
1871 ssh_detect_bugs(ssh, s->vstring);
1874 * Decide which SSH protocol version to support.
1877 /* Anything strictly below "2.0" means protocol 1 is supported. */
1878 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
1879 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
1880 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
1882 if (ssh->cfg.sshprot == 0 && !s->proto1) {
1883 bombout((ssh,"SSH protocol version 1 required by user but not provided by server"));
1886 if (ssh->cfg.sshprot == 3 && !s->proto2) {
1887 bombout((ssh,"SSH protocol version 2 required by user but not provided by server"));
1891 if (s->proto2 && (ssh->cfg.sshprot >= 2 || !s->proto1)) {
1895 char verstring[80], vlog[100];
1896 sprintf(verstring, "SSH-2.0-%s", sshver);
1897 SHA_Init(&ssh->exhashbase);
1899 * Hash our version string and their version string.
1901 sha_string(&ssh->exhashbase, verstring, strlen(verstring));
1902 sha_string(&ssh->exhashbase, s->vstring, strcspn(s->vstring, "\r\n"));
1903 sprintf(vlog, "We claim version: %s", verstring);
1905 strcat(verstring, "\012");
1906 logevent("Using SSH protocol version 2");
1907 sk_write(ssh->s, verstring, strlen(verstring));
1908 ssh->protocol = ssh2_protocol;
1910 ssh->s_rdpkt = ssh2_rdpkt;
1915 char verstring[80], vlog[100];
1916 sprintf(verstring, "SSH-%s-%s",
1917 (ssh_versioncmp(s->version, "1.5") <= 0 ? s->version : "1.5"),
1919 sprintf(vlog, "We claim version: %s", verstring);
1921 strcat(verstring, "\012");
1923 logevent("Using SSH protocol version 1");
1924 sk_write(ssh->s, verstring, strlen(verstring));
1925 ssh->protocol = ssh1_protocol;
1927 ssh->s_rdpkt = ssh1_rdpkt;
1929 ssh->state = SSH_STATE_BEFORE_SIZE;
1936 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
1938 crBegin(ssh->ssh_gotdata_crstate);
1941 * To begin with, feed the characters one by one to the
1942 * protocol initialisation / selection function do_ssh_init().
1943 * When that returns 0, we're done with the initial greeting
1944 * exchange and can move on to packet discipline.
1947 int ret; /* need not be kept across crReturn */
1949 crReturnV; /* more data please */
1950 ret = do_ssh_init(ssh, *data);
1958 * We emerge from that loop when the initial negotiation is
1959 * over and we have selected an s_rdpkt function. Now pass
1960 * everything to s_rdpkt, and then pass the resulting packets
1961 * to the proper protocol handler.
1966 while (datalen > 0) {
1967 if (ssh->s_rdpkt(ssh, &data, &datalen) == 0) {
1968 if (ssh->state == SSH_STATE_CLOSED) {
1971 ssh->protocol(ssh, NULL, 0, 1);
1972 if (ssh->state == SSH_STATE_CLOSED) {
1982 static int ssh_closing(Plug plug, char *error_msg, int error_code,
1985 Ssh ssh = (Ssh) plug;
1986 ssh->state = SSH_STATE_CLOSED;
1992 /* A socket error has occurred. */
1993 logevent(error_msg);
1994 connection_fatal(ssh->frontend, error_msg);
1996 /* Otherwise, the remote side closed the connection normally. */
2001 static int ssh_receive(Plug plug, int urgent, char *data, int len)
2003 Ssh ssh = (Ssh) plug;
2004 ssh_gotdata(ssh, (unsigned char *)data, len);
2005 if (ssh->state == SSH_STATE_CLOSED) {
2015 static void ssh_sent(Plug plug, int bufsize)
2017 Ssh ssh = (Ssh) plug;
2019 * If the send backlog on the SSH socket itself clears, we
2020 * should unthrottle the whole world if it was throttled.
2022 if (bufsize < SSH_MAX_BACKLOG)
2023 ssh_throttle_all(ssh, 0, bufsize);
2027 * Connect to specified host and port.
2028 * Returns an error message, or NULL on success.
2029 * Also places the canonical host name into `realhost'. It must be
2030 * freed by the caller.
2032 static char *connect_to_host(Ssh ssh, char *host, int port,
2033 char **realhost, int nodelay)
2035 static const struct plug_function_table fn_table = {
2045 ssh->savedhost = smalloc(1 + strlen(host));
2046 if (!ssh->savedhost)
2047 fatalbox("Out of memory");
2048 strcpy(ssh->savedhost, host);
2051 port = 22; /* default ssh port */
2052 ssh->savedport = port;
2057 logeventf(ssh, "Looking up host \"%s\"", host);
2058 addr = name_lookup(host, port, realhost, &ssh->cfg);
2059 if ((err = sk_addr_error(addr)) != NULL)
2067 sk_getaddr(addr, addrbuf, 100);
2068 logeventf(ssh, "Connecting to %s port %d", addrbuf, port);
2070 ssh->fn = &fn_table;
2071 ssh->s = new_connection(addr, *realhost, port,
2072 0, 1, nodelay, (Plug) ssh, &ssh->cfg);
2073 if ((err = sk_socket_error(ssh->s)) != NULL) {
2082 * Throttle or unthrottle the SSH connection.
2084 static void ssh1_throttle(Ssh ssh, int adjust)
2086 int old_count = ssh->v1_throttle_count;
2087 ssh->v1_throttle_count += adjust;
2088 assert(ssh->v1_throttle_count >= 0);
2089 if (ssh->v1_throttle_count && !old_count) {
2090 sk_set_frozen(ssh->s, 1);
2091 } else if (!ssh->v1_throttle_count && old_count) {
2092 sk_set_frozen(ssh->s, 0);
2097 * Throttle or unthrottle _all_ local data streams (for when sends
2098 * on the SSH connection itself back up).
2100 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
2103 struct ssh_channel *c;
2105 if (enable == ssh->throttled_all)
2107 ssh->throttled_all = enable;
2108 ssh->overall_bufsize = bufsize;
2111 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
2113 case CHAN_MAINSESSION:
2115 * This is treated separately, outside the switch.
2119 x11_override_throttle(c->u.x11.s, enable);
2122 /* Agent channels require no buffer management. */
2125 pfd_override_throttle(c->u.x11.s, enable);
2132 * Username and password input, abstracted off into routines
2133 * reusable in several places - even between SSH1 and SSH2.
2136 /* Set up a username or password input loop on a given buffer. */
2137 static void setup_userpass_input(Ssh ssh, char *buffer, int buflen, int echo)
2139 ssh->userpass_input_buffer = buffer;
2140 ssh->userpass_input_buflen = buflen;
2141 ssh->userpass_input_bufpos = 0;
2142 ssh->userpass_input_echo = echo;
2146 * Process some terminal data in the course of username/password
2147 * input. Returns >0 for success (line of input returned in
2148 * buffer), <0 for failure (user hit ^C/^D, bomb out and exit), 0
2149 * for inconclusive (keep waiting for more input please).
2151 static int process_userpass_input(Ssh ssh, unsigned char *in, int inlen)
2156 switch (c = *in++) {
2159 ssh->userpass_input_buffer[ssh->userpass_input_bufpos] = 0;
2160 ssh->userpass_input_buffer[ssh->userpass_input_buflen-1] = 0;
2165 if (ssh->userpass_input_bufpos > 0) {
2166 if (ssh->userpass_input_echo)
2167 c_write_str(ssh, "\b \b");
2168 ssh->userpass_input_bufpos--;
2173 while (ssh->userpass_input_bufpos > 0) {
2174 if (ssh->userpass_input_echo)
2175 c_write_str(ssh, "\b \b");
2176 ssh->userpass_input_bufpos--;
2184 if (((c >= ' ' && c <= '~') ||
2185 ((unsigned char) c >= 160))
2186 && ssh->userpass_input_bufpos < ssh->userpass_input_buflen-1) {
2187 ssh->userpass_input_buffer[ssh->userpass_input_bufpos++] = c;
2188 if (ssh->userpass_input_echo)
2189 c_write(ssh, &c, 1);
2198 * Handle the key exchange and user authentication phases.
2200 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
2203 unsigned char cookie[8];
2204 struct RSAKey servkey, hostkey;
2205 struct MD5Context md5c;
2206 struct do_ssh1_login_state {
2208 unsigned char *rsabuf, *keystr1, *keystr2;
2209 unsigned long supported_ciphers_mask, supported_auths_mask;
2210 int tried_publickey, tried_agent;
2211 int tis_auth_refused, ccard_auth_refused;
2212 unsigned char session_id[16];
2215 void *publickey_blob;
2216 int publickey_bloblen;
2222 unsigned char request[5], *response, *p;
2231 crState(do_ssh1_login_state);
2233 crBegin(ssh->do_ssh1_login_crstate);
2238 if (ssh->pktin.type != SSH1_SMSG_PUBLIC_KEY) {
2239 bombout((ssh,"Public key packet not received"));
2243 logevent("Received public keys");
2245 memcpy(cookie, ssh->pktin.body, 8);
2247 i = makekey(ssh->pktin.body + 8, &servkey, &s->keystr1, 0);
2248 j = makekey(ssh->pktin.body + 8 + i, &hostkey, &s->keystr2, 0);
2251 * Log the host key fingerprint.
2255 logevent("Host key fingerprint is:");
2256 strcpy(logmsg, " ");
2257 hostkey.comment = NULL;
2258 rsa_fingerprint(logmsg + strlen(logmsg),
2259 sizeof(logmsg) - strlen(logmsg), &hostkey);
2263 ssh->v1_remote_protoflags = GET_32BIT(ssh->pktin.body + 8 + i + j);
2264 s->supported_ciphers_mask = GET_32BIT(ssh->pktin.body + 12 + i + j);
2265 s->supported_auths_mask = GET_32BIT(ssh->pktin.body + 16 + i + j);
2267 ssh->v1_local_protoflags =
2268 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
2269 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
2272 MD5Update(&md5c, s->keystr2, hostkey.bytes);
2273 MD5Update(&md5c, s->keystr1, servkey.bytes);
2274 MD5Update(&md5c, ssh->pktin.body, 8);
2275 MD5Final(s->session_id, &md5c);
2277 for (i = 0; i < 32; i++)
2278 ssh->session_key[i] = random_byte();
2280 s->len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
2282 s->rsabuf = smalloc(s->len);
2284 fatalbox("Out of memory");
2287 * Verify the host key.
2291 * First format the key into a string.
2293 int len = rsastr_len(&hostkey);
2294 char fingerprint[100];
2295 char *keystr = smalloc(len);
2297 fatalbox("Out of memory");
2298 rsastr_fmt(keystr, &hostkey);
2299 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
2300 verify_ssh_host_key(ssh->frontend,
2301 ssh->savedhost, ssh->savedport, "rsa", keystr,
2306 for (i = 0; i < 32; i++) {
2307 s->rsabuf[i] = ssh->session_key[i];
2309 s->rsabuf[i] ^= s->session_id[i];
2312 if (hostkey.bytes > servkey.bytes) {
2313 rsaencrypt(s->rsabuf, 32, &servkey);
2314 rsaencrypt(s->rsabuf, servkey.bytes, &hostkey);
2316 rsaencrypt(s->rsabuf, 32, &hostkey);
2317 rsaencrypt(s->rsabuf, hostkey.bytes, &servkey);
2320 logevent("Encrypted session key");
2323 int cipher_chosen = 0, warn = 0;
2324 char *cipher_string = NULL;
2326 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
2327 int next_cipher = ssh->cfg.ssh_cipherlist[i];
2328 if (next_cipher == CIPHER_WARN) {
2329 /* If/when we choose a cipher, warn about it */
2331 } else if (next_cipher == CIPHER_AES) {
2332 /* XXX Probably don't need to mention this. */
2333 logevent("AES not supported in SSH1, skipping");
2335 switch (next_cipher) {
2336 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
2337 cipher_string = "3DES"; break;
2338 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
2339 cipher_string = "Blowfish"; break;
2340 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
2341 cipher_string = "single-DES"; break;
2343 if (s->supported_ciphers_mask & (1 << s->cipher_type))
2347 if (!cipher_chosen) {
2348 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
2349 bombout((ssh,"Server violates SSH 1 protocol by not "
2350 "supporting 3DES encryption"));
2352 /* shouldn't happen */
2353 bombout((ssh,"No supported ciphers found"));
2357 /* Warn about chosen cipher if necessary. */
2359 askcipher(ssh->frontend, cipher_string, 0);
2362 switch (s->cipher_type) {
2363 case SSH_CIPHER_3DES:
2364 logevent("Using 3DES encryption");
2366 case SSH_CIPHER_DES:
2367 logevent("Using single-DES encryption");
2369 case SSH_CIPHER_BLOWFISH:
2370 logevent("Using Blowfish encryption");
2374 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
2375 PKT_CHAR, s->cipher_type,
2376 PKT_DATA, cookie, 8,
2377 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
2378 PKT_DATA, s->rsabuf, s->len,
2379 PKT_INT, ssh->v1_local_protoflags, PKT_END);
2381 logevent("Trying to enable encryption...");
2385 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
2386 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
2388 ssh->v1_cipher_ctx = ssh->cipher->make_context();
2389 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
2390 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
2392 ssh->crcda_ctx = crcda_make_context();
2393 logevent("Installing CRC compensation attack detector");
2397 if (ssh->pktin.type != SSH1_SMSG_SUCCESS) {
2398 bombout((ssh,"Encryption not successfully enabled"));
2402 logevent("Successfully started encryption");
2406 if ((flags & FLAG_INTERACTIVE) && !*ssh->cfg.username) {
2407 if (ssh_get_line && !ssh_getline_pw_only) {
2408 if (!ssh_get_line("login as: ",
2409 s->username, sizeof(s->username), FALSE)) {
2411 * get_line failed to get a username.
2414 logevent("No username provided. Abandoning session.");
2415 ssh->state = SSH_STATE_CLOSED;
2419 int ret; /* need not be kept over crReturn */
2420 c_write_str(ssh, "login as: ");
2423 setup_userpass_input(ssh, s->username, sizeof(s->username), 1);
2425 crWaitUntil(!ispkt);
2426 ret = process_userpass_input(ssh, in, inlen);
2430 c_write_str(ssh, "\r\n");
2433 strncpy(s->username, ssh->cfg.username, sizeof(s->username));
2434 s->username[sizeof(s->username)-1] = '\0';
2437 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, s->username, PKT_END);
2439 char userlog[22 + sizeof(s->username)];
2440 sprintf(userlog, "Sent username \"%s\"", s->username);
2442 if (flags & FLAG_INTERACTIVE &&
2443 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
2444 strcat(userlog, "\r\n");
2445 c_write_str(ssh, userlog);
2452 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA)) {
2453 /* We must not attempt PK auth. Pretend we've already tried it. */
2454 s->tried_publickey = s->tried_agent = 1;
2456 s->tried_publickey = s->tried_agent = 0;
2458 s->tis_auth_refused = s->ccard_auth_refused = 0;
2459 /* Load the public half of ssh->cfg.keyfile so we notice if it's in Pageant */
2460 if (*ssh->cfg.keyfile) {
2461 if (!rsakey_pubblob(ssh->cfg.keyfile,
2462 &s->publickey_blob, &s->publickey_bloblen))
2463 s->publickey_blob = NULL;
2465 s->publickey_blob = NULL;
2467 while (ssh->pktin.type == SSH1_SMSG_FAILURE) {
2468 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
2470 if (agent_exists() && !s->tried_agent) {
2472 * Attempt RSA authentication using Pageant.
2478 logevent("Pageant is running. Requesting keys.");
2480 /* Request the keys held by the agent. */
2481 PUT_32BIT(s->request, 1);
2482 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
2483 agent_query(s->request, 5, &r, &s->responselen);
2484 s->response = (unsigned char *) r;
2485 if (s->response && s->responselen >= 5 &&
2486 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
2487 s->p = s->response + 5;
2488 s->nkeys = GET_32BIT(s->p);
2492 sprintf(buf, "Pageant has %d SSH1 keys", s->nkeys);
2495 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
2498 sprintf(buf, "Trying Pageant key #%d", s->keyi);
2501 if (s->publickey_blob &&
2502 !memcmp(s->p, s->publickey_blob,
2503 s->publickey_bloblen)) {
2504 logevent("This key matches configured key file");
2505 s->tried_publickey = 1;
2508 s->p += ssh1_read_bignum(s->p, &s->key.exponent);
2509 s->p += ssh1_read_bignum(s->p, &s->key.modulus);
2510 s->commentlen = GET_32BIT(s->p);
2512 s->commentp = (char *)s->p;
2513 s->p += s->commentlen;
2514 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
2515 PKT_BIGNUM, s->key.modulus, PKT_END);
2517 if (ssh->pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
2518 logevent("Key refused");
2521 logevent("Received RSA challenge");
2522 ssh1_read_bignum(ssh->pktin.body, &s->challenge);
2524 char *agentreq, *q, *ret;
2527 len = 1 + 4; /* message type, bit count */
2528 len += ssh1_bignum_length(s->key.exponent);
2529 len += ssh1_bignum_length(s->key.modulus);
2530 len += ssh1_bignum_length(s->challenge);
2531 len += 16; /* session id */
2532 len += 4; /* response format */
2533 agentreq = smalloc(4 + len);
2534 PUT_32BIT(agentreq, len);
2536 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
2537 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
2539 q += ssh1_write_bignum(q, s->key.exponent);
2540 q += ssh1_write_bignum(q, s->key.modulus);
2541 q += ssh1_write_bignum(q, s->challenge);
2542 memcpy(q, s->session_id, 16);
2544 PUT_32BIT(q, 1); /* response format */
2545 agent_query(agentreq, len + 4, &vret, &retlen);
2549 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
2550 logevent("Sending Pageant's response");
2551 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
2552 PKT_DATA, ret + 5, 16,
2556 if (ssh->pktin.type == SSH1_SMSG_SUCCESS) {
2558 ("Pageant's response accepted");
2559 if (flags & FLAG_VERBOSE) {
2560 c_write_str(ssh, "Authenticated using"
2562 c_write(ssh, s->commentp,
2564 c_write_str(ssh, "\" from agent\r\n");
2569 ("Pageant's response not accepted");
2572 ("Pageant failed to answer challenge");
2576 logevent("No reply received from Pageant");
2579 freebn(s->key.exponent);
2580 freebn(s->key.modulus);
2581 freebn(s->challenge);
2589 if (*ssh->cfg.keyfile && !s->tried_publickey)
2590 s->pwpkt_type = SSH1_CMSG_AUTH_RSA;
2592 if (ssh->cfg.try_tis_auth &&
2593 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
2594 !s->tis_auth_refused) {
2595 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
2596 logevent("Requested TIS authentication");
2597 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
2599 if (ssh->pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
2600 logevent("TIS authentication declined");
2601 if (flags & FLAG_INTERACTIVE)
2602 c_write_str(ssh, "TIS authentication refused.\r\n");
2603 s->tis_auth_refused = 1;
2606 int challengelen = GET_32BIT(ssh->pktin.body);
2607 logevent("Received TIS challenge");
2608 if (challengelen > sizeof(s->prompt) - 1)
2609 challengelen = sizeof(s->prompt) - 1;/* prevent overrun */
2610 memcpy(s->prompt, ssh->pktin.body + 4, challengelen);
2611 /* Prompt heuristic comes from OpenSSH */
2612 strncpy(s->prompt + challengelen,
2613 memchr(s->prompt, '\n', challengelen) ?
2614 "": "\r\nResponse: ",
2615 (sizeof s->prompt) - challengelen);
2616 s->prompt[(sizeof s->prompt) - 1] = '\0';
2619 if (ssh->cfg.try_tis_auth &&
2620 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
2621 !s->ccard_auth_refused) {
2622 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
2623 logevent("Requested CryptoCard authentication");
2624 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
2626 if (ssh->pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
2627 logevent("CryptoCard authentication declined");
2628 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
2629 s->ccard_auth_refused = 1;
2632 int challengelen = GET_32BIT(ssh->pktin.body);
2633 logevent("Received CryptoCard challenge");
2634 if (challengelen > sizeof(s->prompt) - 1)
2635 challengelen = sizeof(s->prompt) - 1;/* prevent overrun */
2636 memcpy(s->prompt, ssh->pktin.body + 4, challengelen);
2637 strncpy(s->prompt + challengelen,
2638 memchr(s->prompt, '\n', challengelen) ?
2639 "" : "\r\nResponse: ",
2640 sizeof(s->prompt) - challengelen);
2641 s->prompt[sizeof(s->prompt) - 1] = '\0';
2644 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
2645 sprintf(s->prompt, "%.90s@%.90s's password: ",
2646 s->username, ssh->savedhost);
2648 if (s->pwpkt_type == SSH1_CMSG_AUTH_RSA) {
2649 char *comment = NULL;
2652 if (flags & FLAG_VERBOSE)
2653 c_write_str(ssh, "Trying public key authentication.\r\n");
2654 logeventf(ssh, "Trying public key \"%s\"", ssh->cfg.keyfile);
2655 type = key_type(ssh->cfg.keyfile);
2656 if (type != SSH_KEYTYPE_SSH1) {
2657 sprintf(msgbuf, "Key is of wrong type (%s)",
2658 key_type_to_str(type));
2660 c_write_str(ssh, msgbuf);
2661 c_write_str(ssh, "\r\n");
2662 s->tried_publickey = 1;
2665 if (!rsakey_encrypted(ssh->cfg.keyfile, &comment)) {
2666 if (flags & FLAG_VERBOSE)
2667 c_write_str(ssh, "No passphrase required.\r\n");
2670 sprintf(s->prompt, "Passphrase for key \"%.100s\": ", comment);
2675 * Show password prompt, having first obtained it via a TIS
2676 * or CryptoCard exchange if we're doing TIS or CryptoCard
2680 if (!ssh_get_line(s->prompt, s->password,
2681 sizeof(s->password), TRUE)) {
2683 * get_line failed to get a password (for example
2684 * because one was supplied on the command line
2685 * which has already failed to work). Terminate.
2687 send_packet(ssh, SSH1_MSG_DISCONNECT,
2688 PKT_STR, "No more passwords available to try",
2690 logevent("Unable to authenticate");
2691 connection_fatal(ssh->frontend, "Unable to authenticate");
2692 ssh->state = SSH_STATE_CLOSED;
2696 /* Prompt may have come from server. We've munged it a bit, so
2697 * we know it to be zero-terminated at least once. */
2698 int ret; /* need not be saved over crReturn */
2699 c_write_untrusted(ssh, s->prompt, strlen(s->prompt));
2702 setup_userpass_input(ssh, s->password, sizeof(s->password), 0);
2704 crWaitUntil(!ispkt);
2705 ret = process_userpass_input(ssh, in, inlen);
2709 c_write_str(ssh, "\r\n");
2713 if (s->pwpkt_type == SSH1_CMSG_AUTH_RSA) {
2715 * Try public key authentication with the specified
2718 s->tried_publickey = 1;
2721 int ret = loadrsakey(ssh->cfg.keyfile, &s->key, s->password);
2723 c_write_str(ssh, "Couldn't load private key from ");
2724 c_write_str(ssh, ssh->cfg.keyfile);
2725 c_write_str(ssh, ".\r\n");
2726 continue; /* go and try password */
2729 c_write_str(ssh, "Wrong passphrase.\r\n");
2730 s->tried_publickey = 0;
2731 continue; /* try again */
2736 * Send a public key attempt.
2738 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
2739 PKT_BIGNUM, s->key.modulus, PKT_END);
2742 if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
2743 c_write_str(ssh, "Server refused our public key.\r\n");
2744 continue; /* go and try password */
2746 if (ssh->pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
2747 bombout((ssh,"Bizarre response to offer of public key"));
2753 unsigned char buffer[32];
2754 Bignum challenge, response;
2756 ssh1_read_bignum(ssh->pktin.body, &challenge);
2757 response = rsadecrypt(challenge, &s->key);
2758 freebn(s->key.private_exponent);/* burn the evidence */
2760 for (i = 0; i < 32; i++) {
2761 buffer[i] = bignum_byte(response, 31 - i);
2765 MD5Update(&md5c, buffer, 32);
2766 MD5Update(&md5c, s->session_id, 16);
2767 MD5Final(buffer, &md5c);
2769 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
2770 PKT_DATA, buffer, 16, PKT_END);
2777 if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
2778 if (flags & FLAG_VERBOSE)
2779 c_write_str(ssh, "Failed to authenticate with"
2780 " our public key.\r\n");
2781 continue; /* go and try password */
2782 } else if (ssh->pktin.type != SSH1_SMSG_SUCCESS) {
2783 bombout((ssh,"Bizarre response to RSA authentication response"));
2787 break; /* we're through! */
2789 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
2791 * Defence against traffic analysis: we send a
2792 * whole bunch of packets containing strings of
2793 * different lengths. One of these strings is the
2794 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
2795 * The others are all random data in
2796 * SSH1_MSG_IGNORE packets. This way a passive
2797 * listener can't tell which is the password, and
2798 * hence can't deduce the password length.
2800 * Anybody with a password length greater than 16
2801 * bytes is going to have enough entropy in their
2802 * password that a listener won't find it _that_
2803 * much help to know how long it is. So what we'll
2806 * - if password length < 16, we send 15 packets
2807 * containing string lengths 1 through 15
2809 * - otherwise, we let N be the nearest multiple
2810 * of 8 below the password length, and send 8
2811 * packets containing string lengths N through
2812 * N+7. This won't obscure the order of
2813 * magnitude of the password length, but it will
2814 * introduce a bit of extra uncertainty.
2816 * A few servers (the old 1.2.18 through 1.2.22)
2817 * can't deal with SSH1_MSG_IGNORE. For these
2818 * servers, we need an alternative defence. We make
2819 * use of the fact that the password is interpreted
2820 * as a C string: so we can append a NUL, then some
2823 * One server (a Cisco one) can deal with neither
2824 * SSH1_MSG_IGNORE _nor_ a padded password string.
2825 * For this server we are left with no defences
2826 * against password length sniffing.
2828 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE)) {
2830 * The server can deal with SSH1_MSG_IGNORE, so
2831 * we can use the primary defence.
2833 int bottom, top, pwlen, i;
2836 pwlen = strlen(s->password);
2838 bottom = 0; /* zero length passwords are OK! :-) */
2841 bottom = pwlen & ~7;
2845 assert(pwlen >= bottom && pwlen <= top);
2847 randomstr = smalloc(top + 1);
2849 for (i = bottom; i <= top; i++) {
2851 defer_packet(ssh, s->pwpkt_type,
2852 PKT_STR, s->password, PKT_END);
2854 for (j = 0; j < i; j++) {
2856 randomstr[j] = random_byte();
2857 } while (randomstr[j] == '\0');
2859 randomstr[i] = '\0';
2860 defer_packet(ssh, SSH1_MSG_IGNORE,
2861 PKT_STR, randomstr, PKT_END);
2864 logevent("Sending password with camouflage packets");
2865 ssh_pkt_defersend(ssh);
2867 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
2869 * The server can't deal with SSH1_MSG_IGNORE
2870 * but can deal with padded passwords, so we
2871 * can use the secondary defence.
2877 len = strlen(s->password);
2878 if (len < sizeof(string)) {
2880 strcpy(string, s->password);
2881 len++; /* cover the zero byte */
2882 while (len < sizeof(string)) {
2883 string[len++] = (char) random_byte();
2888 logevent("Sending length-padded password");
2889 send_packet(ssh, s->pwpkt_type, PKT_INT, len,
2890 PKT_DATA, ss, len, PKT_END);
2893 * The server has _both_
2894 * BUG_CHOKES_ON_SSH1_IGNORE and
2895 * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
2896 * therefore nothing we can do.
2899 len = strlen(s->password);
2900 logevent("Sending unpadded password");
2901 send_packet(ssh, s->pwpkt_type, PKT_INT, len,
2902 PKT_DATA, s->password, len, PKT_END);
2905 send_packet(ssh, s->pwpkt_type, PKT_STR, s->password, PKT_END);
2908 logevent("Sent password");
2909 memset(s->password, 0, strlen(s->password));
2911 if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
2912 if (flags & FLAG_VERBOSE)
2913 c_write_str(ssh, "Access denied\r\n");
2914 logevent("Authentication refused");
2915 } else if (ssh->pktin.type != SSH1_SMSG_SUCCESS) {
2916 bombout((ssh,"Strange packet received, type %d", ssh->pktin.type));
2921 logevent("Authentication successful");
2926 void sshfwd_close(struct ssh_channel *c)
2930 if (c && !c->closes) {
2932 * If the channel's remoteid is -1, we have sent
2933 * CHANNEL_OPEN for this channel, but it hasn't even been
2934 * acknowledged by the server. So we must set a close flag
2935 * on it now, and then when the server acks the channel
2936 * open, we can close it then.
2938 if (((int)c->remoteid) != -1) {
2939 if (ssh->version == 1) {
2940 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
2943 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_CLOSE);
2944 ssh2_pkt_adduint32(ssh, c->remoteid);
2948 c->closes = 1; /* sent MSG_CLOSE */
2949 if (c->type == CHAN_X11) {
2951 logevent("Forwarded X11 connection terminated");
2952 } else if (c->type == CHAN_SOCKDATA ||
2953 c->type == CHAN_SOCKDATA_DORMANT) {
2955 logevent("Forwarded port closed");
2960 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
2964 if (ssh->version == 1) {
2965 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
2966 PKT_INT, c->remoteid,
2967 PKT_INT, len, PKT_DATA, buf, len, PKT_END);
2969 * In SSH1 we can return 0 here - implying that forwarded
2970 * connections are never individually throttled - because
2971 * the only circumstance that can cause throttling will be
2972 * the whole SSH connection backing up, in which case
2973 * _everything_ will be throttled as a whole.
2977 ssh2_add_channel_data(c, buf, len);
2978 return ssh2_try_send(c);
2982 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
2986 if (ssh->version == 1) {
2987 if (c->v.v1.throttling && bufsize < SSH1_BUFFER_LIMIT) {
2988 c->v.v1.throttling = 0;
2989 ssh1_throttle(ssh, -1);
2992 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
2996 static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
2998 crBegin(ssh->ssh1_protocol_crstate);
3002 while (!do_ssh1_login(ssh, in, inlen, ispkt)) {
3005 if (ssh->state == SSH_STATE_CLOSED)
3008 if (ssh->cfg.agentfwd && agent_exists()) {
3009 logevent("Requesting agent forwarding");
3010 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
3014 if (ssh->pktin.type != SSH1_SMSG_SUCCESS
3015 && ssh->pktin.type != SSH1_SMSG_FAILURE) {
3016 bombout((ssh,"Protocol confusion"));
3018 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
3019 logevent("Agent forwarding refused");
3021 logevent("Agent forwarding enabled");
3022 ssh->agentfwd_enabled = TRUE;
3026 if (ssh->cfg.x11_forward) {
3027 char proto[20], data[64];
3028 logevent("Requesting X11 forwarding");
3029 ssh->x11auth = x11_invent_auth(proto, sizeof(proto),
3030 data, sizeof(data), ssh->cfg.x11_auth);
3031 x11_get_real_auth(ssh->x11auth, ssh->cfg.x11_display);
3032 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
3033 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
3034 PKT_STR, proto, PKT_STR, data,
3035 PKT_INT, x11_get_screen_number(ssh->cfg.x11_display),
3038 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
3039 PKT_STR, proto, PKT_STR, data, PKT_END);
3044 if (ssh->pktin.type != SSH1_SMSG_SUCCESS
3045 && ssh->pktin.type != SSH1_SMSG_FAILURE) {
3046 bombout((ssh,"Protocol confusion"));
3048 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
3049 logevent("X11 forwarding refused");
3051 logevent("X11 forwarding enabled");
3052 ssh->X11_fwd_enabled = TRUE;
3059 int sport,dport,sserv,dserv;
3060 char sports[256], dports[256], saddr[256], host[256];
3062 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
3063 /* Add port forwardings. */
3064 ssh->portfwd_strptr = ssh->cfg.portfwd;
3065 while (*ssh->portfwd_strptr) {
3066 type = *ssh->portfwd_strptr++;
3069 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != '\t') {
3070 if (*ssh->portfwd_strptr == ':') {
3072 * We've seen a colon in the middle of the
3073 * source port number. This means that
3074 * everything we've seen until now is the
3075 * source _address_, so we'll move it into
3076 * saddr and start sports from the beginning
3079 ssh->portfwd_strptr++;
3081 strcpy(saddr, sports);
3084 if (n < 255) sports[n++] = *ssh->portfwd_strptr++;
3087 if (*ssh->portfwd_strptr == '\t')
3088 ssh->portfwd_strptr++;
3090 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != ':') {
3091 if (n < 255) host[n++] = *ssh->portfwd_strptr++;
3094 if (*ssh->portfwd_strptr == ':')
3095 ssh->portfwd_strptr++;
3097 while (*ssh->portfwd_strptr) {
3098 if (n < 255) dports[n++] = *ssh->portfwd_strptr++;
3101 ssh->portfwd_strptr++;
3102 dport = atoi(dports);
3106 dport = net_service_lookup(dports);
3108 logeventf(ssh, "Service lookup failed for"
3109 " destination port \"%s\"", dports);
3112 sport = atoi(sports);
3116 sport = net_service_lookup(sports);
3118 logeventf(ssh, "Service lookup failed for source"
3119 " port \"%s\"", sports);
3122 if (sport && dport) {
3124 pfd_addforward(host, dport, *saddr ? saddr : NULL,
3125 sport, ssh, &ssh->cfg);
3126 logeventf(ssh, "Local port %.*s%.*s%.*s%.*s%d%.*s"
3127 " forwarding to %s:%.*s%.*s%d%.*s",
3128 (int)(*saddr?strlen(saddr):0), *saddr?saddr:NULL,
3129 (int)(*saddr?1:0), ":",
3130 (int)(sserv ? strlen(sports) : 0), sports,
3131 sserv, "(", sport, sserv, ")",
3133 (int)(dserv ? strlen(dports) : 0), dports,
3134 dserv, "(", dport, dserv, ")");
3136 struct ssh_rportfwd *pf;
3137 pf = smalloc(sizeof(*pf));
3138 strcpy(pf->dhost, host);
3142 "SSH1 cannot handle source address spec \"%s:%d\"; ignoring",
3145 if (add234(ssh->rportfwds, pf) != pf) {
3147 "Duplicate remote port forwarding to %s:%d",
3151 logeventf(ssh, "Requesting remote port %.*s%.*s%d%.*s"
3152 " forward to %s:%.*s%.*s%d%.*s",
3153 (int)(sserv ? strlen(sports) : 0), sports,
3154 sserv, "(", sport, sserv, ")",
3156 (int)(dserv ? strlen(dports) : 0), dports,
3157 dserv, "(", dport, dserv, ")");
3158 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
3166 if (ssh->pktin.type != SSH1_SMSG_SUCCESS
3167 && ssh->pktin.type != SSH1_SMSG_FAILURE) {
3168 bombout((ssh,"Protocol confusion"));
3170 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
3171 c_write_str(ssh, "Server refused port"
3174 logevent("Remote port forwarding enabled");
3181 if (!ssh->cfg.nopty) {
3182 send_packet(ssh, SSH1_CMSG_REQUEST_PTY,
3183 PKT_STR, ssh->cfg.termtype,
3184 PKT_INT, ssh->term_height,
3185 PKT_INT, ssh->term_width,
3186 PKT_INT, 0, PKT_INT, 0, PKT_CHAR, 0, PKT_END);
3187 ssh->state = SSH_STATE_INTERMED;
3191 if (ssh->pktin.type != SSH1_SMSG_SUCCESS
3192 && ssh->pktin.type != SSH1_SMSG_FAILURE) {
3193 bombout((ssh,"Protocol confusion"));
3195 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
3196 c_write_str(ssh, "Server refused to allocate pty\r\n");
3197 ssh->editing = ssh->echoing = 1;
3199 logevent("Allocated pty");
3201 ssh->editing = ssh->echoing = 1;
3204 if (ssh->cfg.compression) {
3205 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
3209 if (ssh->pktin.type != SSH1_SMSG_SUCCESS
3210 && ssh->pktin.type != SSH1_SMSG_FAILURE) {
3211 bombout((ssh,"Protocol confusion"));
3213 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
3214 c_write_str(ssh, "Server refused to compress\r\n");
3216 logevent("Started compression");
3217 ssh->v1_compressing = TRUE;
3218 ssh->cs_comp_ctx = zlib_compress_init();
3219 logevent("Initialised zlib (RFC1950) compression");
3220 ssh->sc_comp_ctx = zlib_decompress_init();
3221 logevent("Initialised zlib (RFC1950) decompression");
3225 * Start the shell or command.
3227 * Special case: if the first-choice command is an SSH2
3228 * subsystem (hence not usable here) and the second choice
3229 * exists, we fall straight back to that.
3232 char *cmd = ssh->cfg.remote_cmd_ptr;
3234 if (ssh->cfg.ssh_subsys && ssh->cfg.remote_cmd_ptr2) {
3235 cmd = ssh->cfg.remote_cmd_ptr2;
3236 ssh->fallback_cmd = TRUE;
3239 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
3241 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
3242 logevent("Started session");
3245 ssh->state = SSH_STATE_SESSION;
3246 if (ssh->size_needed)
3247 ssh_size(ssh, ssh->term_width, ssh->term_height);
3248 if (ssh->eof_needed)
3249 ssh_special(ssh, TS_EOF);
3252 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
3254 ssh->channels = newtree234(ssh_channelcmp);
3258 if (ssh->pktin.type == SSH1_SMSG_STDOUT_DATA ||
3259 ssh->pktin.type == SSH1_SMSG_STDERR_DATA) {
3260 long len = GET_32BIT(ssh->pktin.body);
3262 from_backend(ssh->frontend,
3263 ssh->pktin.type == SSH1_SMSG_STDERR_DATA,
3264 (char *)(ssh->pktin.body) + 4, len);
3265 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
3266 ssh->v1_stdout_throttling = 1;
3267 ssh1_throttle(ssh, +1);
3269 } else if (ssh->pktin.type == SSH1_MSG_DISCONNECT) {
3270 ssh->state = SSH_STATE_CLOSED;
3271 logevent("Received disconnect request");
3273 } else if (ssh->pktin.type == SSH1_SMSG_X11_OPEN) {
3274 /* Remote side is trying to open a channel to talk to our
3275 * X-Server. Give them back a local channel number. */
3276 struct ssh_channel *c;
3278 logevent("Received X11 connect request");
3279 /* Refuse if X11 forwarding is disabled. */
3280 if (!ssh->X11_fwd_enabled) {
3281 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3282 PKT_INT, GET_32BIT(ssh->pktin.body), PKT_END);
3283 logevent("Rejected X11 connect request");
3285 c = smalloc(sizeof(struct ssh_channel));
3288 if (x11_init(&c->u.x11.s, ssh->cfg.x11_display, c,
3289 ssh->x11auth, NULL, -1, &ssh->cfg) != NULL) {
3290 logevent("opening X11 forward connection failed");
3292 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3293 PKT_INT, GET_32BIT(ssh->pktin.body),
3297 ("opening X11 forward connection succeeded");
3298 c->remoteid = GET_32BIT(ssh->pktin.body);
3299 c->localid = alloc_channel_id(ssh);
3301 c->v.v1.throttling = 0;
3302 c->type = CHAN_X11; /* identify channel type */
3303 add234(ssh->channels, c);
3304 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3305 PKT_INT, c->remoteid, PKT_INT,
3306 c->localid, PKT_END);
3307 logevent("Opened X11 forward channel");
3310 } else if (ssh->pktin.type == SSH1_SMSG_AGENT_OPEN) {
3311 /* Remote side is trying to open a channel to talk to our
3312 * agent. Give them back a local channel number. */
3313 struct ssh_channel *c;
3315 /* Refuse if agent forwarding is disabled. */
3316 if (!ssh->agentfwd_enabled) {
3317 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3318 PKT_INT, GET_32BIT(ssh->pktin.body), PKT_END);
3320 c = smalloc(sizeof(struct ssh_channel));
3322 c->remoteid = GET_32BIT(ssh->pktin.body);
3323 c->localid = alloc_channel_id(ssh);
3325 c->v.v1.throttling = 0;
3326 c->type = CHAN_AGENT; /* identify channel type */
3327 c->u.a.lensofar = 0;
3328 add234(ssh->channels, c);
3329 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3330 PKT_INT, c->remoteid, PKT_INT, c->localid,
3333 } else if (ssh->pktin.type == SSH1_MSG_PORT_OPEN) {
3334 /* Remote side is trying to open a channel to talk to a
3335 * forwarded port. Give them back a local channel number. */
3336 struct ssh_channel *c;
3337 struct ssh_rportfwd pf;
3339 char host[256], buf[1024];
3341 c = smalloc(sizeof(struct ssh_channel));
3344 hostsize = GET_32BIT(ssh->pktin.body+4);
3345 for (h = host, p = (char *)(ssh->pktin.body+8);
3346 hostsize != 0; hostsize--) {
3347 if (h+1 < host+sizeof(host))
3352 port = GET_32BIT(p);
3354 strcpy(pf.dhost, host);
3357 if (find234(ssh->rportfwds, &pf, NULL) == NULL) {
3358 sprintf(buf, "Rejected remote port open request for %s:%d",
3361 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3362 PKT_INT, GET_32BIT(ssh->pktin.body), PKT_END);
3364 sprintf(buf, "Received remote port open request for %s:%d",
3367 e = pfd_newconnect(&c->u.pfd.s, host, port, c, &ssh->cfg);
3370 sprintf(buf, "Port open failed: %s", e);
3373 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3374 PKT_INT, GET_32BIT(ssh->pktin.body),
3377 c->remoteid = GET_32BIT(ssh->pktin.body);
3378 c->localid = alloc_channel_id(ssh);
3380 c->v.v1.throttling = 0;
3381 c->type = CHAN_SOCKDATA; /* identify channel type */
3382 add234(ssh->channels, c);
3383 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3384 PKT_INT, c->remoteid, PKT_INT,
3385 c->localid, PKT_END);
3386 logevent("Forwarded port opened successfully");
3390 } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_OPEN_CONFIRMATION) {
3391 unsigned int remoteid = GET_32BIT(ssh->pktin.body);
3392 unsigned int localid = GET_32BIT(ssh->pktin.body+4);
3393 struct ssh_channel *c;
3395 c = find234(ssh->channels, &remoteid, ssh_channelfind);
3396 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
3397 c->remoteid = localid;
3398 c->type = CHAN_SOCKDATA;
3399 c->v.v1.throttling = 0;
3400 pfd_confirm(c->u.pfd.s);
3403 if (c && c->closes) {
3405 * We have a pending close on this channel,
3406 * which we decided on before the server acked
3407 * the channel open. So now we know the
3408 * remoteid, we can close it again.
3410 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE,
3411 PKT_INT, c->remoteid, PKT_END);
3414 } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_OPEN_FAILURE) {
3415 unsigned int remoteid = GET_32BIT(ssh->pktin.body);
3416 struct ssh_channel *c;
3418 c = find234(ssh->channels, &remoteid, ssh_channelfind);
3419 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
3420 logevent("Forwarded connection refused by server");
3421 pfd_close(c->u.pfd.s);
3422 del234(ssh->channels, c);
3426 } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
3427 ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
3428 /* Remote side closes a channel. */
3429 unsigned i = GET_32BIT(ssh->pktin.body);
3430 struct ssh_channel *c;
3431 c = find234(ssh->channels, &i, ssh_channelfind);
3432 if (c && ((int)c->remoteid) != -1) {
3435 (ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
3437 if ((c->closes == 0) && (c->type == CHAN_X11)) {
3438 logevent("Forwarded X11 connection terminated");
3439 assert(c->u.x11.s != NULL);
3440 x11_close(c->u.x11.s);
3443 if ((c->closes == 0) && (c->type == CHAN_SOCKDATA)) {
3444 logevent("Forwarded port closed");
3445 assert(c->u.pfd.s != NULL);
3446 pfd_close(c->u.pfd.s);
3450 c->closes |= (closetype << 2); /* seen this message */
3451 if (!(c->closes & closetype)) {
3452 send_packet(ssh, ssh->pktin.type, PKT_INT, c->remoteid,
3454 c->closes |= closetype; /* sent it too */
3457 if (c->closes == 15) {
3458 del234(ssh->channels, c);
3462 bombout((ssh,"Received CHANNEL_CLOSE%s for %s channel %d\n",
3463 ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE ? "" :
3464 "_CONFIRMATION", c ? "half-open" : "nonexistent",
3467 } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_DATA) {
3468 /* Data sent down one of our channels. */
3469 int i = GET_32BIT(ssh->pktin.body);
3470 int len = GET_32BIT(ssh->pktin.body + 4);
3471 unsigned char *p = ssh->pktin.body + 8;
3472 struct ssh_channel *c;
3473 c = find234(ssh->channels, &i, ssh_channelfind);
3478 bufsize = x11_send(c->u.x11.s, (char *)p, len);
3481 bufsize = pfd_send(c->u.pfd.s, (char *)p, len);
3484 /* Data for an agent message. Buffer it. */
3486 if (c->u.a.lensofar < 4) {
3487 int l = min(4 - c->u.a.lensofar, len);
3488 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
3492 c->u.a.lensofar += l;
3494 if (c->u.a.lensofar == 4) {
3496 4 + GET_32BIT(c->u.a.msglen);
3497 c->u.a.message = smalloc(c->u.a.totallen);
3498 memcpy(c->u.a.message, c->u.a.msglen, 4);
3500 if (c->u.a.lensofar >= 4 && len > 0) {
3502 min(c->u.a.totallen - c->u.a.lensofar,
3504 memcpy(c->u.a.message + c->u.a.lensofar, p,
3508 c->u.a.lensofar += l;
3510 if (c->u.a.lensofar == c->u.a.totallen) {
3511 void *reply, *sentreply;
3513 agent_query(c->u.a.message,
3514 c->u.a.totallen, &reply,
3519 /* Fake SSH_AGENT_FAILURE. */
3520 sentreply = "\0\0\0\1\5";
3523 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3524 PKT_INT, c->remoteid,
3526 PKT_DATA, sentreply, replylen,
3530 sfree(c->u.a.message);
3531 c->u.a.lensofar = 0;
3534 bufsize = 0; /* agent channels never back up */
3537 if (!c->v.v1.throttling && bufsize > SSH1_BUFFER_LIMIT) {
3538 c->v.v1.throttling = 1;
3539 ssh1_throttle(ssh, +1);
3542 } else if (ssh->pktin.type == SSH1_SMSG_SUCCESS) {
3543 /* may be from EXEC_SHELL on some servers */
3544 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
3545 /* may be from EXEC_SHELL on some servers
3546 * if no pty is available or in other odd cases. Ignore */
3547 } else if (ssh->pktin.type == SSH1_SMSG_EXIT_STATUS) {
3549 ssh->exitcode = GET_32BIT(ssh->pktin.body);
3550 sprintf(buf, "Server sent command exit status %d",
3553 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
3555 * In case `helpful' firewalls or proxies tack
3556 * extra human-readable text on the end of the
3557 * session which we might mistake for another
3558 * encrypted packet, we close the session once
3559 * we've sent EXIT_CONFIRMATION.
3561 ssh->state = SSH_STATE_CLOSED;
3564 bombout((ssh,"Strange packet received: type %d", ssh->pktin.type));
3569 int len = min(inlen, 512);
3570 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
3571 PKT_INT, len, PKT_DATA, in, len, PKT_END);
3582 * Utility routine for decoding comma-separated strings in KEXINIT.
3584 static int in_commasep_string(char *needle, char *haystack, int haylen)
3587 if (!needle || !haystack) /* protect against null pointers */
3589 needlen = strlen(needle);
3592 * Is it at the start of the string?
3594 if (haylen >= needlen && /* haystack is long enough */
3595 !memcmp(needle, haystack, needlen) && /* initial match */
3596 (haylen == needlen || haystack[needlen] == ',')
3597 /* either , or EOS follows */
3601 * If not, search for the next comma and resume after that.
3602 * If no comma found, terminate.
3604 while (haylen > 0 && *haystack != ',')
3605 haylen--, haystack++;
3608 haylen--, haystack++; /* skip over comma itself */
3613 * SSH2 key creation method.
3615 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H,
3616 unsigned char *sessid, char chr,
3617 unsigned char *keyspace)
3620 /* First 20 bytes. */
3622 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
3624 SHA_Bytes(&s, H, 20);
3625 SHA_Bytes(&s, &chr, 1);
3626 SHA_Bytes(&s, sessid, 20);
3627 SHA_Final(&s, keyspace);
3628 /* Next 20 bytes. */
3630 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
3632 SHA_Bytes(&s, H, 20);
3633 SHA_Bytes(&s, keyspace, 20);
3634 SHA_Final(&s, keyspace + 20);
3638 * Handle the SSH2 transport layer.
3640 static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen, int ispkt)
3642 struct do_ssh2_transport_state {
3643 int nbits, pbits, warn;
3644 Bignum p, g, e, f, K;
3645 int kex_init_value, kex_reply_value;
3646 const struct ssh_mac **maclist;
3648 const struct ssh2_cipher *cscipher_tobe;
3649 const struct ssh2_cipher *sccipher_tobe;
3650 const struct ssh_mac *csmac_tobe;
3651 const struct ssh_mac *scmac_tobe;
3652 const struct ssh_compress *cscomp_tobe;
3653 const struct ssh_compress *sccomp_tobe;
3654 char *hostkeydata, *sigdata, *keystr, *fingerprint;
3655 int hostkeylen, siglen;
3656 void *hkey; /* actual host key */
3657 unsigned char exchange_hash[20];
3658 int n_preferred_ciphers;
3659 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
3660 const struct ssh_compress *preferred_comp;
3663 crState(do_ssh2_transport_state);
3665 crBegin(ssh->do_ssh2_transport_crstate);
3667 s->cscipher_tobe = s->sccipher_tobe = NULL;
3668 s->csmac_tobe = s->scmac_tobe = NULL;
3669 s->cscomp_tobe = s->sccomp_tobe = NULL;
3677 * Set up the preferred ciphers. (NULL => warn below here)
3679 s->n_preferred_ciphers = 0;
3680 for (i = 0; i < CIPHER_MAX; i++) {
3681 switch (ssh->cfg.ssh_cipherlist[i]) {
3682 case CIPHER_BLOWFISH:
3683 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
3686 if (ssh->cfg.ssh2_des_cbc) {
3687 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
3691 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
3694 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
3697 /* Flag for later. Don't bother if it's the last in
3699 if (i < CIPHER_MAX - 1) {
3700 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
3708 * Set up preferred compression.
3710 if (ssh->cfg.compression)
3711 s->preferred_comp = &ssh_zlib;
3713 s->preferred_comp = &ssh_comp_none;
3716 * Be prepared to work around the buggy MAC problem.
3718 if (ssh->remote_bugs & BUG_SSH2_HMAC)
3719 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
3721 s->maclist = macs, s->nmacs = lenof(macs);
3725 int i, j, cipherstr_started;
3728 * Construct and send our key exchange packet.
3730 ssh2_pkt_init(ssh, SSH2_MSG_KEXINIT);
3731 for (i = 0; i < 16; i++)
3732 ssh2_pkt_addbyte(ssh, (unsigned char) random_byte());
3733 /* List key exchange algorithms. */
3734 ssh2_pkt_addstring_start(ssh);
3735 for (i = 0; i < lenof(kex_algs); i++) {
3736 if (kex_algs[i] == &ssh_diffiehellman_gex &&
3737 (ssh->remote_bugs & BUG_SSH2_DH_GEX))
3739 ssh2_pkt_addstring_str(ssh, kex_algs[i]->name);
3740 if (i < lenof(kex_algs) - 1)
3741 ssh2_pkt_addstring_str(ssh, ",");
3743 /* List server host key algorithms. */
3744 ssh2_pkt_addstring_start(ssh);
3745 for (i = 0; i < lenof(hostkey_algs); i++) {
3746 ssh2_pkt_addstring_str(ssh, hostkey_algs[i]->name);
3747 if (i < lenof(hostkey_algs) - 1)
3748 ssh2_pkt_addstring_str(ssh, ",");
3750 /* List client->server encryption algorithms. */
3751 ssh2_pkt_addstring_start(ssh);
3752 cipherstr_started = 0;
3753 for (i = 0; i < s->n_preferred_ciphers; i++) {
3754 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
3755 if (!c) continue; /* warning flag */
3756 for (j = 0; j < c->nciphers; j++) {
3757 if (cipherstr_started)
3758 ssh2_pkt_addstring_str(ssh, ",");
3759 ssh2_pkt_addstring_str(ssh, c->list[j]->name);
3760 cipherstr_started = 1;
3763 /* List server->client encryption algorithms. */
3764 ssh2_pkt_addstring_start(ssh);
3765 cipherstr_started = 0;
3766 for (i = 0; i < s->n_preferred_ciphers; i++) {
3767 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
3768 if (!c) continue; /* warning flag */
3769 for (j = 0; j < c->nciphers; j++) {
3770 if (cipherstr_started)
3771 ssh2_pkt_addstring_str(ssh, ",");
3772 ssh2_pkt_addstring_str(ssh, c->list[j]->name);
3773 cipherstr_started = 1;
3776 /* List client->server MAC algorithms. */
3777 ssh2_pkt_addstring_start(ssh);
3778 for (i = 0; i < s->nmacs; i++) {
3779 ssh2_pkt_addstring_str(ssh, s->maclist[i]->name);
3780 if (i < s->nmacs - 1)
3781 ssh2_pkt_addstring_str(ssh, ",");
3783 /* List server->client MAC algorithms. */
3784 ssh2_pkt_addstring_start(ssh);
3785 for (i = 0; i < s->nmacs; i++) {
3786 ssh2_pkt_addstring_str(ssh, s->maclist[i]->name);
3787 if (i < s->nmacs - 1)
3788 ssh2_pkt_addstring_str(ssh, ",");
3790 /* List client->server compression algorithms. */
3791 ssh2_pkt_addstring_start(ssh);
3792 for (i = 0; i < lenof(compressions) + 1; i++) {
3793 const struct ssh_compress *c =
3794 i == 0 ? s->preferred_comp : compressions[i - 1];
3795 ssh2_pkt_addstring_str(ssh, c->name);
3796 if (i < lenof(compressions))
3797 ssh2_pkt_addstring_str(ssh, ",");
3799 /* List server->client compression algorithms. */
3800 ssh2_pkt_addstring_start(ssh);
3801 for (i = 0; i < lenof(compressions) + 1; i++) {
3802 const struct ssh_compress *c =
3803 i == 0 ? s->preferred_comp : compressions[i - 1];
3804 ssh2_pkt_addstring_str(ssh, c->name);
3805 if (i < lenof(compressions))
3806 ssh2_pkt_addstring_str(ssh, ",");
3808 /* List client->server languages. Empty list. */
3809 ssh2_pkt_addstring_start(ssh);
3810 /* List server->client languages. Empty list. */
3811 ssh2_pkt_addstring_start(ssh);
3812 /* First KEX packet does _not_ follow, because we're not that brave. */
3813 ssh2_pkt_addbool(ssh, FALSE);
3815 ssh2_pkt_adduint32(ssh, 0);
3818 ssh->exhash = ssh->exhashbase;
3819 sha_string(&ssh->exhash, ssh->pktout.data + 5, ssh->pktout.length - 5);
3825 if (ssh->pktin.length > 5)
3826 sha_string(&ssh->exhash, ssh->pktin.data + 5, ssh->pktin.length - 5);
3829 * Now examine the other side's KEXINIT to see what we're up
3836 if (ssh->pktin.type != SSH2_MSG_KEXINIT) {
3837 bombout((ssh,"expected key exchange packet from server"));
3841 ssh->hostkey = NULL;
3842 s->cscipher_tobe = NULL;
3843 s->sccipher_tobe = NULL;
3844 s->csmac_tobe = NULL;
3845 s->scmac_tobe = NULL;
3846 s->cscomp_tobe = NULL;
3847 s->sccomp_tobe = NULL;
3848 ssh->pktin.savedpos += 16; /* skip garbage cookie */
3849 ssh2_pkt_getstring(ssh, &str, &len); /* key exchange algorithms */
3850 for (i = 0; i < lenof(kex_algs); i++) {
3851 if (kex_algs[i] == &ssh_diffiehellman_gex &&
3852 (ssh->remote_bugs & BUG_SSH2_DH_GEX))
3854 if (in_commasep_string(kex_algs[i]->name, str, len)) {
3855 ssh->kex = kex_algs[i];
3859 ssh2_pkt_getstring(ssh, &str, &len); /* host key algorithms */
3860 for (i = 0; i < lenof(hostkey_algs); i++) {
3861 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
3862 ssh->hostkey = hostkey_algs[i];
3866 ssh2_pkt_getstring(ssh, &str, &len); /* client->server cipher */
3868 for (i = 0; i < s->n_preferred_ciphers; i++) {
3869 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
3873 for (j = 0; j < c->nciphers; j++) {
3874 if (in_commasep_string(c->list[j]->name, str, len)) {
3875 s->cscipher_tobe = c->list[j];
3880 if (s->cscipher_tobe) {
3882 askcipher(ssh->frontend, s->cscipher_tobe->name, 1);
3886 if (!s->cscipher_tobe) {
3887 bombout((ssh,"Couldn't agree a client-to-server cipher (available: %s)",
3888 str ? str : "(null)"));
3892 ssh2_pkt_getstring(ssh, &str, &len); /* server->client cipher */
3894 for (i = 0; i < s->n_preferred_ciphers; i++) {
3895 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
3899 for (j = 0; j < c->nciphers; j++) {
3900 if (in_commasep_string(c->list[j]->name, str, len)) {
3901 s->sccipher_tobe = c->list[j];
3906 if (s->sccipher_tobe) {
3908 askcipher(ssh->frontend, s->sccipher_tobe->name, 2);
3912 if (!s->sccipher_tobe) {
3913 bombout((ssh,"Couldn't agree a server-to-client cipher (available: %s)",
3914 str ? str : "(null)"));
3918 ssh2_pkt_getstring(ssh, &str, &len); /* client->server mac */
3919 for (i = 0; i < s->nmacs; i++) {
3920 if (in_commasep_string(s->maclist[i]->name, str, len)) {
3921 s->csmac_tobe = s->maclist[i];
3925 ssh2_pkt_getstring(ssh, &str, &len); /* server->client mac */
3926 for (i = 0; i < s->nmacs; i++) {
3927 if (in_commasep_string(s->maclist[i]->name, str, len)) {
3928 s->scmac_tobe = s->maclist[i];
3932 ssh2_pkt_getstring(ssh, &str, &len); /* client->server compression */
3933 for (i = 0; i < lenof(compressions) + 1; i++) {
3934 const struct ssh_compress *c =
3935 i == 0 ? s->preferred_comp : compressions[i - 1];
3936 if (in_commasep_string(c->name, str, len)) {
3941 ssh2_pkt_getstring(ssh, &str, &len); /* server->client compression */
3942 for (i = 0; i < lenof(compressions) + 1; i++) {
3943 const struct ssh_compress *c =
3944 i == 0 ? s->preferred_comp : compressions[i - 1];
3945 if (in_commasep_string(c->name, str, len)) {
3953 * Work out the number of bits of key we will need from the key
3954 * exchange. We start with the maximum key length of either
3960 csbits = s->cscipher_tobe->keylen;
3961 scbits = s->sccipher_tobe->keylen;
3962 s->nbits = (csbits > scbits ? csbits : scbits);
3964 /* The keys only have 160-bit entropy, since they're based on
3965 * a SHA-1 hash. So cap the key size at 160 bits. */
3970 * If we're doing Diffie-Hellman group exchange, start by
3971 * requesting a group.
3973 if (ssh->kex == &ssh_diffiehellman_gex) {
3974 logevent("Doing Diffie-Hellman group exchange");
3975 ssh->pkt_ctx |= SSH2_PKTCTX_DHGEX;
3977 * Work out how big a DH group we will need to allow that
3980 s->pbits = 512 << ((s->nbits - 1) / 64);
3981 ssh2_pkt_init(ssh, SSH2_MSG_KEX_DH_GEX_REQUEST);
3982 ssh2_pkt_adduint32(ssh, s->pbits);
3986 if (ssh->pktin.type != SSH2_MSG_KEX_DH_GEX_GROUP) {
3987 bombout((ssh,"expected key exchange group packet from server"));
3990 s->p = ssh2_pkt_getmp(ssh);
3991 s->g = ssh2_pkt_getmp(ssh);
3992 ssh->kex_ctx = dh_setup_group(s->p, s->g);
3993 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
3994 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
3996 ssh->pkt_ctx |= SSH2_PKTCTX_DHGROUP1;
3997 ssh->kex_ctx = dh_setup_group1();
3998 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
3999 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
4002 logevent("Doing Diffie-Hellman key exchange");
4004 * Now generate and send e for Diffie-Hellman.
4006 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
4007 ssh2_pkt_init(ssh, s->kex_init_value);
4008 ssh2_pkt_addmp(ssh, s->e);
4012 if (ssh->pktin.type != s->kex_reply_value) {
4013 bombout((ssh,"expected key exchange reply packet from server"));
4016 ssh2_pkt_getstring(ssh, &s->hostkeydata, &s->hostkeylen);
4017 s->f = ssh2_pkt_getmp(ssh);
4018 ssh2_pkt_getstring(ssh, &s->sigdata, &s->siglen);
4020 s->K = dh_find_K(ssh->kex_ctx, s->f);
4022 sha_string(&ssh->exhash, s->hostkeydata, s->hostkeylen);
4023 if (ssh->kex == &ssh_diffiehellman_gex) {
4024 sha_uint32(&ssh->exhash, s->pbits);
4025 sha_mpint(&ssh->exhash, s->p);
4026 sha_mpint(&ssh->exhash, s->g);
4028 sha_mpint(&ssh->exhash, s->e);
4029 sha_mpint(&ssh->exhash, s->f);
4030 sha_mpint(&ssh->exhash, s->K);
4031 SHA_Final(&ssh->exhash, s->exchange_hash);
4033 dh_cleanup(ssh->kex_ctx);
4034 ssh->kex_ctx = NULL;
4037 debug(("Exchange hash is:\n"));
4038 dmemdump(s->exchange_hash, 20);
4041 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
4043 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
4044 (char *)s->exchange_hash, 20)) {
4045 bombout((ssh,"Server's host key did not match the signature supplied"));
4050 * Authenticate remote host: verify host key. (We've already
4051 * checked the signature of the exchange hash.)
4053 s->keystr = ssh->hostkey->fmtkey(s->hkey);
4054 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
4055 verify_ssh_host_key(ssh->frontend,
4056 ssh->savedhost, ssh->savedport, ssh->hostkey->keytype,
4057 s->keystr, s->fingerprint);
4058 if (s->first_kex) { /* don't bother logging this in rekeys */
4059 logevent("Host key fingerprint is:");
4060 logevent(s->fingerprint);
4062 sfree(s->fingerprint);
4064 ssh->hostkey->freekey(s->hkey);
4067 * Send SSH2_MSG_NEWKEYS.
4069 ssh2_pkt_init(ssh, SSH2_MSG_NEWKEYS);
4073 * Expect SSH2_MSG_NEWKEYS from server.
4076 if (ssh->pktin.type != SSH2_MSG_NEWKEYS) {
4077 bombout((ssh,"expected new-keys packet from server"));
4082 * Create and initialise session keys.
4084 if (ssh->cs_cipher_ctx)
4085 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
4086 ssh->cscipher = s->cscipher_tobe;
4087 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
4089 if (ssh->sc_cipher_ctx)
4090 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
4091 ssh->sccipher = s->sccipher_tobe;
4092 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
4094 if (ssh->cs_mac_ctx)
4095 ssh->csmac->free_context(ssh->cs_mac_ctx);
4096 ssh->csmac = s->csmac_tobe;
4097 ssh->cs_mac_ctx = ssh->csmac->make_context();
4099 if (ssh->sc_mac_ctx)
4100 ssh->scmac->free_context(ssh->sc_mac_ctx);
4101 ssh->scmac = s->scmac_tobe;
4102 ssh->sc_mac_ctx = ssh->scmac->make_context();
4104 if (ssh->cs_comp_ctx)
4105 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
4106 ssh->cscomp = s->cscomp_tobe;
4107 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
4109 if (ssh->sc_comp_ctx)
4110 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
4111 ssh->sccomp = s->sccomp_tobe;
4112 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
4115 * Set IVs after keys. Here we use the exchange hash from the
4116 * _first_ key exchange.
4119 unsigned char keyspace[40];
4121 memcpy(ssh->v2_session_id, s->exchange_hash,
4122 sizeof(s->exchange_hash));
4123 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'C',keyspace);
4124 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
4125 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'D',keyspace);
4126 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
4127 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'A',keyspace);
4128 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
4129 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'B',keyspace);
4130 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
4131 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'E',keyspace);
4132 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
4133 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'F',keyspace);
4134 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
4136 logeventf(ssh, "Initialised %.200s client->server encryption",
4137 ssh->cscipher->text_name);
4138 logeventf(ssh, "Initialised %.200s server->client encryption",
4139 ssh->sccipher->text_name);
4140 if (ssh->cscomp->text_name)
4141 logeventf(ssh, "Initialised %s compression",
4142 ssh->cscomp->text_name);
4143 if (ssh->sccomp->text_name)
4144 logeventf(ssh, "Initialised %s decompression",
4145 ssh->sccomp->text_name);
4148 * If this is the first key exchange phase, we must pass the
4149 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
4150 * wants to see it but because it will need time to initialise
4151 * itself before it sees an actual packet. In subsequent key
4152 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
4153 * it would only confuse the layer above.
4155 if (!s->first_kex) {
4161 * Now we're encrypting. Begin returning 1 to the protocol main
4162 * function so that other things can run on top of the
4163 * transport. If we ever see a KEXINIT, we must go back to the
4166 while (!(ispkt && ssh->pktin.type == SSH2_MSG_KEXINIT)) {
4169 logevent("Server initiated key re-exchange");
4170 goto begin_key_exchange;
4176 * Add data to an SSH2 channel output buffer.
4178 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
4181 bufchain_add(&c->v.v2.outbuffer, buf, len);
4185 * Attempt to send data on an SSH2 channel.
4187 static int ssh2_try_send(struct ssh_channel *c)
4191 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
4194 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
4195 if ((unsigned)len > c->v.v2.remwindow)
4196 len = c->v.v2.remwindow;
4197 if ((unsigned)len > c->v.v2.remmaxpkt)
4198 len = c->v.v2.remmaxpkt;
4199 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_DATA);
4200 ssh2_pkt_adduint32(ssh, c->remoteid);
4201 ssh2_pkt_addstring_start(ssh);
4202 ssh2_pkt_addstring_data(ssh, data, len);
4204 bufchain_consume(&c->v.v2.outbuffer, len);
4205 c->v.v2.remwindow -= len;
4209 * After having sent as much data as we can, return the amount
4212 return bufchain_size(&c->v.v2.outbuffer);
4216 * Potentially enlarge the window on an SSH2 channel.
4218 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin)
4223 * Never send WINDOW_ADJUST for a channel that the remote side
4224 * already thinks it's closed; there's no point, since it won't
4225 * be sending any more data anyway.
4230 if (newwin > c->v.v2.locwindow) {
4231 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4232 ssh2_pkt_adduint32(ssh, c->remoteid);
4233 ssh2_pkt_adduint32(ssh, newwin - c->v.v2.locwindow);
4235 c->v.v2.locwindow = newwin;
4240 * Handle the SSH2 userauth and connection layers.
4242 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
4244 struct do_ssh2_authconn_state {
4246 AUTH_INVALID, AUTH_PUBLICKEY_AGENT, AUTH_PUBLICKEY_FILE,
4248 AUTH_KEYBOARD_INTERACTIVE
4252 AUTH_TYPE_PUBLICKEY,
4253 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
4254 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
4256 AUTH_TYPE_KEYBOARD_INTERACTIVE,
4257 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
4259 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
4260 int tried_pubkey_config, tried_agent, tried_keyb_inter;
4261 int kbd_inter_running;
4263 int num_prompts, curr_prompt, echo;
4268 void *publickey_blob;
4269 int publickey_bloblen;
4270 unsigned char request[5], *response, *p;
4274 char *pkblob, *alg, *commentp;
4275 int pklen, alglen, commentlen;
4276 int siglen, retlen, len;
4277 char *q, *agentreq, *ret;
4280 crState(do_ssh2_authconn_state);
4282 crBegin(ssh->do_ssh2_authconn_crstate);
4285 * Request userauth protocol, and await a response to it.
4287 ssh2_pkt_init(ssh, SSH2_MSG_SERVICE_REQUEST);
4288 ssh2_pkt_addstring(ssh, "ssh-userauth");
4290 crWaitUntilV(ispkt);
4291 if (ssh->pktin.type != SSH2_MSG_SERVICE_ACCEPT) {
4292 bombout((ssh,"Server refused user authentication protocol"));
4297 * We repeat this whole loop, including the username prompt,
4298 * until we manage a successful authentication. If the user
4299 * types the wrong _password_, they can be sent back to the
4300 * beginning to try another username, if this is configured on.
4301 * (If they specify a username in the config, they are never
4302 * asked, even if they do give a wrong password.)
4304 * I think this best serves the needs of
4306 * - the people who have no configuration, no keys, and just
4307 * want to try repeated (username,password) pairs until they
4308 * type both correctly
4310 * - people who have keys and configuration but occasionally
4311 * need to fall back to passwords
4313 * - people with a key held in Pageant, who might not have
4314 * logged in to a particular machine before; so they want to
4315 * type a username, and then _either_ their key will be
4316 * accepted, _or_ they will type a password. If they mistype
4317 * the username they will want to be able to get back and
4320 s->username[0] = '\0';
4321 s->got_username = FALSE;
4326 if (s->got_username && !ssh->cfg.change_username) {
4328 * We got a username last time round this loop, and
4329 * with change_username turned off we don't try to get
4332 } else if ((flags & FLAG_INTERACTIVE) && !*ssh->cfg.username) {
4333 if (ssh_get_line && !ssh_getline_pw_only) {
4334 if (!ssh_get_line("login as: ",
4335 s->username, sizeof(s->username), FALSE)) {
4337 * get_line failed to get a username.
4340 logevent("No username provided. Abandoning session.");
4341 ssh->state = SSH_STATE_CLOSED;
4345 int ret; /* need not be saved across crReturn */
4346 c_write_str(ssh, "login as: ");
4348 setup_userpass_input(ssh, s->username, sizeof(s->username), 1);
4350 crWaitUntilV(!ispkt);
4351 ret = process_userpass_input(ssh, in, inlen);
4355 c_write_str(ssh, "\r\n");
4357 s->username[strcspn(s->username, "\n\r")] = '\0';
4360 strncpy(s->username, ssh->cfg.username, sizeof(s->username));
4361 s->username[sizeof(s->username)-1] = '\0';
4362 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
4363 stuff = dupprintf("Using username \"%s\".\r\n", s->username);
4364 c_write_str(ssh, stuff);
4368 s->got_username = TRUE;
4371 * Send an authentication request using method "none": (a)
4372 * just in case it succeeds, and (b) so that we know what
4373 * authentication methods we can usefully try next.
4375 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4377 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4378 ssh2_pkt_addstring(ssh, s->username);
4379 ssh2_pkt_addstring(ssh, "ssh-connection");/* service requested */
4380 ssh2_pkt_addstring(ssh, "none"); /* method */
4382 s->type = AUTH_TYPE_NONE;
4384 s->we_are_in = FALSE;
4386 s->tried_pubkey_config = FALSE;
4387 s->tried_agent = FALSE;
4388 s->tried_keyb_inter = FALSE;
4389 s->kbd_inter_running = FALSE;
4390 /* Load the pub half of ssh->cfg.keyfile so we notice if it's in Pageant */
4391 if (*ssh->cfg.keyfile) {
4393 logeventf(ssh, "Reading private key file \"%.150s\"", ssh->cfg.keyfile);
4394 keytype = key_type(ssh->cfg.keyfile);
4395 if (keytype == SSH_KEYTYPE_SSH2) {
4397 ssh2_userkey_loadpub(ssh->cfg.keyfile, NULL,
4398 &s->publickey_bloblen);
4401 logeventf(ssh, "Unable to use this key file (%s)",
4402 key_type_to_str(keytype));
4403 msgbuf = dupprintf("Unable to use key file \"%.150s\""
4404 " (%s)\r\n", ssh->cfg.keyfile,
4405 key_type_to_str(keytype));
4406 c_write_str(ssh, msgbuf);
4408 s->publickey_blob = NULL;
4411 s->publickey_blob = NULL;
4415 * Wait for the result of the last authentication request.
4418 crWaitUntilV(ispkt);
4419 while (ssh->pktin.type == SSH2_MSG_USERAUTH_BANNER) {
4423 * Don't show the banner if we're operating in
4424 * non-verbose non-interactive mode. (It's probably
4425 * a script, which means nobody will read the
4426 * banner _anyway_, and moreover the printing of
4427 * the banner will screw up processing on the
4428 * output of (say) plink.)
4430 if (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE)) {
4431 ssh2_pkt_getstring(ssh, &banner, &size);
4433 c_write_untrusted(ssh, banner, size);
4435 crWaitUntilV(ispkt);
4437 if (ssh->pktin.type == SSH2_MSG_USERAUTH_SUCCESS) {
4438 logevent("Access granted");
4439 s->we_are_in = TRUE;
4443 if (s->kbd_inter_running &&
4444 ssh->pktin.type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
4446 * This is either a further set-of-prompts packet
4447 * in keyboard-interactive authentication, or it's
4448 * the same one and we came back here with `gotit'
4449 * set. In the former case, we must reset the
4450 * curr_prompt variable.
4454 } else if (ssh->pktin.type != SSH2_MSG_USERAUTH_FAILURE) {
4455 bombout((ssh,"Strange packet received during authentication: type %d",
4463 * OK, we're now sitting on a USERAUTH_FAILURE message, so
4464 * we can look at the string in it and know what we can
4465 * helpfully try next.
4467 if (ssh->pktin.type == SSH2_MSG_USERAUTH_FAILURE) {
4470 ssh2_pkt_getstring(ssh, &methods, &methlen);
4471 s->kbd_inter_running = FALSE;
4472 if (!ssh2_pkt_getbool(ssh)) {
4474 * We have received an unequivocal Access
4475 * Denied. This can translate to a variety of
4478 * - if we'd just tried "none" authentication,
4479 * it's not worth printing anything at all
4481 * - if we'd just tried a public key _offer_,
4482 * the message should be "Server refused our
4483 * key" (or no message at all if the key
4484 * came from Pageant)
4486 * - if we'd just tried anything else, the
4487 * message really should be "Access denied".
4489 * Additionally, if we'd just tried password
4490 * authentication, we should break out of this
4491 * whole loop so as to go back to the username
4494 if (s->type == AUTH_TYPE_NONE) {
4496 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
4497 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
4498 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
4499 c_write_str(ssh, "Server refused our key\r\n");
4500 logevent("Server refused public key");
4501 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
4502 /* server declined keyboard-interactive; ignore */
4504 c_write_str(ssh, "Access denied\r\n");
4505 logevent("Access denied");
4506 if (s->type == AUTH_TYPE_PASSWORD) {
4507 s->we_are_in = FALSE;
4512 c_write_str(ssh, "Further authentication required\r\n");
4513 logevent("Further authentication required");
4517 in_commasep_string("publickey", methods, methlen);
4519 in_commasep_string("password", methods, methlen);
4520 s->can_keyb_inter = ssh->cfg.try_ki_auth &&
4521 in_commasep_string("keyboard-interactive", methods, methlen);
4525 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4528 * Most password/passphrase prompts will be
4529 * non-echoing, so we set this to 0 by default.
4530 * Exception is that some keyboard-interactive prompts
4531 * can be echoing, in which case we'll set this to 1.
4535 if (!s->method && s->can_pubkey &&
4536 agent_exists() && !s->tried_agent) {
4538 * Attempt public-key authentication using Pageant.
4543 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4544 ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
4546 s->tried_agent = TRUE;
4548 logevent("Pageant is running. Requesting keys.");
4550 /* Request the keys held by the agent. */
4551 PUT_32BIT(s->request, 1);
4552 s->request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
4553 agent_query(s->request, 5, &r, &s->responselen);
4554 s->response = (unsigned char *) r;
4555 if (s->response && s->responselen >= 5 &&
4556 s->response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
4557 s->p = s->response + 5;
4558 s->nkeys = GET_32BIT(s->p);
4562 sprintf(buf, "Pageant has %d SSH2 keys", s->nkeys);
4565 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
4570 sprintf(buf, "Trying Pageant key #%d", s->keyi);
4573 s->pklen = GET_32BIT(s->p);
4575 if (s->publickey_blob &&
4576 s->pklen == s->publickey_bloblen &&
4577 !memcmp(s->p, s->publickey_blob,
4578 s->publickey_bloblen)) {
4579 logevent("This key matches configured key file");
4580 s->tried_pubkey_config = 1;
4582 s->pkblob = (char *)s->p;
4584 s->alglen = GET_32BIT(s->pkblob);
4585 s->alg = s->pkblob + 4;
4586 s->commentlen = GET_32BIT(s->p);
4588 s->commentp = (char *)s->p;
4589 s->p += s->commentlen;
4590 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4591 ssh2_pkt_addstring(ssh, s->username);
4592 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4593 ssh2_pkt_addstring(ssh, "publickey"); /* method */
4594 ssh2_pkt_addbool(ssh, FALSE); /* no signature included */
4595 ssh2_pkt_addstring_start(ssh);
4596 ssh2_pkt_addstring_data(ssh, s->alg, s->alglen);
4597 ssh2_pkt_addstring_start(ssh);
4598 ssh2_pkt_addstring_data(ssh, s->pkblob, s->pklen);
4601 crWaitUntilV(ispkt);
4602 if (ssh->pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
4603 logevent("Key refused");
4607 if (flags & FLAG_VERBOSE) {
4608 c_write_str(ssh, "Authenticating with "
4610 c_write(ssh, s->commentp, s->commentlen);
4611 c_write_str(ssh, "\" from agent\r\n");
4615 * Server is willing to accept the key.
4616 * Construct a SIGN_REQUEST.
4618 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4619 ssh2_pkt_addstring(ssh, s->username);
4620 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4621 ssh2_pkt_addstring(ssh, "publickey"); /* method */
4622 ssh2_pkt_addbool(ssh, TRUE);
4623 ssh2_pkt_addstring_start(ssh);
4624 ssh2_pkt_addstring_data(ssh, s->alg, s->alglen);
4625 ssh2_pkt_addstring_start(ssh);
4626 ssh2_pkt_addstring_data(ssh, s->pkblob, s->pklen);
4628 s->siglen = ssh->pktout.length - 5 + 4 + 20;
4629 s->len = 1; /* message type */
4630 s->len += 4 + s->pklen; /* key blob */
4631 s->len += 4 + s->siglen; /* data to sign */
4632 s->len += 4; /* flags */
4633 s->agentreq = smalloc(4 + s->len);
4634 PUT_32BIT(s->agentreq, s->len);
4635 s->q = s->agentreq + 4;
4636 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
4637 PUT_32BIT(s->q, s->pklen);
4639 memcpy(s->q, s->pkblob, s->pklen);
4641 PUT_32BIT(s->q, s->siglen);
4643 /* Now the data to be signed... */
4644 PUT_32BIT(s->q, 20);
4646 memcpy(s->q, ssh->v2_session_id, 20);
4648 memcpy(s->q, ssh->pktout.data + 5,
4649 ssh->pktout.length - 5);
4650 s->q += ssh->pktout.length - 5;
4651 /* And finally the (zero) flags word. */
4653 agent_query(s->agentreq, s->len + 4, &vret, &s->retlen);
4657 if (s->ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
4658 logevent("Sending Pageant's response");
4659 ssh2_add_sigblob(ssh, s->pkblob, s->pklen,
4661 GET_32BIT(s->ret + 5));
4667 ("Pageant failed to answer challenge");
4677 if (!s->method && s->can_pubkey && s->publickey_blob
4678 && !s->tried_pubkey_config) {
4679 unsigned char *pub_blob;
4680 char *algorithm, *comment;
4683 s->tried_pubkey_config = TRUE;
4685 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4686 ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
4689 * Try the public key supplied in the configuration.
4691 * First, offer the public blob to see if the server is
4692 * willing to accept it.
4695 (unsigned char *)ssh2_userkey_loadpub(ssh->cfg.keyfile,
4699 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4700 ssh2_pkt_addstring(ssh, s->username);
4701 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4702 ssh2_pkt_addstring(ssh, "publickey"); /* method */
4703 ssh2_pkt_addbool(ssh, FALSE); /* no signature included */
4704 ssh2_pkt_addstring(ssh, algorithm);
4705 ssh2_pkt_addstring_start(ssh);
4706 ssh2_pkt_addstring_data(ssh, (char *)pub_blob,
4709 logevent("Offered public key"); /* FIXME */
4711 crWaitUntilV(ispkt);
4712 if (ssh->pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
4714 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
4715 continue; /* key refused; give up on it */
4718 logevent("Offer of public key accepted");
4720 * Actually attempt a serious authentication using
4723 if (ssh2_userkey_encrypted(ssh->cfg.keyfile, &comment)) {
4724 sprintf(s->pwprompt,
4725 "Passphrase for key \"%.100s\": ",
4731 c_write_str(ssh, "Authenticating with public key \"");
4732 c_write_str(ssh, comment);
4733 c_write_str(ssh, "\"\r\n");
4734 s->method = AUTH_PUBLICKEY_FILE;
4738 if (!s->method && s->can_keyb_inter && !s->tried_keyb_inter) {
4739 s->method = AUTH_KEYBOARD_INTERACTIVE;
4740 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4741 s->tried_keyb_inter = TRUE;
4743 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4744 ssh->pkt_ctx |= SSH2_PKTCTX_KBDINTER;
4746 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4747 ssh2_pkt_addstring(ssh, s->username);
4748 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4749 ssh2_pkt_addstring(ssh, "keyboard-interactive"); /* method */
4750 ssh2_pkt_addstring(ssh, ""); /* lang */
4751 ssh2_pkt_addstring(ssh, "");
4754 crWaitUntilV(ispkt);
4755 if (ssh->pktin.type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
4756 if (ssh->pktin.type == SSH2_MSG_USERAUTH_FAILURE)
4758 logevent("Keyboard-interactive authentication refused");
4759 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
4763 s->kbd_inter_running = TRUE;
4767 if (s->kbd_inter_running) {
4768 s->method = AUTH_KEYBOARD_INTERACTIVE;
4769 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4770 s->tried_keyb_inter = TRUE;
4772 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4773 ssh->pkt_ctx |= SSH2_PKTCTX_KBDINTER;
4775 if (s->curr_prompt == 0) {
4777 * We've got a fresh USERAUTH_INFO_REQUEST.
4778 * Display header data, and start going through
4781 char *name, *inst, *lang;
4782 int name_len, inst_len, lang_len;
4784 ssh2_pkt_getstring(ssh, &name, &name_len);
4785 ssh2_pkt_getstring(ssh, &inst, &inst_len);
4786 ssh2_pkt_getstring(ssh, &lang, &lang_len);
4788 c_write_untrusted(ssh, name, name_len);
4789 c_write_str(ssh, "\r\n");
4792 c_write_untrusted(ssh, inst, inst_len);
4793 c_write_str(ssh, "\r\n");
4795 s->num_prompts = ssh2_pkt_getuint32(ssh);
4799 * If there are prompts remaining in the packet,
4800 * display one and get a response.
4802 if (s->curr_prompt < s->num_prompts) {
4806 ssh2_pkt_getstring(ssh, &prompt, &prompt_len);
4807 if (prompt_len > 0) {
4808 strncpy(s->pwprompt, prompt, sizeof(s->pwprompt));
4809 s->pwprompt[prompt_len < sizeof(s->pwprompt) ?
4810 prompt_len : sizeof(s->pwprompt)-1] = '\0';
4813 "<server failed to send prompt>: ");
4815 s->echo = ssh2_pkt_getbool(ssh);
4821 if (!s->method && s->can_passwd) {
4822 s->method = AUTH_PASSWORD;
4823 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4824 ssh->pkt_ctx |= SSH2_PKTCTX_PASSWORD;
4825 sprintf(s->pwprompt, "%.90s@%.90s's password: ", s->username,
4832 if (!ssh_get_line(s->pwprompt, s->password,
4833 sizeof(s->password), TRUE)) {
4835 * get_line failed to get a password (for
4836 * example because one was supplied on the
4837 * command line which has already failed to
4840 ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
4841 ssh2_pkt_adduint32(ssh,SSH2_DISCONNECT_BY_APPLICATION);
4842 ssh2_pkt_addstring(ssh, "No more passwords available"
4844 ssh2_pkt_addstring(ssh, "en"); /* language tag */
4846 logevent("Unable to authenticate");
4847 connection_fatal(ssh->frontend,
4848 "Unable to authenticate");
4849 ssh->state = SSH_STATE_CLOSED;
4853 int ret; /* need not be saved across crReturn */
4854 c_write_untrusted(ssh, s->pwprompt, strlen(s->pwprompt));
4857 setup_userpass_input(ssh, s->password,
4858 sizeof(s->password), s->echo);
4860 crWaitUntilV(!ispkt);
4861 ret = process_userpass_input(ssh, in, inlen);
4865 c_write_str(ssh, "\r\n");
4869 if (s->method == AUTH_PUBLICKEY_FILE) {
4871 * We have our passphrase. Now try the actual authentication.
4873 struct ssh2_userkey *key;
4875 key = ssh2_load_userkey(ssh->cfg.keyfile, s->password);
4876 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
4877 if (key == SSH2_WRONG_PASSPHRASE) {
4878 c_write_str(ssh, "Wrong passphrase\r\n");
4879 s->tried_pubkey_config = FALSE;
4881 c_write_str(ssh, "Unable to load private key\r\n");
4882 s->tried_pubkey_config = TRUE;
4884 /* Send a spurious AUTH_NONE to return to the top. */
4885 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4886 ssh2_pkt_addstring(ssh, s->username);
4887 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4888 ssh2_pkt_addstring(ssh, "none"); /* method */
4890 s->type = AUTH_TYPE_NONE;
4892 unsigned char *pkblob, *sigblob, *sigdata;
4893 int pkblob_len, sigblob_len, sigdata_len;
4896 * We have loaded the private key and the server
4897 * has announced that it's willing to accept it.
4898 * Hallelujah. Generate a signature and send it.
4900 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4901 ssh2_pkt_addstring(ssh, s->username);
4902 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4903 ssh2_pkt_addstring(ssh, "publickey"); /* method */
4904 ssh2_pkt_addbool(ssh, TRUE);
4905 ssh2_pkt_addstring(ssh, key->alg->name);
4906 pkblob = key->alg->public_blob(key->data, &pkblob_len);
4907 ssh2_pkt_addstring_start(ssh);
4908 ssh2_pkt_addstring_data(ssh, (char *)pkblob, pkblob_len);
4911 * The data to be signed is:
4915 * followed by everything so far placed in the
4918 sigdata_len = ssh->pktout.length - 5 + 4 + 20;
4919 sigdata = smalloc(sigdata_len);
4920 PUT_32BIT(sigdata, 20);
4921 memcpy(sigdata + 4, ssh->v2_session_id, 20);
4922 memcpy(sigdata + 24, ssh->pktout.data + 5,
4923 ssh->pktout.length - 5);
4924 sigblob = key->alg->sign(key->data, (char *)sigdata,
4925 sigdata_len, &sigblob_len);
4926 ssh2_add_sigblob(ssh, pkblob, pkblob_len,
4927 sigblob, sigblob_len);
4933 s->type = AUTH_TYPE_PUBLICKEY;
4935 } else if (s->method == AUTH_PASSWORD) {
4937 * We send the password packet lumped tightly together with
4938 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
4939 * string long enough to make the total length of the two
4940 * packets constant. This should ensure that a passive
4941 * listener doing traffic analyis can't work out the length
4944 * For this to work, we need an assumption about the
4945 * maximum length of the password packet. I think 256 is
4946 * pretty conservative. Anyone using a password longer than
4947 * that probably doesn't have much to worry about from
4948 * people who find out how long their password is!
4950 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4951 ssh2_pkt_addstring(ssh, s->username);
4952 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4953 ssh2_pkt_addstring(ssh, "password");
4954 ssh2_pkt_addbool(ssh, FALSE);
4955 ssh2_pkt_addstring(ssh, s->password);
4956 memset(s->password, 0, sizeof(s->password));
4957 ssh2_pkt_defer(ssh);
4959 * We'll include a string that's an exact multiple of the
4960 * cipher block size. If the cipher is NULL for some
4961 * reason, we don't do this trick at all because we gain
4964 if (ssh->cscipher) {
4967 stringlen = (256 - ssh->deferred_len);
4968 stringlen += ssh->cscipher->blksize - 1;
4969 stringlen -= (stringlen % ssh->cscipher->blksize);
4972 * Temporarily disable actual compression,
4973 * so we can guarantee to get this string
4974 * exactly the length we want it. The
4975 * compression-disabling routine should
4976 * return an integer indicating how many
4977 * bytes we should adjust our string length
4981 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
4983 ssh2_pkt_init(ssh, SSH2_MSG_IGNORE);
4984 ssh2_pkt_addstring_start(ssh);
4985 for (i = 0; i < stringlen; i++) {
4986 char c = (char) random_byte();
4987 ssh2_pkt_addstring_data(ssh, &c, 1);
4989 ssh2_pkt_defer(ssh);
4991 ssh_pkt_defersend(ssh);
4992 logevent("Sent password");
4993 s->type = AUTH_TYPE_PASSWORD;
4994 } else if (s->method == AUTH_KEYBOARD_INTERACTIVE) {
4995 if (s->curr_prompt == 0) {
4996 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_INFO_RESPONSE);
4997 ssh2_pkt_adduint32(ssh, s->num_prompts);
4999 if (s->need_pw) { /* only add pw if we just got one! */
5000 ssh2_pkt_addstring(ssh, s->password);
5001 memset(s->password, 0, sizeof(s->password));
5004 if (s->curr_prompt >= s->num_prompts) {
5008 * If there are prompts remaining, we set
5009 * `gotit' so that we won't attempt to get
5010 * another packet. Then we go back round the
5011 * loop and will end up retrieving another
5012 * prompt out of the existing packet. Funky or
5017 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
5019 c_write_str(ssh, "No supported authentication methods"
5020 " left to try!\r\n");
5021 logevent("No supported authentications offered."
5023 ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
5024 ssh2_pkt_adduint32(ssh, SSH2_DISCONNECT_BY_APPLICATION);
5025 ssh2_pkt_addstring(ssh, "No supported authentication"
5026 " methods available");
5027 ssh2_pkt_addstring(ssh, "en"); /* language tag */
5029 ssh->state = SSH_STATE_CLOSED;
5033 } while (!s->we_are_in);
5036 * Now we're authenticated for the connection protocol. The
5037 * connection protocol will automatically have started at this
5038 * point; there's no need to send SERVICE_REQUEST.
5042 * So now create a channel with a session in it.
5044 ssh->channels = newtree234(ssh_channelcmp);
5045 ssh->mainchan = smalloc(sizeof(struct ssh_channel));
5046 ssh->mainchan->ssh = ssh;
5047 ssh->mainchan->localid = alloc_channel_id(ssh);
5048 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_OPEN);
5049 ssh2_pkt_addstring(ssh, "session");
5050 ssh2_pkt_adduint32(ssh, ssh->mainchan->localid);
5051 ssh->mainchan->v.v2.locwindow = OUR_V2_WINSIZE;
5052 ssh2_pkt_adduint32(ssh, ssh->mainchan->v.v2.locwindow);/* our window size */
5053 ssh2_pkt_adduint32(ssh, 0x4000UL); /* our max pkt size */
5055 crWaitUntilV(ispkt);
5056 if (ssh->pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
5057 bombout((ssh,"Server refused to open a session"));
5059 /* FIXME: error data comes back in FAILURE packet */
5061 if (ssh2_pkt_getuint32(ssh) != ssh->mainchan->localid) {
5062 bombout((ssh,"Server's channel confirmation cited wrong channel"));
5065 ssh->mainchan->remoteid = ssh2_pkt_getuint32(ssh);
5066 ssh->mainchan->type = CHAN_MAINSESSION;
5067 ssh->mainchan->closes = 0;
5068 ssh->mainchan->v.v2.remwindow = ssh2_pkt_getuint32(ssh);
5069 ssh->mainchan->v.v2.remmaxpkt = ssh2_pkt_getuint32(ssh);
5070 bufchain_init(&ssh->mainchan->v.v2.outbuffer);
5071 add234(ssh->channels, ssh->mainchan);
5072 logevent("Opened channel for session");
5075 * Potentially enable X11 forwarding.
5077 if (ssh->cfg.x11_forward) {
5078 char proto[20], data[64];
5079 logevent("Requesting X11 forwarding");
5080 ssh->x11auth = x11_invent_auth(proto, sizeof(proto),
5081 data, sizeof(data), ssh->cfg.x11_auth);
5082 x11_get_real_auth(ssh->x11auth, ssh->cfg.x11_display);
5083 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
5084 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
5085 ssh2_pkt_addstring(ssh, "x11-req");
5086 ssh2_pkt_addbool(ssh, 1); /* want reply */
5087 ssh2_pkt_addbool(ssh, 0); /* many connections */
5088 ssh2_pkt_addstring(ssh, proto);
5089 ssh2_pkt_addstring(ssh, data);
5090 ssh2_pkt_adduint32(ssh, x11_get_screen_number(ssh->cfg.x11_display));
5094 crWaitUntilV(ispkt);
5095 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5096 unsigned i = ssh2_pkt_getuint32(ssh);
5097 struct ssh_channel *c;
5098 c = find234(ssh->channels, &i, ssh_channelfind);
5100 continue; /* nonexistent channel */
5101 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5103 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5105 if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5106 if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5107 bombout((ssh,"Unexpected response to X11 forwarding request:"
5108 " packet type %d", ssh->pktin.type));
5111 logevent("X11 forwarding refused");
5113 logevent("X11 forwarding enabled");
5114 ssh->X11_fwd_enabled = TRUE;
5119 * Enable port forwardings.
5124 int sport,dport,sserv,dserv;
5125 char sports[256], dports[256], saddr[256], host[256];
5127 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5128 /* Add port forwardings. */
5129 ssh->portfwd_strptr = ssh->cfg.portfwd;
5130 while (*ssh->portfwd_strptr) {
5131 type = *ssh->portfwd_strptr++;
5134 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != '\t') {
5135 if (*ssh->portfwd_strptr == ':') {
5137 * We've seen a colon in the middle of the
5138 * source port number. This means that
5139 * everything we've seen until now is the
5140 * source _address_, so we'll move it into
5141 * saddr and start sports from the beginning
5144 ssh->portfwd_strptr++;
5146 strcpy(saddr, sports);
5149 if (n < 255) sports[n++] = *ssh->portfwd_strptr++;
5152 if (*ssh->portfwd_strptr == '\t')
5153 ssh->portfwd_strptr++;
5155 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != ':') {
5156 if (n < 255) host[n++] = *ssh->portfwd_strptr++;
5159 if (*ssh->portfwd_strptr == ':')
5160 ssh->portfwd_strptr++;
5162 while (*ssh->portfwd_strptr) {
5163 if (n < 255) dports[n++] = *ssh->portfwd_strptr++;
5166 ssh->portfwd_strptr++;
5167 dport = atoi(dports);
5171 dport = net_service_lookup(dports);
5173 logeventf(ssh, "Service lookup failed for destination"
5174 " port \"%s\"", dports);
5177 sport = atoi(sports);
5181 sport = net_service_lookup(sports);
5183 logeventf(ssh, "Service lookup failed for source"
5184 " port \"%s\"", sports);
5187 if (sport && dport) {
5189 pfd_addforward(host, dport, *saddr ? saddr : NULL,
5190 sport, ssh, &ssh->cfg);
5191 logeventf(ssh, "Local port %.*s%.*s%.*s%.*s%d%.*s"
5192 " forwarding to %s:%.*s%.*s%d%.*s",
5193 (int)(*saddr?strlen(saddr):0), *saddr?saddr:NULL,
5194 (int)(*saddr?1:0), ":",
5195 (int)(sserv ? strlen(sports) : 0), sports,
5196 sserv, "(", sport, sserv, ")",
5198 (int)(dserv ? strlen(dports) : 0), dports,
5199 dserv, "(", dport, dserv, ")");
5201 struct ssh_rportfwd *pf;
5202 pf = smalloc(sizeof(*pf));
5203 strcpy(pf->dhost, host);
5206 if (add234(ssh->rportfwds, pf) != pf) {
5207 logeventf(ssh, "Duplicate remote port forwarding"
5208 " to %s:%d", host, dport);
5211 logeventf(ssh, "Requesting remote port "
5212 "%.*s%.*s%.*s%.*s%d%.*s"
5213 " forward to %s:%.*s%.*s%d%.*s",
5214 (int)(*saddr?strlen(saddr):0),
5216 (int)(*saddr?1:0), ":",
5217 (int)(sserv ? strlen(sports) : 0), sports,
5218 sserv, "(", sport, sserv, ")",
5220 (int)(dserv ? strlen(dports) : 0), dports,
5221 dserv, "(", dport, dserv, ")");
5222 ssh2_pkt_init(ssh, SSH2_MSG_GLOBAL_REQUEST);
5223 ssh2_pkt_addstring(ssh, "tcpip-forward");
5224 ssh2_pkt_addbool(ssh, 1);/* want reply */
5226 ssh2_pkt_addstring(ssh, saddr);
5227 if (ssh->cfg.rport_acceptall)
5228 ssh2_pkt_addstring(ssh, "0.0.0.0");
5230 ssh2_pkt_addstring(ssh, "127.0.0.1");
5231 ssh2_pkt_adduint32(ssh, sport);
5235 crWaitUntilV(ispkt);
5236 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5237 unsigned i = ssh2_pkt_getuint32(ssh);
5238 struct ssh_channel *c;
5239 c = find234(ssh->channels, &i, ssh_channelfind);
5241 continue;/* nonexistent channel */
5242 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5244 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5246 if (ssh->pktin.type != SSH2_MSG_REQUEST_SUCCESS) {
5247 if (ssh->pktin.type != SSH2_MSG_REQUEST_FAILURE) {
5248 bombout((ssh,"Unexpected response to port "
5249 "forwarding request: packet type %d",
5253 logevent("Server refused this port forwarding");
5255 logevent("Remote port forwarding enabled");
5264 * Potentially enable agent forwarding.
5266 if (ssh->cfg.agentfwd && agent_exists()) {
5267 logevent("Requesting OpenSSH-style agent forwarding");
5268 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
5269 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
5270 ssh2_pkt_addstring(ssh, "auth-agent-req@openssh.com");
5271 ssh2_pkt_addbool(ssh, 1); /* want reply */
5275 crWaitUntilV(ispkt);
5276 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5277 unsigned i = ssh2_pkt_getuint32(ssh);
5278 struct ssh_channel *c;
5279 c = find234(ssh->channels, &i, ssh_channelfind);
5281 continue; /* nonexistent channel */
5282 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5284 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5286 if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5287 if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5288 bombout((ssh,"Unexpected response to agent forwarding request:"
5289 " packet type %d", ssh->pktin.type));
5292 logevent("Agent forwarding refused");
5294 logevent("Agent forwarding enabled");
5295 ssh->agentfwd_enabled = TRUE;
5300 * Now allocate a pty for the session.
5302 if (!ssh->cfg.nopty) {
5303 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
5304 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid); /* recipient channel */
5305 ssh2_pkt_addstring(ssh, "pty-req");
5306 ssh2_pkt_addbool(ssh, 1); /* want reply */
5307 ssh2_pkt_addstring(ssh, ssh->cfg.termtype);
5308 ssh2_pkt_adduint32(ssh, ssh->term_width);
5309 ssh2_pkt_adduint32(ssh, ssh->term_height);
5310 ssh2_pkt_adduint32(ssh, 0); /* pixel width */
5311 ssh2_pkt_adduint32(ssh, 0); /* pixel height */
5312 ssh2_pkt_addstring_start(ssh);
5313 ssh2_pkt_addstring_data(ssh, "\0", 1); /* TTY_OP_END, no special options */
5315 ssh->state = SSH_STATE_INTERMED;
5318 crWaitUntilV(ispkt);
5319 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5320 unsigned i = ssh2_pkt_getuint32(ssh);
5321 struct ssh_channel *c;
5322 c = find234(ssh->channels, &i, ssh_channelfind);
5324 continue; /* nonexistent channel */
5325 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5327 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5329 if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5330 if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5331 bombout((ssh,"Unexpected response to pty request:"
5332 " packet type %d", ssh->pktin.type));
5335 c_write_str(ssh, "Server refused to allocate pty\r\n");
5336 ssh->editing = ssh->echoing = 1;
5338 logevent("Allocated pty");
5341 ssh->editing = ssh->echoing = 1;
5345 * Start a shell or a remote command. We may have to attempt
5346 * this twice if the config data has provided a second choice
5353 if (ssh->fallback_cmd) {
5354 subsys = ssh->cfg.ssh_subsys2;
5355 cmd = ssh->cfg.remote_cmd_ptr2;
5357 subsys = ssh->cfg.ssh_subsys;
5358 cmd = ssh->cfg.remote_cmd_ptr;
5361 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
5362 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid); /* recipient channel */
5364 ssh2_pkt_addstring(ssh, "subsystem");
5365 ssh2_pkt_addbool(ssh, 1); /* want reply */
5366 ssh2_pkt_addstring(ssh, cmd);
5368 ssh2_pkt_addstring(ssh, "exec");
5369 ssh2_pkt_addbool(ssh, 1); /* want reply */
5370 ssh2_pkt_addstring(ssh, cmd);
5372 ssh2_pkt_addstring(ssh, "shell");
5373 ssh2_pkt_addbool(ssh, 1); /* want reply */
5377 crWaitUntilV(ispkt);
5378 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5379 unsigned i = ssh2_pkt_getuint32(ssh);
5380 struct ssh_channel *c;
5381 c = find234(ssh->channels, &i, ssh_channelfind);
5383 continue; /* nonexistent channel */
5384 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5386 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5387 if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5388 if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5389 bombout((ssh,"Unexpected response to shell/command request:"
5390 " packet type %d", ssh->pktin.type));
5394 * We failed to start the command. If this is the
5395 * fallback command, we really are finished; if it's
5396 * not, and if the fallback command exists, try falling
5397 * back to it before complaining.
5399 if (!ssh->fallback_cmd && ssh->cfg.remote_cmd_ptr2 != NULL) {
5400 logevent("Primary command failed; attempting fallback");
5401 ssh->fallback_cmd = TRUE;
5404 bombout((ssh,"Server refused to start a shell/command"));
5407 logevent("Started a shell/command");
5412 ssh->state = SSH_STATE_SESSION;
5413 if (ssh->size_needed)
5414 ssh_size(ssh, ssh->term_width, ssh->term_height);
5415 if (ssh->eof_needed)
5416 ssh_special(ssh, TS_EOF);
5422 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
5426 s->try_send = FALSE;
5428 if (ssh->pktin.type == SSH2_MSG_CHANNEL_DATA ||
5429 ssh->pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
5432 unsigned i = ssh2_pkt_getuint32(ssh);
5433 struct ssh_channel *c;
5434 c = find234(ssh->channels, &i, ssh_channelfind);
5436 continue; /* nonexistent channel */
5437 if (ssh->pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
5438 ssh2_pkt_getuint32(ssh) != SSH2_EXTENDED_DATA_STDERR)
5439 continue; /* extended but not stderr */
5440 ssh2_pkt_getstring(ssh, &data, &length);
5443 c->v.v2.locwindow -= length;
5445 case CHAN_MAINSESSION:
5447 from_backend(ssh->frontend, ssh->pktin.type ==
5448 SSH2_MSG_CHANNEL_EXTENDED_DATA,
5452 bufsize = x11_send(c->u.x11.s, data, length);
5455 bufsize = pfd_send(c->u.pfd.s, data, length);
5458 while (length > 0) {
5459 if (c->u.a.lensofar < 4) {
5460 int l = min(4 - c->u.a.lensofar, length);
5461 memcpy(c->u.a.msglen + c->u.a.lensofar,
5465 c->u.a.lensofar += l;
5467 if (c->u.a.lensofar == 4) {
5469 4 + GET_32BIT(c->u.a.msglen);
5470 c->u.a.message = smalloc(c->u.a.totallen);
5471 memcpy(c->u.a.message, c->u.a.msglen, 4);
5473 if (c->u.a.lensofar >= 4 && length > 0) {
5475 min(c->u.a.totallen - c->u.a.lensofar,
5477 memcpy(c->u.a.message + c->u.a.lensofar,
5481 c->u.a.lensofar += l;
5483 if (c->u.a.lensofar == c->u.a.totallen) {
5484 void *reply, *sentreply;
5486 agent_query(c->u.a.message,
5487 c->u.a.totallen, &reply,
5492 /* Fake SSH_AGENT_FAILURE. */
5493 sentreply = "\0\0\0\1\5";
5496 ssh2_add_channel_data(c, sentreply, replylen);
5500 sfree(c->u.a.message);
5501 c->u.a.lensofar = 0;
5508 * If we are not buffering too much data,
5509 * enlarge the window again at the remote side.
5511 if (bufsize < OUR_V2_WINSIZE)
5512 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
5514 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_EOF) {
5515 unsigned i = ssh2_pkt_getuint32(ssh);
5516 struct ssh_channel *c;
5518 c = find234(ssh->channels, &i, ssh_channelfind);
5520 continue; /* nonexistent channel */
5522 if (c->type == CHAN_X11) {
5524 * Remote EOF on an X11 channel means we should
5525 * wrap up and close the channel ourselves.
5527 x11_close(c->u.x11.s);
5529 } else if (c->type == CHAN_AGENT) {
5531 } else if (c->type == CHAN_SOCKDATA) {
5532 pfd_close(c->u.pfd.s);
5535 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
5536 unsigned i = ssh2_pkt_getuint32(ssh);
5537 struct ssh_channel *c;
5539 c = find234(ssh->channels, &i, ssh_channelfind);
5540 if (!c || ((int)c->remoteid) == -1) {
5541 bombout((ssh,"Received CHANNEL_CLOSE for %s channel %d\n",
5542 c ? "half-open" : "nonexistent", i));
5544 /* Do pre-close processing on the channel. */
5546 case CHAN_MAINSESSION:
5547 break; /* nothing to see here, move along */
5549 if (c->u.x11.s != NULL)
5550 x11_close(c->u.x11.s);
5557 if (c->u.pfd.s != NULL)
5558 pfd_close(c->u.pfd.s);
5562 if (c->closes == 0) {
5563 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_CLOSE);
5564 ssh2_pkt_adduint32(ssh, c->remoteid);
5567 del234(ssh->channels, c);
5568 bufchain_clear(&c->v.v2.outbuffer);
5572 * See if that was the last channel left open.
5574 if (count234(ssh->channels) == 0) {
5577 * We used to send SSH_MSG_DISCONNECT here,
5578 * because I'd believed that _every_ conforming
5579 * SSH2 connection had to end with a disconnect
5580 * being sent by at least one side; apparently
5581 * I was wrong and it's perfectly OK to
5582 * unceremoniously slam the connection shut
5583 * when you're done, and indeed OpenSSH feels
5584 * this is more polite than sending a
5585 * DISCONNECT. So now we don't.
5587 logevent("All channels closed. Disconnecting");
5588 ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
5589 ssh2_pkt_adduint32(ssh, SSH2_DISCONNECT_BY_APPLICATION);
5590 ssh2_pkt_addstring(ssh, "All open channels closed");
5591 ssh2_pkt_addstring(ssh, "en"); /* language tag */
5594 ssh->state = SSH_STATE_CLOSED;
5597 continue; /* remote sends close; ignore (FIXME) */
5598 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5599 unsigned i = ssh2_pkt_getuint32(ssh);
5600 struct ssh_channel *c;
5601 c = find234(ssh->channels, &i, ssh_channelfind);
5602 if (!c || c->closes)
5603 continue; /* nonexistent or closing channel */
5604 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5606 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
5607 unsigned i = ssh2_pkt_getuint32(ssh);
5608 struct ssh_channel *c;
5609 c = find234(ssh->channels, &i, ssh_channelfind);
5611 continue; /* nonexistent channel */
5612 if (c->type != CHAN_SOCKDATA_DORMANT)
5613 continue; /* dunno why they're confirming this */
5614 c->remoteid = ssh2_pkt_getuint32(ssh);
5615 c->type = CHAN_SOCKDATA;
5616 c->v.v2.remwindow = ssh2_pkt_getuint32(ssh);
5617 c->v.v2.remmaxpkt = ssh2_pkt_getuint32(ssh);
5619 pfd_confirm(c->u.pfd.s);
5622 * We have a pending close on this channel,
5623 * which we decided on before the server acked
5624 * the channel open. So now we know the
5625 * remoteid, we can close it again.
5627 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_CLOSE);
5628 ssh2_pkt_adduint32(ssh, c->remoteid);
5631 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_OPEN_FAILURE) {
5632 unsigned i = ssh2_pkt_getuint32(ssh);
5633 struct ssh_channel *c;
5634 c = find234(ssh->channels, &i, ssh_channelfind);
5636 continue; /* nonexistent channel */
5637 if (c->type != CHAN_SOCKDATA_DORMANT)
5638 continue; /* dunno why they're failing this */
5640 logevent("Forwarded connection refused by server");
5642 pfd_close(c->u.pfd.s);
5644 del234(ssh->channels, c);
5646 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
5649 int typelen, want_reply;
5650 struct ssh_channel *c;
5652 localid = ssh2_pkt_getuint32(ssh);
5653 ssh2_pkt_getstring(ssh, &type, &typelen);
5654 want_reply = ssh2_pkt_getbool(ssh);
5657 * First, check that the channel exists. Otherwise,
5658 * we can instantly disconnect with a rude message.
5660 c = find234(ssh->channels, &localid, ssh_channelfind);
5663 sprintf(buf, "Received channel request for nonexistent"
5664 " channel %d", localid);
5666 ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
5667 ssh2_pkt_adduint32(ssh, SSH2_DISCONNECT_BY_APPLICATION);
5668 ssh2_pkt_addstring(ssh, buf);
5669 ssh2_pkt_addstring(ssh, "en"); /* language tag */
5671 connection_fatal("%s", buf);
5672 ssh->state = SSH_STATE_CLOSED;
5677 * Having got the channel number, we now look at
5678 * the request type string to see if it's something
5681 if (typelen == 11 && !memcmp(type, "exit-status", 11) &&
5682 c == ssh->mainchan) {
5683 /* We recognise "exit-status" on the primary channel. */
5685 ssh->exitcode = ssh2_pkt_getuint32(ssh);
5686 sprintf(buf, "Server sent command exit status %d",
5690 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_SUCCESS);
5691 ssh2_pkt_adduint32(ssh, c->remoteid);
5696 * This is a channel request we don't know
5697 * about, so we now either ignore the request
5698 * or respond with CHANNEL_FAILURE, depending
5702 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_FAILURE);
5703 ssh2_pkt_adduint32(ssh, c->remoteid);
5707 } else if (ssh->pktin.type == SSH2_MSG_GLOBAL_REQUEST) {
5709 int typelen, want_reply;
5711 ssh2_pkt_getstring(ssh, &type, &typelen);
5712 want_reply = ssh2_pkt_getbool(ssh);
5715 * We currently don't support any global requests
5716 * at all, so we either ignore the request or
5717 * respond with REQUEST_FAILURE, depending on
5721 ssh2_pkt_init(ssh, SSH2_MSG_REQUEST_FAILURE);
5724 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_OPEN) {
5731 struct ssh_channel *c;
5732 unsigned remid, winsize, pktsize;
5733 ssh2_pkt_getstring(ssh, &type, &typelen);
5734 c = smalloc(sizeof(struct ssh_channel));
5737 remid = ssh2_pkt_getuint32(ssh);
5738 winsize = ssh2_pkt_getuint32(ssh);
5739 pktsize = ssh2_pkt_getuint32(ssh);
5740 ssh2_pkt_getstring(ssh, &peeraddr, &peeraddrlen);
5741 port = ssh2_pkt_getuint32(ssh);
5743 if (typelen == 3 && !memcmp(type, "x11", 3)) {
5744 char *addrstr = smalloc(peeraddrlen+1);
5745 memcpy(addrstr, peeraddr, peeraddrlen);
5746 peeraddr[peeraddrlen] = '\0';
5748 if (!ssh->X11_fwd_enabled)
5749 error = "X11 forwarding is not enabled";
5750 else if (x11_init(&c->u.x11.s, ssh->cfg.x11_display, c,
5751 ssh->x11auth, addrstr, port,
5752 &ssh->cfg) != NULL) {
5753 error = "Unable to open an X11 connection";
5759 } else if (typelen == 15 &&
5760 !memcmp(type, "forwarded-tcpip", 15)) {
5761 struct ssh_rportfwd pf, *realpf;
5764 ssh2_pkt_getstring(ssh, &dummy, &dummylen);/* skip address */
5765 pf.sport = ssh2_pkt_getuint32(ssh);
5766 realpf = find234(ssh->rportfwds, &pf, NULL);
5767 if (realpf == NULL) {
5768 error = "Remote port is not recognised";
5770 char *e = pfd_newconnect(&c->u.pfd.s, realpf->dhost,
5771 realpf->dport, c, &ssh->cfg);
5772 logeventf(ssh, "Received remote port open request"
5773 " for %s:%d", realpf->dhost, realpf->dport);
5775 logeventf(ssh, "Port open failed: %s", e);
5776 error = "Port open failed";
5778 logevent("Forwarded port opened successfully");
5779 c->type = CHAN_SOCKDATA;
5782 } else if (typelen == 22 &&
5783 !memcmp(type, "auth-agent@openssh.com", 3)) {
5784 if (!ssh->agentfwd_enabled)
5785 error = "Agent forwarding is not enabled";
5787 c->type = CHAN_AGENT; /* identify channel type */
5788 c->u.a.lensofar = 0;
5791 error = "Unsupported channel type requested";
5794 c->remoteid = remid;
5796 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE);
5797 ssh2_pkt_adduint32(ssh, c->remoteid);
5798 ssh2_pkt_adduint32(ssh, SSH2_OPEN_CONNECT_FAILED);
5799 ssh2_pkt_addstring(ssh, error);
5800 ssh2_pkt_addstring(ssh, "en"); /* language tag */
5804 c->localid = alloc_channel_id(ssh);
5806 c->v.v2.locwindow = OUR_V2_WINSIZE;
5807 c->v.v2.remwindow = winsize;
5808 c->v.v2.remmaxpkt = pktsize;
5809 bufchain_init(&c->v.v2.outbuffer);
5810 add234(ssh->channels, c);
5811 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
5812 ssh2_pkt_adduint32(ssh, c->remoteid);
5813 ssh2_pkt_adduint32(ssh, c->localid);
5814 ssh2_pkt_adduint32(ssh, c->v.v2.locwindow);
5815 ssh2_pkt_adduint32(ssh, 0x4000UL); /* our max pkt size */
5819 bombout((ssh,"Strange packet received: type %d", ssh->pktin.type));
5824 * We have spare data. Add it to the channel buffer.
5826 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
5831 struct ssh_channel *c;
5833 * Try to send data on all channels if we can.
5835 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
5838 continue; /* don't send on closing channels */
5839 bufsize = ssh2_try_send(c);
5842 case CHAN_MAINSESSION:
5843 /* stdin need not receive an unthrottle
5844 * notification since it will be polled */
5847 x11_unthrottle(c->u.x11.s);
5850 /* agent sockets are request/response and need no
5851 * buffer management */
5854 pfd_unthrottle(c->u.pfd.s);
5866 * Handle the top-level SSH2 protocol.
5868 static void ssh2_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
5870 if (do_ssh2_transport(ssh, in, inlen, ispkt) == 0)
5872 do_ssh2_authconn(ssh, in, inlen, ispkt);
5876 * Called to set up the connection.
5878 * Returns an error message, or NULL on success.
5880 static char *ssh_init(void *frontend_handle, void **backend_handle,
5882 char *host, int port, char **realhost, int nodelay)
5887 ssh = smalloc(sizeof(*ssh));
5888 ssh->cfg = *cfg; /* STRUCTURE COPY */
5891 ssh->v1_cipher_ctx = NULL;
5892 ssh->crcda_ctx = NULL;
5893 ssh->cscipher = NULL;
5894 ssh->cs_cipher_ctx = NULL;
5895 ssh->sccipher = NULL;
5896 ssh->sc_cipher_ctx = NULL;
5898 ssh->cs_mac_ctx = NULL;
5900 ssh->sc_mac_ctx = NULL;
5902 ssh->cs_comp_ctx = NULL;
5904 ssh->sc_comp_ctx = NULL;
5906 ssh->hostkey = NULL;
5908 ssh->state = SSH_STATE_PREPACKET;
5909 ssh->size_needed = FALSE;
5910 ssh->eof_needed = FALSE;
5914 static const struct Packet empty = { 0, 0, NULL, NULL, 0 };
5915 ssh->pktin = ssh->pktout = empty;
5917 ssh->deferred_send_data = NULL;
5918 ssh->deferred_len = 0;
5919 ssh->deferred_size = 0;
5920 ssh->fallback_cmd = 0;
5922 ssh->x11auth = NULL;
5923 ssh->v1_compressing = FALSE;
5924 ssh->v2_outgoing_sequence = 0;
5925 ssh->ssh1_rdpkt_crstate = 0;
5926 ssh->ssh2_rdpkt_crstate = 0;
5927 ssh->do_ssh_init_crstate = 0;
5928 ssh->ssh_gotdata_crstate = 0;
5929 ssh->ssh1_protocol_crstate = 0;
5930 ssh->do_ssh1_login_crstate = 0;
5931 ssh->do_ssh2_transport_crstate = 0;
5932 ssh->do_ssh2_authconn_crstate = 0;
5933 ssh->do_ssh_init_state = NULL;
5934 ssh->do_ssh1_login_state = NULL;
5935 ssh->do_ssh2_transport_state = NULL;
5936 ssh->do_ssh2_authconn_state = NULL;
5937 ssh->mainchan = NULL;
5938 ssh->throttled_all = 0;
5939 ssh->v1_stdout_throttling = 0;
5941 *backend_handle = ssh;
5944 if (crypto_startup() == 0)
5945 return "Microsoft high encryption pack not installed!";
5948 ssh->frontend = frontend_handle;
5949 ssh->term_width = ssh->cfg.width;
5950 ssh->term_height = ssh->cfg.height;
5952 ssh->channels = NULL;
5953 ssh->rportfwds = NULL;
5958 ssh->v1_throttle_count = 0;
5959 ssh->overall_bufsize = 0;
5960 ssh->fallback_cmd = 0;
5962 ssh->protocol = NULL;
5964 p = connect_to_host(ssh, host, port, realhost, nodelay);
5971 static void ssh_free(void *handle)
5973 Ssh ssh = (Ssh) handle;
5974 struct ssh_channel *c;
5975 struct ssh_rportfwd *pf;
5977 if (ssh->v1_cipher_ctx)
5978 ssh->cipher->free_context(ssh->v1_cipher_ctx);
5979 if (ssh->cs_cipher_ctx)
5980 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
5981 if (ssh->sc_cipher_ctx)
5982 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
5983 if (ssh->cs_mac_ctx)
5984 ssh->csmac->free_context(ssh->cs_mac_ctx);
5985 if (ssh->sc_mac_ctx)
5986 ssh->scmac->free_context(ssh->sc_mac_ctx);
5987 if (ssh->cs_comp_ctx)
5988 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
5989 if (ssh->sc_comp_ctx)
5990 ssh->sccomp->compress_cleanup(ssh->sc_comp_ctx);
5992 dh_cleanup(ssh->kex_ctx);
5993 sfree(ssh->savedhost);
5995 if (ssh->channels) {
5996 while ((c = delpos234(ssh->channels, 0)) != NULL) {
5999 if (c->u.x11.s != NULL)
6000 x11_close(c->u.x11.s);
6003 if (c->u.pfd.s != NULL)
6004 pfd_close(c->u.pfd.s);
6009 freetree234(ssh->channels);
6012 if (ssh->rportfwds) {
6013 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
6015 freetree234(ssh->rportfwds);
6017 sfree(ssh->deferred_send_data);
6019 x11_free_auth(ssh->x11auth);
6020 sfree(ssh->do_ssh_init_state);
6021 sfree(ssh->do_ssh1_login_state);
6022 sfree(ssh->do_ssh2_transport_state);
6023 sfree(ssh->do_ssh2_authconn_state);
6031 * Reconfigure the SSH backend.
6033 * Currently, this function does nothing very useful. In future,
6034 * however, we could do some handy things with it. For example, we
6035 * could make the port forwarding configurer active in the Change
6036 * Settings box, and this routine could close down existing
6037 * forwardings and open up new ones in response to changes.
6039 static void ssh_reconfig(void *handle, Config *cfg)
6041 Ssh ssh = (Ssh) handle;
6042 ssh->cfg = *cfg; /* STRUCTURE COPY */
6046 * Called to send data down the Telnet connection.
6048 static int ssh_send(void *handle, char *buf, int len)
6050 Ssh ssh = (Ssh) handle;
6052 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
6055 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
6057 return ssh_sendbuffer(ssh);
6061 * Called to query the current amount of buffered stdin data.
6063 static int ssh_sendbuffer(void *handle)
6065 Ssh ssh = (Ssh) handle;
6068 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
6072 * If the SSH socket itself has backed up, add the total backup
6073 * size on that to any individual buffer on the stdin channel.
6076 if (ssh->throttled_all)
6077 override_value = ssh->overall_bufsize;
6079 if (ssh->version == 1) {
6080 return override_value;
6081 } else if (ssh->version == 2) {
6082 if (!ssh->mainchan || ssh->mainchan->closes > 0)
6083 return override_value;
6085 return (override_value +
6086 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
6093 * Called to set the size of the window from SSH's POV.
6095 static void ssh_size(void *handle, int width, int height)
6097 Ssh ssh = (Ssh) handle;
6099 ssh->term_width = width;
6100 ssh->term_height = height;
6102 switch (ssh->state) {
6103 case SSH_STATE_BEFORE_SIZE:
6104 case SSH_STATE_PREPACKET:
6105 case SSH_STATE_CLOSED:
6106 break; /* do nothing */
6107 case SSH_STATE_INTERMED:
6108 ssh->size_needed = TRUE; /* buffer for later */
6110 case SSH_STATE_SESSION:
6111 if (!ssh->cfg.nopty) {
6112 if (ssh->version == 1) {
6113 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
6114 PKT_INT, ssh->term_height,
6115 PKT_INT, ssh->term_width,
6116 PKT_INT, 0, PKT_INT, 0, PKT_END);
6118 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
6119 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
6120 ssh2_pkt_addstring(ssh, "window-change");
6121 ssh2_pkt_addbool(ssh, 0);
6122 ssh2_pkt_adduint32(ssh, ssh->term_width);
6123 ssh2_pkt_adduint32(ssh, ssh->term_height);
6124 ssh2_pkt_adduint32(ssh, 0);
6125 ssh2_pkt_adduint32(ssh, 0);
6134 * Send Telnet special codes. TS_EOF is useful for `plink', so you
6135 * can send an EOF and collect resulting output (e.g. `plink
6138 static void ssh_special(void *handle, Telnet_Special code)
6140 Ssh ssh = (Ssh) handle;
6142 if (code == TS_EOF) {
6143 if (ssh->state != SSH_STATE_SESSION) {
6145 * Buffer the EOF in case we are pre-SESSION, so we can
6146 * send it as soon as we reach SESSION.
6149 ssh->eof_needed = TRUE;
6152 if (ssh->version == 1) {
6153 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
6155 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_EOF);
6156 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
6159 logevent("Sent EOF message");
6160 } else if (code == TS_PING) {
6161 if (ssh->state == SSH_STATE_CLOSED
6162 || ssh->state == SSH_STATE_PREPACKET) return;
6163 if (ssh->version == 1) {
6164 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
6165 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
6167 ssh2_pkt_init(ssh, SSH2_MSG_IGNORE);
6168 ssh2_pkt_addstring_start(ssh);
6176 void *new_sock_channel(void *handle, Socket s)
6178 Ssh ssh = (Ssh) handle;
6179 struct ssh_channel *c;
6180 c = smalloc(sizeof(struct ssh_channel));
6184 c->remoteid = -1; /* to be set when open confirmed */
6185 c->localid = alloc_channel_id(ssh);
6187 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
6189 bufchain_init(&c->v.v2.outbuffer);
6190 add234(ssh->channels, c);
6196 * This is called when stdout/stderr (the entity to which
6197 * from_backend sends data) manages to clear some backlog.
6199 static void ssh_unthrottle(void *handle, int bufsize)
6201 Ssh ssh = (Ssh) handle;
6202 if (ssh->version == 1) {
6203 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
6204 ssh->v1_stdout_throttling = 0;
6205 ssh1_throttle(ssh, -1);
6208 if (ssh->mainchan && ssh->mainchan->closes == 0)
6209 ssh2_set_window(ssh->mainchan, OUR_V2_WINSIZE - bufsize);
6213 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
6215 struct ssh_channel *c = (struct ssh_channel *)channel;
6218 logeventf(ssh, "Opening forwarded connection to %s:%d", hostname, port);
6220 if (ssh->version == 1) {
6221 send_packet(ssh, SSH1_MSG_PORT_OPEN,
6222 PKT_INT, c->localid,
6225 //PKT_STR, <org:orgport>,
6228 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_OPEN);
6229 ssh2_pkt_addstring(ssh, "direct-tcpip");
6230 ssh2_pkt_adduint32(ssh, c->localid);
6231 c->v.v2.locwindow = OUR_V2_WINSIZE;
6232 ssh2_pkt_adduint32(ssh, c->v.v2.locwindow);/* our window size */
6233 ssh2_pkt_adduint32(ssh, 0x4000UL); /* our max pkt size */
6234 ssh2_pkt_addstring(ssh, hostname);
6235 ssh2_pkt_adduint32(ssh, port);
6237 * We make up values for the originator data; partly it's
6238 * too much hassle to keep track, and partly I'm not
6239 * convinced the server should be told details like that
6240 * about my local network configuration.
6242 ssh2_pkt_addstring(ssh, "client-side-connection");
6243 ssh2_pkt_adduint32(ssh, 0);
6249 static Socket ssh_socket(void *handle)
6251 Ssh ssh = (Ssh) handle;
6255 static int ssh_sendok(void *handle)
6257 Ssh ssh = (Ssh) handle;
6258 return ssh->send_ok;
6261 static int ssh_ldisc(void *handle, int option)
6263 Ssh ssh = (Ssh) handle;
6264 if (option == LD_ECHO)
6265 return ssh->echoing;
6266 if (option == LD_EDIT)
6267 return ssh->editing;
6271 static void ssh_provide_ldisc(void *handle, void *ldisc)
6273 Ssh ssh = (Ssh) handle;
6277 static void ssh_provide_logctx(void *handle, void *logctx)
6279 Ssh ssh = (Ssh) handle;
6280 ssh->logctx = logctx;
6283 static int ssh_return_exitcode(void *handle)
6285 Ssh ssh = (Ssh) handle;
6286 return ssh->exitcode;
6290 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
6291 * that fails. This variable is the means by which scp.c can reach
6292 * into the SSH code and find out which one it got.
6294 extern int ssh_fallback_cmd(void *handle)
6296 Ssh ssh = (Ssh) handle;
6297 return ssh->fallback_cmd;
6300 Backend ssh_backend = {
6309 ssh_return_exitcode,