18 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
19 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
20 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
21 #define SSH1_CMSG_USER 4 /* 0x4 */
22 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
23 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
24 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
25 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
26 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
27 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
28 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
29 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
30 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
31 #define SSH1_SMSG_FAILURE 15 /* 0xf */
32 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
33 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
34 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
35 #define SSH1_CMSG_EOF 19 /* 0x13 */
36 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
37 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
38 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
39 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
40 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
41 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
42 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
43 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
44 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
45 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
46 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
47 #define SSH1_MSG_IGNORE 32 /* 0x20 */
48 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
49 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
50 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
51 #define SSH1_MSG_DEBUG 36 /* 0x24 */
52 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
53 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
54 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
55 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
56 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
57 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
58 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
60 #define SSH1_AUTH_TIS 5 /* 0x5 */
61 #define SSH1_AUTH_CCARD 16 /* 0x10 */
63 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
64 /* Mask for protoflags we will echo back to server if seen */
65 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
67 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
68 #define SSH2_MSG_IGNORE 2 /* 0x2 */
69 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
70 #define SSH2_MSG_DEBUG 4 /* 0x4 */
71 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
72 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
73 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
74 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
75 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
76 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
77 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
78 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
79 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
80 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
81 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
82 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
83 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
84 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
85 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
86 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
87 #define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */
88 #define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */
89 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
90 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
91 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
92 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
93 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
94 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
95 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
96 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
97 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
98 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
99 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
100 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
101 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
102 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
105 * Packet type contexts, so that ssh2_pkt_type can correctly decode
106 * the ambiguous type numbers back into the correct type strings.
108 #define SSH2_PKTCTX_DHGROUP1 0x0001
109 #define SSH2_PKTCTX_DHGEX 0x0002
110 #define SSH2_PKTCTX_PUBLICKEY 0x0010
111 #define SSH2_PKTCTX_PASSWORD 0x0020
112 #define SSH2_PKTCTX_KBDINTER 0x0040
113 #define SSH2_PKTCTX_AUTH_MASK 0x00F0
115 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
116 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
117 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
118 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
119 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
120 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
121 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
122 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
123 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
124 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
125 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
126 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
127 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
128 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
129 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
131 static const char *const ssh2_disconnect_reasons[] = {
133 "SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT",
134 "SSH_DISCONNECT_PROTOCOL_ERROR",
135 "SSH_DISCONNECT_KEY_EXCHANGE_FAILED",
136 "SSH_DISCONNECT_HOST_AUTHENTICATION_FAILED",
137 "SSH_DISCONNECT_MAC_ERROR",
138 "SSH_DISCONNECT_COMPRESSION_ERROR",
139 "SSH_DISCONNECT_SERVICE_NOT_AVAILABLE",
140 "SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED",
141 "SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE",
142 "SSH_DISCONNECT_CONNECTION_LOST",
143 "SSH_DISCONNECT_BY_APPLICATION",
144 "SSH_DISCONNECT_TOO_MANY_CONNECTIONS",
145 "SSH_DISCONNECT_AUTH_CANCELLED_BY_USER",
146 "SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE",
147 "SSH_DISCONNECT_ILLEGAL_USER_NAME",
150 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
151 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
152 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
153 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
155 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
158 * Various remote-bug flags.
160 #define BUG_CHOKES_ON_SSH1_IGNORE 1
161 #define BUG_SSH2_HMAC 2
162 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
163 #define BUG_CHOKES_ON_RSA 8
164 #define BUG_SSH2_RSA_PADDING 16
165 #define BUG_SSH2_DERIVEKEY 32
166 #define BUG_SSH2_DH_GEX 64
168 #define translate(x) if (type == x) return #x
169 #define translatec(x,ctx) if (type == x && (pkt_ctx & ctx)) return #x
170 char *ssh1_pkt_type(int type)
172 translate(SSH1_MSG_DISCONNECT);
173 translate(SSH1_SMSG_PUBLIC_KEY);
174 translate(SSH1_CMSG_SESSION_KEY);
175 translate(SSH1_CMSG_USER);
176 translate(SSH1_CMSG_AUTH_RSA);
177 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
178 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
179 translate(SSH1_CMSG_AUTH_PASSWORD);
180 translate(SSH1_CMSG_REQUEST_PTY);
181 translate(SSH1_CMSG_WINDOW_SIZE);
182 translate(SSH1_CMSG_EXEC_SHELL);
183 translate(SSH1_CMSG_EXEC_CMD);
184 translate(SSH1_SMSG_SUCCESS);
185 translate(SSH1_SMSG_FAILURE);
186 translate(SSH1_CMSG_STDIN_DATA);
187 translate(SSH1_SMSG_STDOUT_DATA);
188 translate(SSH1_SMSG_STDERR_DATA);
189 translate(SSH1_CMSG_EOF);
190 translate(SSH1_SMSG_EXIT_STATUS);
191 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
192 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
193 translate(SSH1_MSG_CHANNEL_DATA);
194 translate(SSH1_MSG_CHANNEL_CLOSE);
195 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
196 translate(SSH1_SMSG_X11_OPEN);
197 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
198 translate(SSH1_MSG_PORT_OPEN);
199 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
200 translate(SSH1_SMSG_AGENT_OPEN);
201 translate(SSH1_MSG_IGNORE);
202 translate(SSH1_CMSG_EXIT_CONFIRMATION);
203 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
204 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
205 translate(SSH1_MSG_DEBUG);
206 translate(SSH1_CMSG_REQUEST_COMPRESSION);
207 translate(SSH1_CMSG_AUTH_TIS);
208 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
209 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
210 translate(SSH1_CMSG_AUTH_CCARD);
211 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
212 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
215 char *ssh2_pkt_type(int pkt_ctx, int type)
217 translate(SSH2_MSG_DISCONNECT);
218 translate(SSH2_MSG_IGNORE);
219 translate(SSH2_MSG_UNIMPLEMENTED);
220 translate(SSH2_MSG_DEBUG);
221 translate(SSH2_MSG_SERVICE_REQUEST);
222 translate(SSH2_MSG_SERVICE_ACCEPT);
223 translate(SSH2_MSG_KEXINIT);
224 translate(SSH2_MSG_NEWKEYS);
225 translatec(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP1);
226 translatec(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP1);
227 translatec(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
228 translatec(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
229 translatec(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
230 translatec(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
231 translate(SSH2_MSG_USERAUTH_REQUEST);
232 translate(SSH2_MSG_USERAUTH_FAILURE);
233 translate(SSH2_MSG_USERAUTH_SUCCESS);
234 translate(SSH2_MSG_USERAUTH_BANNER);
235 translatec(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
236 translatec(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
237 translatec(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
238 translatec(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
239 translate(SSH2_MSG_GLOBAL_REQUEST);
240 translate(SSH2_MSG_REQUEST_SUCCESS);
241 translate(SSH2_MSG_REQUEST_FAILURE);
242 translate(SSH2_MSG_CHANNEL_OPEN);
243 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
244 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
245 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
246 translate(SSH2_MSG_CHANNEL_DATA);
247 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
248 translate(SSH2_MSG_CHANNEL_EOF);
249 translate(SSH2_MSG_CHANNEL_CLOSE);
250 translate(SSH2_MSG_CHANNEL_REQUEST);
251 translate(SSH2_MSG_CHANNEL_SUCCESS);
252 translate(SSH2_MSG_CHANNEL_FAILURE);
258 #define GET_32BIT(cp) \
259 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
260 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
261 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
262 ((unsigned long)(unsigned char)(cp)[3]))
264 #define PUT_32BIT(cp, value) { \
265 (cp)[0] = (unsigned char)((value) >> 24); \
266 (cp)[1] = (unsigned char)((value) >> 16); \
267 (cp)[2] = (unsigned char)((value) >> 8); \
268 (cp)[3] = (unsigned char)(value); }
270 enum { PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM };
272 /* Coroutine mechanics for the sillier bits of the code */
273 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
276 if (!ssh->t) ssh->t = smalloc(sizeof(struct t)); \
278 #define crFinish(z) } *crLine = 0; return (z); }
279 #define crFinishV } *crLine = 0; return; }
280 #define crReturn(z) \
282 *crLine =__LINE__; return (z); case __LINE__:;\
286 *crLine=__LINE__; return; case __LINE__:;\
288 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
289 #define crStopV do{ *crLine = 0; return; }while(0)
290 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
291 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
293 typedef struct ssh_tag *Ssh;
295 extern char *x11_init(Socket *, char *, void *, void *);
296 extern void x11_close(Socket);
297 extern int x11_send(Socket, char *, int);
298 extern void *x11_invent_auth(char *, int, char *, int);
299 extern void x11_unthrottle(Socket s);
300 extern void x11_override_throttle(Socket s, int enable);
302 extern char *pfd_newconnect(Socket * s, char *hostname, int port, void *c);
303 extern char *pfd_addforward(char *desthost, int destport, int port,
305 extern void pfd_close(Socket s);
306 extern int pfd_send(Socket s, char *data, int len);
307 extern void pfd_confirm(Socket s);
308 extern void pfd_unthrottle(Socket s);
309 extern void pfd_override_throttle(Socket s, int enable);
311 static void ssh2_pkt_init(Ssh, int pkt_type);
312 static void ssh2_pkt_addbool(Ssh, unsigned char value);
313 static void ssh2_pkt_adduint32(Ssh, unsigned long value);
314 static void ssh2_pkt_addstring_start(Ssh);
315 static void ssh2_pkt_addstring_str(Ssh, char *data);
316 static void ssh2_pkt_addstring_data(Ssh, char *data, int len);
317 static void ssh2_pkt_addstring(Ssh, char *data);
318 static char *ssh2_mpint_fmt(Bignum b, int *len);
319 static void ssh2_pkt_addmp(Ssh, Bignum b);
320 static int ssh2_pkt_construct(Ssh);
321 static void ssh2_pkt_send(Ssh);
324 * Buffer management constants. There are several of these for
325 * various different purposes:
327 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
328 * on a local data stream before we throttle the whole SSH
329 * connection (in SSH1 only). Throttling the whole connection is
330 * pretty drastic so we set this high in the hope it won't
333 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
334 * on the SSH connection itself before we defensively throttle
335 * _all_ local data streams. This is pretty drastic too (though
336 * thankfully unlikely in SSH2 since the window mechanism should
337 * ensure that the server never has any need to throttle its end
338 * of the connection), so we set this high as well.
340 * - OUR_V2_WINSIZE is the maximum window size we present on SSH2
344 #define SSH1_BUFFER_LIMIT 32768
345 #define SSH_MAX_BACKLOG 32768
346 #define OUR_V2_WINSIZE 16384
348 const static struct ssh_kex *kex_algs[] = {
349 &ssh_diffiehellman_gex,
353 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
355 static void *nullmac_make_context(void)
359 static void nullmac_free_context(void *handle)
362 static void nullmac_key(void *handle, unsigned char *key)
365 static void nullmac_generate(void *handle, unsigned char *blk, int len,
369 static int nullmac_verify(void *handle, unsigned char *blk, int len,
374 const static struct ssh_mac ssh_mac_none = {
375 nullmac_make_context, nullmac_free_context, nullmac_key,
376 nullmac_generate, nullmac_verify, "none", 0
378 const static struct ssh_mac *macs[] = {
379 &ssh_sha1, &ssh_md5, &ssh_mac_none
381 const static struct ssh_mac *buggymacs[] = {
382 &ssh_sha1_buggy, &ssh_md5, &ssh_mac_none
385 static void *ssh_comp_none_init(void)
389 static void ssh_comp_none_cleanup(void *handle)
392 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
393 unsigned char **outblock, int *outlen)
397 static int ssh_comp_none_disable(void *handle)
401 const static struct ssh_compress ssh_comp_none = {
403 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
404 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
405 ssh_comp_none_disable, NULL
407 extern const struct ssh_compress ssh_zlib;
408 const static struct ssh_compress *compressions[] = {
409 &ssh_zlib, &ssh_comp_none
412 enum { /* channel types */
417 CHAN_SOCKDATA_DORMANT /* one the remote hasn't confirmed */
421 * 2-3-4 tree storing channels.
424 Ssh ssh; /* pointer back to main context */
425 unsigned remoteid, localid;
428 * In SSH1, this value contains four bits:
430 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
431 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
432 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
433 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
435 * A channel is completely finished with when all four bits are set.
439 struct ssh1_data_channel {
442 struct ssh2_data_channel {
444 unsigned remwindow, remmaxpkt;
449 struct ssh_agent_channel {
450 unsigned char *message;
451 unsigned char msglen[4];
452 int lensofar, totallen;
454 struct ssh_x11_channel {
457 struct ssh_pfd_channel {
464 * 2-3-4 tree storing remote->local port forwardings. SSH 1 and SSH
465 * 2 use this structure in different ways, reflecting SSH 2's
466 * altogether saner approach to port forwarding.
468 * In SSH 1, you arrange a remote forwarding by sending the server
469 * the remote port number, and the local destination host:port.
470 * When a connection comes in, the server sends you back that
471 * host:port pair, and you connect to it. This is a ready-made
472 * security hole if you're not on the ball: a malicious server
473 * could send you back _any_ host:port pair, so if you trustingly
474 * connect to the address it gives you then you've just opened the
475 * entire inside of your corporate network just by connecting
476 * through it to a dodgy SSH server. Hence, we must store a list of
477 * host:port pairs we _are_ trying to forward to, and reject a
478 * connection request from the server if it's not in the list.
480 * In SSH 2, each side of the connection minds its own business and
481 * doesn't send unnecessary information to the other. You arrange a
482 * remote forwarding by sending the server just the remote port
483 * number. When a connection comes in, the server tells you which
484 * of its ports was connected to; and _you_ have to remember what
485 * local host:port pair went with that port number.
487 * Hence: in SSH 1 this structure stores host:port pairs we intend
488 * to allow connections to, and is indexed by those host:port
489 * pairs. In SSH 2 it stores a mapping from source port to
490 * destination host:port pair, and is indexed by source port.
492 struct ssh_rportfwd {
493 unsigned sport, dport;
506 static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt);
507 static void ssh2_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt);
508 static void ssh_size(void *handle, int width, int height);
509 static void ssh_special(void *handle, Telnet_Special);
510 static int ssh2_try_send(struct ssh_channel *c);
511 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
512 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
513 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin);
514 static int ssh_sendbuffer(void *handle);
516 struct rdpkt1_state_tag {
517 long len, pad, biglen, to_read;
518 unsigned long realcrc, gotcrc;
524 struct rdpkt2_state_tag {
525 long len, pad, payload, packetlen, maclen;
528 unsigned long incoming_sequence;
532 const struct plug_function_table *fn;
533 /* the above field _must_ be first in the structure */
535 SHA_State exhash, exhashbase;
542 unsigned char session_key[32];
544 int v1_remote_protoflags;
545 int v1_local_protoflags;
546 int agentfwd_enabled;
549 const struct ssh_cipher *cipher;
552 const struct ssh2_cipher *cscipher, *sccipher;
553 void *cs_cipher_ctx, *sc_cipher_ctx;
554 const struct ssh_mac *csmac, *scmac;
555 void *cs_mac_ctx, *sc_mac_ctx;
556 const struct ssh_compress *cscomp, *sccomp;
557 void *cs_comp_ctx, *sc_comp_ctx;
558 const struct ssh_kex *kex;
559 const struct ssh_signkey *hostkey;
560 unsigned char v2_session_id[20];
566 int echoing, editing;
570 int term_width, term_height;
572 tree234 *channels; /* indexed by local id */
573 struct ssh_channel *mainchan; /* primary session channel */
580 SSH_STATE_BEFORE_SIZE,
586 int size_needed, eof_needed;
589 struct Packet pktout;
590 unsigned char *deferred_send_data;
591 int deferred_len, deferred_size;
594 * Gross hack: pscp will try to start SFTP but fall back to
595 * scp1 if that fails. This variable is the means by which
596 * scp.c can reach into the SSH code and find out which one it
602 * Used for username and password input.
604 char *userpass_input_buffer;
605 int userpass_input_buflen;
606 int userpass_input_bufpos;
607 int userpass_input_echo;
609 char *portfwd_strptr;
615 int v1_throttle_count;
618 int v1_stdout_throttling;
619 int v2_outgoing_sequence;
621 int ssh1_rdpkt_crstate;
622 int ssh2_rdpkt_crstate;
623 int do_ssh_init_crstate;
624 int ssh_gotdata_crstate;
625 int ssh1_protocol_crstate;
626 int do_ssh1_login_crstate;
627 int do_ssh2_transport_crstate;
628 int do_ssh2_authconn_crstate;
630 void *do_ssh_init_state;
631 void *do_ssh1_login_state;
632 void *do_ssh2_transport_state;
633 void *do_ssh2_authconn_state;
635 struct rdpkt1_state_tag rdpkt1_state;
636 struct rdpkt2_state_tag rdpkt2_state;
638 void (*protocol) (Ssh ssh, unsigned char *in, int inlen, int ispkt);
639 int (*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
642 #define logevent(s) { logevent(ssh->frontend, s); \
643 if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)) \
644 { fprintf(stderr, "%s\n", s); fflush(stderr); } }
646 /* logevent, only printf-formatted. */
647 void logeventf(Ssh ssh, char *fmt, ...)
653 vsprintf(stuff, fmt, ap);
658 #define bombout(msg) ( ssh->state = SSH_STATE_CLOSED, \
659 (ssh->s ? sk_close(ssh->s), ssh->s = NULL : 0), \
660 logeventf msg, connection_fatal msg )
662 static int ssh_channelcmp(void *av, void *bv)
664 struct ssh_channel *a = (struct ssh_channel *) av;
665 struct ssh_channel *b = (struct ssh_channel *) bv;
666 if (a->localid < b->localid)
668 if (a->localid > b->localid)
672 static int ssh_channelfind(void *av, void *bv)
674 unsigned *a = (unsigned *) av;
675 struct ssh_channel *b = (struct ssh_channel *) bv;
683 static int ssh_rportcmp_ssh1(void *av, void *bv)
685 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
686 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
688 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
689 return i < 0 ? -1 : +1;
690 if (a->dport > b->dport)
692 if (a->dport < b->dport)
697 static int ssh_rportcmp_ssh2(void *av, void *bv)
699 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
700 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
702 if (a->sport > b->sport)
704 if (a->sport < b->sport)
709 static int alloc_channel_id(Ssh ssh)
711 const unsigned CHANNEL_NUMBER_OFFSET = 256;
712 unsigned low, high, mid;
714 struct ssh_channel *c;
717 * First-fit allocation of channel numbers: always pick the
718 * lowest unused one. To do this, binary-search using the
719 * counted B-tree to find the largest channel ID which is in a
720 * contiguous sequence from the beginning. (Precisely
721 * everything in that sequence must have ID equal to its tree
722 * index plus CHANNEL_NUMBER_OFFSET.)
724 tsize = count234(ssh->channels);
728 while (high - low > 1) {
729 mid = (high + low) / 2;
730 c = index234(ssh->channels, mid);
731 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
732 low = mid; /* this one is fine */
734 high = mid; /* this one is past it */
737 * Now low points to either -1, or the tree index of the
738 * largest ID in the initial sequence.
741 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
742 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
744 return low + 1 + CHANNEL_NUMBER_OFFSET;
747 static void c_write(Ssh ssh, char *buf, int len)
749 if ((flags & FLAG_STDERR)) {
751 for (i = 0; i < len; i++)
753 fputc(buf[i], stderr);
756 from_backend(ssh->frontend, 1, buf, len);
759 static void c_write_untrusted(Ssh ssh, char *buf, int len)
762 for (i = 0; i < len; i++) {
764 c_write(ssh, "\r\n", 2);
765 else if ((buf[i] & 0x60) || (buf[i] == '\r'))
766 c_write(ssh, buf + i, 1);
770 static void c_write_str(Ssh ssh, char *buf)
772 c_write(ssh, buf, strlen(buf));
776 * Collect incoming data in the incoming packet buffer.
777 * Decipher and verify the packet when it is completely read.
778 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
779 * Update the *data and *datalen variables.
780 * Return the additional nr of bytes needed, or 0 when
781 * a complete packet is available.
783 static int ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
785 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
787 crBegin(ssh->ssh1_rdpkt_crstate);
792 ssh->pktin.length = 0;
794 for (st->i = st->len = 0; st->i < 4; st->i++) {
795 while ((*datalen) == 0)
797 st->len = (st->len << 8) + **data;
798 (*data)++, (*datalen)--;
801 st->pad = 8 - (st->len % 8);
802 st->biglen = st->len + st->pad;
803 ssh->pktin.length = st->len - 5;
805 if (ssh->pktin.maxlen < st->biglen) {
806 ssh->pktin.maxlen = st->biglen;
807 ssh->pktin.data = srealloc(ssh->pktin.data, st->biglen + APIEXTRA);
810 st->to_read = st->biglen;
811 st->p = ssh->pktin.data;
812 while (st->to_read > 0) {
813 st->chunk = st->to_read;
814 while ((*datalen) == 0)
815 crReturn(st->to_read);
816 if (st->chunk > (*datalen))
817 st->chunk = (*datalen);
818 memcpy(st->p, *data, st->chunk);
820 *datalen -= st->chunk;
822 st->to_read -= st->chunk;
825 if (ssh->cipher && detect_attack(ssh->crcda_ctx, ssh->pktin.data,
827 bombout((ssh,"Network attack (CRC compensation) detected!"));
832 ssh->cipher->decrypt(ssh->v1_cipher_ctx, ssh->pktin.data, st->biglen);
834 st->realcrc = crc32(ssh->pktin.data, st->biglen - 4);
835 st->gotcrc = GET_32BIT(ssh->pktin.data + st->biglen - 4);
836 if (st->gotcrc != st->realcrc) {
837 bombout((ssh,"Incorrect CRC received on packet"));
841 ssh->pktin.body = ssh->pktin.data + st->pad + 1;
843 if (ssh->v1_compressing) {
844 unsigned char *decompblk;
846 zlib_decompress_block(ssh->sc_comp_ctx,
847 ssh->pktin.body - 1, ssh->pktin.length + 1,
848 &decompblk, &decomplen);
850 if (ssh->pktin.maxlen < st->pad + decomplen) {
851 ssh->pktin.maxlen = st->pad + decomplen;
852 ssh->pktin.data = srealloc(ssh->pktin.data,
853 ssh->pktin.maxlen + APIEXTRA);
854 ssh->pktin.body = ssh->pktin.data + st->pad + 1;
857 memcpy(ssh->pktin.body - 1, decompblk, decomplen);
859 ssh->pktin.length = decomplen - 1;
862 ssh->pktin.type = ssh->pktin.body[-1];
865 log_packet(ssh->logctx,
866 PKT_INCOMING, ssh->pktin.type,
867 ssh1_pkt_type(ssh->pktin.type),
868 ssh->pktin.body, ssh->pktin.length);
870 if (ssh->pktin.type == SSH1_SMSG_STDOUT_DATA ||
871 ssh->pktin.type == SSH1_SMSG_STDERR_DATA ||
872 ssh->pktin.type == SSH1_MSG_DEBUG ||
873 ssh->pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE ||
874 ssh->pktin.type == SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
875 long stringlen = GET_32BIT(ssh->pktin.body);
876 if (stringlen + 4 != ssh->pktin.length) {
877 bombout((ssh,"Received data packet with bogus string length"));
882 if (ssh->pktin.type == SSH1_MSG_DEBUG) {
883 /* log debug message */
885 int stringlen = GET_32BIT(ssh->pktin.body);
886 strcpy(buf, "Remote debug message: ");
889 memcpy(buf + 8, ssh->pktin.body + 4, stringlen);
890 buf[8 + stringlen] = '\0';
893 } else if (ssh->pktin.type == SSH1_MSG_IGNORE) {
898 if (ssh->pktin.type == SSH1_MSG_DISCONNECT) {
899 /* log reason code in disconnect message */
901 unsigned msglen = GET_32BIT(ssh->pktin.body);
903 strcpy(buf, "Remote sent disconnect: ");
904 nowlen = strlen(buf);
905 if (msglen > sizeof(buf) - nowlen - 1)
906 msglen = sizeof(buf) - nowlen - 1;
907 memcpy(buf + nowlen, ssh->pktin.body + 4, msglen);
908 buf[nowlen + msglen] = '\0';
909 /* logevent(buf); (this is now done within the bombout macro) */
910 bombout((ssh,"Server sent disconnect message:\n\"%s\"", buf+nowlen));
917 static int ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
919 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
921 crBegin(ssh->ssh2_rdpkt_crstate);
925 ssh->pktin.length = 0;
927 st->cipherblk = ssh->sccipher->blksize;
930 if (st->cipherblk < 8)
933 if (ssh->pktin.maxlen < st->cipherblk) {
934 ssh->pktin.maxlen = st->cipherblk;
935 ssh->pktin.data = srealloc(ssh->pktin.data, st->cipherblk + APIEXTRA);
939 * Acquire and decrypt the first block of the packet. This will
940 * contain the length and padding details.
942 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
943 while ((*datalen) == 0)
944 crReturn(st->cipherblk - st->i);
945 ssh->pktin.data[st->i] = *(*data)++;
950 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
951 ssh->pktin.data, st->cipherblk);
954 * Now get the length and padding figures.
956 st->len = GET_32BIT(ssh->pktin.data);
957 st->pad = ssh->pktin.data[4];
960 * _Completely_ silly lengths should be stomped on before they
961 * do us any more damage.
963 if (st->len < 0 || st->pad < 0 || st->len + st->pad < 0) {
964 bombout((ssh,"Incoming packet was garbled on decryption"));
969 * This enables us to deduce the payload length.
971 st->payload = st->len - st->pad - 1;
973 ssh->pktin.length = st->payload + 5;
976 * So now we can work out the total packet length.
978 st->packetlen = st->len + 4;
979 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
982 * Adjust memory allocation if packet is too big.
984 if (ssh->pktin.maxlen < st->packetlen + st->maclen) {
985 ssh->pktin.maxlen = st->packetlen + st->maclen;
986 ssh->pktin.data = srealloc(ssh->pktin.data,
987 ssh->pktin.maxlen + APIEXTRA);
991 * Read and decrypt the remainder of the packet.
993 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
995 while ((*datalen) == 0)
996 crReturn(st->packetlen + st->maclen - st->i);
997 ssh->pktin.data[st->i] = *(*data)++;
1000 /* Decrypt everything _except_ the MAC. */
1002 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1003 ssh->pktin.data + st->cipherblk,
1004 st->packetlen - st->cipherblk);
1010 && !ssh->scmac->verify(ssh->sc_mac_ctx, ssh->pktin.data, st->len + 4,
1011 st->incoming_sequence)) {
1012 bombout((ssh,"Incorrect MAC received on packet"));
1015 st->incoming_sequence++; /* whether or not we MACed */
1018 * Decompress packet payload.
1021 unsigned char *newpayload;
1024 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1025 ssh->pktin.data + 5, ssh->pktin.length - 5,
1026 &newpayload, &newlen)) {
1027 if (ssh->pktin.maxlen < newlen + 5) {
1028 ssh->pktin.maxlen = newlen + 5;
1029 ssh->pktin.data = srealloc(ssh->pktin.data,
1030 ssh->pktin.maxlen + APIEXTRA);
1032 ssh->pktin.length = 5 + newlen;
1033 memcpy(ssh->pktin.data + 5, newpayload, newlen);
1038 ssh->pktin.savedpos = 6;
1039 ssh->pktin.type = ssh->pktin.data[5];
1042 log_packet(ssh->logctx, PKT_INCOMING, ssh->pktin.type,
1043 ssh2_pkt_type(ssh->pkt_ctx, ssh->pktin.type),
1044 ssh->pktin.data+6, ssh->pktin.length-6);
1046 switch (ssh->pktin.type) {
1048 * These packets we must handle instantly.
1050 case SSH2_MSG_DISCONNECT:
1052 /* log reason code in disconnect message */
1054 int reason = GET_32BIT(ssh->pktin.data + 6);
1055 unsigned msglen = GET_32BIT(ssh->pktin.data + 10);
1057 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
1058 sprintf(buf, "Received disconnect message (%s)",
1059 ssh2_disconnect_reasons[reason]);
1061 sprintf(buf, "Received disconnect message (unknown type %d)",
1065 strcpy(buf, "Disconnection message text: ");
1066 nowlen = strlen(buf);
1067 if (msglen > sizeof(buf) - nowlen - 1)
1068 msglen = sizeof(buf) - nowlen - 1;
1069 memcpy(buf + nowlen, ssh->pktin.data + 14, msglen);
1070 buf[nowlen + msglen] = '\0';
1072 bombout((ssh,"Server sent disconnect message\ntype %d (%s):\n\"%s\"",
1074 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
1075 ssh2_disconnect_reasons[reason] : "unknown",
1080 case SSH2_MSG_IGNORE:
1082 case SSH2_MSG_DEBUG:
1084 /* log the debug message */
1086 /* int display = ssh->pktin.body[6]; */
1087 int stringlen = GET_32BIT(ssh->pktin.data+7);
1089 strcpy(buf, "Remote debug message: ");
1090 prefix = strlen(buf);
1091 if (stringlen > (int)(sizeof(buf)-prefix-1))
1092 stringlen = sizeof(buf)-prefix-1;
1093 memcpy(buf + prefix, ssh->pktin.data + 11, stringlen);
1094 buf[prefix + stringlen] = '\0';
1097 goto next_packet; /* FIXME: print the debug message */
1100 * These packets we need do nothing about here.
1102 case SSH2_MSG_UNIMPLEMENTED:
1103 case SSH2_MSG_SERVICE_REQUEST:
1104 case SSH2_MSG_SERVICE_ACCEPT:
1105 case SSH2_MSG_KEXINIT:
1106 case SSH2_MSG_NEWKEYS:
1107 case SSH2_MSG_KEXDH_INIT:
1108 case SSH2_MSG_KEXDH_REPLY:
1109 /* case SSH2_MSG_KEX_DH_GEX_REQUEST: duplicate case value */
1110 /* case SSH2_MSG_KEX_DH_GEX_GROUP: duplicate case value */
1111 case SSH2_MSG_KEX_DH_GEX_INIT:
1112 case SSH2_MSG_KEX_DH_GEX_REPLY:
1113 case SSH2_MSG_USERAUTH_REQUEST:
1114 case SSH2_MSG_USERAUTH_FAILURE:
1115 case SSH2_MSG_USERAUTH_SUCCESS:
1116 case SSH2_MSG_USERAUTH_BANNER:
1117 case SSH2_MSG_USERAUTH_PK_OK:
1118 /* case SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ: duplicate case value */
1119 /* case SSH2_MSG_USERAUTH_INFO_REQUEST: duplicate case value */
1120 case SSH2_MSG_USERAUTH_INFO_RESPONSE:
1121 case SSH2_MSG_GLOBAL_REQUEST:
1122 case SSH2_MSG_REQUEST_SUCCESS:
1123 case SSH2_MSG_REQUEST_FAILURE:
1124 case SSH2_MSG_CHANNEL_OPEN:
1125 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
1126 case SSH2_MSG_CHANNEL_OPEN_FAILURE:
1127 case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
1128 case SSH2_MSG_CHANNEL_DATA:
1129 case SSH2_MSG_CHANNEL_EXTENDED_DATA:
1130 case SSH2_MSG_CHANNEL_EOF:
1131 case SSH2_MSG_CHANNEL_CLOSE:
1132 case SSH2_MSG_CHANNEL_REQUEST:
1133 case SSH2_MSG_CHANNEL_SUCCESS:
1134 case SSH2_MSG_CHANNEL_FAILURE:
1138 * For anything else we send SSH2_MSG_UNIMPLEMENTED.
1141 ssh2_pkt_init(ssh, SSH2_MSG_UNIMPLEMENTED);
1142 ssh2_pkt_adduint32(ssh, st->incoming_sequence - 1);
1150 static void ssh1_pktout_size(Ssh ssh, int len)
1154 len += 5; /* type and CRC */
1155 pad = 8 - (len % 8);
1158 ssh->pktout.length = len - 5;
1159 if (ssh->pktout.maxlen < biglen) {
1160 ssh->pktout.maxlen = biglen;
1162 /* Allocate enough buffer space for extra block
1163 * for MS CryptEncrypt() */
1164 ssh->pktout.data = srealloc(ssh->pktout.data, biglen + 12);
1166 ssh->pktout.data = srealloc(ssh->pktout.data, biglen + 4);
1169 ssh->pktout.body = ssh->pktout.data + 4 + pad + 1;
1172 static void s_wrpkt_start(Ssh ssh, int type, int len)
1174 ssh1_pktout_size(ssh, len);
1175 ssh->pktout.type = type;
1178 static int s_wrpkt_prepare(Ssh ssh)
1180 int pad, len, biglen, i;
1183 ssh->pktout.body[-1] = ssh->pktout.type;
1186 log_packet(ssh->logctx, PKT_OUTGOING, ssh->pktout.type,
1187 ssh1_pkt_type(ssh->pktout.type),
1188 ssh->pktout.body, ssh->pktout.length);
1190 if (ssh->v1_compressing) {
1191 unsigned char *compblk;
1193 zlib_compress_block(ssh->cs_comp_ctx,
1194 ssh->pktout.body - 1, ssh->pktout.length + 1,
1195 &compblk, &complen);
1196 ssh1_pktout_size(ssh, complen - 1);
1197 memcpy(ssh->pktout.body - 1, compblk, complen);
1201 len = ssh->pktout.length + 5; /* type and CRC */
1202 pad = 8 - (len % 8);
1205 for (i = 0; i < pad; i++)
1206 ssh->pktout.data[i + 4] = random_byte();
1207 crc = crc32(ssh->pktout.data + 4, biglen - 4);
1208 PUT_32BIT(ssh->pktout.data + biglen, crc);
1209 PUT_32BIT(ssh->pktout.data, len);
1212 ssh->cipher->encrypt(ssh->v1_cipher_ctx, ssh->pktout.data + 4, biglen);
1217 static void s_wrpkt(Ssh ssh)
1220 len = s_wrpkt_prepare(ssh);
1221 backlog = sk_write(ssh->s, ssh->pktout.data, len);
1222 if (backlog > SSH_MAX_BACKLOG)
1223 ssh_throttle_all(ssh, 1, backlog);
1226 static void s_wrpkt_defer(Ssh ssh)
1229 len = s_wrpkt_prepare(ssh);
1230 if (ssh->deferred_len + len > ssh->deferred_size) {
1231 ssh->deferred_size = ssh->deferred_len + len + 128;
1232 ssh->deferred_send_data = srealloc(ssh->deferred_send_data,
1233 ssh->deferred_size);
1235 memcpy(ssh->deferred_send_data + ssh->deferred_len, ssh->pktout.data, len);
1236 ssh->deferred_len += len;
1240 * Construct a packet with the specified contents.
1242 static void construct_packet(Ssh ssh, int pkttype, va_list ap1, va_list ap2)
1244 unsigned char *p, *argp, argchar;
1245 unsigned long argint;
1246 int pktlen, argtype, arglen;
1250 while ((argtype = va_arg(ap1, int)) != PKT_END) {
1253 (void) va_arg(ap1, int);
1257 (void) va_arg(ap1, char);
1261 (void) va_arg(ap1, unsigned char *);
1262 arglen = va_arg(ap1, int);
1266 argp = va_arg(ap1, unsigned char *);
1267 arglen = strlen(argp);
1268 pktlen += 4 + arglen;
1271 bn = va_arg(ap1, Bignum);
1272 pktlen += ssh1_bignum_length(bn);
1279 s_wrpkt_start(ssh, pkttype, pktlen);
1280 p = ssh->pktout.body;
1282 while ((argtype = va_arg(ap2, int)) != PKT_END) {
1285 argint = va_arg(ap2, int);
1286 PUT_32BIT(p, argint);
1290 argchar = va_arg(ap2, unsigned char);
1295 argp = va_arg(ap2, unsigned char *);
1296 arglen = va_arg(ap2, int);
1297 memcpy(p, argp, arglen);
1301 argp = va_arg(ap2, unsigned char *);
1302 arglen = strlen(argp);
1303 PUT_32BIT(p, arglen);
1304 memcpy(p + 4, argp, arglen);
1308 bn = va_arg(ap2, Bignum);
1309 p += ssh1_write_bignum(p, bn);
1315 static void send_packet(Ssh ssh, int pkttype, ...)
1318 va_start(ap1, pkttype);
1319 va_start(ap2, pkttype);
1320 construct_packet(ssh, pkttype, ap1, ap2);
1324 static void defer_packet(Ssh ssh, int pkttype, ...)
1327 va_start(ap1, pkttype);
1328 va_start(ap2, pkttype);
1329 construct_packet(ssh, pkttype, ap1, ap2);
1333 static int ssh_versioncmp(char *a, char *b)
1336 unsigned long av, bv;
1338 av = strtoul(a, &ae, 10);
1339 bv = strtoul(b, &be, 10);
1341 return (av < bv ? -1 : +1);
1346 av = strtoul(ae, &ae, 10);
1347 bv = strtoul(be, &be, 10);
1349 return (av < bv ? -1 : +1);
1354 * Utility routines for putting an SSH-protocol `string' and
1355 * `uint32' into a SHA state.
1358 static void sha_string(SHA_State * s, void *str, int len)
1360 unsigned char lenblk[4];
1361 PUT_32BIT(lenblk, len);
1362 SHA_Bytes(s, lenblk, 4);
1363 SHA_Bytes(s, str, len);
1366 static void sha_uint32(SHA_State * s, unsigned i)
1368 unsigned char intblk[4];
1369 PUT_32BIT(intblk, i);
1370 SHA_Bytes(s, intblk, 4);
1374 * SSH2 packet construction functions.
1376 static void ssh2_pkt_ensure(Ssh ssh, int length)
1378 if (ssh->pktout.maxlen < length) {
1379 ssh->pktout.maxlen = length + 256;
1380 ssh->pktout.data = srealloc(ssh->pktout.data,
1381 ssh->pktout.maxlen + APIEXTRA);
1382 if (!ssh->pktout.data)
1383 fatalbox("Out of memory");
1386 static void ssh2_pkt_adddata(Ssh ssh, void *data, int len)
1388 ssh->pktout.length += len;
1389 ssh2_pkt_ensure(ssh, ssh->pktout.length);
1390 memcpy(ssh->pktout.data + ssh->pktout.length - len, data, len);
1392 static void ssh2_pkt_addbyte(Ssh ssh, unsigned char byte)
1394 ssh2_pkt_adddata(ssh, &byte, 1);
1396 static void ssh2_pkt_init(Ssh ssh, int pkt_type)
1398 ssh->pktout.length = 5;
1399 ssh2_pkt_addbyte(ssh, (unsigned char) pkt_type);
1401 static void ssh2_pkt_addbool(Ssh ssh, unsigned char value)
1403 ssh2_pkt_adddata(ssh, &value, 1);
1405 static void ssh2_pkt_adduint32(Ssh ssh, unsigned long value)
1408 PUT_32BIT(x, value);
1409 ssh2_pkt_adddata(ssh, x, 4);
1411 static void ssh2_pkt_addstring_start(Ssh ssh)
1413 ssh2_pkt_adduint32(ssh, 0);
1414 ssh->pktout.savedpos = ssh->pktout.length;
1416 static void ssh2_pkt_addstring_str(Ssh ssh, char *data)
1418 ssh2_pkt_adddata(ssh, data, strlen(data));
1419 PUT_32BIT(ssh->pktout.data + ssh->pktout.savedpos - 4,
1420 ssh->pktout.length - ssh->pktout.savedpos);
1422 static void ssh2_pkt_addstring_data(Ssh ssh, char *data, int len)
1424 ssh2_pkt_adddata(ssh, data, len);
1425 PUT_32BIT(ssh->pktout.data + ssh->pktout.savedpos - 4,
1426 ssh->pktout.length - ssh->pktout.savedpos);
1428 static void ssh2_pkt_addstring(Ssh ssh, char *data)
1430 ssh2_pkt_addstring_start(ssh);
1431 ssh2_pkt_addstring_str(ssh, data);
1433 static char *ssh2_mpint_fmt(Bignum b, int *len)
1436 int i, n = (bignum_bitcount(b) + 7) / 8;
1439 fatalbox("out of memory");
1441 for (i = 1; i <= n; i++)
1442 p[i] = bignum_byte(b, n - i);
1444 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1446 memmove(p, p + i, n + 1 - i);
1450 static void ssh2_pkt_addmp(Ssh ssh, Bignum b)
1454 p = ssh2_mpint_fmt(b, &len);
1455 ssh2_pkt_addstring_start(ssh);
1456 ssh2_pkt_addstring_data(ssh, p, len);
1461 * Construct an SSH2 final-form packet: compress it, encrypt it,
1462 * put the MAC on it. Final packet, ready to be sent, is stored in
1463 * ssh->pktout.data. Total length is returned.
1465 static int ssh2_pkt_construct(Ssh ssh)
1467 int cipherblk, maclen, padding, i;
1470 log_packet(ssh->logctx, PKT_OUTGOING, ssh->pktout.data[5],
1471 ssh2_pkt_type(ssh->pkt_ctx, ssh->pktout.data[5]),
1472 ssh->pktout.data + 6, ssh->pktout.length - 6);
1475 * Compress packet payload.
1478 unsigned char *newpayload;
1481 ssh->cscomp->compress(ssh->cs_comp_ctx, ssh->pktout.data + 5,
1482 ssh->pktout.length - 5,
1483 &newpayload, &newlen)) {
1484 ssh->pktout.length = 5;
1485 ssh2_pkt_adddata(ssh, newpayload, newlen);
1491 * Add padding. At least four bytes, and must also bring total
1492 * length (minus MAC) up to a multiple of the block size.
1494 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
1495 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1498 (cipherblk - (ssh->pktout.length + padding) % cipherblk) % cipherblk;
1499 maclen = ssh->csmac ? ssh->csmac->len : 0;
1500 ssh2_pkt_ensure(ssh, ssh->pktout.length + padding + maclen);
1501 ssh->pktout.data[4] = padding;
1502 for (i = 0; i < padding; i++)
1503 ssh->pktout.data[ssh->pktout.length + i] = random_byte();
1504 PUT_32BIT(ssh->pktout.data, ssh->pktout.length + padding - 4);
1506 ssh->csmac->generate(ssh->cs_mac_ctx, ssh->pktout.data,
1507 ssh->pktout.length + padding,
1508 ssh->v2_outgoing_sequence);
1509 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
1512 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
1513 ssh->pktout.data, ssh->pktout.length + padding);
1515 /* Ready-to-send packet starts at ssh->pktout.data. We return length. */
1516 return ssh->pktout.length + padding + maclen;
1520 * Construct and send an SSH2 packet immediately.
1522 static void ssh2_pkt_send(Ssh ssh)
1526 len = ssh2_pkt_construct(ssh);
1527 backlog = sk_write(ssh->s, ssh->pktout.data, len);
1528 if (backlog > SSH_MAX_BACKLOG)
1529 ssh_throttle_all(ssh, 1, backlog);
1533 * Construct an SSH2 packet and add it to a deferred data block.
1534 * Useful for sending multiple packets in a single sk_write() call,
1535 * to prevent a traffic-analysing listener from being able to work
1536 * out the length of any particular packet (such as the password
1539 * Note that because SSH2 sequence-numbers its packets, this can
1540 * NOT be used as an m4-style `defer' allowing packets to be
1541 * constructed in one order and sent in another.
1543 static void ssh2_pkt_defer(Ssh ssh)
1545 int len = ssh2_pkt_construct(ssh);
1546 if (ssh->deferred_len + len > ssh->deferred_size) {
1547 ssh->deferred_size = ssh->deferred_len + len + 128;
1548 ssh->deferred_send_data = srealloc(ssh->deferred_send_data,
1549 ssh->deferred_size);
1551 memcpy(ssh->deferred_send_data + ssh->deferred_len, ssh->pktout.data, len);
1552 ssh->deferred_len += len;
1556 * Send the whole deferred data block constructed by
1557 * ssh2_pkt_defer() or SSH1's defer_packet().
1559 static void ssh_pkt_defersend(Ssh ssh)
1562 backlog = sk_write(ssh->s, ssh->deferred_send_data, ssh->deferred_len);
1563 ssh->deferred_len = ssh->deferred_size = 0;
1564 sfree(ssh->deferred_send_data);
1565 ssh->deferred_send_data = NULL;
1566 if (backlog > SSH_MAX_BACKLOG)
1567 ssh_throttle_all(ssh, 1, backlog);
1571 void bndebug(char *string, Bignum b)
1575 p = ssh2_mpint_fmt(b, &len);
1576 debug(("%s", string));
1577 for (i = 0; i < len; i++)
1578 debug((" %02x", p[i]));
1584 static void sha_mpint(SHA_State * s, Bignum b)
1588 p = ssh2_mpint_fmt(b, &len);
1589 sha_string(s, p, len);
1594 * SSH2 packet decode functions.
1596 static unsigned long ssh2_pkt_getuint32(Ssh ssh)
1598 unsigned long value;
1599 if (ssh->pktin.length - ssh->pktin.savedpos < 4)
1600 return 0; /* arrgh, no way to decline (FIXME?) */
1601 value = GET_32BIT(ssh->pktin.data + ssh->pktin.savedpos);
1602 ssh->pktin.savedpos += 4;
1605 static int ssh2_pkt_getbool(Ssh ssh)
1607 unsigned long value;
1608 if (ssh->pktin.length - ssh->pktin.savedpos < 1)
1609 return 0; /* arrgh, no way to decline (FIXME?) */
1610 value = ssh->pktin.data[ssh->pktin.savedpos] != 0;
1611 ssh->pktin.savedpos++;
1614 static void ssh2_pkt_getstring(Ssh ssh, char **p, int *length)
1618 if (ssh->pktin.length - ssh->pktin.savedpos < 4)
1620 *length = GET_32BIT(ssh->pktin.data + ssh->pktin.savedpos);
1621 ssh->pktin.savedpos += 4;
1622 if (ssh->pktin.length - ssh->pktin.savedpos < *length)
1624 *p = ssh->pktin.data + ssh->pktin.savedpos;
1625 ssh->pktin.savedpos += *length;
1627 static Bignum ssh2_pkt_getmp(Ssh ssh)
1633 ssh2_pkt_getstring(ssh, &p, &length);
1637 bombout((ssh,"internal error: Can't handle negative mpints"));
1640 b = bignum_from_bytes(p, length);
1645 * Helper function to add an SSH2 signature blob to a packet.
1646 * Expects to be shown the public key blob as well as the signature
1647 * blob. Normally works just like ssh2_pkt_addstring, but will
1648 * fiddle with the signature packet if necessary for
1649 * BUG_SSH2_RSA_PADDING.
1651 static void ssh2_add_sigblob(Ssh ssh, void *pkblob_v, int pkblob_len,
1652 void *sigblob_v, int sigblob_len)
1654 unsigned char *pkblob = (unsigned char *)pkblob_v;
1655 unsigned char *sigblob = (unsigned char *)sigblob_v;
1657 /* dmemdump(pkblob, pkblob_len); */
1658 /* dmemdump(sigblob, sigblob_len); */
1661 * See if this is in fact an ssh-rsa signature and a buggy
1662 * server; otherwise we can just do this the easy way.
1664 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) &&
1665 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
1666 int pos, len, siglen;
1669 * Find the byte length of the modulus.
1672 pos = 4+7; /* skip over "ssh-rsa" */
1673 pos += 4 + GET_32BIT(pkblob+pos); /* skip over exponent */
1674 len = GET_32BIT(pkblob+pos); /* find length of modulus */
1675 pos += 4; /* find modulus itself */
1676 while (len > 0 && pkblob[pos] == 0)
1678 /* debug(("modulus length is %d\n", len)); */
1681 * Now find the signature integer.
1683 pos = 4+7; /* skip over "ssh-rsa" */
1684 siglen = GET_32BIT(sigblob+pos);
1685 /* debug(("signature length is %d\n", siglen)); */
1687 if (len != siglen) {
1688 unsigned char newlen[4];
1689 ssh2_pkt_addstring_start(ssh);
1690 ssh2_pkt_addstring_data(ssh, sigblob, pos);
1691 /* dmemdump(sigblob, pos); */
1692 pos += 4; /* point to start of actual sig */
1693 PUT_32BIT(newlen, len);
1694 ssh2_pkt_addstring_data(ssh, newlen, 4);
1695 /* dmemdump(newlen, 4); */
1697 while (len-- > siglen) {
1698 ssh2_pkt_addstring_data(ssh, newlen, 1);
1699 /* dmemdump(newlen, 1); */
1701 ssh2_pkt_addstring_data(ssh, sigblob+pos, siglen);
1702 /* dmemdump(sigblob+pos, siglen); */
1706 /* Otherwise fall through and do it the easy way. */
1709 ssh2_pkt_addstring_start(ssh);
1710 ssh2_pkt_addstring_data(ssh, sigblob, sigblob_len);
1714 * Examine the remote side's version string and compare it against
1715 * a list of known buggy implementations.
1717 static void ssh_detect_bugs(Ssh ssh, char *vstring)
1719 char *imp; /* pointer to implementation part */
1721 imp += strcspn(imp, "-");
1723 imp += strcspn(imp, "-");
1726 ssh->remote_bugs = 0;
1728 if (cfg.sshbug_ignore1 == BUG_ON ||
1729 (cfg.sshbug_ignore1 == BUG_AUTO &&
1730 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
1731 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
1732 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25")))) {
1734 * These versions don't support SSH1_MSG_IGNORE, so we have
1735 * to use a different defence against password length
1738 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
1739 logevent("We believe remote version has SSH1 ignore bug");
1742 if (cfg.sshbug_plainpw1 == BUG_ON ||
1743 (cfg.sshbug_plainpw1 == BUG_AUTO &&
1744 (!strcmp(imp, "Cisco-1.25")))) {
1746 * These versions need a plain password sent; they can't
1747 * handle having a null and a random length of data after
1750 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
1751 logevent("We believe remote version needs a plain SSH1 password");
1754 if (cfg.sshbug_rsa1 == BUG_ON ||
1755 (cfg.sshbug_rsa1 == BUG_AUTO &&
1756 (!strcmp(imp, "Cisco-1.25")))) {
1758 * These versions apparently have no clue whatever about
1759 * RSA authentication and will panic and die if they see
1760 * an AUTH_RSA message.
1762 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
1763 logevent("We believe remote version can't handle RSA authentication");
1766 if (cfg.sshbug_hmac2 == BUG_ON ||
1767 (cfg.sshbug_hmac2 == BUG_AUTO &&
1768 (!strncmp(imp, "2.1.0", 5) || !strncmp(imp, "2.0.", 4) ||
1769 !strncmp(imp, "2.2.0", 5) || !strncmp(imp, "2.3.0", 5) ||
1770 !strncmp(imp, "2.1 ", 4)))) {
1772 * These versions have the HMAC bug.
1774 ssh->remote_bugs |= BUG_SSH2_HMAC;
1775 logevent("We believe remote version has SSH2 HMAC bug");
1778 if (cfg.sshbug_derivekey2 == BUG_ON ||
1779 (cfg.sshbug_derivekey2 == BUG_AUTO &&
1780 (!strncmp(imp, "2.0.", 4)))) {
1782 * These versions have the key-derivation bug (failing to
1783 * include the literal shared secret in the hashes that
1784 * generate the keys).
1786 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
1787 logevent("We believe remote version has SSH2 key-derivation bug");
1790 if (cfg.sshbug_rsapad2 == BUG_ON ||
1791 (cfg.sshbug_rsapad2 == BUG_AUTO &&
1792 ((!strncmp(imp, "OpenSSH_2.", 10) && imp[10]>='5' && imp[10]<='9') ||
1793 (!strncmp(imp, "OpenSSH_3.", 10) && imp[10]>='0' && imp[10]<='2')))){
1795 * These versions have the SSH2 RSA padding bug.
1797 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
1798 logevent("We believe remote version has SSH2 RSA padding bug");
1801 if (cfg.sshbug_dhgex2 == BUG_ON) {
1803 * These versions have the SSH2 DH GEX bug.
1805 ssh->remote_bugs |= BUG_SSH2_DH_GEX;
1806 logevent("We believe remote version has SSH2 DH group exchange bug");
1810 static int do_ssh_init(Ssh ssh, unsigned char c)
1812 struct do_ssh_init_state {
1820 crState(do_ssh_init_state);
1822 crBegin(ssh->do_ssh_init_crstate);
1824 /* Search for the string "SSH-" in the input. */
1827 static const int transS[] = { 1, 2, 2, 1 };
1828 static const int transH[] = { 0, 0, 3, 0 };
1829 static const int transminus[] = { 0, 0, 0, -1 };
1831 s->i = transS[s->i];
1833 s->i = transH[s->i];
1835 s->i = transminus[s->i];
1840 crReturn(1); /* get another character */
1844 s->vstring = smalloc(s->vstrsize);
1845 strcpy(s->vstring, "SSH-");
1849 crReturn(1); /* get another char */
1850 if (s->vslen >= s->vstrsize - 1) {
1852 s->vstring = srealloc(s->vstring, s->vstrsize);
1854 s->vstring[s->vslen++] = c;
1857 s->version[s->i] = '\0';
1859 } else if (s->i < sizeof(s->version) - 1)
1860 s->version[s->i++] = c;
1861 } else if (c == '\n')
1865 ssh->agentfwd_enabled = FALSE;
1866 ssh->rdpkt2_state.incoming_sequence = 0;
1868 s->vstring[s->vslen] = 0;
1869 s->vstring[strcspn(s->vstring, "\r\n")] = '\0';/* remove EOL chars */
1872 vlog = smalloc(20 + s->vslen);
1873 sprintf(vlog, "Server version: %s", s->vstring);
1877 ssh_detect_bugs(ssh, s->vstring);
1880 * Decide which SSH protocol version to support.
1883 /* Anything strictly below "2.0" means protocol 1 is supported. */
1884 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
1885 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
1886 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
1888 if (cfg.sshprot == 0 && !s->proto1) {
1889 bombout((ssh,"SSH protocol version 1 required by user but not provided by server"));
1892 if (cfg.sshprot == 3 && !s->proto2) {
1893 bombout((ssh,"SSH protocol version 2 required by user but not provided by server"));
1897 if (s->proto2 && (cfg.sshprot >= 2 || !s->proto1)) {
1901 char verstring[80], vlog[100];
1902 sprintf(verstring, "SSH-2.0-%s", sshver);
1903 SHA_Init(&ssh->exhashbase);
1905 * Hash our version string and their version string.
1907 sha_string(&ssh->exhashbase, verstring, strlen(verstring));
1908 sha_string(&ssh->exhashbase, s->vstring, strcspn(s->vstring, "\r\n"));
1909 sprintf(vlog, "We claim version: %s", verstring);
1911 strcat(verstring, "\n");
1912 logevent("Using SSH protocol version 2");
1913 sk_write(ssh->s, verstring, strlen(verstring));
1914 ssh->protocol = ssh2_protocol;
1916 ssh->s_rdpkt = ssh2_rdpkt;
1921 char verstring[80], vlog[100];
1922 sprintf(verstring, "SSH-%s-%s",
1923 (ssh_versioncmp(s->version, "1.5") <= 0 ? s->version : "1.5"),
1925 sprintf(vlog, "We claim version: %s", verstring);
1927 strcat(verstring, "\n");
1929 logevent("Using SSH protocol version 1");
1930 sk_write(ssh->s, verstring, strlen(verstring));
1931 ssh->protocol = ssh1_protocol;
1933 ssh->s_rdpkt = ssh1_rdpkt;
1935 ssh->state = SSH_STATE_BEFORE_SIZE;
1942 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
1944 crBegin(ssh->ssh_gotdata_crstate);
1947 * To begin with, feed the characters one by one to the
1948 * protocol initialisation / selection function do_ssh_init().
1949 * When that returns 0, we're done with the initial greeting
1950 * exchange and can move on to packet discipline.
1953 int ret; /* need not be kept across crReturn */
1955 crReturnV; /* more data please */
1956 ret = do_ssh_init(ssh, *data);
1964 * We emerge from that loop when the initial negotiation is
1965 * over and we have selected an s_rdpkt function. Now pass
1966 * everything to s_rdpkt, and then pass the resulting packets
1967 * to the proper protocol handler.
1972 while (datalen > 0) {
1973 if (ssh->s_rdpkt(ssh, &data, &datalen) == 0) {
1974 if (ssh->state == SSH_STATE_CLOSED) {
1977 ssh->protocol(ssh, NULL, 0, 1);
1978 if (ssh->state == SSH_STATE_CLOSED) {
1988 static int ssh_closing(Plug plug, char *error_msg, int error_code,
1991 Ssh ssh = (Ssh) plug;
1992 ssh->state = SSH_STATE_CLOSED;
1998 /* A socket error has occurred. */
1999 logevent(error_msg);
2000 connection_fatal(ssh->frontend, error_msg);
2002 /* Otherwise, the remote side closed the connection normally. */
2007 static int ssh_receive(Plug plug, int urgent, char *data, int len)
2009 Ssh ssh = (Ssh) plug;
2010 ssh_gotdata(ssh, data, len);
2011 if (ssh->state == SSH_STATE_CLOSED) {
2021 static void ssh_sent(Plug plug, int bufsize)
2023 Ssh ssh = (Ssh) plug;
2025 * If the send backlog on the SSH socket itself clears, we
2026 * should unthrottle the whole world if it was throttled.
2028 if (bufsize < SSH_MAX_BACKLOG)
2029 ssh_throttle_all(ssh, 0, bufsize);
2033 * Connect to specified host and port.
2034 * Returns an error message, or NULL on success.
2035 * Also places the canonical host name into `realhost'. It must be
2036 * freed by the caller.
2038 static char *connect_to_host(Ssh ssh, char *host, int port,
2039 char **realhost, int nodelay)
2041 static const struct plug_function_table fn_table = {
2051 ssh->savedhost = smalloc(1 + strlen(host));
2052 if (!ssh->savedhost)
2053 fatalbox("Out of memory");
2054 strcpy(ssh->savedhost, host);
2057 port = 22; /* default ssh port */
2058 ssh->savedport = port;
2065 sprintf(buf, "Looking up host \"%.170s\"", host);
2068 addr = sk_namelookup(host, realhost);
2069 if ((err = sk_addr_error(addr)))
2076 char buf[200], addrbuf[100];
2077 sk_getaddr(addr, addrbuf, 100);
2078 sprintf(buf, "Connecting to %.100s port %d", addrbuf, port);
2081 ssh->fn = &fn_table;
2082 ssh->s = new_connection(addr, *realhost, port, 0, 1, nodelay, (Plug) ssh);
2083 if ((err = sk_socket_error(ssh->s))) {
2092 * Throttle or unthrottle the SSH connection.
2094 static void ssh1_throttle(Ssh ssh, int adjust)
2096 int old_count = ssh->v1_throttle_count;
2097 ssh->v1_throttle_count += adjust;
2098 assert(ssh->v1_throttle_count >= 0);
2099 if (ssh->v1_throttle_count && !old_count) {
2100 sk_set_frozen(ssh->s, 1);
2101 } else if (!ssh->v1_throttle_count && old_count) {
2102 sk_set_frozen(ssh->s, 0);
2107 * Throttle or unthrottle _all_ local data streams (for when sends
2108 * on the SSH connection itself back up).
2110 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
2113 struct ssh_channel *c;
2115 if (enable == ssh->throttled_all)
2117 ssh->throttled_all = enable;
2118 ssh->overall_bufsize = bufsize;
2121 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
2123 case CHAN_MAINSESSION:
2125 * This is treated separately, outside the switch.
2129 x11_override_throttle(c->u.x11.s, enable);
2132 /* Agent channels require no buffer management. */
2135 pfd_override_throttle(c->u.x11.s, enable);
2142 * Username and password input, abstracted off into routines
2143 * reusable in several places - even between SSH1 and SSH2.
2146 /* Set up a username or password input loop on a given buffer. */
2147 void setup_userpass_input(Ssh ssh, char *buffer, int buflen, int echo)
2149 ssh->userpass_input_buffer = buffer;
2150 ssh->userpass_input_buflen = buflen;
2151 ssh->userpass_input_bufpos = 0;
2152 ssh->userpass_input_echo = echo;
2156 * Process some terminal data in the course of username/password
2157 * input. Returns >0 for success (line of input returned in
2158 * buffer), <0 for failure (user hit ^C/^D, bomb out and exit), 0
2159 * for inconclusive (keep waiting for more input please).
2161 int process_userpass_input(Ssh ssh, unsigned char *in, int inlen)
2166 switch (c = *in++) {
2169 ssh->userpass_input_buffer[ssh->userpass_input_bufpos] = 0;
2170 ssh->userpass_input_buffer[ssh->userpass_input_buflen-1] = 0;
2175 if (ssh->userpass_input_bufpos > 0) {
2176 if (ssh->userpass_input_echo)
2177 c_write_str(ssh, "\b \b");
2178 ssh->userpass_input_bufpos--;
2183 while (ssh->userpass_input_bufpos > 0) {
2184 if (ssh->userpass_input_echo)
2185 c_write_str(ssh, "\b \b");
2186 ssh->userpass_input_bufpos--;
2194 if (((c >= ' ' && c <= '~') ||
2195 ((unsigned char) c >= 160))
2196 && ssh->userpass_input_bufpos < ssh->userpass_input_buflen-1) {
2197 ssh->userpass_input_buffer[ssh->userpass_input_bufpos++] = c;
2198 if (ssh->userpass_input_echo)
2199 c_write(ssh, &c, 1);
2208 * Handle the key exchange and user authentication phases.
2210 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
2213 unsigned char cookie[8];
2214 struct RSAKey servkey, hostkey;
2215 struct MD5Context md5c;
2216 struct do_ssh1_login_state {
2218 unsigned char *rsabuf, *keystr1, *keystr2;
2219 unsigned long supported_ciphers_mask, supported_auths_mask;
2220 int tried_publickey, tried_agent;
2221 int tis_auth_refused, ccard_auth_refused;
2222 unsigned char session_id[16];
2225 void *publickey_blob;
2226 int publickey_bloblen;
2232 unsigned char request[5], *response, *p;
2241 crState(do_ssh1_login_state);
2243 crBegin(ssh->do_ssh1_login_crstate);
2248 if (ssh->pktin.type != SSH1_SMSG_PUBLIC_KEY) {
2249 bombout((ssh,"Public key packet not received"));
2253 logevent("Received public keys");
2255 memcpy(cookie, ssh->pktin.body, 8);
2257 i = makekey(ssh->pktin.body + 8, &servkey, &s->keystr1, 0);
2258 j = makekey(ssh->pktin.body + 8 + i, &hostkey, &s->keystr2, 0);
2261 * Log the host key fingerprint.
2265 logevent("Host key fingerprint is:");
2266 strcpy(logmsg, " ");
2267 hostkey.comment = NULL;
2268 rsa_fingerprint(logmsg + strlen(logmsg),
2269 sizeof(logmsg) - strlen(logmsg), &hostkey);
2273 ssh->v1_remote_protoflags = GET_32BIT(ssh->pktin.body + 8 + i + j);
2274 s->supported_ciphers_mask = GET_32BIT(ssh->pktin.body + 12 + i + j);
2275 s->supported_auths_mask = GET_32BIT(ssh->pktin.body + 16 + i + j);
2277 ssh->v1_local_protoflags =
2278 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
2279 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
2282 MD5Update(&md5c, s->keystr2, hostkey.bytes);
2283 MD5Update(&md5c, s->keystr1, servkey.bytes);
2284 MD5Update(&md5c, ssh->pktin.body, 8);
2285 MD5Final(s->session_id, &md5c);
2287 for (i = 0; i < 32; i++)
2288 ssh->session_key[i] = random_byte();
2290 s->len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
2292 s->rsabuf = smalloc(s->len);
2294 fatalbox("Out of memory");
2297 * Verify the host key.
2301 * First format the key into a string.
2303 int len = rsastr_len(&hostkey);
2304 char fingerprint[100];
2305 char *keystr = smalloc(len);
2307 fatalbox("Out of memory");
2308 rsastr_fmt(keystr, &hostkey);
2309 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
2310 verify_ssh_host_key(ssh->frontend,
2311 ssh->savedhost, ssh->savedport, "rsa", keystr,
2316 for (i = 0; i < 32; i++) {
2317 s->rsabuf[i] = ssh->session_key[i];
2319 s->rsabuf[i] ^= s->session_id[i];
2322 if (hostkey.bytes > servkey.bytes) {
2323 rsaencrypt(s->rsabuf, 32, &servkey);
2324 rsaencrypt(s->rsabuf, servkey.bytes, &hostkey);
2326 rsaencrypt(s->rsabuf, 32, &hostkey);
2327 rsaencrypt(s->rsabuf, hostkey.bytes, &servkey);
2330 logevent("Encrypted session key");
2333 int cipher_chosen = 0, warn = 0;
2334 char *cipher_string = NULL;
2336 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
2337 int next_cipher = cfg.ssh_cipherlist[i];
2338 if (next_cipher == CIPHER_WARN) {
2339 /* If/when we choose a cipher, warn about it */
2341 } else if (next_cipher == CIPHER_AES) {
2342 /* XXX Probably don't need to mention this. */
2343 logevent("AES not supported in SSH1, skipping");
2345 switch (next_cipher) {
2346 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
2347 cipher_string = "3DES"; break;
2348 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
2349 cipher_string = "Blowfish"; break;
2350 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
2351 cipher_string = "single-DES"; break;
2353 if (s->supported_ciphers_mask & (1 << s->cipher_type))
2357 if (!cipher_chosen) {
2358 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
2359 bombout((ssh,"Server violates SSH 1 protocol by not "
2360 "supporting 3DES encryption"));
2362 /* shouldn't happen */
2363 bombout((ssh,"No supported ciphers found"));
2367 /* Warn about chosen cipher if necessary. */
2369 askcipher(ssh->frontend, cipher_string, 0);
2372 switch (s->cipher_type) {
2373 case SSH_CIPHER_3DES:
2374 logevent("Using 3DES encryption");
2376 case SSH_CIPHER_DES:
2377 logevent("Using single-DES encryption");
2379 case SSH_CIPHER_BLOWFISH:
2380 logevent("Using Blowfish encryption");
2384 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
2385 PKT_CHAR, s->cipher_type,
2386 PKT_DATA, cookie, 8,
2387 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
2388 PKT_DATA, s->rsabuf, s->len,
2389 PKT_INT, ssh->v1_local_protoflags, PKT_END);
2391 logevent("Trying to enable encryption...");
2395 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
2396 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
2398 ssh->v1_cipher_ctx = ssh->cipher->make_context();
2399 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
2402 sprintf(buf, "Initialised %.200s encryption", ssh->cipher->text_name);
2406 ssh->crcda_ctx = crcda_make_context();
2407 logevent("Installing CRC compensation attack detector");
2411 if (ssh->pktin.type != SSH1_SMSG_SUCCESS) {
2412 bombout((ssh,"Encryption not successfully enabled"));
2416 logevent("Successfully started encryption");
2420 if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
2421 if (ssh_get_line && !ssh_getline_pw_only) {
2422 if (!ssh_get_line("login as: ",
2423 s->username, sizeof(s->username), FALSE)) {
2425 * get_line failed to get a username.
2428 logevent("No username provided. Abandoning session.");
2429 ssh->state = SSH_STATE_CLOSED;
2433 int ret; /* need not be kept over crReturn */
2434 c_write_str(ssh, "login as: ");
2437 setup_userpass_input(ssh, s->username, sizeof(s->username), 1);
2439 crWaitUntil(!ispkt);
2440 ret = process_userpass_input(ssh, in, inlen);
2444 c_write_str(ssh, "\r\n");
2447 strncpy(s->username, cfg.username, sizeof(s->username));
2448 s->username[sizeof(s->username)-1] = '\0';
2451 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, s->username, PKT_END);
2453 char userlog[22 + sizeof(s->username)];
2454 sprintf(userlog, "Sent username \"%s\"", s->username);
2456 if (flags & FLAG_INTERACTIVE &&
2457 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
2458 strcat(userlog, "\r\n");
2459 c_write_str(ssh, userlog);
2466 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA)) {
2467 /* We must not attempt PK auth. Pretend we've already tried it. */
2468 s->tried_publickey = s->tried_agent = 1;
2470 s->tried_publickey = s->tried_agent = 0;
2472 s->tis_auth_refused = s->ccard_auth_refused = 0;
2473 /* Load the public half of cfg.keyfile so we notice if it's in Pageant */
2475 if (!rsakey_pubblob(cfg.keyfile,
2476 &s->publickey_blob, &s->publickey_bloblen))
2477 s->publickey_blob = NULL;
2479 s->publickey_blob = NULL;
2481 while (ssh->pktin.type == SSH1_SMSG_FAILURE) {
2482 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
2484 if (agent_exists() && !s->tried_agent) {
2486 * Attempt RSA authentication using Pageant.
2492 logevent("Pageant is running. Requesting keys.");
2494 /* Request the keys held by the agent. */
2495 PUT_32BIT(s->request, 1);
2496 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
2497 agent_query(s->request, 5, &r, &s->responselen);
2498 s->response = (unsigned char *) r;
2499 if (s->response && s->responselen >= 5 &&
2500 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
2501 s->p = s->response + 5;
2502 s->nkeys = GET_32BIT(s->p);
2506 sprintf(buf, "Pageant has %d SSH1 keys", s->nkeys);
2509 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
2512 sprintf(buf, "Trying Pageant key #%d", s->keyi);
2515 if (s->publickey_blob &&
2516 !memcmp(s->p, s->publickey_blob,
2517 s->publickey_bloblen)) {
2518 logevent("This key matches configured key file");
2519 s->tried_publickey = 1;
2522 s->p += ssh1_read_bignum(s->p, &s->key.exponent);
2523 s->p += ssh1_read_bignum(s->p, &s->key.modulus);
2524 s->commentlen = GET_32BIT(s->p);
2527 s->p += s->commentlen;
2528 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
2529 PKT_BIGNUM, s->key.modulus, PKT_END);
2531 if (ssh->pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
2532 logevent("Key refused");
2535 logevent("Received RSA challenge");
2536 ssh1_read_bignum(ssh->pktin.body, &s->challenge);
2538 char *agentreq, *q, *ret;
2541 len = 1 + 4; /* message type, bit count */
2542 len += ssh1_bignum_length(s->key.exponent);
2543 len += ssh1_bignum_length(s->key.modulus);
2544 len += ssh1_bignum_length(s->challenge);
2545 len += 16; /* session id */
2546 len += 4; /* response format */
2547 agentreq = smalloc(4 + len);
2548 PUT_32BIT(agentreq, len);
2550 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
2551 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
2553 q += ssh1_write_bignum(q, s->key.exponent);
2554 q += ssh1_write_bignum(q, s->key.modulus);
2555 q += ssh1_write_bignum(q, s->challenge);
2556 memcpy(q, s->session_id, 16);
2558 PUT_32BIT(q, 1); /* response format */
2559 agent_query(agentreq, len + 4, &vret, &retlen);
2563 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
2564 logevent("Sending Pageant's response");
2565 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
2566 PKT_DATA, ret + 5, 16,
2570 if (ssh->pktin.type == SSH1_SMSG_SUCCESS) {
2572 ("Pageant's response accepted");
2573 if (flags & FLAG_VERBOSE) {
2574 c_write_str(ssh, "Authenticated using"
2576 c_write(ssh, s->commentp,
2578 c_write_str(ssh, "\" from agent\r\n");
2583 ("Pageant's response not accepted");
2586 ("Pageant failed to answer challenge");
2590 logevent("No reply received from Pageant");
2593 freebn(s->key.exponent);
2594 freebn(s->key.modulus);
2595 freebn(s->challenge);
2603 if (*cfg.keyfile && !s->tried_publickey)
2604 s->pwpkt_type = SSH1_CMSG_AUTH_RSA;
2606 if (cfg.try_tis_auth &&
2607 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
2608 !s->tis_auth_refused) {
2609 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
2610 logevent("Requested TIS authentication");
2611 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
2613 if (ssh->pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
2614 logevent("TIS authentication declined");
2615 if (flags & FLAG_INTERACTIVE)
2616 c_write_str(ssh, "TIS authentication refused.\r\n");
2617 s->tis_auth_refused = 1;
2620 int challengelen = GET_32BIT(ssh->pktin.body);
2621 logevent("Received TIS challenge");
2622 if (challengelen > sizeof(s->prompt) - 1)
2623 challengelen = sizeof(s->prompt) - 1;/* prevent overrun */
2624 memcpy(s->prompt, ssh->pktin.body + 4, challengelen);
2625 /* Prompt heuristic comes from OpenSSH */
2626 strncpy(s->prompt + challengelen,
2627 memchr(s->prompt, '\n', challengelen) ?
2628 "": "\r\nResponse: ",
2629 (sizeof s->prompt) - challengelen);
2630 s->prompt[(sizeof s->prompt) - 1] = '\0';
2633 if (cfg.try_tis_auth &&
2634 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
2635 !s->ccard_auth_refused) {
2636 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
2637 logevent("Requested CryptoCard authentication");
2638 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
2640 if (ssh->pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
2641 logevent("CryptoCard authentication declined");
2642 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
2643 s->ccard_auth_refused = 1;
2646 int challengelen = GET_32BIT(ssh->pktin.body);
2647 logevent("Received CryptoCard challenge");
2648 if (challengelen > sizeof(s->prompt) - 1)
2649 challengelen = sizeof(s->prompt) - 1;/* prevent overrun */
2650 memcpy(s->prompt, ssh->pktin.body + 4, challengelen);
2651 strncpy(s->prompt + challengelen,
2652 memchr(s->prompt, '\n', challengelen) ?
2653 "" : "\r\nResponse: ",
2654 sizeof(s->prompt) - challengelen);
2655 s->prompt[sizeof(s->prompt) - 1] = '\0';
2658 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
2659 sprintf(s->prompt, "%.90s@%.90s's password: ",
2660 s->username, ssh->savedhost);
2662 if (s->pwpkt_type == SSH1_CMSG_AUTH_RSA) {
2663 char *comment = NULL;
2666 if (flags & FLAG_VERBOSE)
2667 c_write_str(ssh, "Trying public key authentication.\r\n");
2668 sprintf(msgbuf, "Trying public key \"%.200s\"", cfg.keyfile);
2670 type = key_type(cfg.keyfile);
2671 if (type != SSH_KEYTYPE_SSH1) {
2672 sprintf(msgbuf, "Key is of wrong type (%s)",
2673 key_type_to_str(type));
2675 c_write_str(ssh, msgbuf);
2676 c_write_str(ssh, "\r\n");
2677 s->tried_publickey = 1;
2680 if (!rsakey_encrypted(cfg.keyfile, &comment)) {
2681 if (flags & FLAG_VERBOSE)
2682 c_write_str(ssh, "No passphrase required.\r\n");
2685 sprintf(s->prompt, "Passphrase for key \"%.100s\": ", comment);
2690 * Show password prompt, having first obtained it via a TIS
2691 * or CryptoCard exchange if we're doing TIS or CryptoCard
2695 if (!ssh_get_line(s->prompt, s->password,
2696 sizeof(s->password), TRUE)) {
2698 * get_line failed to get a password (for example
2699 * because one was supplied on the command line
2700 * which has already failed to work). Terminate.
2702 send_packet(ssh, SSH1_MSG_DISCONNECT,
2703 PKT_STR, "No more passwords available to try",
2705 logevent("Unable to authenticate");
2706 connection_fatal(ssh->frontend, "Unable to authenticate");
2707 ssh->state = SSH_STATE_CLOSED;
2711 /* Prompt may have come from server. We've munged it a bit, so
2712 * we know it to be zero-terminated at least once. */
2713 int ret; /* need not be saved over crReturn */
2714 c_write_untrusted(ssh, s->prompt, strlen(s->prompt));
2717 setup_userpass_input(ssh, s->password, sizeof(s->password), 0);
2719 crWaitUntil(!ispkt);
2720 ret = process_userpass_input(ssh, in, inlen);
2724 c_write_str(ssh, "\r\n");
2728 if (s->pwpkt_type == SSH1_CMSG_AUTH_RSA) {
2730 * Try public key authentication with the specified
2733 s->tried_publickey = 1;
2736 int ret = loadrsakey(cfg.keyfile, &s->key, s->password);
2738 c_write_str(ssh, "Couldn't load private key from ");
2739 c_write_str(ssh, cfg.keyfile);
2740 c_write_str(ssh, ".\r\n");
2741 continue; /* go and try password */
2744 c_write_str(ssh, "Wrong passphrase.\r\n");
2745 s->tried_publickey = 0;
2746 continue; /* try again */
2751 * Send a public key attempt.
2753 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
2754 PKT_BIGNUM, s->key.modulus, PKT_END);
2757 if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
2758 c_write_str(ssh, "Server refused our public key.\r\n");
2759 continue; /* go and try password */
2761 if (ssh->pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
2762 bombout((ssh,"Bizarre response to offer of public key"));
2768 unsigned char buffer[32];
2769 Bignum challenge, response;
2771 ssh1_read_bignum(ssh->pktin.body, &challenge);
2772 response = rsadecrypt(challenge, &s->key);
2773 freebn(s->key.private_exponent);/* burn the evidence */
2775 for (i = 0; i < 32; i++) {
2776 buffer[i] = bignum_byte(response, 31 - i);
2780 MD5Update(&md5c, buffer, 32);
2781 MD5Update(&md5c, s->session_id, 16);
2782 MD5Final(buffer, &md5c);
2784 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
2785 PKT_DATA, buffer, 16, PKT_END);
2792 if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
2793 if (flags & FLAG_VERBOSE)
2794 c_write_str(ssh, "Failed to authenticate with"
2795 " our public key.\r\n");
2796 continue; /* go and try password */
2797 } else if (ssh->pktin.type != SSH1_SMSG_SUCCESS) {
2798 bombout((ssh,"Bizarre response to RSA authentication response"));
2802 break; /* we're through! */
2804 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
2806 * Defence against traffic analysis: we send a
2807 * whole bunch of packets containing strings of
2808 * different lengths. One of these strings is the
2809 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
2810 * The others are all random data in
2811 * SSH1_MSG_IGNORE packets. This way a passive
2812 * listener can't tell which is the password, and
2813 * hence can't deduce the password length.
2815 * Anybody with a password length greater than 16
2816 * bytes is going to have enough entropy in their
2817 * password that a listener won't find it _that_
2818 * much help to know how long it is. So what we'll
2821 * - if password length < 16, we send 15 packets
2822 * containing string lengths 1 through 15
2824 * - otherwise, we let N be the nearest multiple
2825 * of 8 below the password length, and send 8
2826 * packets containing string lengths N through
2827 * N+7. This won't obscure the order of
2828 * magnitude of the password length, but it will
2829 * introduce a bit of extra uncertainty.
2831 * A few servers (the old 1.2.18 through 1.2.22)
2832 * can't deal with SSH1_MSG_IGNORE. For these
2833 * servers, we need an alternative defence. We make
2834 * use of the fact that the password is interpreted
2835 * as a C string: so we can append a NUL, then some
2838 * One server (a Cisco one) can deal with neither
2839 * SSH1_MSG_IGNORE _nor_ a padded password string.
2840 * For this server we are left with no defences
2841 * against password length sniffing.
2843 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE)) {
2845 * The server can deal with SSH1_MSG_IGNORE, so
2846 * we can use the primary defence.
2848 int bottom, top, pwlen, i;
2851 pwlen = strlen(s->password);
2853 bottom = 0; /* zero length passwords are OK! :-) */
2856 bottom = pwlen & ~7;
2860 assert(pwlen >= bottom && pwlen <= top);
2862 randomstr = smalloc(top + 1);
2864 for (i = bottom; i <= top; i++) {
2866 defer_packet(ssh, s->pwpkt_type,
2867 PKT_STR, s->password, PKT_END);
2869 for (j = 0; j < i; j++) {
2871 randomstr[j] = random_byte();
2872 } while (randomstr[j] == '\0');
2874 randomstr[i] = '\0';
2875 defer_packet(ssh, SSH1_MSG_IGNORE,
2876 PKT_STR, randomstr, PKT_END);
2879 logevent("Sending password with camouflage packets");
2880 ssh_pkt_defersend(ssh);
2882 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
2884 * The server can't deal with SSH1_MSG_IGNORE
2885 * but can deal with padded passwords, so we
2886 * can use the secondary defence.
2892 len = strlen(s->password);
2893 if (len < sizeof(string)) {
2895 strcpy(string, s->password);
2896 len++; /* cover the zero byte */
2897 while (len < sizeof(string)) {
2898 string[len++] = (char) random_byte();
2903 logevent("Sending length-padded password");
2904 send_packet(ssh, s->pwpkt_type, PKT_INT, len,
2905 PKT_DATA, ss, len, PKT_END);
2908 * The server has _both_
2909 * BUG_CHOKES_ON_SSH1_IGNORE and
2910 * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
2911 * therefore nothing we can do.
2914 len = strlen(s->password);
2915 logevent("Sending unpadded password");
2916 send_packet(ssh, s->pwpkt_type, PKT_INT, len,
2917 PKT_DATA, s->password, len, PKT_END);
2920 send_packet(ssh, s->pwpkt_type, PKT_STR, s->password, PKT_END);
2923 logevent("Sent password");
2924 memset(s->password, 0, strlen(s->password));
2926 if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
2927 if (flags & FLAG_VERBOSE)
2928 c_write_str(ssh, "Access denied\r\n");
2929 logevent("Authentication refused");
2930 } else if (ssh->pktin.type != SSH1_SMSG_SUCCESS) {
2931 bombout((ssh,"Strange packet received, type %d", ssh->pktin.type));
2936 logevent("Authentication successful");
2941 void sshfwd_close(struct ssh_channel *c)
2945 if (c && !c->closes) {
2947 * If the channel's remoteid is -1, we have sent
2948 * CHANNEL_OPEN for this channel, but it hasn't even been
2949 * acknowledged by the server. So we must set a close flag
2950 * on it now, and then when the server acks the channel
2951 * open, we can close it then.
2953 if (((int)c->remoteid) != -1) {
2954 if (ssh->version == 1) {
2955 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
2958 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_CLOSE);
2959 ssh2_pkt_adduint32(ssh, c->remoteid);
2963 c->closes = 1; /* sent MSG_CLOSE */
2964 if (c->type == CHAN_X11) {
2966 logevent("Forwarded X11 connection terminated");
2967 } else if (c->type == CHAN_SOCKDATA ||
2968 c->type == CHAN_SOCKDATA_DORMANT) {
2970 logevent("Forwarded port closed");
2975 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
2979 if (ssh->version == 1) {
2980 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
2981 PKT_INT, c->remoteid,
2982 PKT_INT, len, PKT_DATA, buf, len, PKT_END);
2984 * In SSH1 we can return 0 here - implying that forwarded
2985 * connections are never individually throttled - because
2986 * the only circumstance that can cause throttling will be
2987 * the whole SSH connection backing up, in which case
2988 * _everything_ will be throttled as a whole.
2992 ssh2_add_channel_data(c, buf, len);
2993 return ssh2_try_send(c);
2997 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
3001 if (ssh->version == 1) {
3002 if (c->v.v1.throttling && bufsize < SSH1_BUFFER_LIMIT) {
3003 c->v.v1.throttling = 0;
3004 ssh1_throttle(ssh, -1);
3007 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
3011 static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
3013 crBegin(ssh->ssh1_protocol_crstate);
3017 while (!do_ssh1_login(ssh, in, inlen, ispkt)) {
3020 if (ssh->state == SSH_STATE_CLOSED)
3023 if (cfg.agentfwd && agent_exists()) {
3024 logevent("Requesting agent forwarding");
3025 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
3029 if (ssh->pktin.type != SSH1_SMSG_SUCCESS
3030 && ssh->pktin.type != SSH1_SMSG_FAILURE) {
3031 bombout((ssh,"Protocol confusion"));
3033 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
3034 logevent("Agent forwarding refused");
3036 logevent("Agent forwarding enabled");
3037 ssh->agentfwd_enabled = TRUE;
3041 if (cfg.x11_forward) {
3042 char proto[20], data[64];
3043 logevent("Requesting X11 forwarding");
3044 ssh->x11auth = x11_invent_auth(proto, sizeof(proto),
3045 data, sizeof(data));
3046 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
3047 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
3048 PKT_STR, proto, PKT_STR, data,
3049 PKT_INT, 0, PKT_END);
3051 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
3052 PKT_STR, proto, PKT_STR, data, PKT_END);
3057 if (ssh->pktin.type != SSH1_SMSG_SUCCESS
3058 && ssh->pktin.type != SSH1_SMSG_FAILURE) {
3059 bombout((ssh,"Protocol confusion"));
3061 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
3062 logevent("X11 forwarding refused");
3064 logevent("X11 forwarding enabled");
3065 ssh->X11_fwd_enabled = TRUE;
3072 int sport,dport,sserv,dserv;
3073 char sports[256], dports[256], host[256];
3077 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
3078 /* Add port forwardings. */
3079 ssh->portfwd_strptr = cfg.portfwd;
3080 while (*ssh->portfwd_strptr) {
3081 type = *ssh->portfwd_strptr++;
3083 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != '\t')
3084 sports[n++] = *ssh->portfwd_strptr++;
3086 if (*ssh->portfwd_strptr == '\t')
3087 ssh->portfwd_strptr++;
3089 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != ':')
3090 host[n++] = *ssh->portfwd_strptr++;
3092 if (*ssh->portfwd_strptr == ':')
3093 ssh->portfwd_strptr++;
3095 while (*ssh->portfwd_strptr)
3096 dports[n++] = *ssh->portfwd_strptr++;
3098 ssh->portfwd_strptr++;
3099 dport = atoi(dports);
3103 se = getservbyname(dports, NULL);
3105 dport = ntohs(se->s_port);
3108 "Service lookup failed for destination port \"%s\"",
3113 sport = atoi(sports);
3117 se = getservbyname(sports, NULL);
3119 sport = ntohs(se->s_port);
3122 "Service lookup failed for source port \"%s\"",
3127 if (sport && dport) {
3129 pfd_addforward(host, dport, sport, ssh);
3130 sprintf(buf, "Local port %.*s%.*s%d%.*s forwarding to"
3131 " %s:%.*s%.*s%d%.*s",
3132 sserv ? strlen(sports) : 0, sports,
3133 sserv, "(", sport, sserv, ")",
3135 dserv ? strlen(dports) : 0, dports,
3136 dserv, "(", dport, dserv, ")");
3139 struct ssh_rportfwd *pf;
3140 pf = smalloc(sizeof(*pf));
3141 strcpy(pf->dhost, host);
3143 if (add234(ssh->rportfwds, pf) != pf) {
3145 "Duplicate remote port forwarding to %s:%d",
3150 sprintf(buf, "Requesting remote port %.*s%.*s%d%.*s"
3151 " forward to %s:%.*s%.*s%d%.*s",
3152 sserv ? strlen(sports) : 0, sports,
3153 sserv, "(", sport, sserv, ")",
3155 dserv ? strlen(dports) : 0, dports,
3156 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");
3182 send_packet(ssh, SSH1_CMSG_REQUEST_PTY,
3183 PKT_STR, 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 (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 = cfg.remote_cmd_ptr;
3234 if (cfg.ssh_subsys && cfg.remote_cmd_ptr2) {
3235 cmd = 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 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, cfg.x11_display, c,
3289 ssh->x11auth) != 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 = ssh->pktin.body+8; hostsize != 0; hostsize--) {
3346 if (h+1 < host+sizeof(host))
3351 port = GET_32BIT(p);
3353 strcpy(pf.dhost, host);
3356 if (find234(ssh->rportfwds, &pf, NULL) == NULL) {
3357 sprintf(buf, "Rejected remote port open request for %s:%d",
3360 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3361 PKT_INT, GET_32BIT(ssh->pktin.body), PKT_END);
3363 sprintf(buf, "Received remote port open request for %s:%d",
3366 e = pfd_newconnect(&c->u.pfd.s, host, port, c);
3369 sprintf(buf, "Port open failed: %s", e);
3372 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3373 PKT_INT, GET_32BIT(ssh->pktin.body),
3376 c->remoteid = GET_32BIT(ssh->pktin.body);
3377 c->localid = alloc_channel_id(ssh);
3379 c->v.v1.throttling = 0;
3380 c->type = CHAN_SOCKDATA; /* identify channel type */
3381 add234(ssh->channels, c);
3382 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3383 PKT_INT, c->remoteid, PKT_INT,
3384 c->localid, PKT_END);
3385 logevent("Forwarded port opened successfully");
3389 } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_OPEN_CONFIRMATION) {
3390 unsigned int remoteid = GET_32BIT(ssh->pktin.body);
3391 unsigned int localid = GET_32BIT(ssh->pktin.body+4);
3392 struct ssh_channel *c;
3394 c = find234(ssh->channels, &remoteid, ssh_channelfind);
3395 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
3396 c->remoteid = localid;
3397 c->type = CHAN_SOCKDATA;
3398 c->v.v1.throttling = 0;
3399 pfd_confirm(c->u.pfd.s);
3402 if (c && c->closes) {
3404 * We have a pending close on this channel,
3405 * which we decided on before the server acked
3406 * the channel open. So now we know the
3407 * remoteid, we can close it again.
3409 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE,
3410 PKT_INT, c->remoteid, PKT_END);
3413 } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_OPEN_FAILURE) {
3414 unsigned int remoteid = GET_32BIT(ssh->pktin.body);
3415 unsigned int localid = GET_32BIT(ssh->pktin.body+4);
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, p, len);
3481 bufsize = pfd_send(c->u.pfd.s, 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)
3586 int needlen = strlen(needle);
3589 * Is it at the start of the string?
3591 if (haylen >= needlen && /* haystack is long enough */
3592 !memcmp(needle, haystack, needlen) && /* initial match */
3593 (haylen == needlen || haystack[needlen] == ',')
3594 /* either , or EOS follows */
3598 * If not, search for the next comma and resume after that.
3599 * If no comma found, terminate.
3601 while (haylen > 0 && *haystack != ',')
3602 haylen--, haystack++;
3605 haylen--, haystack++; /* skip over comma itself */
3610 * SSH2 key creation method.
3612 static void ssh2_mkkey(Ssh ssh, Bignum K, char *H, char *sessid, char chr,
3616 /* First 20 bytes. */
3618 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
3620 SHA_Bytes(&s, H, 20);
3621 SHA_Bytes(&s, &chr, 1);
3622 SHA_Bytes(&s, sessid, 20);
3623 SHA_Final(&s, keyspace);
3624 /* Next 20 bytes. */
3626 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
3628 SHA_Bytes(&s, H, 20);
3629 SHA_Bytes(&s, keyspace, 20);
3630 SHA_Final(&s, keyspace + 20);
3634 * Handle the SSH2 transport layer.
3636 static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen, int ispkt)
3638 struct do_ssh2_transport_state {
3639 int nbits, pbits, warn;
3640 Bignum p, g, e, f, K;
3641 int kex_init_value, kex_reply_value;
3642 const struct ssh_mac **maclist;
3644 const struct ssh2_cipher *cscipher_tobe;
3645 const struct ssh2_cipher *sccipher_tobe;
3646 const struct ssh_mac *csmac_tobe;
3647 const struct ssh_mac *scmac_tobe;
3648 const struct ssh_compress *cscomp_tobe;
3649 const struct ssh_compress *sccomp_tobe;
3650 char *hostkeydata, *sigdata, *keystr, *fingerprint;
3651 int hostkeylen, siglen;
3652 void *hkey; /* actual host key */
3653 unsigned char exchange_hash[20];
3654 int n_preferred_ciphers;
3655 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
3656 const struct ssh_compress *preferred_comp;
3659 crState(do_ssh2_transport_state);
3661 crBegin(ssh->do_ssh2_transport_crstate);
3663 s->cscipher_tobe = s->sccipher_tobe = NULL;
3664 s->csmac_tobe = s->scmac_tobe = NULL;
3665 s->cscomp_tobe = s->sccomp_tobe = NULL;
3673 * Set up the preferred ciphers. (NULL => warn below here)
3675 s->n_preferred_ciphers = 0;
3676 for (i = 0; i < CIPHER_MAX; i++) {
3677 switch (cfg.ssh_cipherlist[i]) {
3678 case CIPHER_BLOWFISH:
3679 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
3682 if (cfg.ssh2_des_cbc) {
3683 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
3687 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
3690 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
3693 /* Flag for later. Don't bother if it's the last in
3695 if (i < CIPHER_MAX - 1) {
3696 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
3704 * Set up preferred compression.
3706 if (cfg.compression)
3707 s->preferred_comp = &ssh_zlib;
3709 s->preferred_comp = &ssh_comp_none;
3712 * Be prepared to work around the buggy MAC problem.
3714 if (ssh->remote_bugs & BUG_SSH2_HMAC)
3715 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
3717 s->maclist = macs, s->nmacs = lenof(macs);
3721 int i, j, cipherstr_started;
3724 * Construct and send our key exchange packet.
3726 ssh2_pkt_init(ssh, SSH2_MSG_KEXINIT);
3727 for (i = 0; i < 16; i++)
3728 ssh2_pkt_addbyte(ssh, (unsigned char) random_byte());
3729 /* List key exchange algorithms. */
3730 ssh2_pkt_addstring_start(ssh);
3731 for (i = 0; i < lenof(kex_algs); i++) {
3732 if (kex_algs[i] == &ssh_diffiehellman_gex &&
3733 (ssh->remote_bugs & BUG_SSH2_DH_GEX))
3735 ssh2_pkt_addstring_str(ssh, kex_algs[i]->name);
3736 if (i < lenof(kex_algs) - 1)
3737 ssh2_pkt_addstring_str(ssh, ",");
3739 /* List server host key algorithms. */
3740 ssh2_pkt_addstring_start(ssh);
3741 for (i = 0; i < lenof(hostkey_algs); i++) {
3742 ssh2_pkt_addstring_str(ssh, hostkey_algs[i]->name);
3743 if (i < lenof(hostkey_algs) - 1)
3744 ssh2_pkt_addstring_str(ssh, ",");
3746 /* List client->server encryption algorithms. */
3747 ssh2_pkt_addstring_start(ssh);
3748 cipherstr_started = 0;
3749 for (i = 0; i < s->n_preferred_ciphers; i++) {
3750 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
3751 if (!c) continue; /* warning flag */
3752 for (j = 0; j < c->nciphers; j++) {
3753 if (cipherstr_started)
3754 ssh2_pkt_addstring_str(ssh, ",");
3755 ssh2_pkt_addstring_str(ssh, c->list[j]->name);
3756 cipherstr_started = 1;
3759 /* List server->client encryption algorithms. */
3760 ssh2_pkt_addstring_start(ssh);
3761 cipherstr_started = 0;
3762 for (i = 0; i < s->n_preferred_ciphers; i++) {
3763 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
3764 if (!c) continue; /* warning flag */
3765 for (j = 0; j < c->nciphers; j++) {
3766 if (cipherstr_started)
3767 ssh2_pkt_addstring_str(ssh, ",");
3768 ssh2_pkt_addstring_str(ssh, c->list[j]->name);
3769 cipherstr_started = 1;
3772 /* List client->server MAC algorithms. */
3773 ssh2_pkt_addstring_start(ssh);
3774 for (i = 0; i < s->nmacs; i++) {
3775 ssh2_pkt_addstring_str(ssh, s->maclist[i]->name);
3776 if (i < s->nmacs - 1)
3777 ssh2_pkt_addstring_str(ssh, ",");
3779 /* List server->client MAC algorithms. */
3780 ssh2_pkt_addstring_start(ssh);
3781 for (i = 0; i < s->nmacs; i++) {
3782 ssh2_pkt_addstring_str(ssh, s->maclist[i]->name);
3783 if (i < s->nmacs - 1)
3784 ssh2_pkt_addstring_str(ssh, ",");
3786 /* List client->server compression algorithms. */
3787 ssh2_pkt_addstring_start(ssh);
3788 for (i = 0; i < lenof(compressions) + 1; i++) {
3789 const struct ssh_compress *c =
3790 i == 0 ? s->preferred_comp : compressions[i - 1];
3791 ssh2_pkt_addstring_str(ssh, c->name);
3792 if (i < lenof(compressions))
3793 ssh2_pkt_addstring_str(ssh, ",");
3795 /* List server->client compression algorithms. */
3796 ssh2_pkt_addstring_start(ssh);
3797 for (i = 0; i < lenof(compressions) + 1; i++) {
3798 const struct ssh_compress *c =
3799 i == 0 ? s->preferred_comp : compressions[i - 1];
3800 ssh2_pkt_addstring_str(ssh, c->name);
3801 if (i < lenof(compressions))
3802 ssh2_pkt_addstring_str(ssh, ",");
3804 /* List client->server languages. Empty list. */
3805 ssh2_pkt_addstring_start(ssh);
3806 /* List server->client languages. Empty list. */
3807 ssh2_pkt_addstring_start(ssh);
3808 /* First KEX packet does _not_ follow, because we're not that brave. */
3809 ssh2_pkt_addbool(ssh, FALSE);
3811 ssh2_pkt_adduint32(ssh, 0);
3814 ssh->exhash = ssh->exhashbase;
3815 sha_string(&ssh->exhash, ssh->pktout.data + 5, ssh->pktout.length - 5);
3821 sha_string(&ssh->exhash, ssh->pktin.data + 5, ssh->pktin.length - 5);
3824 * Now examine the other side's KEXINIT to see what we're up
3831 if (ssh->pktin.type != SSH2_MSG_KEXINIT) {
3832 bombout((ssh,"expected key exchange packet from server"));
3836 ssh->hostkey = NULL;
3837 s->cscipher_tobe = NULL;
3838 s->sccipher_tobe = NULL;
3839 s->csmac_tobe = NULL;
3840 s->scmac_tobe = NULL;
3841 s->cscomp_tobe = NULL;
3842 s->sccomp_tobe = NULL;
3843 ssh->pktin.savedpos += 16; /* skip garbage cookie */
3844 ssh2_pkt_getstring(ssh, &str, &len); /* key exchange algorithms */
3845 for (i = 0; i < lenof(kex_algs); i++) {
3846 if (kex_algs[i] == &ssh_diffiehellman_gex &&
3847 (ssh->remote_bugs & BUG_SSH2_DH_GEX))
3849 if (in_commasep_string(kex_algs[i]->name, str, len)) {
3850 ssh->kex = kex_algs[i];
3854 ssh2_pkt_getstring(ssh, &str, &len); /* host key algorithms */
3855 for (i = 0; i < lenof(hostkey_algs); i++) {
3856 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
3857 ssh->hostkey = hostkey_algs[i];
3861 ssh2_pkt_getstring(ssh, &str, &len); /* client->server cipher */
3863 for (i = 0; i < s->n_preferred_ciphers; i++) {
3864 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
3868 for (j = 0; j < c->nciphers; j++) {
3869 if (in_commasep_string(c->list[j]->name, str, len)) {
3870 s->cscipher_tobe = c->list[j];
3875 if (s->cscipher_tobe) {
3877 askcipher(ssh->frontend, s->cscipher_tobe->name, 1);
3881 if (!s->cscipher_tobe) {
3882 bombout((ssh,"Couldn't agree a client-to-server cipher (available: %s)", str));
3886 ssh2_pkt_getstring(ssh, &str, &len); /* server->client cipher */
3888 for (i = 0; i < s->n_preferred_ciphers; i++) {
3889 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
3893 for (j = 0; j < c->nciphers; j++) {
3894 if (in_commasep_string(c->list[j]->name, str, len)) {
3895 s->sccipher_tobe = c->list[j];
3900 if (s->sccipher_tobe) {
3902 askcipher(ssh->frontend, s->sccipher_tobe->name, 2);
3906 if (!s->sccipher_tobe) {
3907 bombout((ssh,"Couldn't agree a server-to-client cipher (available: %s)", str));
3911 ssh2_pkt_getstring(ssh, &str, &len); /* client->server mac */
3912 for (i = 0; i < s->nmacs; i++) {
3913 if (in_commasep_string(s->maclist[i]->name, str, len)) {
3914 s->csmac_tobe = s->maclist[i];
3918 ssh2_pkt_getstring(ssh, &str, &len); /* server->client mac */
3919 for (i = 0; i < s->nmacs; i++) {
3920 if (in_commasep_string(s->maclist[i]->name, str, len)) {
3921 s->scmac_tobe = s->maclist[i];
3925 ssh2_pkt_getstring(ssh, &str, &len); /* client->server compression */
3926 for (i = 0; i < lenof(compressions) + 1; i++) {
3927 const struct ssh_compress *c =
3928 i == 0 ? s->preferred_comp : compressions[i - 1];
3929 if (in_commasep_string(c->name, str, len)) {
3934 ssh2_pkt_getstring(ssh, &str, &len); /* server->client compression */
3935 for (i = 0; i < lenof(compressions) + 1; i++) {
3936 const struct ssh_compress *c =
3937 i == 0 ? s->preferred_comp : compressions[i - 1];
3938 if (in_commasep_string(c->name, str, len)) {
3946 * Work out the number of bits of key we will need from the key
3947 * exchange. We start with the maximum key length of either
3953 csbits = s->cscipher_tobe->keylen;
3954 scbits = s->sccipher_tobe->keylen;
3955 s->nbits = (csbits > scbits ? csbits : scbits);
3957 /* The keys only have 160-bit entropy, since they're based on
3958 * a SHA-1 hash. So cap the key size at 160 bits. */
3963 * If we're doing Diffie-Hellman group exchange, start by
3964 * requesting a group.
3966 if (ssh->kex == &ssh_diffiehellman_gex) {
3967 logevent("Doing Diffie-Hellman group exchange");
3968 ssh->pkt_ctx |= SSH2_PKTCTX_DHGEX;
3970 * Work out how big a DH group we will need to allow that
3973 s->pbits = 512 << ((s->nbits - 1) / 64);
3974 ssh2_pkt_init(ssh, SSH2_MSG_KEX_DH_GEX_REQUEST);
3975 ssh2_pkt_adduint32(ssh, s->pbits);
3979 if (ssh->pktin.type != SSH2_MSG_KEX_DH_GEX_GROUP) {
3980 bombout((ssh,"expected key exchange group packet from server"));
3983 s->p = ssh2_pkt_getmp(ssh);
3984 s->g = ssh2_pkt_getmp(ssh);
3985 ssh->kex_ctx = dh_setup_group(s->p, s->g);
3986 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
3987 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
3989 ssh->pkt_ctx |= SSH2_PKTCTX_DHGROUP1;
3990 ssh->kex_ctx = dh_setup_group1();
3991 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
3992 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
3995 logevent("Doing Diffie-Hellman key exchange");
3997 * Now generate and send e for Diffie-Hellman.
3999 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
4000 ssh2_pkt_init(ssh, s->kex_init_value);
4001 ssh2_pkt_addmp(ssh, s->e);
4005 if (ssh->pktin.type != s->kex_reply_value) {
4006 bombout((ssh,"expected key exchange reply packet from server"));
4009 ssh2_pkt_getstring(ssh, &s->hostkeydata, &s->hostkeylen);
4010 s->f = ssh2_pkt_getmp(ssh);
4011 ssh2_pkt_getstring(ssh, &s->sigdata, &s->siglen);
4013 s->K = dh_find_K(ssh->kex_ctx, s->f);
4015 sha_string(&ssh->exhash, s->hostkeydata, s->hostkeylen);
4016 if (ssh->kex == &ssh_diffiehellman_gex) {
4017 sha_uint32(&ssh->exhash, s->pbits);
4018 sha_mpint(&ssh->exhash, s->p);
4019 sha_mpint(&ssh->exhash, s->g);
4021 sha_mpint(&ssh->exhash, s->e);
4022 sha_mpint(&ssh->exhash, s->f);
4023 sha_mpint(&ssh->exhash, s->K);
4024 SHA_Final(&ssh->exhash, s->exchange_hash);
4026 dh_cleanup(ssh->kex_ctx);
4029 debug(("Exchange hash is:\n"));
4030 dmemdump(s->exchange_hash, 20);
4033 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
4035 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
4036 s->exchange_hash, 20)) {
4037 bombout((ssh,"Server's host key did not match the signature supplied"));
4042 * Authenticate remote host: verify host key. (We've already
4043 * checked the signature of the exchange hash.)
4045 s->keystr = ssh->hostkey->fmtkey(s->hkey);
4046 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
4047 verify_ssh_host_key(ssh->frontend,
4048 ssh->savedhost, ssh->savedport, ssh->hostkey->keytype,
4049 s->keystr, s->fingerprint);
4050 if (s->first_kex) { /* don't bother logging this in rekeys */
4051 logevent("Host key fingerprint is:");
4052 logevent(s->fingerprint);
4054 sfree(s->fingerprint);
4056 ssh->hostkey->freekey(s->hkey);
4059 * Send SSH2_MSG_NEWKEYS.
4061 ssh2_pkt_init(ssh, SSH2_MSG_NEWKEYS);
4065 * Expect SSH2_MSG_NEWKEYS from server.
4068 if (ssh->pktin.type != SSH2_MSG_NEWKEYS) {
4069 bombout((ssh,"expected new-keys packet from server"));
4074 * Create and initialise session keys.
4076 if (ssh->cs_cipher_ctx)
4077 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
4078 ssh->cscipher = s->cscipher_tobe;
4079 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
4081 if (ssh->sc_cipher_ctx)
4082 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
4083 ssh->sccipher = s->sccipher_tobe;
4084 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
4086 if (ssh->cs_mac_ctx)
4087 ssh->csmac->free_context(ssh->cs_mac_ctx);
4088 ssh->csmac = s->csmac_tobe;
4089 ssh->cs_mac_ctx = ssh->csmac->make_context();
4091 if (ssh->sc_mac_ctx)
4092 ssh->scmac->free_context(ssh->sc_mac_ctx);
4093 ssh->scmac = s->scmac_tobe;
4094 ssh->sc_mac_ctx = ssh->scmac->make_context();
4096 if (ssh->cs_comp_ctx)
4097 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
4098 ssh->cscomp = s->cscomp_tobe;
4099 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
4101 if (ssh->sc_comp_ctx)
4102 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
4103 ssh->sccomp = s->sccomp_tobe;
4104 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
4107 * Set IVs after keys. Here we use the exchange hash from the
4108 * _first_ key exchange.
4111 unsigned char keyspace[40];
4113 memcpy(ssh->v2_session_id, s->exchange_hash,
4114 sizeof(s->exchange_hash));
4115 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'C',keyspace);
4116 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
4117 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'D',keyspace);
4118 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
4119 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'A',keyspace);
4120 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
4121 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'B',keyspace);
4122 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
4123 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'E',keyspace);
4124 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
4125 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'F',keyspace);
4126 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
4130 sprintf(buf, "Initialised %.200s client->server encryption",
4131 ssh->cscipher->text_name);
4133 sprintf(buf, "Initialised %.200s server->client encryption",
4134 ssh->sccipher->text_name);
4136 if (ssh->cscomp->text_name) {
4137 sprintf(buf, "Initialised %.200s compression",
4138 ssh->cscomp->text_name);
4141 if (ssh->sccomp->text_name) {
4142 sprintf(buf, "Initialised %.200s decompression",
4143 ssh->sccomp->text_name);
4150 * If this is the first key exchange phase, we must pass the
4151 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
4152 * wants to see it but because it will need time to initialise
4153 * itself before it sees an actual packet. In subsequent key
4154 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
4155 * it would only confuse the layer above.
4157 if (!s->first_kex) {
4163 * Now we're encrypting. Begin returning 1 to the protocol main
4164 * function so that other things can run on top of the
4165 * transport. If we ever see a KEXINIT, we must go back to the
4168 while (!(ispkt && ssh->pktin.type == SSH2_MSG_KEXINIT)) {
4171 logevent("Server initiated key re-exchange");
4172 goto begin_key_exchange;
4178 * Add data to an SSH2 channel output buffer.
4180 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
4183 bufchain_add(&c->v.v2.outbuffer, buf, len);
4187 * Attempt to send data on an SSH2 channel.
4189 static int ssh2_try_send(struct ssh_channel *c)
4193 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
4196 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
4197 if ((unsigned)len > c->v.v2.remwindow)
4198 len = c->v.v2.remwindow;
4199 if ((unsigned)len > c->v.v2.remmaxpkt)
4200 len = c->v.v2.remmaxpkt;
4201 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_DATA);
4202 ssh2_pkt_adduint32(ssh, c->remoteid);
4203 ssh2_pkt_addstring_start(ssh);
4204 ssh2_pkt_addstring_data(ssh, data, len);
4206 bufchain_consume(&c->v.v2.outbuffer, len);
4207 c->v.v2.remwindow -= len;
4211 * After having sent as much data as we can, return the amount
4214 return bufchain_size(&c->v.v2.outbuffer);
4218 * Potentially enlarge the window on an SSH2 channel.
4220 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin)
4225 * Never send WINDOW_ADJUST for a channel that the remote side
4226 * already thinks it's closed; there's no point, since it won't
4227 * be sending any more data anyway.
4232 if (newwin > c->v.v2.locwindow) {
4233 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4234 ssh2_pkt_adduint32(ssh, c->remoteid);
4235 ssh2_pkt_adduint32(ssh, newwin - c->v.v2.locwindow);
4237 c->v.v2.locwindow = newwin;
4242 * Handle the SSH2 userauth and connection layers.
4244 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
4246 struct do_ssh2_authconn_state {
4248 AUTH_INVALID, AUTH_PUBLICKEY_AGENT, AUTH_PUBLICKEY_FILE,
4250 AUTH_KEYBOARD_INTERACTIVE
4254 AUTH_TYPE_PUBLICKEY,
4255 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
4256 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
4258 AUTH_TYPE_KEYBOARD_INTERACTIVE,
4259 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
4261 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
4262 int tried_pubkey_config, tried_agent, tried_keyb_inter;
4263 int kbd_inter_running;
4265 int num_prompts, curr_prompt, echo;
4270 void *publickey_blob;
4271 int publickey_bloblen;
4272 unsigned char request[5], *response, *p;
4276 char *pkblob, *alg, *commentp;
4277 int pklen, alglen, commentlen;
4278 int siglen, retlen, len;
4279 char *q, *agentreq, *ret;
4282 crState(do_ssh2_authconn_state);
4284 crBegin(ssh->do_ssh2_authconn_crstate);
4287 * Request userauth protocol, and await a response to it.
4289 ssh2_pkt_init(ssh, SSH2_MSG_SERVICE_REQUEST);
4290 ssh2_pkt_addstring(ssh, "ssh-userauth");
4292 crWaitUntilV(ispkt);
4293 if (ssh->pktin.type != SSH2_MSG_SERVICE_ACCEPT) {
4294 bombout((ssh,"Server refused user authentication protocol"));
4299 * We repeat this whole loop, including the username prompt,
4300 * until we manage a successful authentication. If the user
4301 * types the wrong _password_, they can be sent back to the
4302 * beginning to try another username, if this is configured on.
4303 * (If they specify a username in the config, they are never
4304 * asked, even if they do give a wrong password.)
4306 * I think this best serves the needs of
4308 * - the people who have no configuration, no keys, and just
4309 * want to try repeated (username,password) pairs until they
4310 * type both correctly
4312 * - people who have keys and configuration but occasionally
4313 * need to fall back to passwords
4315 * - people with a key held in Pageant, who might not have
4316 * logged in to a particular machine before; so they want to
4317 * type a username, and then _either_ their key will be
4318 * accepted, _or_ they will type a password. If they mistype
4319 * the username they will want to be able to get back and
4322 s->username[0] = '\0';
4323 s->got_username = FALSE;
4328 if (s->got_username && !cfg.change_username) {
4330 * We got a username last time round this loop, and
4331 * with change_username turned off we don't try to get
4334 } else if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
4335 if (ssh_get_line && !ssh_getline_pw_only) {
4336 if (!ssh_get_line("login as: ",
4337 s->username, sizeof(s->username), FALSE)) {
4339 * get_line failed to get a username.
4342 logevent("No username provided. Abandoning session.");
4343 ssh->state = SSH_STATE_CLOSED;
4347 int ret; /* need not be saved across crReturn */
4348 c_write_str(ssh, "login as: ");
4350 setup_userpass_input(ssh, s->username, sizeof(s->username), 1);
4352 crWaitUntilV(!ispkt);
4353 ret = process_userpass_input(ssh, in, inlen);
4358 c_write_str(ssh, "\r\n");
4359 s->username[strcspn(s->username, "\n\r")] = '\0';
4362 strncpy(s->username, cfg.username, sizeof(s->username));
4363 s->username[sizeof(s->username)-1] = '\0';
4364 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
4365 sprintf(stuff, "Using username \"%s\".\r\n", s->username);
4366 c_write_str(ssh, stuff);
4369 s->got_username = TRUE;
4372 * Send an authentication request using method "none": (a)
4373 * just in case it succeeds, and (b) so that we know what
4374 * authentication methods we can usefully try next.
4376 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4378 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4379 ssh2_pkt_addstring(ssh, s->username);
4380 ssh2_pkt_addstring(ssh, "ssh-connection");/* service requested */
4381 ssh2_pkt_addstring(ssh, "none"); /* method */
4383 s->type = AUTH_TYPE_NONE;
4385 s->we_are_in = FALSE;
4387 s->tried_pubkey_config = FALSE;
4388 s->tried_agent = FALSE;
4389 s->tried_keyb_inter = FALSE;
4390 s->kbd_inter_running = FALSE;
4391 /* Load the pub half of cfg.keyfile so we notice if it's in Pageant */
4394 logeventf(ssh->frontend,
4395 "Reading private key file \"%.150s\"", cfg.keyfile);
4396 keytype = key_type(cfg.keyfile);
4397 if (keytype == SSH_KEYTYPE_SSH2) {
4399 ssh2_userkey_loadpub(cfg.keyfile, NULL,
4400 &s->publickey_bloblen);
4403 logeventf(ssh->frontend,
4404 "Unable to use this key file (%s)",
4405 key_type_to_str(keytype));
4406 sprintf(msgbuf, "Unable to use key file \"%.150s\" (%s)\r\n",
4407 cfg.keyfile, key_type_to_str(keytype));
4408 c_write_str(ssh, msgbuf);
4409 s->publickey_blob = NULL;
4412 s->publickey_blob = NULL;
4416 * Wait for the result of the last authentication request.
4419 crWaitUntilV(ispkt);
4420 while (ssh->pktin.type == SSH2_MSG_USERAUTH_BANNER) {
4424 * Don't show the banner if we're operating in
4425 * non-verbose non-interactive mode. (It's probably
4426 * a script, which means nobody will read the
4427 * banner _anyway_, and moreover the printing of
4428 * the banner will screw up processing on the
4429 * output of (say) plink.)
4431 if (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE)) {
4432 ssh2_pkt_getstring(ssh, &banner, &size);
4434 c_write_untrusted(ssh, banner, size);
4436 crWaitUntilV(ispkt);
4438 if (ssh->pktin.type == SSH2_MSG_USERAUTH_SUCCESS) {
4439 logevent("Access granted");
4440 s->we_are_in = TRUE;
4444 if (s->kbd_inter_running &&
4445 ssh->pktin.type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
4447 * This is either a further set-of-prompts packet
4448 * in keyboard-interactive authentication, or it's
4449 * the same one and we came back here with `gotit'
4450 * set. In the former case, we must reset the
4451 * curr_prompt variable.
4455 } else if (ssh->pktin.type != SSH2_MSG_USERAUTH_FAILURE) {
4456 bombout((ssh,"Strange packet received during authentication: type %d",
4464 * OK, we're now sitting on a USERAUTH_FAILURE message, so
4465 * we can look at the string in it and know what we can
4466 * helpfully try next.
4468 if (ssh->pktin.type == SSH2_MSG_USERAUTH_FAILURE) {
4471 ssh2_pkt_getstring(ssh, &methods, &methlen);
4472 s->kbd_inter_running = FALSE;
4473 if (!ssh2_pkt_getbool(ssh)) {
4475 * We have received an unequivocal Access
4476 * Denied. This can translate to a variety of
4479 * - if we'd just tried "none" authentication,
4480 * it's not worth printing anything at all
4482 * - if we'd just tried a public key _offer_,
4483 * the message should be "Server refused our
4484 * key" (or no message at all if the key
4485 * came from Pageant)
4487 * - if we'd just tried anything else, the
4488 * message really should be "Access denied".
4490 * Additionally, if we'd just tried password
4491 * authentication, we should break out of this
4492 * whole loop so as to go back to the username
4495 if (s->type == AUTH_TYPE_NONE) {
4497 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
4498 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
4499 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
4500 c_write_str(ssh, "Server refused our key\r\n");
4501 logevent("Server refused public key");
4502 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
4503 /* server declined keyboard-interactive; ignore */
4505 c_write_str(ssh, "Access denied\r\n");
4506 logevent("Access denied");
4507 if (s->type == AUTH_TYPE_PASSWORD) {
4508 s->we_are_in = FALSE;
4513 c_write_str(ssh, "Further authentication required\r\n");
4514 logevent("Further authentication required");
4518 in_commasep_string("publickey", methods, methlen);
4520 in_commasep_string("password", methods, methlen);
4521 s->can_keyb_inter = cfg.try_ki_auth &&
4522 in_commasep_string("keyboard-interactive", methods, methlen);
4526 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4529 * Most password/passphrase prompts will be
4530 * non-echoing, so we set this to 0 by default.
4531 * Exception is that some keyboard-interactive prompts
4532 * can be echoing, in which case we'll set this to 1.
4536 if (!s->method && s->can_pubkey &&
4537 agent_exists() && !s->tried_agent) {
4539 * Attempt public-key authentication using Pageant.
4544 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4545 ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
4547 s->tried_agent = TRUE;
4549 logevent("Pageant is running. Requesting keys.");
4551 /* Request the keys held by the agent. */
4552 PUT_32BIT(s->request, 1);
4553 s->request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
4554 agent_query(s->request, 5, &r, &s->responselen);
4555 s->response = (unsigned char *) r;
4556 if (s->response && s->responselen >= 5 &&
4557 s->response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
4558 s->p = s->response + 5;
4559 s->nkeys = GET_32BIT(s->p);
4563 sprintf(buf, "Pageant has %d SSH2 keys", s->nkeys);
4566 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
4571 sprintf(buf, "Trying Pageant key #%d", s->keyi);
4574 s->pklen = GET_32BIT(s->p);
4576 if (s->publickey_blob &&
4577 s->pklen == s->publickey_bloblen &&
4578 !memcmp(s->p, s->publickey_blob,
4579 s->publickey_bloblen)) {
4580 logevent("This key matches configured key file");
4581 s->tried_pubkey_config = 1;
4585 s->alglen = GET_32BIT(s->pkblob);
4586 s->alg = s->pkblob + 4;
4587 s->commentlen = GET_32BIT(s->p);
4590 s->p += s->commentlen;
4591 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4592 ssh2_pkt_addstring(ssh, s->username);
4593 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4594 ssh2_pkt_addstring(ssh, "publickey"); /* method */
4595 ssh2_pkt_addbool(ssh, FALSE); /* no signature included */
4596 ssh2_pkt_addstring_start(ssh);
4597 ssh2_pkt_addstring_data(ssh, s->alg, s->alglen);
4598 ssh2_pkt_addstring_start(ssh);
4599 ssh2_pkt_addstring_data(ssh, s->pkblob, s->pklen);
4602 crWaitUntilV(ispkt);
4603 if (ssh->pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
4604 logevent("Key refused");
4608 if (flags & FLAG_VERBOSE) {
4609 c_write_str(ssh, "Authenticating with "
4611 c_write(ssh, s->commentp, s->commentlen);
4612 c_write_str(ssh, "\" from agent\r\n");
4616 * Server is willing to accept the key.
4617 * Construct a SIGN_REQUEST.
4619 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4620 ssh2_pkt_addstring(ssh, s->username);
4621 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4622 ssh2_pkt_addstring(ssh, "publickey"); /* method */
4623 ssh2_pkt_addbool(ssh, TRUE);
4624 ssh2_pkt_addstring_start(ssh);
4625 ssh2_pkt_addstring_data(ssh, s->alg, s->alglen);
4626 ssh2_pkt_addstring_start(ssh);
4627 ssh2_pkt_addstring_data(ssh, s->pkblob, s->pklen);
4629 s->siglen = ssh->pktout.length - 5 + 4 + 20;
4630 s->len = 1; /* message type */
4631 s->len += 4 + s->pklen; /* key blob */
4632 s->len += 4 + s->siglen; /* data to sign */
4633 s->len += 4; /* flags */
4634 s->agentreq = smalloc(4 + s->len);
4635 PUT_32BIT(s->agentreq, s->len);
4636 s->q = s->agentreq + 4;
4637 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
4638 PUT_32BIT(s->q, s->pklen);
4640 memcpy(s->q, s->pkblob, s->pklen);
4642 PUT_32BIT(s->q, s->siglen);
4644 /* Now the data to be signed... */
4645 PUT_32BIT(s->q, 20);
4647 memcpy(s->q, ssh->v2_session_id, 20);
4649 memcpy(s->q, ssh->pktout.data + 5,
4650 ssh->pktout.length - 5);
4651 s->q += ssh->pktout.length - 5;
4652 /* And finally the (zero) flags word. */
4654 agent_query(s->agentreq, s->len + 4, &vret, &s->retlen);
4658 if (s->ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
4659 logevent("Sending Pageant's response");
4660 ssh2_add_sigblob(ssh, s->pkblob, s->pklen,
4662 GET_32BIT(s->ret + 5));
4668 ("Pageant failed to answer challenge");
4678 if (!s->method && s->can_pubkey && s->publickey_blob
4679 && !s->tried_pubkey_config) {
4680 unsigned char *pub_blob;
4681 char *algorithm, *comment;
4684 s->tried_pubkey_config = TRUE;
4686 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4687 ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
4690 * Try the public key supplied in the configuration.
4692 * First, offer the public blob to see if the server is
4693 * willing to accept it.
4695 pub_blob = ssh2_userkey_loadpub(cfg.keyfile, &algorithm,
4698 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4699 ssh2_pkt_addstring(ssh, s->username);
4700 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4701 ssh2_pkt_addstring(ssh, "publickey"); /* method */
4702 ssh2_pkt_addbool(ssh, FALSE); /* no signature included */
4703 ssh2_pkt_addstring(ssh, algorithm);
4704 ssh2_pkt_addstring_start(ssh);
4705 ssh2_pkt_addstring_data(ssh, pub_blob, pub_blob_len);
4707 logevent("Offered public key"); /* FIXME */
4709 crWaitUntilV(ispkt);
4710 if (ssh->pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
4712 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
4713 continue; /* key refused; give up on it */
4716 logevent("Offer of public key accepted");
4718 * Actually attempt a serious authentication using
4721 if (ssh2_userkey_encrypted(cfg.keyfile, &comment)) {
4722 sprintf(s->pwprompt,
4723 "Passphrase for key \"%.100s\": ",
4729 c_write_str(ssh, "Authenticating with public key \"");
4730 c_write_str(ssh, comment);
4731 c_write_str(ssh, "\"\r\n");
4732 s->method = AUTH_PUBLICKEY_FILE;
4736 if (!s->method && s->can_keyb_inter && !s->tried_keyb_inter) {
4737 s->method = AUTH_KEYBOARD_INTERACTIVE;
4738 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4739 s->tried_keyb_inter = TRUE;
4741 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4742 ssh->pkt_ctx |= SSH2_PKTCTX_KBDINTER;
4744 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4745 ssh2_pkt_addstring(ssh, s->username);
4746 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4747 ssh2_pkt_addstring(ssh, "keyboard-interactive"); /* method */
4748 ssh2_pkt_addstring(ssh, ""); /* lang */
4749 ssh2_pkt_addstring(ssh, "");
4752 crWaitUntilV(ispkt);
4753 if (ssh->pktin.type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
4754 if (ssh->pktin.type == SSH2_MSG_USERAUTH_FAILURE)
4756 logevent("Keyboard-interactive authentication refused");
4757 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
4761 s->kbd_inter_running = TRUE;
4765 if (s->kbd_inter_running) {
4766 s->method = AUTH_KEYBOARD_INTERACTIVE;
4767 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4768 s->tried_keyb_inter = TRUE;
4770 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4771 ssh->pkt_ctx |= SSH2_PKTCTX_KBDINTER;
4773 if (s->curr_prompt == 0) {
4775 * We've got a fresh USERAUTH_INFO_REQUEST.
4776 * Display header data, and start going through
4779 char *name, *inst, *lang;
4780 int name_len, inst_len, lang_len;
4782 ssh2_pkt_getstring(ssh, &name, &name_len);
4783 ssh2_pkt_getstring(ssh, &inst, &inst_len);
4784 ssh2_pkt_getstring(ssh, &lang, &lang_len);
4786 c_write_untrusted(ssh, name, name_len);
4787 c_write_str(ssh, "\r\n");
4790 c_write_untrusted(ssh, inst, inst_len);
4791 c_write_str(ssh, "\r\n");
4793 s->num_prompts = ssh2_pkt_getuint32(ssh);
4797 * If there are prompts remaining in the packet,
4798 * display one and get a response.
4800 if (s->curr_prompt < s->num_prompts) {
4804 ssh2_pkt_getstring(ssh, &prompt, &prompt_len);
4805 if (prompt_len > 0) {
4806 strncpy(s->pwprompt, prompt, sizeof(s->pwprompt));
4807 s->pwprompt[prompt_len < sizeof(s->pwprompt) ?
4808 prompt_len : sizeof(s->pwprompt)-1] = '\0';
4811 "<server failed to send prompt>: ");
4813 s->echo = ssh2_pkt_getbool(ssh);
4819 if (!s->method && s->can_passwd) {
4820 s->method = AUTH_PASSWORD;
4821 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4822 ssh->pkt_ctx |= SSH2_PKTCTX_PASSWORD;
4823 sprintf(s->pwprompt, "%.90s@%.90s's password: ", s->username,
4830 if (!ssh_get_line(s->pwprompt, s->password,
4831 sizeof(s->password), TRUE)) {
4833 * get_line failed to get a password (for
4834 * example because one was supplied on the
4835 * command line which has already failed to
4838 ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
4839 ssh2_pkt_adduint32(ssh,SSH2_DISCONNECT_BY_APPLICATION);
4840 ssh2_pkt_addstring(ssh, "No more passwords available"
4842 ssh2_pkt_addstring(ssh, "en"); /* language tag */
4844 logevent("Unable to authenticate");
4845 connection_fatal(ssh->frontend,
4846 "Unable to authenticate");
4847 ssh->state = SSH_STATE_CLOSED;
4851 int ret; /* need not be saved across crReturn */
4852 c_write_untrusted(ssh, s->pwprompt, strlen(s->pwprompt));
4855 setup_userpass_input(ssh, s->password,
4856 sizeof(s->password), s->echo);
4858 crWaitUntilV(!ispkt);
4859 ret = process_userpass_input(ssh, in, inlen);
4863 c_write_str(ssh, "\r\n");
4867 if (s->method == AUTH_PUBLICKEY_FILE) {
4869 * We have our passphrase. Now try the actual authentication.
4871 struct ssh2_userkey *key;
4873 key = ssh2_load_userkey(cfg.keyfile, s->password);
4874 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
4875 if (key == SSH2_WRONG_PASSPHRASE) {
4876 c_write_str(ssh, "Wrong passphrase\r\n");
4877 s->tried_pubkey_config = FALSE;
4879 c_write_str(ssh, "Unable to load private key\r\n");
4880 s->tried_pubkey_config = TRUE;
4882 /* Send a spurious AUTH_NONE to return to the top. */
4883 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4884 ssh2_pkt_addstring(ssh, s->username);
4885 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4886 ssh2_pkt_addstring(ssh, "none"); /* method */
4888 s->type = AUTH_TYPE_NONE;
4890 unsigned char *pkblob, *sigblob, *sigdata;
4891 int pkblob_len, sigblob_len, sigdata_len;
4894 * We have loaded the private key and the server
4895 * has announced that it's willing to accept it.
4896 * Hallelujah. Generate a signature and send it.
4898 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4899 ssh2_pkt_addstring(ssh, s->username);
4900 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4901 ssh2_pkt_addstring(ssh, "publickey"); /* method */
4902 ssh2_pkt_addbool(ssh, TRUE);
4903 ssh2_pkt_addstring(ssh, key->alg->name);
4904 pkblob = key->alg->public_blob(key->data, &pkblob_len);
4905 ssh2_pkt_addstring_start(ssh);
4906 ssh2_pkt_addstring_data(ssh, pkblob, pkblob_len);
4909 * The data to be signed is:
4913 * followed by everything so far placed in the
4916 sigdata_len = ssh->pktout.length - 5 + 4 + 20;
4917 sigdata = smalloc(sigdata_len);
4918 PUT_32BIT(sigdata, 20);
4919 memcpy(sigdata + 4, ssh->v2_session_id, 20);
4920 memcpy(sigdata + 24, ssh->pktout.data + 5,
4921 ssh->pktout.length - 5);
4922 sigblob = key->alg->sign(key->data, sigdata,
4923 sigdata_len, &sigblob_len);
4924 ssh2_add_sigblob(ssh, pkblob, pkblob_len,
4925 sigblob, sigblob_len);
4931 s->type = AUTH_TYPE_PUBLICKEY;
4933 } else if (s->method == AUTH_PASSWORD) {
4935 * We send the password packet lumped tightly together with
4936 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
4937 * string long enough to make the total length of the two
4938 * packets constant. This should ensure that a passive
4939 * listener doing traffic analyis can't work out the length
4942 * For this to work, we need an assumption about the
4943 * maximum length of the password packet. I think 256 is
4944 * pretty conservative. Anyone using a password longer than
4945 * that probably doesn't have much to worry about from
4946 * people who find out how long their password is!
4948 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4949 ssh2_pkt_addstring(ssh, s->username);
4950 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4951 ssh2_pkt_addstring(ssh, "password");
4952 ssh2_pkt_addbool(ssh, FALSE);
4953 ssh2_pkt_addstring(ssh, s->password);
4954 ssh2_pkt_defer(ssh);
4956 * We'll include a string that's an exact multiple of the
4957 * cipher block size. If the cipher is NULL for some
4958 * reason, we don't do this trick at all because we gain
4961 if (ssh->cscipher) {
4964 stringlen = (256 - ssh->deferred_len);
4965 stringlen += ssh->cscipher->blksize - 1;
4966 stringlen -= (stringlen % ssh->cscipher->blksize);
4969 * Temporarily disable actual compression,
4970 * so we can guarantee to get this string
4971 * exactly the length we want it. The
4972 * compression-disabling routine should
4973 * return an integer indicating how many
4974 * bytes we should adjust our string length
4978 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
4980 ssh2_pkt_init(ssh, SSH2_MSG_IGNORE);
4981 ssh2_pkt_addstring_start(ssh);
4982 for (i = 0; i < stringlen; i++) {
4983 char c = (char) random_byte();
4984 ssh2_pkt_addstring_data(ssh, &c, 1);
4986 ssh2_pkt_defer(ssh);
4988 ssh_pkt_defersend(ssh);
4989 logevent("Sent password");
4990 s->type = AUTH_TYPE_PASSWORD;
4991 } else if (s->method == AUTH_KEYBOARD_INTERACTIVE) {
4992 if (s->curr_prompt == 0) {
4993 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_INFO_RESPONSE);
4994 ssh2_pkt_adduint32(ssh, s->num_prompts);
4996 if (s->need_pw) { /* only add pw if we just got one! */
4997 ssh2_pkt_addstring(ssh, s->password);
4998 memset(s->password, 0, sizeof(s->password));
5001 if (s->curr_prompt >= s->num_prompts) {
5005 * If there are prompts remaining, we set
5006 * `gotit' so that we won't attempt to get
5007 * another packet. Then we go back round the
5008 * loop and will end up retrieving another
5009 * prompt out of the existing packet. Funky or
5014 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
5016 c_write_str(ssh, "No supported authentication methods"
5017 " left to try!\r\n");
5018 logevent("No supported authentications offered."
5020 ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
5021 ssh2_pkt_adduint32(ssh, SSH2_DISCONNECT_BY_APPLICATION);
5022 ssh2_pkt_addstring(ssh, "No supported authentication"
5023 " methods available");
5024 ssh2_pkt_addstring(ssh, "en"); /* language tag */
5026 ssh->state = SSH_STATE_CLOSED;
5030 } while (!s->we_are_in);
5033 * Now we're authenticated for the connection protocol. The
5034 * connection protocol will automatically have started at this
5035 * point; there's no need to send SERVICE_REQUEST.
5039 * So now create a channel with a session in it.
5041 ssh->channels = newtree234(ssh_channelcmp);
5042 ssh->mainchan = smalloc(sizeof(struct ssh_channel));
5043 ssh->mainchan->ssh = ssh;
5044 ssh->mainchan->localid = alloc_channel_id(ssh);
5045 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_OPEN);
5046 ssh2_pkt_addstring(ssh, "session");
5047 ssh2_pkt_adduint32(ssh, ssh->mainchan->localid);
5048 ssh->mainchan->v.v2.locwindow = OUR_V2_WINSIZE;
5049 ssh2_pkt_adduint32(ssh, ssh->mainchan->v.v2.locwindow);/* our window size */
5050 ssh2_pkt_adduint32(ssh, 0x4000UL); /* our max pkt size */
5052 crWaitUntilV(ispkt);
5053 if (ssh->pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
5054 bombout((ssh,"Server refused to open a session"));
5056 /* FIXME: error data comes back in FAILURE packet */
5058 if (ssh2_pkt_getuint32(ssh) != ssh->mainchan->localid) {
5059 bombout((ssh,"Server's channel confirmation cited wrong channel"));
5062 ssh->mainchan->remoteid = ssh2_pkt_getuint32(ssh);
5063 ssh->mainchan->type = CHAN_MAINSESSION;
5064 ssh->mainchan->closes = 0;
5065 ssh->mainchan->v.v2.remwindow = ssh2_pkt_getuint32(ssh);
5066 ssh->mainchan->v.v2.remmaxpkt = ssh2_pkt_getuint32(ssh);
5067 bufchain_init(&ssh->mainchan->v.v2.outbuffer);
5068 add234(ssh->channels, ssh->mainchan);
5069 logevent("Opened channel for session");
5072 * Potentially enable X11 forwarding.
5074 if (cfg.x11_forward) {
5075 char proto[20], data[64];
5076 logevent("Requesting X11 forwarding");
5077 ssh->x11auth = x11_invent_auth(proto, sizeof(proto),
5078 data, sizeof(data));
5079 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
5080 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
5081 ssh2_pkt_addstring(ssh, "x11-req");
5082 ssh2_pkt_addbool(ssh, 1); /* want reply */
5083 ssh2_pkt_addbool(ssh, 0); /* many connections */
5084 ssh2_pkt_addstring(ssh, proto);
5085 ssh2_pkt_addstring(ssh, data);
5086 ssh2_pkt_adduint32(ssh, 0); /* screen number */
5090 crWaitUntilV(ispkt);
5091 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5092 unsigned i = ssh2_pkt_getuint32(ssh);
5093 struct ssh_channel *c;
5094 c = find234(ssh->channels, &i, ssh_channelfind);
5096 continue; /* nonexistent channel */
5097 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5099 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5101 if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5102 if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5103 bombout((ssh,"Unexpected response to X11 forwarding request:"
5104 " packet type %d", ssh->pktin.type));
5107 logevent("X11 forwarding refused");
5109 logevent("X11 forwarding enabled");
5110 ssh->X11_fwd_enabled = TRUE;
5115 * Enable port forwardings.
5120 int sport,dport,sserv,dserv;
5121 char sports[256], dports[256], host[256];
5125 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5126 /* Add port forwardings. */
5127 ssh->portfwd_strptr = cfg.portfwd;
5128 while (*ssh->portfwd_strptr) {
5129 type = *ssh->portfwd_strptr++;
5131 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != '\t')
5132 sports[n++] = *ssh->portfwd_strptr++;
5134 if (*ssh->portfwd_strptr == '\t')
5135 ssh->portfwd_strptr++;
5137 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != ':')
5138 host[n++] = *ssh->portfwd_strptr++;
5140 if (*ssh->portfwd_strptr == ':')
5141 ssh->portfwd_strptr++;
5143 while (*ssh->portfwd_strptr)
5144 dports[n++] = *ssh->portfwd_strptr++;
5146 ssh->portfwd_strptr++;
5147 dport = atoi(dports);
5151 se = getservbyname(dports, NULL);
5153 dport = ntohs(se->s_port);
5156 "Service lookup failed for destination port \"%s\"",
5161 sport = atoi(sports);
5165 se = getservbyname(sports, NULL);
5167 sport = ntohs(se->s_port);
5170 "Service lookup failed for source port \"%s\"",
5175 if (sport && dport) {
5177 pfd_addforward(host, dport, sport, ssh);
5178 sprintf(buf, "Local port %.*s%.*s%d%.*s forwarding to"
5179 " %s:%.*s%.*s%d%.*s",
5180 sserv ? strlen(sports) : 0, sports,
5181 sserv, "(", sport, sserv, ")",
5183 dserv ? strlen(dports) : 0, dports,
5184 dserv, "(", dport, dserv, ")");
5187 struct ssh_rportfwd *pf;
5188 pf = smalloc(sizeof(*pf));
5189 strcpy(pf->dhost, host);
5192 if (add234(ssh->rportfwds, pf) != pf) {
5194 "Duplicate remote port forwarding to %s:%d",
5199 sprintf(buf, "Requesting remote port %.*s%.*s%d%.*s"
5200 " forward to %s:%.*s%.*s%d%.*s",
5201 sserv ? strlen(sports) : 0, sports,
5202 sserv, "(", sport, sserv, ")",
5204 dserv ? strlen(dports) : 0, dports,
5205 dserv, "(", dport, dserv, ")");
5207 ssh2_pkt_init(ssh, SSH2_MSG_GLOBAL_REQUEST);
5208 ssh2_pkt_addstring(ssh, "tcpip-forward");
5209 ssh2_pkt_addbool(ssh, 1);/* want reply */
5210 if (cfg.rport_acceptall)
5211 ssh2_pkt_addstring(ssh, "0.0.0.0");
5213 ssh2_pkt_addstring(ssh, "127.0.0.1");
5214 ssh2_pkt_adduint32(ssh, sport);
5218 crWaitUntilV(ispkt);
5219 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5220 unsigned i = ssh2_pkt_getuint32(ssh);
5221 struct ssh_channel *c;
5222 c = find234(ssh->channels, &i, ssh_channelfind);
5224 continue;/* nonexistent channel */
5225 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5227 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5229 if (ssh->pktin.type != SSH2_MSG_REQUEST_SUCCESS) {
5230 if (ssh->pktin.type != SSH2_MSG_REQUEST_FAILURE) {
5231 bombout((ssh,"Unexpected response to port "
5232 "forwarding request: packet type %d",
5236 logevent("Server refused this port forwarding");
5238 logevent("Remote port forwarding enabled");
5247 * Potentially enable agent forwarding.
5249 if (cfg.agentfwd && agent_exists()) {
5250 logevent("Requesting OpenSSH-style agent forwarding");
5251 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
5252 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
5253 ssh2_pkt_addstring(ssh, "auth-agent-req@openssh.com");
5254 ssh2_pkt_addbool(ssh, 1); /* want reply */
5258 crWaitUntilV(ispkt);
5259 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5260 unsigned i = ssh2_pkt_getuint32(ssh);
5261 struct ssh_channel *c;
5262 c = find234(ssh->channels, &i, ssh_channelfind);
5264 continue; /* nonexistent channel */
5265 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5267 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5269 if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5270 if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5271 bombout((ssh,"Unexpected response to agent forwarding request:"
5272 " packet type %d", ssh->pktin.type));
5275 logevent("Agent forwarding refused");
5277 logevent("Agent forwarding enabled");
5278 ssh->agentfwd_enabled = TRUE;
5283 * Now allocate a pty for the session.
5286 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
5287 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid); /* recipient channel */
5288 ssh2_pkt_addstring(ssh, "pty-req");
5289 ssh2_pkt_addbool(ssh, 1); /* want reply */
5290 ssh2_pkt_addstring(ssh, cfg.termtype);
5291 ssh2_pkt_adduint32(ssh, ssh->term_width);
5292 ssh2_pkt_adduint32(ssh, ssh->term_height);
5293 ssh2_pkt_adduint32(ssh, 0); /* pixel width */
5294 ssh2_pkt_adduint32(ssh, 0); /* pixel height */
5295 ssh2_pkt_addstring_start(ssh);
5296 ssh2_pkt_addstring_data(ssh, "\0", 1); /* TTY_OP_END, no special options */
5298 ssh->state = SSH_STATE_INTERMED;
5301 crWaitUntilV(ispkt);
5302 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5303 unsigned i = ssh2_pkt_getuint32(ssh);
5304 struct ssh_channel *c;
5305 c = find234(ssh->channels, &i, ssh_channelfind);
5307 continue; /* nonexistent channel */
5308 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5310 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5312 if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5313 if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5314 bombout((ssh,"Unexpected response to pty request:"
5315 " packet type %d", ssh->pktin.type));
5318 c_write_str(ssh, "Server refused to allocate pty\r\n");
5319 ssh->editing = ssh->echoing = 1;
5321 logevent("Allocated pty");
5324 ssh->editing = ssh->echoing = 1;
5328 * Start a shell or a remote command. We may have to attempt
5329 * this twice if the config data has provided a second choice
5336 if (ssh->fallback_cmd) {
5337 subsys = cfg.ssh_subsys2;
5338 cmd = cfg.remote_cmd_ptr2;
5340 subsys = cfg.ssh_subsys;
5341 cmd = cfg.remote_cmd_ptr;
5344 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
5345 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid); /* recipient channel */
5347 ssh2_pkt_addstring(ssh, "subsystem");
5348 ssh2_pkt_addbool(ssh, 1); /* want reply */
5349 ssh2_pkt_addstring(ssh, cmd);
5351 ssh2_pkt_addstring(ssh, "exec");
5352 ssh2_pkt_addbool(ssh, 1); /* want reply */
5353 ssh2_pkt_addstring(ssh, cmd);
5355 ssh2_pkt_addstring(ssh, "shell");
5356 ssh2_pkt_addbool(ssh, 1); /* want reply */
5360 crWaitUntilV(ispkt);
5361 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5362 unsigned i = ssh2_pkt_getuint32(ssh);
5363 struct ssh_channel *c;
5364 c = find234(ssh->channels, &i, ssh_channelfind);
5366 continue; /* nonexistent channel */
5367 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5369 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5370 if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5371 if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5372 bombout((ssh,"Unexpected response to shell/command request:"
5373 " packet type %d", ssh->pktin.type));
5377 * We failed to start the command. If this is the
5378 * fallback command, we really are finished; if it's
5379 * not, and if the fallback command exists, try falling
5380 * back to it before complaining.
5382 if (!ssh->fallback_cmd && cfg.remote_cmd_ptr2 != NULL) {
5383 logevent("Primary command failed; attempting fallback");
5384 ssh->fallback_cmd = TRUE;
5387 bombout((ssh,"Server refused to start a shell/command"));
5390 logevent("Started a shell/command");
5395 ssh->state = SSH_STATE_SESSION;
5396 if (ssh->size_needed)
5397 ssh_size(ssh, ssh->term_width, ssh->term_height);
5398 if (ssh->eof_needed)
5399 ssh_special(ssh, TS_EOF);
5405 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
5409 s->try_send = FALSE;
5411 if (ssh->pktin.type == SSH2_MSG_CHANNEL_DATA ||
5412 ssh->pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
5415 unsigned i = ssh2_pkt_getuint32(ssh);
5416 struct ssh_channel *c;
5417 c = find234(ssh->channels, &i, ssh_channelfind);
5419 continue; /* nonexistent channel */
5420 if (ssh->pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
5421 ssh2_pkt_getuint32(ssh) != SSH2_EXTENDED_DATA_STDERR)
5422 continue; /* extended but not stderr */
5423 ssh2_pkt_getstring(ssh, &data, &length);
5426 c->v.v2.locwindow -= length;
5428 case CHAN_MAINSESSION:
5430 from_backend(ssh->frontend, ssh->pktin.type ==
5431 SSH2_MSG_CHANNEL_EXTENDED_DATA,
5435 bufsize = x11_send(c->u.x11.s, data, length);
5438 bufsize = pfd_send(c->u.pfd.s, data, length);
5441 while (length > 0) {
5442 if (c->u.a.lensofar < 4) {
5443 int l = min(4 - c->u.a.lensofar, length);
5444 memcpy(c->u.a.msglen + c->u.a.lensofar,
5448 c->u.a.lensofar += l;
5450 if (c->u.a.lensofar == 4) {
5452 4 + GET_32BIT(c->u.a.msglen);
5453 c->u.a.message = smalloc(c->u.a.totallen);
5454 memcpy(c->u.a.message, c->u.a.msglen, 4);
5456 if (c->u.a.lensofar >= 4 && length > 0) {
5458 min(c->u.a.totallen - c->u.a.lensofar,
5460 memcpy(c->u.a.message + c->u.a.lensofar,
5464 c->u.a.lensofar += l;
5466 if (c->u.a.lensofar == c->u.a.totallen) {
5467 void *reply, *sentreply;
5469 agent_query(c->u.a.message,
5470 c->u.a.totallen, &reply,
5475 /* Fake SSH_AGENT_FAILURE. */
5476 sentreply = "\0\0\0\1\5";
5479 ssh2_add_channel_data(c, sentreply, replylen);
5483 sfree(c->u.a.message);
5484 c->u.a.lensofar = 0;
5491 * If we are not buffering too much data,
5492 * enlarge the window again at the remote side.
5494 if (bufsize < OUR_V2_WINSIZE)
5495 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
5497 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_EOF) {
5498 unsigned i = ssh2_pkt_getuint32(ssh);
5499 struct ssh_channel *c;
5501 c = find234(ssh->channels, &i, ssh_channelfind);
5503 continue; /* nonexistent channel */
5505 if (c->type == CHAN_X11) {
5507 * Remote EOF on an X11 channel means we should
5508 * wrap up and close the channel ourselves.
5510 x11_close(c->u.x11.s);
5512 } else if (c->type == CHAN_AGENT) {
5514 } else if (c->type == CHAN_SOCKDATA) {
5515 pfd_close(c->u.pfd.s);
5518 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
5519 unsigned i = ssh2_pkt_getuint32(ssh);
5520 struct ssh_channel *c;
5522 c = find234(ssh->channels, &i, ssh_channelfind);
5523 if (!c || ((int)c->remoteid) == -1) {
5524 bombout((ssh,"Received CHANNEL_CLOSE for %s channel %d\n",
5525 c ? "half-open" : "nonexistent", i));
5527 /* Do pre-close processing on the channel. */
5529 case CHAN_MAINSESSION:
5530 break; /* nothing to see here, move along */
5532 if (c->u.x11.s != NULL)
5533 x11_close(c->u.x11.s);
5540 if (c->u.pfd.s != NULL)
5541 pfd_close(c->u.pfd.s);
5545 if (c->closes == 0) {
5546 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_CLOSE);
5547 ssh2_pkt_adduint32(ssh, c->remoteid);
5550 del234(ssh->channels, c);
5551 bufchain_clear(&c->v.v2.outbuffer);
5555 * See if that was the last channel left open.
5557 if (count234(ssh->channels) == 0) {
5560 * We used to send SSH_MSG_DISCONNECT here,
5561 * because I'd believed that _every_ conforming
5562 * SSH2 connection had to end with a disconnect
5563 * being sent by at least one side; apparently
5564 * I was wrong and it's perfectly OK to
5565 * unceremoniously slam the connection shut
5566 * when you're done, and indeed OpenSSH feels
5567 * this is more polite than sending a
5568 * DISCONNECT. So now we don't.
5570 logevent("All channels closed. Disconnecting");
5571 ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
5572 ssh2_pkt_adduint32(ssh, SSH2_DISCONNECT_BY_APPLICATION);
5573 ssh2_pkt_addstring(ssh, "All open channels closed");
5574 ssh2_pkt_addstring(ssh, "en"); /* language tag */
5577 ssh->state = SSH_STATE_CLOSED;
5580 continue; /* remote sends close; ignore (FIXME) */
5581 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5582 unsigned i = ssh2_pkt_getuint32(ssh);
5583 struct ssh_channel *c;
5584 c = find234(ssh->channels, &i, ssh_channelfind);
5586 continue; /* nonexistent channel */
5587 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5589 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
5590 unsigned i = ssh2_pkt_getuint32(ssh);
5591 struct ssh_channel *c;
5592 c = find234(ssh->channels, &i, ssh_channelfind);
5594 continue; /* nonexistent channel */
5595 if (c->type != CHAN_SOCKDATA_DORMANT)
5596 continue; /* dunno why they're confirming this */
5597 c->remoteid = ssh2_pkt_getuint32(ssh);
5598 c->type = CHAN_SOCKDATA;
5599 c->v.v2.remwindow = ssh2_pkt_getuint32(ssh);
5600 c->v.v2.remmaxpkt = ssh2_pkt_getuint32(ssh);
5602 pfd_confirm(c->u.pfd.s);
5605 * We have a pending close on this channel,
5606 * which we decided on before the server acked
5607 * the channel open. So now we know the
5608 * remoteid, we can close it again.
5610 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_CLOSE);
5611 ssh2_pkt_adduint32(ssh, c->remoteid);
5614 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_OPEN_FAILURE) {
5615 unsigned i = ssh2_pkt_getuint32(ssh);
5616 struct ssh_channel *c;
5617 c = find234(ssh->channels, &i, ssh_channelfind);
5619 continue; /* nonexistent channel */
5620 if (c->type != CHAN_SOCKDATA_DORMANT)
5621 continue; /* dunno why they're failing this */
5623 logevent("Forwarded connection refused by server");
5625 pfd_close(c->u.pfd.s);
5627 del234(ssh->channels, c);
5629 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
5632 int typelen, want_reply;
5633 struct ssh_channel *c;
5635 localid = ssh2_pkt_getuint32(ssh);
5636 ssh2_pkt_getstring(ssh, &type, &typelen);
5637 want_reply = ssh2_pkt_getbool(ssh);
5640 * First, check that the channel exists. Otherwise,
5641 * we can instantly disconnect with a rude message.
5643 c = find234(ssh->channels, &localid, ssh_channelfind);
5646 sprintf(buf, "Received channel request for nonexistent"
5647 " channel %d", localid);
5649 ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
5650 ssh2_pkt_adduint32(ssh, SSH2_DISCONNECT_BY_APPLICATION);
5651 ssh2_pkt_addstring(ssh, buf);
5652 ssh2_pkt_addstring(ssh, "en"); /* language tag */
5654 connection_fatal("%s", buf);
5655 ssh->state = SSH_STATE_CLOSED;
5660 * Having got the channel number, we now look at
5661 * the request type string to see if it's something
5664 if (typelen == 11 && !memcmp(type, "exit-status", 11) &&
5665 c == ssh->mainchan) {
5666 /* We recognise "exit-status" on the primary channel. */
5668 ssh->exitcode = ssh2_pkt_getuint32(ssh);
5669 sprintf(buf, "Server sent command exit status %d",
5673 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_SUCCESS);
5674 ssh2_pkt_adduint32(ssh, c->remoteid);
5679 * This is a channel request we don't know
5680 * about, so we now either ignore the request
5681 * or respond with CHANNEL_FAILURE, depending
5685 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_FAILURE);
5686 ssh2_pkt_adduint32(ssh, c->remoteid);
5690 } else if (ssh->pktin.type == SSH2_MSG_GLOBAL_REQUEST) {
5692 int typelen, want_reply;
5694 ssh2_pkt_getstring(ssh, &type, &typelen);
5695 want_reply = ssh2_pkt_getbool(ssh);
5698 * We currently don't support any global requests
5699 * at all, so we either ignore the request or
5700 * respond with REQUEST_FAILURE, depending on
5704 ssh2_pkt_init(ssh, SSH2_MSG_REQUEST_FAILURE);
5707 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_OPEN) {
5711 struct ssh_channel *c;
5712 unsigned remid, winsize, pktsize;
5713 ssh2_pkt_getstring(ssh, &type, &typelen);
5714 c = smalloc(sizeof(struct ssh_channel));
5717 remid = ssh2_pkt_getuint32(ssh);
5718 winsize = ssh2_pkt_getuint32(ssh);
5719 pktsize = ssh2_pkt_getuint32(ssh);
5721 if (typelen == 3 && !memcmp(type, "x11", 3)) {
5722 if (!ssh->X11_fwd_enabled)
5723 error = "X11 forwarding is not enabled";
5724 else if (x11_init(&c->u.x11.s, cfg.x11_display, c,
5725 ssh->x11auth) != NULL) {
5726 error = "Unable to open an X11 connection";
5730 } else if (typelen == 15 &&
5731 !memcmp(type, "forwarded-tcpip", 15)) {
5732 struct ssh_rportfwd pf, *realpf;
5735 ssh2_pkt_getstring(ssh, &dummy, &dummylen);/* skip address */
5736 pf.sport = ssh2_pkt_getuint32(ssh);
5737 realpf = find234(ssh->rportfwds, &pf, NULL);
5738 if (realpf == NULL) {
5739 error = "Remote port is not recognised";
5741 char *e = pfd_newconnect(&c->u.pfd.s, realpf->dhost,
5744 sprintf(buf, "Received remote port open request for %s:%d",
5745 realpf->dhost, realpf->dport);
5748 sprintf(buf, "Port open failed: %s", e);
5750 error = "Port open failed";
5752 logevent("Forwarded port opened successfully");
5753 c->type = CHAN_SOCKDATA;
5756 } else if (typelen == 22 &&
5757 !memcmp(type, "auth-agent@openssh.com", 3)) {
5758 if (!ssh->agentfwd_enabled)
5759 error = "Agent forwarding is not enabled";
5761 c->type = CHAN_AGENT; /* identify channel type */
5762 c->u.a.lensofar = 0;
5765 error = "Unsupported channel type requested";
5768 c->remoteid = remid;
5770 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE);
5771 ssh2_pkt_adduint32(ssh, c->remoteid);
5772 ssh2_pkt_adduint32(ssh, SSH2_OPEN_CONNECT_FAILED);
5773 ssh2_pkt_addstring(ssh, error);
5774 ssh2_pkt_addstring(ssh, "en"); /* language tag */
5778 c->localid = alloc_channel_id(ssh);
5780 c->v.v2.locwindow = OUR_V2_WINSIZE;
5781 c->v.v2.remwindow = winsize;
5782 c->v.v2.remmaxpkt = pktsize;
5783 bufchain_init(&c->v.v2.outbuffer);
5784 add234(ssh->channels, c);
5785 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
5786 ssh2_pkt_adduint32(ssh, c->remoteid);
5787 ssh2_pkt_adduint32(ssh, c->localid);
5788 ssh2_pkt_adduint32(ssh, c->v.v2.locwindow);
5789 ssh2_pkt_adduint32(ssh, 0x4000UL); /* our max pkt size */
5793 bombout((ssh,"Strange packet received: type %d", ssh->pktin.type));
5798 * We have spare data. Add it to the channel buffer.
5800 ssh2_add_channel_data(ssh->mainchan, in, inlen);
5805 struct ssh_channel *c;
5807 * Try to send data on all channels if we can.
5809 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
5810 int bufsize = ssh2_try_send(c);
5813 case CHAN_MAINSESSION:
5814 /* stdin need not receive an unthrottle
5815 * notification since it will be polled */
5818 x11_unthrottle(c->u.x11.s);
5821 /* agent sockets are request/response and need no
5822 * buffer management */
5825 pfd_unthrottle(c->u.pfd.s);
5837 * Handle the top-level SSH2 protocol.
5839 static void ssh2_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
5841 if (do_ssh2_transport(ssh, in, inlen, ispkt) == 0)
5843 do_ssh2_authconn(ssh, in, inlen, ispkt);
5847 * Called to set up the connection.
5849 * Returns an error message, or NULL on success.
5851 static char *ssh_init(void *frontend_handle, void **backend_handle,
5852 char *host, int port, char **realhost, int nodelay)
5857 ssh = smalloc(sizeof(*ssh));
5860 ssh->v1_cipher_ctx = NULL;
5861 ssh->crcda_ctx = NULL;
5862 ssh->cscipher = NULL;
5863 ssh->cs_cipher_ctx = NULL;
5864 ssh->sccipher = NULL;
5865 ssh->sc_cipher_ctx = NULL;
5867 ssh->cs_mac_ctx = NULL;
5869 ssh->sc_mac_ctx = NULL;
5871 ssh->cs_comp_ctx = NULL;
5873 ssh->sc_comp_ctx = NULL;
5875 ssh->hostkey = NULL;
5877 ssh->state = SSH_STATE_PREPACKET;
5878 ssh->size_needed = FALSE;
5879 ssh->eof_needed = FALSE;
5883 static const struct Packet empty = { 0, 0, NULL, NULL, 0 };
5884 ssh->pktin = ssh->pktout = empty;
5886 ssh->deferred_send_data = NULL;
5887 ssh->deferred_len = 0;
5888 ssh->deferred_size = 0;
5889 ssh->fallback_cmd = 0;
5891 ssh->x11auth = NULL;
5892 ssh->v2_outgoing_sequence = 0;
5893 ssh->ssh1_rdpkt_crstate = 0;
5894 ssh->ssh2_rdpkt_crstate = 0;
5895 ssh->do_ssh_init_crstate = 0;
5896 ssh->ssh_gotdata_crstate = 0;
5897 ssh->ssh1_protocol_crstate = 0;
5898 ssh->do_ssh1_login_crstate = 0;
5899 ssh->do_ssh2_transport_crstate = 0;
5900 ssh->do_ssh2_authconn_crstate = 0;
5901 ssh->do_ssh_init_state = NULL;
5902 ssh->do_ssh1_login_state = NULL;
5903 ssh->do_ssh2_transport_state = NULL;
5904 ssh->do_ssh2_authconn_state = NULL;
5906 *backend_handle = ssh;
5909 if (crypto_startup() == 0)
5910 return "Microsoft high encryption pack not installed!";
5913 ssh->frontend = frontend_handle;
5914 ssh->term_width = cfg.width;
5915 ssh->term_height = cfg.height;
5920 ssh->v1_throttle_count = 0;
5921 ssh->overall_bufsize = 0;
5922 ssh->fallback_cmd = 0;
5924 p = connect_to_host(ssh, host, port, realhost, nodelay);
5932 * Called to send data down the Telnet connection.
5934 static int ssh_send(void *handle, char *buf, int len)
5936 Ssh ssh = (Ssh) handle;
5938 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
5941 ssh->protocol(ssh, buf, len, 0);
5943 return ssh_sendbuffer(ssh);
5947 * Called to query the current amount of buffered stdin data.
5949 static int ssh_sendbuffer(void *handle)
5951 Ssh ssh = (Ssh) handle;
5954 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
5958 * If the SSH socket itself has backed up, add the total backup
5959 * size on that to any individual buffer on the stdin channel.
5962 if (ssh->throttled_all)
5963 override_value = ssh->overall_bufsize;
5965 if (ssh->version == 1) {
5966 return override_value;
5967 } else if (ssh->version == 2) {
5968 if (!ssh->mainchan || ssh->mainchan->closes > 0)
5969 return override_value;
5971 return (override_value +
5972 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
5979 * Called to set the size of the window from SSH's POV.
5981 static void ssh_size(void *handle, int width, int height)
5983 Ssh ssh = (Ssh) handle;
5985 ssh->term_width = width;
5986 ssh->term_height = height;
5988 switch (ssh->state) {
5989 case SSH_STATE_BEFORE_SIZE:
5990 case SSH_STATE_PREPACKET:
5991 case SSH_STATE_CLOSED:
5992 break; /* do nothing */
5993 case SSH_STATE_INTERMED:
5994 ssh->size_needed = TRUE; /* buffer for later */
5996 case SSH_STATE_SESSION:
5998 if (ssh->version == 1) {
5999 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
6000 PKT_INT, ssh->term_height,
6001 PKT_INT, ssh->term_width,
6002 PKT_INT, 0, PKT_INT, 0, PKT_END);
6004 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
6005 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
6006 ssh2_pkt_addstring(ssh, "window-change");
6007 ssh2_pkt_addbool(ssh, 0);
6008 ssh2_pkt_adduint32(ssh, ssh->term_width);
6009 ssh2_pkt_adduint32(ssh, ssh->term_height);
6010 ssh2_pkt_adduint32(ssh, 0);
6011 ssh2_pkt_adduint32(ssh, 0);
6020 * Send Telnet special codes. TS_EOF is useful for `plink', so you
6021 * can send an EOF and collect resulting output (e.g. `plink
6024 static void ssh_special(void *handle, Telnet_Special code)
6026 Ssh ssh = (Ssh) handle;
6028 if (code == TS_EOF) {
6029 if (ssh->state != SSH_STATE_SESSION) {
6031 * Buffer the EOF in case we are pre-SESSION, so we can
6032 * send it as soon as we reach SESSION.
6035 ssh->eof_needed = TRUE;
6038 if (ssh->version == 1) {
6039 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
6041 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_EOF);
6042 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
6045 logevent("Sent EOF message");
6046 } else if (code == TS_PING) {
6047 if (ssh->state == SSH_STATE_CLOSED
6048 || ssh->state == SSH_STATE_PREPACKET) return;
6049 if (ssh->version == 1) {
6050 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
6051 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
6053 ssh2_pkt_init(ssh, SSH2_MSG_IGNORE);
6054 ssh2_pkt_addstring_start(ssh);
6062 void *new_sock_channel(void *handle, Socket s)
6064 Ssh ssh = (Ssh) handle;
6065 struct ssh_channel *c;
6066 c = smalloc(sizeof(struct ssh_channel));
6070 c->remoteid = -1; /* to be set when open confirmed */
6071 c->localid = alloc_channel_id(ssh);
6073 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
6075 bufchain_init(&c->v.v2.outbuffer);
6076 add234(ssh->channels, c);
6082 * This is called when stdout/stderr (the entity to which
6083 * from_backend sends data) manages to clear some backlog.
6085 void ssh_unthrottle(void *handle, int bufsize)
6087 Ssh ssh = (Ssh) handle;
6088 if (ssh->version == 1) {
6089 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
6090 ssh->v1_stdout_throttling = 0;
6091 ssh1_throttle(ssh, -1);
6094 if (ssh->mainchan && ssh->mainchan->closes == 0)
6095 ssh2_set_window(ssh->mainchan, OUR_V2_WINSIZE - bufsize);
6099 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
6101 struct ssh_channel *c = (struct ssh_channel *)channel;
6105 sprintf(buf, "Opening forwarded connection to %.512s:%d", hostname, port);
6108 if (ssh->version == 1) {
6109 send_packet(ssh, SSH1_MSG_PORT_OPEN,
6110 PKT_INT, c->localid,
6113 //PKT_STR, <org:orgport>,
6116 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_OPEN);
6117 ssh2_pkt_addstring(ssh, "direct-tcpip");
6118 ssh2_pkt_adduint32(ssh, c->localid);
6119 c->v.v2.locwindow = OUR_V2_WINSIZE;
6120 ssh2_pkt_adduint32(ssh, c->v.v2.locwindow);/* our window size */
6121 ssh2_pkt_adduint32(ssh, 0x4000UL); /* our max pkt size */
6122 ssh2_pkt_addstring(ssh, hostname);
6123 ssh2_pkt_adduint32(ssh, port);
6125 * We make up values for the originator data; partly it's
6126 * too much hassle to keep track, and partly I'm not
6127 * convinced the server should be told details like that
6128 * about my local network configuration.
6130 ssh2_pkt_addstring(ssh, "client-side-connection");
6131 ssh2_pkt_adduint32(ssh, 0);
6137 static Socket ssh_socket(void *handle)
6139 Ssh ssh = (Ssh) handle;
6143 static int ssh_sendok(void *handle)
6145 Ssh ssh = (Ssh) handle;
6146 return ssh->send_ok;
6149 static int ssh_ldisc(void *handle, int option)
6151 Ssh ssh = (Ssh) handle;
6152 if (option == LD_ECHO)
6153 return ssh->echoing;
6154 if (option == LD_EDIT)
6155 return ssh->editing;
6159 static void ssh_provide_ldisc(void *handle, void *ldisc)
6161 Ssh ssh = (Ssh) handle;
6165 static void ssh_provide_logctx(void *handle, void *logctx)
6167 Ssh ssh = (Ssh) handle;
6168 ssh->logctx = logctx;
6171 static int ssh_return_exitcode(void *handle)
6173 Ssh ssh = (Ssh) handle;
6174 return ssh->exitcode;
6178 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
6179 * that fails. This variable is the means by which scp.c can reach
6180 * into the SSH code and find out which one it got.
6182 extern int ssh_fallback_cmd(void *handle)
6184 Ssh ssh = (Ssh) handle;
6185 return ssh->fallback_cmd;
6188 Backend ssh_backend = {
6195 ssh_return_exitcode,