18 #define logevent(s) { logevent(s); \
19 if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)) \
20 { fprintf(stderr, "%s\n", s); fflush(stderr); } }
22 /* logevent, only printf-formatted. */
23 void logeventf(char *fmt, ...)
29 vsprintf(stuff, fmt, ap);
34 #define bombout(msg) ( ssh->state = SSH_STATE_CLOSED, \
35 (ssh->s ? sk_close(ssh->s), ssh->s = NULL : 0), \
36 logeventf msg, connection_fatal msg )
38 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
39 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
40 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
41 #define SSH1_CMSG_USER 4 /* 0x4 */
42 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
43 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
44 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
45 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
46 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
47 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
48 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
49 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
50 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
51 #define SSH1_SMSG_FAILURE 15 /* 0xf */
52 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
53 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
54 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
55 #define SSH1_CMSG_EOF 19 /* 0x13 */
56 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
57 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
58 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
59 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
60 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
61 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
62 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
63 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
64 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
65 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
66 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
67 #define SSH1_MSG_IGNORE 32 /* 0x20 */
68 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
69 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
70 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
71 #define SSH1_MSG_DEBUG 36 /* 0x24 */
72 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
73 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
74 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
75 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
76 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
77 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
78 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
80 #define SSH1_AUTH_TIS 5 /* 0x5 */
81 #define SSH1_AUTH_CCARD 16 /* 0x10 */
83 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
84 /* Mask for protoflags we will echo back to server if seen */
85 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
87 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
88 #define SSH2_MSG_IGNORE 2 /* 0x2 */
89 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
90 #define SSH2_MSG_DEBUG 4 /* 0x4 */
91 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
92 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
93 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
94 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
95 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
96 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
97 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
98 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
99 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
100 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
101 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
102 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
103 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
104 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
105 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
106 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
107 #define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */
108 #define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */
109 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
110 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
111 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
112 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
113 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
114 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
115 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
116 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
117 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
118 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
119 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
120 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
121 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
122 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
125 * Packet type contexts, so that ssh2_pkt_type can correctly decode
126 * the ambiguous type numbers back into the correct type strings.
128 #define SSH2_PKTCTX_DHGROUP1 0x0001
129 #define SSH2_PKTCTX_DHGEX 0x0002
130 #define SSH2_PKTCTX_PUBLICKEY 0x0010
131 #define SSH2_PKTCTX_PASSWORD 0x0020
132 #define SSH2_PKTCTX_KBDINTER 0x0040
133 #define SSH2_PKTCTX_AUTH_MASK 0x00F0
135 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
136 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
137 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
138 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
139 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
140 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
141 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
142 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
143 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
144 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
145 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
146 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
147 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
148 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
149 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
151 static const char *const ssh2_disconnect_reasons[] = {
153 "SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT",
154 "SSH_DISCONNECT_PROTOCOL_ERROR",
155 "SSH_DISCONNECT_KEY_EXCHANGE_FAILED",
156 "SSH_DISCONNECT_HOST_AUTHENTICATION_FAILED",
157 "SSH_DISCONNECT_MAC_ERROR",
158 "SSH_DISCONNECT_COMPRESSION_ERROR",
159 "SSH_DISCONNECT_SERVICE_NOT_AVAILABLE",
160 "SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED",
161 "SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE",
162 "SSH_DISCONNECT_CONNECTION_LOST",
163 "SSH_DISCONNECT_BY_APPLICATION",
164 "SSH_DISCONNECT_TOO_MANY_CONNECTIONS",
165 "SSH_DISCONNECT_AUTH_CANCELLED_BY_USER",
166 "SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE",
167 "SSH_DISCONNECT_ILLEGAL_USER_NAME",
170 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
171 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
172 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
173 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
175 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
178 * Various remote-bug flags.
180 #define BUG_CHOKES_ON_SSH1_IGNORE 1
181 #define BUG_SSH2_HMAC 2
182 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
183 #define BUG_CHOKES_ON_RSA 8
184 #define BUG_SSH2_RSA_PADDING 16
185 #define BUG_SSH2_DERIVEKEY 32
186 #define BUG_SSH2_DH_GEX 64
188 #define translate(x) if (type == x) return #x
189 #define translatec(x,ctx) if (type == x && (pkt_ctx & ctx)) return #x
190 char *ssh1_pkt_type(int type)
192 translate(SSH1_MSG_DISCONNECT);
193 translate(SSH1_SMSG_PUBLIC_KEY);
194 translate(SSH1_CMSG_SESSION_KEY);
195 translate(SSH1_CMSG_USER);
196 translate(SSH1_CMSG_AUTH_RSA);
197 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
198 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
199 translate(SSH1_CMSG_AUTH_PASSWORD);
200 translate(SSH1_CMSG_REQUEST_PTY);
201 translate(SSH1_CMSG_WINDOW_SIZE);
202 translate(SSH1_CMSG_EXEC_SHELL);
203 translate(SSH1_CMSG_EXEC_CMD);
204 translate(SSH1_SMSG_SUCCESS);
205 translate(SSH1_SMSG_FAILURE);
206 translate(SSH1_CMSG_STDIN_DATA);
207 translate(SSH1_SMSG_STDOUT_DATA);
208 translate(SSH1_SMSG_STDERR_DATA);
209 translate(SSH1_CMSG_EOF);
210 translate(SSH1_SMSG_EXIT_STATUS);
211 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
212 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
213 translate(SSH1_MSG_CHANNEL_DATA);
214 translate(SSH1_MSG_CHANNEL_CLOSE);
215 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
216 translate(SSH1_SMSG_X11_OPEN);
217 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
218 translate(SSH1_MSG_PORT_OPEN);
219 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
220 translate(SSH1_SMSG_AGENT_OPEN);
221 translate(SSH1_MSG_IGNORE);
222 translate(SSH1_CMSG_EXIT_CONFIRMATION);
223 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
224 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
225 translate(SSH1_MSG_DEBUG);
226 translate(SSH1_CMSG_REQUEST_COMPRESSION);
227 translate(SSH1_CMSG_AUTH_TIS);
228 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
229 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
230 translate(SSH1_CMSG_AUTH_CCARD);
231 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
232 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
235 char *ssh2_pkt_type(int pkt_ctx, int type)
237 translate(SSH2_MSG_DISCONNECT);
238 translate(SSH2_MSG_IGNORE);
239 translate(SSH2_MSG_UNIMPLEMENTED);
240 translate(SSH2_MSG_DEBUG);
241 translate(SSH2_MSG_SERVICE_REQUEST);
242 translate(SSH2_MSG_SERVICE_ACCEPT);
243 translate(SSH2_MSG_KEXINIT);
244 translate(SSH2_MSG_NEWKEYS);
245 translatec(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP1);
246 translatec(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP1);
247 translatec(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
248 translatec(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
249 translatec(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
250 translatec(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
251 translate(SSH2_MSG_USERAUTH_REQUEST);
252 translate(SSH2_MSG_USERAUTH_FAILURE);
253 translate(SSH2_MSG_USERAUTH_SUCCESS);
254 translate(SSH2_MSG_USERAUTH_BANNER);
255 translatec(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
256 translatec(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
257 translatec(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
258 translatec(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
259 translate(SSH2_MSG_GLOBAL_REQUEST);
260 translate(SSH2_MSG_REQUEST_SUCCESS);
261 translate(SSH2_MSG_REQUEST_FAILURE);
262 translate(SSH2_MSG_CHANNEL_OPEN);
263 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
264 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
265 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
266 translate(SSH2_MSG_CHANNEL_DATA);
267 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
268 translate(SSH2_MSG_CHANNEL_EOF);
269 translate(SSH2_MSG_CHANNEL_CLOSE);
270 translate(SSH2_MSG_CHANNEL_REQUEST);
271 translate(SSH2_MSG_CHANNEL_SUCCESS);
272 translate(SSH2_MSG_CHANNEL_FAILURE);
278 #define GET_32BIT(cp) \
279 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
280 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
281 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
282 ((unsigned long)(unsigned char)(cp)[3]))
284 #define PUT_32BIT(cp, value) { \
285 (cp)[0] = (unsigned char)((value) >> 24); \
286 (cp)[1] = (unsigned char)((value) >> 16); \
287 (cp)[2] = (unsigned char)((value) >> 8); \
288 (cp)[3] = (unsigned char)(value); }
290 enum { PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM };
292 /* Coroutine mechanics for the sillier bits of the code */
293 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
296 if (!ssh->t) ssh->t = smalloc(sizeof(struct t)); \
298 #define crFinish(z) } *crLine = 0; return (z); }
299 #define crFinishV } *crLine = 0; return; }
300 #define crReturn(z) \
302 *crLine =__LINE__; return (z); case __LINE__:;\
306 *crLine=__LINE__; return; case __LINE__:;\
308 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
309 #define crStopV do{ *crLine = 0; return; }while(0)
310 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
311 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
313 typedef struct ssh_tag *Ssh;
315 extern char *x11_init(Socket *, char *, void *);
316 extern void x11_close(Socket);
317 extern int x11_send(Socket, char *, int);
318 extern void x11_invent_auth(char *, int, char *, int);
319 extern void x11_unthrottle(Socket s);
320 extern void x11_override_throttle(Socket s, int enable);
322 extern char *pfd_newconnect(Socket * s, char *hostname, int port, void *c);
323 extern char *pfd_addforward(char *desthost, int destport, int port);
324 extern void pfd_close(Socket s);
325 extern int pfd_send(Socket s, char *data, int len);
326 extern void pfd_confirm(Socket s);
327 extern void pfd_unthrottle(Socket s);
328 extern void pfd_override_throttle(Socket s, int enable);
330 static void ssh2_pkt_init(Ssh, int pkt_type);
331 static void ssh2_pkt_addbool(Ssh, unsigned char value);
332 static void ssh2_pkt_adduint32(Ssh, unsigned long value);
333 static void ssh2_pkt_addstring_start(Ssh);
334 static void ssh2_pkt_addstring_str(Ssh, char *data);
335 static void ssh2_pkt_addstring_data(Ssh, char *data, int len);
336 static void ssh2_pkt_addstring(Ssh, char *data);
337 static char *ssh2_mpint_fmt(Bignum b, int *len);
338 static void ssh2_pkt_addmp(Ssh, Bignum b);
339 static int ssh2_pkt_construct(Ssh);
340 static void ssh2_pkt_send(Ssh);
343 * Buffer management constants. There are several of these for
344 * various different purposes:
346 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
347 * on a local data stream before we throttle the whole SSH
348 * connection (in SSH1 only). Throttling the whole connection is
349 * pretty drastic so we set this high in the hope it won't
352 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
353 * on the SSH connection itself before we defensively throttle
354 * _all_ local data streams. This is pretty drastic too (though
355 * thankfully unlikely in SSH2 since the window mechanism should
356 * ensure that the server never has any need to throttle its end
357 * of the connection), so we set this high as well.
359 * - OUR_V2_WINSIZE is the maximum window size we present on SSH2
363 #define SSH1_BUFFER_LIMIT 32768
364 #define SSH_MAX_BACKLOG 32768
365 #define OUR_V2_WINSIZE 16384
367 const static struct ssh_kex *kex_algs[] = {
368 &ssh_diffiehellman_gex,
372 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
374 static void *nullmac_make_context(void)
378 static void nullmac_free_context(void *handle)
381 static void nullmac_key(void *handle, unsigned char *key)
384 static void nullmac_generate(void *handle, unsigned char *blk, int len,
388 static int nullmac_verify(void *handle, unsigned char *blk, int len,
393 const static struct ssh_mac ssh_mac_none = {
394 nullmac_make_context, nullmac_free_context, nullmac_key,
395 nullmac_generate, nullmac_verify, "none", 0
397 const static struct ssh_mac *macs[] = {
398 &ssh_sha1, &ssh_md5, &ssh_mac_none
400 const static struct ssh_mac *buggymacs[] = {
401 &ssh_sha1_buggy, &ssh_md5, &ssh_mac_none
404 static void *ssh_comp_none_init(void)
408 static void ssh_comp_none_cleanup(void *handle)
411 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
412 unsigned char **outblock, int *outlen)
416 static int ssh_comp_none_disable(void *handle)
420 const static struct ssh_compress ssh_comp_none = {
422 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
423 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
424 ssh_comp_none_disable, NULL
426 extern const struct ssh_compress ssh_zlib;
427 const static struct ssh_compress *compressions[] = {
428 &ssh_zlib, &ssh_comp_none
431 enum { /* channel types */
436 CHAN_SOCKDATA_DORMANT /* one the remote hasn't confirmed */
440 * 2-3-4 tree storing channels.
443 Ssh ssh; /* pointer back to main context */
444 unsigned remoteid, localid;
447 * In SSH1, this value contains four bits:
449 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
450 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
451 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
452 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
454 * A channel is completely finished with when all four bits are set.
458 struct ssh1_data_channel {
461 struct ssh2_data_channel {
463 unsigned remwindow, remmaxpkt;
468 struct ssh_agent_channel {
469 unsigned char *message;
470 unsigned char msglen[4];
471 int lensofar, totallen;
473 struct ssh_x11_channel {
476 struct ssh_pfd_channel {
483 * 2-3-4 tree storing remote->local port forwardings. SSH 1 and SSH
484 * 2 use this structure in different ways, reflecting SSH 2's
485 * altogether saner approach to port forwarding.
487 * In SSH 1, you arrange a remote forwarding by sending the server
488 * the remote port number, and the local destination host:port.
489 * When a connection comes in, the server sends you back that
490 * host:port pair, and you connect to it. This is a ready-made
491 * security hole if you're not on the ball: a malicious server
492 * could send you back _any_ host:port pair, so if you trustingly
493 * connect to the address it gives you then you've just opened the
494 * entire inside of your corporate network just by connecting
495 * through it to a dodgy SSH server. Hence, we must store a list of
496 * host:port pairs we _are_ trying to forward to, and reject a
497 * connection request from the server if it's not in the list.
499 * In SSH 2, each side of the connection minds its own business and
500 * doesn't send unnecessary information to the other. You arrange a
501 * remote forwarding by sending the server just the remote port
502 * number. When a connection comes in, the server tells you which
503 * of its ports was connected to; and _you_ have to remember what
504 * local host:port pair went with that port number.
506 * Hence: in SSH 1 this structure stores host:port pairs we intend
507 * to allow connections to, and is indexed by those host:port
508 * pairs. In SSH 2 it stores a mapping from source port to
509 * destination host:port pair, and is indexed by source port.
511 struct ssh_rportfwd {
512 unsigned sport, dport;
525 static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt);
526 static void ssh2_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt);
527 static void ssh_size(void *handle, int width, int height);
528 static void ssh_special(void *handle, Telnet_Special);
529 static int ssh2_try_send(struct ssh_channel *c);
530 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
531 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
532 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin);
533 static int ssh_sendbuffer(void *handle);
535 struct rdpkt1_state_tag {
536 long len, pad, biglen, to_read;
537 unsigned long realcrc, gotcrc;
543 struct rdpkt2_state_tag {
544 long len, pad, payload, packetlen, maclen;
547 unsigned long incoming_sequence;
551 const struct plug_function_table *fn;
552 /* the above field _must_ be first in the structure */
554 SHA_State exhash, exhashbase;
560 unsigned char session_key[32];
562 int v1_remote_protoflags;
563 int v1_local_protoflags;
564 int agentfwd_enabled;
567 const struct ssh_cipher *cipher;
570 const struct ssh2_cipher *cscipher, *sccipher;
571 void *cs_cipher_ctx, *sc_cipher_ctx;
572 const struct ssh_mac *csmac, *scmac;
573 void *cs_mac_ctx, *sc_mac_ctx;
574 const struct ssh_compress *cscomp, *sccomp;
575 void *cs_comp_ctx, *sc_comp_ctx;
576 const struct ssh_kex *kex;
577 const struct ssh_signkey *hostkey;
578 unsigned char v2_session_id[20];
584 int echoing, editing;
588 int term_width, term_height;
590 tree234 *channels; /* indexed by local id */
591 struct ssh_channel *mainchan; /* primary session channel */
598 SSH_STATE_BEFORE_SIZE,
604 int size_needed, eof_needed;
607 struct Packet pktout;
608 unsigned char *deferred_send_data;
609 int deferred_len, deferred_size;
612 * Gross hack: pscp will try to start SFTP but fall back to
613 * scp1 if that fails. This variable is the means by which
614 * scp.c can reach into the SSH code and find out which one it
620 * Used for username and password input.
622 char *userpass_input_buffer;
623 int userpass_input_buflen;
624 int userpass_input_bufpos;
625 int userpass_input_echo;
627 char *portfwd_strptr;
631 int v1_throttle_count;
634 int v1_stdout_throttling;
635 int v2_outgoing_sequence;
637 int ssh1_rdpkt_crstate;
638 int ssh2_rdpkt_crstate;
639 int do_ssh_init_crstate;
640 int ssh_gotdata_crstate;
641 int ssh1_protocol_crstate;
642 int do_ssh1_login_crstate;
643 int do_ssh2_transport_crstate;
644 int do_ssh2_authconn_crstate;
646 void *do_ssh_init_state;
647 void *do_ssh1_login_state;
648 void *do_ssh2_transport_state;
649 void *do_ssh2_authconn_state;
651 struct rdpkt1_state_tag rdpkt1_state;
652 struct rdpkt2_state_tag rdpkt2_state;
654 void (*protocol) (Ssh ssh, unsigned char *in, int inlen, int ispkt);
655 int (*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
658 static int ssh_channelcmp(void *av, void *bv)
660 struct ssh_channel *a = (struct ssh_channel *) av;
661 struct ssh_channel *b = (struct ssh_channel *) bv;
662 if (a->localid < b->localid)
664 if (a->localid > b->localid)
668 static int ssh_channelfind(void *av, void *bv)
670 unsigned *a = (unsigned *) av;
671 struct ssh_channel *b = (struct ssh_channel *) bv;
679 static int ssh_rportcmp_ssh1(void *av, void *bv)
681 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
682 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
684 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
685 return i < 0 ? -1 : +1;
686 if (a->dport > b->dport)
688 if (a->dport < b->dport)
693 static int ssh_rportcmp_ssh2(void *av, void *bv)
695 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
696 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
698 if (a->sport > b->sport)
700 if (a->sport < b->sport)
705 static int alloc_channel_id(Ssh ssh)
707 const unsigned CHANNEL_NUMBER_OFFSET = 256;
708 unsigned low, high, mid;
710 struct ssh_channel *c;
713 * First-fit allocation of channel numbers: always pick the
714 * lowest unused one. To do this, binary-search using the
715 * counted B-tree to find the largest channel ID which is in a
716 * contiguous sequence from the beginning. (Precisely
717 * everything in that sequence must have ID equal to its tree
718 * index plus CHANNEL_NUMBER_OFFSET.)
720 tsize = count234(ssh->channels);
724 while (high - low > 1) {
725 mid = (high + low) / 2;
726 c = index234(ssh->channels, mid);
727 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
728 low = mid; /* this one is fine */
730 high = mid; /* this one is past it */
733 * Now low points to either -1, or the tree index of the
734 * largest ID in the initial sequence.
737 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
738 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
740 return low + 1 + CHANNEL_NUMBER_OFFSET;
743 static void c_write(Ssh ssh, char *buf, int len)
745 if ((flags & FLAG_STDERR)) {
747 for (i = 0; i < len; i++)
749 fputc(buf[i], stderr);
752 from_backend(ssh->frontend, 1, buf, len);
755 static void c_write_untrusted(Ssh ssh, char *buf, int len)
758 for (i = 0; i < len; i++) {
760 c_write(ssh, "\r\n", 2);
761 else if ((buf[i] & 0x60) || (buf[i] == '\r'))
762 c_write(ssh, buf + i, 1);
766 static void c_write_str(Ssh ssh, char *buf)
768 c_write(ssh, buf, strlen(buf));
772 * Collect incoming data in the incoming packet buffer.
773 * Decipher and verify the packet when it is completely read.
774 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
775 * Update the *data and *datalen variables.
776 * Return the additional nr of bytes needed, or 0 when
777 * a complete packet is available.
779 static int ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
781 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
783 crBegin(ssh->ssh1_rdpkt_crstate);
788 ssh->pktin.length = 0;
790 for (st->i = st->len = 0; st->i < 4; st->i++) {
791 while ((*datalen) == 0)
793 st->len = (st->len << 8) + **data;
794 (*data)++, (*datalen)--;
797 st->pad = 8 - (st->len % 8);
798 st->biglen = st->len + st->pad;
799 ssh->pktin.length = st->len - 5;
801 if (ssh->pktin.maxlen < st->biglen) {
802 ssh->pktin.maxlen = st->biglen;
803 ssh->pktin.data = srealloc(ssh->pktin.data, st->biglen + APIEXTRA);
806 st->to_read = st->biglen;
807 st->p = ssh->pktin.data;
808 while (st->to_read > 0) {
809 st->chunk = st->to_read;
810 while ((*datalen) == 0)
811 crReturn(st->to_read);
812 if (st->chunk > (*datalen))
813 st->chunk = (*datalen);
814 memcpy(st->p, *data, st->chunk);
816 *datalen -= st->chunk;
818 st->to_read -= st->chunk;
821 if (ssh->cipher && detect_attack(ssh->crcda_ctx, ssh->pktin.data,
823 bombout(("Network attack (CRC compensation) detected!"));
828 ssh->cipher->decrypt(ssh->v1_cipher_ctx, ssh->pktin.data, st->biglen);
830 st->realcrc = crc32(ssh->pktin.data, st->biglen - 4);
831 st->gotcrc = GET_32BIT(ssh->pktin.data + st->biglen - 4);
832 if (st->gotcrc != st->realcrc) {
833 bombout(("Incorrect CRC received on packet"));
837 ssh->pktin.body = ssh->pktin.data + st->pad + 1;
839 if (ssh->v1_compressing) {
840 unsigned char *decompblk;
842 zlib_decompress_block(ssh->sc_comp_ctx,
843 ssh->pktin.body - 1, ssh->pktin.length + 1,
844 &decompblk, &decomplen);
846 if (ssh->pktin.maxlen < st->pad + decomplen) {
847 ssh->pktin.maxlen = st->pad + decomplen;
848 ssh->pktin.data = srealloc(ssh->pktin.data,
849 ssh->pktin.maxlen + APIEXTRA);
850 ssh->pktin.body = ssh->pktin.data + st->pad + 1;
853 memcpy(ssh->pktin.body - 1, decompblk, decomplen);
855 ssh->pktin.length = decomplen - 1;
858 ssh->pktin.type = ssh->pktin.body[-1];
860 log_packet(PKT_INCOMING, ssh->pktin.type, ssh1_pkt_type(ssh->pktin.type),
861 ssh->pktin.body, ssh->pktin.length);
863 if (ssh->pktin.type == SSH1_SMSG_STDOUT_DATA ||
864 ssh->pktin.type == SSH1_SMSG_STDERR_DATA ||
865 ssh->pktin.type == SSH1_MSG_DEBUG ||
866 ssh->pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE ||
867 ssh->pktin.type == SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
868 long stringlen = GET_32BIT(ssh->pktin.body);
869 if (stringlen + 4 != ssh->pktin.length) {
870 bombout(("Received data packet with bogus string length"));
875 if (ssh->pktin.type == SSH1_MSG_DEBUG) {
876 /* log debug message */
878 int stringlen = GET_32BIT(ssh->pktin.body);
879 strcpy(buf, "Remote debug message: ");
882 memcpy(buf + 8, ssh->pktin.body + 4, stringlen);
883 buf[8 + stringlen] = '\0';
886 } else if (ssh->pktin.type == SSH1_MSG_IGNORE) {
891 if (ssh->pktin.type == SSH1_MSG_DISCONNECT) {
892 /* log reason code in disconnect message */
894 unsigned msglen = GET_32BIT(ssh->pktin.body);
896 strcpy(buf, "Remote sent disconnect: ");
897 nowlen = strlen(buf);
898 if (msglen > sizeof(buf) - nowlen - 1)
899 msglen = sizeof(buf) - nowlen - 1;
900 memcpy(buf + nowlen, ssh->pktin.body + 4, msglen);
901 buf[nowlen + msglen] = '\0';
902 /* logevent(buf); (this is now done within the bombout macro) */
903 bombout(("Server sent disconnect message:\n\"%s\"", buf+nowlen));
910 static int ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
912 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
914 crBegin(ssh->ssh2_rdpkt_crstate);
918 ssh->pktin.length = 0;
920 st->cipherblk = ssh->sccipher->blksize;
923 if (st->cipherblk < 8)
926 if (ssh->pktin.maxlen < st->cipherblk) {
927 ssh->pktin.maxlen = st->cipherblk;
928 ssh->pktin.data = srealloc(ssh->pktin.data, st->cipherblk + APIEXTRA);
932 * Acquire and decrypt the first block of the packet. This will
933 * contain the length and padding details.
935 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
936 while ((*datalen) == 0)
937 crReturn(st->cipherblk - st->i);
938 ssh->pktin.data[st->i] = *(*data)++;
943 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
944 ssh->pktin.data, st->cipherblk);
947 * Now get the length and padding figures.
949 st->len = GET_32BIT(ssh->pktin.data);
950 st->pad = ssh->pktin.data[4];
953 * _Completely_ silly lengths should be stomped on before they
954 * do us any more damage.
956 if (st->len < 0 || st->pad < 0 || st->len + st->pad < 0) {
957 bombout(("Incoming packet was garbled on decryption"));
962 * This enables us to deduce the payload length.
964 st->payload = st->len - st->pad - 1;
966 ssh->pktin.length = st->payload + 5;
969 * So now we can work out the total packet length.
971 st->packetlen = st->len + 4;
972 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
975 * Adjust memory allocation if packet is too big.
977 if (ssh->pktin.maxlen < st->packetlen + st->maclen) {
978 ssh->pktin.maxlen = st->packetlen + st->maclen;
979 ssh->pktin.data = srealloc(ssh->pktin.data,
980 ssh->pktin.maxlen + APIEXTRA);
984 * Read and decrypt the remainder of the packet.
986 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
988 while ((*datalen) == 0)
989 crReturn(st->packetlen + st->maclen - st->i);
990 ssh->pktin.data[st->i] = *(*data)++;
993 /* Decrypt everything _except_ the MAC. */
995 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
996 ssh->pktin.data + st->cipherblk,
997 st->packetlen - st->cipherblk);
1003 && !ssh->scmac->verify(ssh->sc_mac_ctx, ssh->pktin.data, st->len + 4,
1004 st->incoming_sequence)) {
1005 bombout(("Incorrect MAC received on packet"));
1008 st->incoming_sequence++; /* whether or not we MACed */
1011 * Decompress packet payload.
1014 unsigned char *newpayload;
1017 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1018 ssh->pktin.data + 5, ssh->pktin.length - 5,
1019 &newpayload, &newlen)) {
1020 if (ssh->pktin.maxlen < newlen + 5) {
1021 ssh->pktin.maxlen = newlen + 5;
1022 ssh->pktin.data = srealloc(ssh->pktin.data,
1023 ssh->pktin.maxlen + APIEXTRA);
1025 ssh->pktin.length = 5 + newlen;
1026 memcpy(ssh->pktin.data + 5, newpayload, newlen);
1031 ssh->pktin.savedpos = 6;
1032 ssh->pktin.type = ssh->pktin.data[5];
1034 log_packet(PKT_INCOMING, ssh->pktin.type,
1035 ssh2_pkt_type(ssh->pkt_ctx, ssh->pktin.type),
1036 ssh->pktin.data+6, ssh->pktin.length-6);
1038 switch (ssh->pktin.type) {
1040 * These packets we must handle instantly.
1042 case SSH2_MSG_DISCONNECT:
1044 /* log reason code in disconnect message */
1046 int reason = GET_32BIT(ssh->pktin.data + 6);
1047 unsigned msglen = GET_32BIT(ssh->pktin.data + 10);
1049 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
1050 sprintf(buf, "Received disconnect message (%s)",
1051 ssh2_disconnect_reasons[reason]);
1053 sprintf(buf, "Received disconnect message (unknown type %d)",
1057 strcpy(buf, "Disconnection message text: ");
1058 nowlen = strlen(buf);
1059 if (msglen > sizeof(buf) - nowlen - 1)
1060 msglen = sizeof(buf) - nowlen - 1;
1061 memcpy(buf + nowlen, ssh->pktin.data + 14, msglen);
1062 buf[nowlen + msglen] = '\0';
1064 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
1066 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
1067 ssh2_disconnect_reasons[reason] : "unknown",
1072 case SSH2_MSG_IGNORE:
1074 case SSH2_MSG_DEBUG:
1076 /* log the debug message */
1078 /* int display = ssh->pktin.body[6]; */
1079 int stringlen = GET_32BIT(ssh->pktin.data+7);
1081 strcpy(buf, "Remote debug message: ");
1082 prefix = strlen(buf);
1083 if (stringlen > (int)(sizeof(buf)-prefix-1))
1084 stringlen = sizeof(buf)-prefix-1;
1085 memcpy(buf + prefix, ssh->pktin.data + 11, stringlen);
1086 buf[prefix + stringlen] = '\0';
1089 goto next_packet; /* FIXME: print the debug message */
1092 * These packets we need do nothing about here.
1094 case SSH2_MSG_UNIMPLEMENTED:
1095 case SSH2_MSG_SERVICE_REQUEST:
1096 case SSH2_MSG_SERVICE_ACCEPT:
1097 case SSH2_MSG_KEXINIT:
1098 case SSH2_MSG_NEWKEYS:
1099 case SSH2_MSG_KEXDH_INIT:
1100 case SSH2_MSG_KEXDH_REPLY:
1101 /* case SSH2_MSG_KEX_DH_GEX_REQUEST: duplicate case value */
1102 /* case SSH2_MSG_KEX_DH_GEX_GROUP: duplicate case value */
1103 case SSH2_MSG_KEX_DH_GEX_INIT:
1104 case SSH2_MSG_KEX_DH_GEX_REPLY:
1105 case SSH2_MSG_USERAUTH_REQUEST:
1106 case SSH2_MSG_USERAUTH_FAILURE:
1107 case SSH2_MSG_USERAUTH_SUCCESS:
1108 case SSH2_MSG_USERAUTH_BANNER:
1109 case SSH2_MSG_USERAUTH_PK_OK:
1110 /* case SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ: duplicate case value */
1111 /* case SSH2_MSG_USERAUTH_INFO_REQUEST: duplicate case value */
1112 case SSH2_MSG_USERAUTH_INFO_RESPONSE:
1113 case SSH2_MSG_GLOBAL_REQUEST:
1114 case SSH2_MSG_REQUEST_SUCCESS:
1115 case SSH2_MSG_REQUEST_FAILURE:
1116 case SSH2_MSG_CHANNEL_OPEN:
1117 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
1118 case SSH2_MSG_CHANNEL_OPEN_FAILURE:
1119 case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
1120 case SSH2_MSG_CHANNEL_DATA:
1121 case SSH2_MSG_CHANNEL_EXTENDED_DATA:
1122 case SSH2_MSG_CHANNEL_EOF:
1123 case SSH2_MSG_CHANNEL_CLOSE:
1124 case SSH2_MSG_CHANNEL_REQUEST:
1125 case SSH2_MSG_CHANNEL_SUCCESS:
1126 case SSH2_MSG_CHANNEL_FAILURE:
1130 * For anything else we send SSH2_MSG_UNIMPLEMENTED.
1133 ssh2_pkt_init(ssh, SSH2_MSG_UNIMPLEMENTED);
1134 ssh2_pkt_adduint32(ssh, st->incoming_sequence - 1);
1142 static void ssh1_pktout_size(Ssh ssh, int len)
1146 len += 5; /* type and CRC */
1147 pad = 8 - (len % 8);
1150 ssh->pktout.length = len - 5;
1151 if (ssh->pktout.maxlen < biglen) {
1152 ssh->pktout.maxlen = biglen;
1154 /* Allocate enough buffer space for extra block
1155 * for MS CryptEncrypt() */
1156 ssh->pktout.data = srealloc(ssh->pktout.data, biglen + 12);
1158 ssh->pktout.data = srealloc(ssh->pktout.data, biglen + 4);
1161 ssh->pktout.body = ssh->pktout.data + 4 + pad + 1;
1164 static void s_wrpkt_start(Ssh ssh, int type, int len)
1166 ssh1_pktout_size(ssh, len);
1167 ssh->pktout.type = type;
1170 static int s_wrpkt_prepare(Ssh ssh)
1172 int pad, len, biglen, i;
1175 ssh->pktout.body[-1] = ssh->pktout.type;
1177 log_packet(PKT_OUTGOING, ssh->pktout.type, ssh1_pkt_type(ssh->pktout.type),
1178 ssh->pktout.body, ssh->pktout.length);
1180 if (ssh->v1_compressing) {
1181 unsigned char *compblk;
1183 zlib_compress_block(ssh->cs_comp_ctx,
1184 ssh->pktout.body - 1, ssh->pktout.length + 1,
1185 &compblk, &complen);
1186 ssh1_pktout_size(ssh, complen - 1);
1187 memcpy(ssh->pktout.body - 1, compblk, complen);
1191 len = ssh->pktout.length + 5; /* type and CRC */
1192 pad = 8 - (len % 8);
1195 for (i = 0; i < pad; i++)
1196 ssh->pktout.data[i + 4] = random_byte();
1197 crc = crc32(ssh->pktout.data + 4, biglen - 4);
1198 PUT_32BIT(ssh->pktout.data + biglen, crc);
1199 PUT_32BIT(ssh->pktout.data, len);
1202 ssh->cipher->encrypt(ssh->v1_cipher_ctx, ssh->pktout.data + 4, biglen);
1207 static void s_wrpkt(Ssh ssh)
1210 len = s_wrpkt_prepare(ssh);
1211 backlog = sk_write(ssh->s, ssh->pktout.data, len);
1212 if (backlog > SSH_MAX_BACKLOG)
1213 ssh_throttle_all(ssh, 1, backlog);
1216 static void s_wrpkt_defer(Ssh ssh)
1219 len = s_wrpkt_prepare(ssh);
1220 if (ssh->deferred_len + len > ssh->deferred_size) {
1221 ssh->deferred_size = ssh->deferred_len + len + 128;
1222 ssh->deferred_send_data = srealloc(ssh->deferred_send_data,
1223 ssh->deferred_size);
1225 memcpy(ssh->deferred_send_data + ssh->deferred_len, ssh->pktout.data, len);
1226 ssh->deferred_len += len;
1230 * Construct a packet with the specified contents.
1232 static void construct_packet(Ssh ssh, int pkttype, va_list ap1, va_list ap2)
1234 unsigned char *p, *argp, argchar;
1235 unsigned long argint;
1236 int pktlen, argtype, arglen;
1240 while ((argtype = va_arg(ap1, int)) != PKT_END) {
1243 (void) va_arg(ap1, int);
1247 (void) va_arg(ap1, char);
1251 (void) va_arg(ap1, unsigned char *);
1252 arglen = va_arg(ap1, int);
1256 argp = va_arg(ap1, unsigned char *);
1257 arglen = strlen(argp);
1258 pktlen += 4 + arglen;
1261 bn = va_arg(ap1, Bignum);
1262 pktlen += ssh1_bignum_length(bn);
1269 s_wrpkt_start(ssh, pkttype, pktlen);
1270 p = ssh->pktout.body;
1272 while ((argtype = va_arg(ap2, int)) != PKT_END) {
1275 argint = va_arg(ap2, int);
1276 PUT_32BIT(p, argint);
1280 argchar = va_arg(ap2, unsigned char);
1285 argp = va_arg(ap2, unsigned char *);
1286 arglen = va_arg(ap2, int);
1287 memcpy(p, argp, arglen);
1291 argp = va_arg(ap2, unsigned char *);
1292 arglen = strlen(argp);
1293 PUT_32BIT(p, arglen);
1294 memcpy(p + 4, argp, arglen);
1298 bn = va_arg(ap2, Bignum);
1299 p += ssh1_write_bignum(p, bn);
1305 static void send_packet(Ssh ssh, int pkttype, ...)
1308 va_start(ap1, pkttype);
1309 va_start(ap2, pkttype);
1310 construct_packet(ssh, pkttype, ap1, ap2);
1314 static void defer_packet(Ssh ssh, int pkttype, ...)
1317 va_start(ap1, pkttype);
1318 va_start(ap2, pkttype);
1319 construct_packet(ssh, pkttype, ap1, ap2);
1323 static int ssh_versioncmp(char *a, char *b)
1326 unsigned long av, bv;
1328 av = strtoul(a, &ae, 10);
1329 bv = strtoul(b, &be, 10);
1331 return (av < bv ? -1 : +1);
1336 av = strtoul(ae, &ae, 10);
1337 bv = strtoul(be, &be, 10);
1339 return (av < bv ? -1 : +1);
1344 * Utility routines for putting an SSH-protocol `string' and
1345 * `uint32' into a SHA state.
1348 static void sha_string(SHA_State * s, void *str, int len)
1350 unsigned char lenblk[4];
1351 PUT_32BIT(lenblk, len);
1352 SHA_Bytes(s, lenblk, 4);
1353 SHA_Bytes(s, str, len);
1356 static void sha_uint32(SHA_State * s, unsigned i)
1358 unsigned char intblk[4];
1359 PUT_32BIT(intblk, i);
1360 SHA_Bytes(s, intblk, 4);
1364 * SSH2 packet construction functions.
1366 static void ssh2_pkt_ensure(Ssh ssh, int length)
1368 if (ssh->pktout.maxlen < length) {
1369 ssh->pktout.maxlen = length + 256;
1370 ssh->pktout.data = srealloc(ssh->pktout.data,
1371 ssh->pktout.maxlen + APIEXTRA);
1372 if (!ssh->pktout.data)
1373 fatalbox("Out of memory");
1376 static void ssh2_pkt_adddata(Ssh ssh, void *data, int len)
1378 ssh->pktout.length += len;
1379 ssh2_pkt_ensure(ssh, ssh->pktout.length);
1380 memcpy(ssh->pktout.data + ssh->pktout.length - len, data, len);
1382 static void ssh2_pkt_addbyte(Ssh ssh, unsigned char byte)
1384 ssh2_pkt_adddata(ssh, &byte, 1);
1386 static void ssh2_pkt_init(Ssh ssh, int pkt_type)
1388 ssh->pktout.length = 5;
1389 ssh2_pkt_addbyte(ssh, (unsigned char) pkt_type);
1391 static void ssh2_pkt_addbool(Ssh ssh, unsigned char value)
1393 ssh2_pkt_adddata(ssh, &value, 1);
1395 static void ssh2_pkt_adduint32(Ssh ssh, unsigned long value)
1398 PUT_32BIT(x, value);
1399 ssh2_pkt_adddata(ssh, x, 4);
1401 static void ssh2_pkt_addstring_start(Ssh ssh)
1403 ssh2_pkt_adduint32(ssh, 0);
1404 ssh->pktout.savedpos = ssh->pktout.length;
1406 static void ssh2_pkt_addstring_str(Ssh ssh, char *data)
1408 ssh2_pkt_adddata(ssh, data, strlen(data));
1409 PUT_32BIT(ssh->pktout.data + ssh->pktout.savedpos - 4,
1410 ssh->pktout.length - ssh->pktout.savedpos);
1412 static void ssh2_pkt_addstring_data(Ssh ssh, char *data, int len)
1414 ssh2_pkt_adddata(ssh, data, len);
1415 PUT_32BIT(ssh->pktout.data + ssh->pktout.savedpos - 4,
1416 ssh->pktout.length - ssh->pktout.savedpos);
1418 static void ssh2_pkt_addstring(Ssh ssh, char *data)
1420 ssh2_pkt_addstring_start(ssh);
1421 ssh2_pkt_addstring_str(ssh, data);
1423 static char *ssh2_mpint_fmt(Bignum b, int *len)
1426 int i, n = (bignum_bitcount(b) + 7) / 8;
1429 fatalbox("out of memory");
1431 for (i = 1; i <= n; i++)
1432 p[i] = bignum_byte(b, n - i);
1434 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1436 memmove(p, p + i, n + 1 - i);
1440 static void ssh2_pkt_addmp(Ssh ssh, Bignum b)
1444 p = ssh2_mpint_fmt(b, &len);
1445 ssh2_pkt_addstring_start(ssh);
1446 ssh2_pkt_addstring_data(ssh, p, len);
1451 * Construct an SSH2 final-form packet: compress it, encrypt it,
1452 * put the MAC on it. Final packet, ready to be sent, is stored in
1453 * ssh->pktout.data. Total length is returned.
1455 static int ssh2_pkt_construct(Ssh ssh)
1457 int cipherblk, maclen, padding, i;
1459 log_packet(PKT_OUTGOING, ssh->pktout.data[5],
1460 ssh2_pkt_type(ssh->pkt_ctx, ssh->pktout.data[5]),
1461 ssh->pktout.data + 6, ssh->pktout.length - 6);
1464 * Compress packet payload.
1467 unsigned char *newpayload;
1470 ssh->cscomp->compress(ssh->cs_comp_ctx, ssh->pktout.data + 5,
1471 ssh->pktout.length - 5,
1472 &newpayload, &newlen)) {
1473 ssh->pktout.length = 5;
1474 ssh2_pkt_adddata(ssh, newpayload, newlen);
1480 * Add padding. At least four bytes, and must also bring total
1481 * length (minus MAC) up to a multiple of the block size.
1483 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
1484 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1487 (cipherblk - (ssh->pktout.length + padding) % cipherblk) % cipherblk;
1488 maclen = ssh->csmac ? ssh->csmac->len : 0;
1489 ssh2_pkt_ensure(ssh, ssh->pktout.length + padding + maclen);
1490 ssh->pktout.data[4] = padding;
1491 for (i = 0; i < padding; i++)
1492 ssh->pktout.data[ssh->pktout.length + i] = random_byte();
1493 PUT_32BIT(ssh->pktout.data, ssh->pktout.length + padding - 4);
1495 ssh->csmac->generate(ssh->cs_mac_ctx, ssh->pktout.data,
1496 ssh->pktout.length + padding,
1497 ssh->v2_outgoing_sequence);
1498 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
1501 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
1502 ssh->pktout.data, ssh->pktout.length + padding);
1504 /* Ready-to-send packet starts at ssh->pktout.data. We return length. */
1505 return ssh->pktout.length + padding + maclen;
1509 * Construct and send an SSH2 packet immediately.
1511 static void ssh2_pkt_send(Ssh ssh)
1515 len = ssh2_pkt_construct(ssh);
1516 backlog = sk_write(ssh->s, ssh->pktout.data, len);
1517 if (backlog > SSH_MAX_BACKLOG)
1518 ssh_throttle_all(ssh, 1, backlog);
1522 * Construct an SSH2 packet and add it to a deferred data block.
1523 * Useful for sending multiple packets in a single sk_write() call,
1524 * to prevent a traffic-analysing listener from being able to work
1525 * out the length of any particular packet (such as the password
1528 * Note that because SSH2 sequence-numbers its packets, this can
1529 * NOT be used as an m4-style `defer' allowing packets to be
1530 * constructed in one order and sent in another.
1532 static void ssh2_pkt_defer(Ssh ssh)
1534 int len = ssh2_pkt_construct(ssh);
1535 if (ssh->deferred_len + len > ssh->deferred_size) {
1536 ssh->deferred_size = ssh->deferred_len + len + 128;
1537 ssh->deferred_send_data = srealloc(ssh->deferred_send_data,
1538 ssh->deferred_size);
1540 memcpy(ssh->deferred_send_data + ssh->deferred_len, ssh->pktout.data, len);
1541 ssh->deferred_len += len;
1545 * Send the whole deferred data block constructed by
1546 * ssh2_pkt_defer() or SSH1's defer_packet().
1548 static void ssh_pkt_defersend(Ssh ssh)
1551 backlog = sk_write(ssh->s, ssh->deferred_send_data, ssh->deferred_len);
1552 ssh->deferred_len = ssh->deferred_size = 0;
1553 sfree(ssh->deferred_send_data);
1554 ssh->deferred_send_data = NULL;
1555 if (backlog > SSH_MAX_BACKLOG)
1556 ssh_throttle_all(ssh, 1, backlog);
1560 void bndebug(char *string, Bignum b)
1564 p = ssh2_mpint_fmt(b, &len);
1565 debug(("%s", string));
1566 for (i = 0; i < len; i++)
1567 debug((" %02x", p[i]));
1573 static void sha_mpint(SHA_State * s, Bignum b)
1577 p = ssh2_mpint_fmt(b, &len);
1578 sha_string(s, p, len);
1583 * SSH2 packet decode functions.
1585 static unsigned long ssh2_pkt_getuint32(Ssh ssh)
1587 unsigned long value;
1588 if (ssh->pktin.length - ssh->pktin.savedpos < 4)
1589 return 0; /* arrgh, no way to decline (FIXME?) */
1590 value = GET_32BIT(ssh->pktin.data + ssh->pktin.savedpos);
1591 ssh->pktin.savedpos += 4;
1594 static int ssh2_pkt_getbool(Ssh ssh)
1596 unsigned long value;
1597 if (ssh->pktin.length - ssh->pktin.savedpos < 1)
1598 return 0; /* arrgh, no way to decline (FIXME?) */
1599 value = ssh->pktin.data[ssh->pktin.savedpos] != 0;
1600 ssh->pktin.savedpos++;
1603 static void ssh2_pkt_getstring(Ssh ssh, char **p, int *length)
1607 if (ssh->pktin.length - ssh->pktin.savedpos < 4)
1609 *length = GET_32BIT(ssh->pktin.data + ssh->pktin.savedpos);
1610 ssh->pktin.savedpos += 4;
1611 if (ssh->pktin.length - ssh->pktin.savedpos < *length)
1613 *p = ssh->pktin.data + ssh->pktin.savedpos;
1614 ssh->pktin.savedpos += *length;
1616 static Bignum ssh2_pkt_getmp(Ssh ssh)
1622 ssh2_pkt_getstring(ssh, &p, &length);
1626 bombout(("internal error: Can't handle negative mpints"));
1629 b = bignum_from_bytes(p, length);
1634 * Helper function to add an SSH2 signature blob to a packet.
1635 * Expects to be shown the public key blob as well as the signature
1636 * blob. Normally works just like ssh2_pkt_addstring, but will
1637 * fiddle with the signature packet if necessary for
1638 * BUG_SSH2_RSA_PADDING.
1640 static void ssh2_add_sigblob(Ssh ssh, void *pkblob_v, int pkblob_len,
1641 void *sigblob_v, int sigblob_len)
1643 unsigned char *pkblob = (unsigned char *)pkblob_v;
1644 unsigned char *sigblob = (unsigned char *)sigblob_v;
1646 /* dmemdump(pkblob, pkblob_len); */
1647 /* dmemdump(sigblob, sigblob_len); */
1650 * See if this is in fact an ssh-rsa signature and a buggy
1651 * server; otherwise we can just do this the easy way.
1653 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) &&
1654 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
1655 int pos, len, siglen;
1658 * Find the byte length of the modulus.
1661 pos = 4+7; /* skip over "ssh-rsa" */
1662 pos += 4 + GET_32BIT(pkblob+pos); /* skip over exponent */
1663 len = GET_32BIT(pkblob+pos); /* find length of modulus */
1664 pos += 4; /* find modulus itself */
1665 while (len > 0 && pkblob[pos] == 0)
1667 /* debug(("modulus length is %d\n", len)); */
1670 * Now find the signature integer.
1672 pos = 4+7; /* skip over "ssh-rsa" */
1673 siglen = GET_32BIT(sigblob+pos);
1674 /* debug(("signature length is %d\n", siglen)); */
1676 if (len != siglen) {
1677 unsigned char newlen[4];
1678 ssh2_pkt_addstring_start(ssh);
1679 ssh2_pkt_addstring_data(ssh, sigblob, pos);
1680 /* dmemdump(sigblob, pos); */
1681 pos += 4; /* point to start of actual sig */
1682 PUT_32BIT(newlen, len);
1683 ssh2_pkt_addstring_data(ssh, newlen, 4);
1684 /* dmemdump(newlen, 4); */
1686 while (len-- > siglen) {
1687 ssh2_pkt_addstring_data(ssh, newlen, 1);
1688 /* dmemdump(newlen, 1); */
1690 ssh2_pkt_addstring_data(ssh, sigblob+pos, siglen);
1691 /* dmemdump(sigblob+pos, siglen); */
1695 /* Otherwise fall through and do it the easy way. */
1698 ssh2_pkt_addstring_start(ssh);
1699 ssh2_pkt_addstring_data(ssh, sigblob, sigblob_len);
1703 * Examine the remote side's version string and compare it against
1704 * a list of known buggy implementations.
1706 static void ssh_detect_bugs(Ssh ssh, char *vstring)
1708 char *imp; /* pointer to implementation part */
1710 imp += strcspn(imp, "-");
1712 imp += strcspn(imp, "-");
1715 ssh->remote_bugs = 0;
1717 if (cfg.sshbug_ignore1 == BUG_ON ||
1718 (cfg.sshbug_ignore1 == BUG_AUTO &&
1719 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
1720 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
1721 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25")))) {
1723 * These versions don't support SSH1_MSG_IGNORE, so we have
1724 * to use a different defence against password length
1727 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
1728 logevent("We believe remote version has SSH1 ignore bug");
1731 if (cfg.sshbug_plainpw1 == BUG_ON ||
1732 (cfg.sshbug_plainpw1 == BUG_AUTO &&
1733 (!strcmp(imp, "Cisco-1.25")))) {
1735 * These versions need a plain password sent; they can't
1736 * handle having a null and a random length of data after
1739 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
1740 logevent("We believe remote version needs a plain SSH1 password");
1743 if (cfg.sshbug_rsa1 == BUG_ON ||
1744 (cfg.sshbug_rsa1 == BUG_AUTO &&
1745 (!strcmp(imp, "Cisco-1.25")))) {
1747 * These versions apparently have no clue whatever about
1748 * RSA authentication and will panic and die if they see
1749 * an AUTH_RSA message.
1751 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
1752 logevent("We believe remote version can't handle RSA authentication");
1755 if (cfg.sshbug_hmac2 == BUG_ON ||
1756 (cfg.sshbug_hmac2 == BUG_AUTO &&
1757 (!strncmp(imp, "2.1.0", 5) || !strncmp(imp, "2.0.", 4) ||
1758 !strncmp(imp, "2.2.0", 5) || !strncmp(imp, "2.3.0", 5) ||
1759 !strncmp(imp, "2.1 ", 4)))) {
1761 * These versions have the HMAC bug.
1763 ssh->remote_bugs |= BUG_SSH2_HMAC;
1764 logevent("We believe remote version has SSH2 HMAC bug");
1767 if (cfg.sshbug_derivekey2 == BUG_ON ||
1768 (cfg.sshbug_derivekey2 == BUG_AUTO &&
1769 (!strncmp(imp, "2.0.", 4)))) {
1771 * These versions have the key-derivation bug (failing to
1772 * include the literal shared secret in the hashes that
1773 * generate the keys).
1775 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
1776 logevent("We believe remote version has SSH2 key-derivation bug");
1779 if (cfg.sshbug_rsapad2 == BUG_ON ||
1780 (cfg.sshbug_rsapad2 == BUG_AUTO &&
1781 ((!strncmp(imp, "OpenSSH_2.", 10) && imp[10]>='5' && imp[10]<='9') ||
1782 (!strncmp(imp, "OpenSSH_3.", 10) && imp[10]>='0' && imp[10]<='2')))){
1784 * These versions have the SSH2 RSA padding bug.
1786 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
1787 logevent("We believe remote version has SSH2 RSA padding bug");
1790 if (cfg.sshbug_dhgex2 == BUG_ON) {
1792 * These versions have the SSH2 DH GEX bug.
1794 ssh->remote_bugs |= BUG_SSH2_DH_GEX;
1795 logevent("We believe remote version has SSH2 DH group exchange bug");
1799 static int do_ssh_init(Ssh ssh, unsigned char c)
1801 struct do_ssh_init_state {
1809 crState(do_ssh_init_state);
1811 crBegin(ssh->do_ssh_init_crstate);
1813 /* Search for the string "SSH-" in the input. */
1816 static const int transS[] = { 1, 2, 2, 1 };
1817 static const int transH[] = { 0, 0, 3, 0 };
1818 static const int transminus[] = { 0, 0, 0, -1 };
1820 s->i = transS[s->i];
1822 s->i = transH[s->i];
1824 s->i = transminus[s->i];
1829 crReturn(1); /* get another character */
1833 s->vstring = smalloc(s->vstrsize);
1834 strcpy(s->vstring, "SSH-");
1838 crReturn(1); /* get another char */
1839 if (s->vslen >= s->vstrsize - 1) {
1841 s->vstring = srealloc(s->vstring, s->vstrsize);
1843 s->vstring[s->vslen++] = c;
1846 s->version[s->i] = '\0';
1848 } else if (s->i < sizeof(s->version) - 1)
1849 s->version[s->i++] = c;
1850 } else if (c == '\n')
1854 ssh->agentfwd_enabled = FALSE;
1855 ssh->rdpkt2_state.incoming_sequence = 0;
1857 s->vstring[s->vslen] = 0;
1858 s->vstring[strcspn(s->vstring, "\r\n")] = '\0';/* remove EOL chars */
1861 vlog = smalloc(20 + s->vslen);
1862 sprintf(vlog, "Server version: %s", s->vstring);
1866 ssh_detect_bugs(ssh, s->vstring);
1869 * Decide which SSH protocol version to support.
1872 /* Anything strictly below "2.0" means protocol 1 is supported. */
1873 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
1874 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
1875 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
1877 if (cfg.sshprot == 0 && !s->proto1) {
1878 bombout(("SSH protocol version 1 required by user but not provided by server"));
1881 if (cfg.sshprot == 3 && !s->proto2) {
1882 bombout(("SSH protocol version 2 required by user but not provided by server"));
1886 if (s->proto2 && (cfg.sshprot >= 2 || !s->proto1)) {
1890 char verstring[80], vlog[100];
1891 sprintf(verstring, "SSH-2.0-%s", sshver);
1892 SHA_Init(&ssh->exhashbase);
1894 * Hash our version string and their version string.
1896 sha_string(&ssh->exhashbase, verstring, strlen(verstring));
1897 sha_string(&ssh->exhashbase, s->vstring, strcspn(s->vstring, "\r\n"));
1898 sprintf(vlog, "We claim version: %s", verstring);
1900 strcat(verstring, "\n");
1901 logevent("Using SSH protocol version 2");
1902 sk_write(ssh->s, verstring, strlen(verstring));
1903 ssh->protocol = ssh2_protocol;
1905 ssh->s_rdpkt = ssh2_rdpkt;
1910 char verstring[80], vlog[100];
1911 sprintf(verstring, "SSH-%s-%s",
1912 (ssh_versioncmp(s->version, "1.5") <= 0 ? s->version : "1.5"),
1914 sprintf(vlog, "We claim version: %s", verstring);
1916 strcat(verstring, "\n");
1918 logevent("Using SSH protocol version 1");
1919 sk_write(ssh->s, verstring, strlen(verstring));
1920 ssh->protocol = ssh1_protocol;
1922 ssh->s_rdpkt = ssh1_rdpkt;
1924 ssh->state = SSH_STATE_BEFORE_SIZE;
1931 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
1933 crBegin(ssh->ssh_gotdata_crstate);
1936 * To begin with, feed the characters one by one to the
1937 * protocol initialisation / selection function do_ssh_init().
1938 * When that returns 0, we're done with the initial greeting
1939 * exchange and can move on to packet discipline.
1942 int ret; /* need not be kept across crReturn */
1944 crReturnV; /* more data please */
1945 ret = do_ssh_init(ssh, *data);
1953 * We emerge from that loop when the initial negotiation is
1954 * over and we have selected an s_rdpkt function. Now pass
1955 * everything to s_rdpkt, and then pass the resulting packets
1956 * to the proper protocol handler.
1961 while (datalen > 0) {
1962 if (ssh->s_rdpkt(ssh, &data, &datalen) == 0) {
1963 if (ssh->state == SSH_STATE_CLOSED) {
1966 ssh->protocol(ssh, NULL, 0, 1);
1967 if (ssh->state == SSH_STATE_CLOSED) {
1977 static int ssh_closing(Plug plug, char *error_msg, int error_code,
1980 Ssh ssh = (Ssh) plug;
1981 ssh->state = SSH_STATE_CLOSED;
1987 /* A socket error has occurred. */
1988 logevent(error_msg);
1989 connection_fatal(error_msg);
1991 /* Otherwise, the remote side closed the connection normally. */
1996 static int ssh_receive(Plug plug, int urgent, char *data, int len)
1998 Ssh ssh = (Ssh) plug;
1999 ssh_gotdata(ssh, data, len);
2000 if (ssh->state == SSH_STATE_CLOSED) {
2010 static void ssh_sent(Plug plug, int bufsize)
2012 Ssh ssh = (Ssh) plug;
2014 * If the send backlog on the SSH socket itself clears, we
2015 * should unthrottle the whole world if it was throttled.
2017 if (bufsize < SSH_MAX_BACKLOG)
2018 ssh_throttle_all(ssh, 0, bufsize);
2022 * Connect to specified host and port.
2023 * Returns an error message, or NULL on success.
2024 * Also places the canonical host name into `realhost'. It must be
2025 * freed by the caller.
2027 static char *connect_to_host(Ssh ssh, char *host, int port,
2028 char **realhost, int nodelay)
2030 static const struct plug_function_table fn_table = {
2040 ssh->savedhost = smalloc(1 + strlen(host));
2041 if (!ssh->savedhost)
2042 fatalbox("Out of memory");
2043 strcpy(ssh->savedhost, host);
2046 port = 22; /* default ssh port */
2047 ssh->savedport = port;
2054 sprintf(buf, "Looking up host \"%.170s\"", host);
2057 addr = sk_namelookup(host, realhost);
2058 if ((err = sk_addr_error(addr)))
2065 char buf[200], addrbuf[100];
2066 sk_getaddr(addr, addrbuf, 100);
2067 sprintf(buf, "Connecting to %.100s port %d", addrbuf, port);
2070 ssh->fn = &fn_table;
2071 ssh->s = new_connection(addr, *realhost, port, 0, 1, nodelay, (Plug) ssh);
2072 if ((err = sk_socket_error(ssh->s))) {
2081 * Throttle or unthrottle the SSH connection.
2083 static void ssh1_throttle(Ssh ssh, int adjust)
2085 int old_count = ssh->v1_throttle_count;
2086 ssh->v1_throttle_count += adjust;
2087 assert(ssh->v1_throttle_count >= 0);
2088 if (ssh->v1_throttle_count && !old_count) {
2089 sk_set_frozen(ssh->s, 1);
2090 } else if (!ssh->v1_throttle_count && old_count) {
2091 sk_set_frozen(ssh->s, 0);
2096 * Throttle or unthrottle _all_ local data streams (for when sends
2097 * on the SSH connection itself back up).
2099 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
2102 struct ssh_channel *c;
2104 if (enable == ssh->throttled_all)
2106 ssh->throttled_all = enable;
2107 ssh->overall_bufsize = bufsize;
2110 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
2112 case CHAN_MAINSESSION:
2114 * This is treated separately, outside the switch.
2118 x11_override_throttle(c->u.x11.s, enable);
2121 /* Agent channels require no buffer management. */
2124 pfd_override_throttle(c->u.x11.s, enable);
2131 * Username and password input, abstracted off into routines
2132 * reusable in several places - even between SSH1 and SSH2.
2135 /* Set up a username or password input loop on a given buffer. */
2136 void setup_userpass_input(Ssh ssh, char *buffer, int buflen, int echo)
2138 ssh->userpass_input_buffer = buffer;
2139 ssh->userpass_input_buflen = buflen;
2140 ssh->userpass_input_bufpos = 0;
2141 ssh->userpass_input_echo = echo;
2145 * Process some terminal data in the course of username/password
2146 * input. Returns >0 for success (line of input returned in
2147 * buffer), <0 for failure (user hit ^C/^D, bomb out and exit), 0
2148 * for inconclusive (keep waiting for more input please).
2150 int process_userpass_input(Ssh ssh, unsigned char *in, int inlen)
2155 switch (c = *in++) {
2158 ssh->userpass_input_buffer[ssh->userpass_input_bufpos] = 0;
2159 ssh->userpass_input_buffer[ssh->userpass_input_buflen-1] = 0;
2164 if (ssh->userpass_input_bufpos > 0) {
2165 if (ssh->userpass_input_echo)
2166 c_write_str(ssh, "\b \b");
2167 ssh->userpass_input_bufpos--;
2172 while (ssh->userpass_input_bufpos > 0) {
2173 if (ssh->userpass_input_echo)
2174 c_write_str(ssh, "\b \b");
2175 ssh->userpass_input_bufpos--;
2183 if (((c >= ' ' && c <= '~') ||
2184 ((unsigned char) c >= 160))
2185 && ssh->userpass_input_bufpos < ssh->userpass_input_buflen-1) {
2186 ssh->userpass_input_buffer[ssh->userpass_input_bufpos++] = c;
2187 if (ssh->userpass_input_echo)
2188 c_write(ssh, &c, 1);
2197 * Handle the key exchange and user authentication phases.
2199 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
2202 unsigned char cookie[8];
2203 struct RSAKey servkey, hostkey;
2204 struct MD5Context md5c;
2205 struct do_ssh1_login_state {
2207 unsigned char *rsabuf, *keystr1, *keystr2;
2208 unsigned long supported_ciphers_mask, supported_auths_mask;
2209 int tried_publickey, tried_agent;
2210 int tis_auth_refused, ccard_auth_refused;
2211 unsigned char session_id[16];
2214 void *publickey_blob;
2215 int publickey_bloblen;
2221 unsigned char request[5], *response, *p;
2230 crState(do_ssh1_login_state);
2232 crBegin(ssh->do_ssh1_login_crstate);
2237 if (ssh->pktin.type != SSH1_SMSG_PUBLIC_KEY) {
2238 bombout(("Public key packet not received"));
2242 logevent("Received public keys");
2244 memcpy(cookie, ssh->pktin.body, 8);
2246 i = makekey(ssh->pktin.body + 8, &servkey, &s->keystr1, 0);
2247 j = makekey(ssh->pktin.body + 8 + i, &hostkey, &s->keystr2, 0);
2250 * Log the host key fingerprint.
2254 logevent("Host key fingerprint is:");
2255 strcpy(logmsg, " ");
2256 hostkey.comment = NULL;
2257 rsa_fingerprint(logmsg + strlen(logmsg),
2258 sizeof(logmsg) - strlen(logmsg), &hostkey);
2262 ssh->v1_remote_protoflags = GET_32BIT(ssh->pktin.body + 8 + i + j);
2263 s->supported_ciphers_mask = GET_32BIT(ssh->pktin.body + 12 + i + j);
2264 s->supported_auths_mask = GET_32BIT(ssh->pktin.body + 16 + i + j);
2266 ssh->v1_local_protoflags =
2267 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
2268 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
2271 MD5Update(&md5c, s->keystr2, hostkey.bytes);
2272 MD5Update(&md5c, s->keystr1, servkey.bytes);
2273 MD5Update(&md5c, ssh->pktin.body, 8);
2274 MD5Final(s->session_id, &md5c);
2276 for (i = 0; i < 32; i++)
2277 ssh->session_key[i] = random_byte();
2279 s->len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
2281 s->rsabuf = smalloc(s->len);
2283 fatalbox("Out of memory");
2286 * Verify the host key.
2290 * First format the key into a string.
2292 int len = rsastr_len(&hostkey);
2293 char fingerprint[100];
2294 char *keystr = smalloc(len);
2296 fatalbox("Out of memory");
2297 rsastr_fmt(keystr, &hostkey);
2298 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
2299 verify_ssh_host_key(ssh->savedhost, ssh->savedport, "rsa", keystr,
2304 for (i = 0; i < 32; i++) {
2305 s->rsabuf[i] = ssh->session_key[i];
2307 s->rsabuf[i] ^= s->session_id[i];
2310 if (hostkey.bytes > servkey.bytes) {
2311 rsaencrypt(s->rsabuf, 32, &servkey);
2312 rsaencrypt(s->rsabuf, servkey.bytes, &hostkey);
2314 rsaencrypt(s->rsabuf, 32, &hostkey);
2315 rsaencrypt(s->rsabuf, hostkey.bytes, &servkey);
2318 logevent("Encrypted session key");
2321 int cipher_chosen = 0, warn = 0;
2322 char *cipher_string = NULL;
2324 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
2325 int next_cipher = cfg.ssh_cipherlist[i];
2326 if (next_cipher == CIPHER_WARN) {
2327 /* If/when we choose a cipher, warn about it */
2329 } else if (next_cipher == CIPHER_AES) {
2330 /* XXX Probably don't need to mention this. */
2331 logevent("AES not supported in SSH1, skipping");
2333 switch (next_cipher) {
2334 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
2335 cipher_string = "3DES"; break;
2336 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
2337 cipher_string = "Blowfish"; break;
2338 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
2339 cipher_string = "single-DES"; break;
2341 if (s->supported_ciphers_mask & (1 << s->cipher_type))
2345 if (!cipher_chosen) {
2346 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
2347 bombout(("Server violates SSH 1 protocol by not "
2348 "supporting 3DES encryption"));
2350 /* shouldn't happen */
2351 bombout(("No supported ciphers found"));
2355 /* Warn about chosen cipher if necessary. */
2357 askcipher(cipher_string, 0);
2360 switch (s->cipher_type) {
2361 case SSH_CIPHER_3DES:
2362 logevent("Using 3DES encryption");
2364 case SSH_CIPHER_DES:
2365 logevent("Using single-DES encryption");
2367 case SSH_CIPHER_BLOWFISH:
2368 logevent("Using Blowfish encryption");
2372 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
2373 PKT_CHAR, s->cipher_type,
2374 PKT_DATA, cookie, 8,
2375 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
2376 PKT_DATA, s->rsabuf, s->len,
2377 PKT_INT, ssh->v1_local_protoflags, PKT_END);
2379 logevent("Trying to enable encryption...");
2383 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
2384 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
2386 ssh->v1_cipher_ctx = ssh->cipher->make_context();
2387 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
2390 sprintf(buf, "Initialised %.200s encryption", ssh->cipher->text_name);
2394 ssh->crcda_ctx = crcda_make_context();
2395 logevent("Installing CRC compensation attack detector");
2399 if (ssh->pktin.type != SSH1_SMSG_SUCCESS) {
2400 bombout(("Encryption not successfully enabled"));
2404 logevent("Successfully started encryption");
2408 if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
2409 if (ssh_get_line && !ssh_getline_pw_only) {
2410 if (!ssh_get_line("login as: ",
2411 s->username, sizeof(s->username), FALSE)) {
2413 * get_line failed to get a username.
2416 logevent("No username provided. Abandoning session.");
2417 ssh->state = SSH_STATE_CLOSED;
2421 int ret; /* need not be kept over crReturn */
2422 c_write_str(ssh, "login as: ");
2425 setup_userpass_input(ssh, s->username, sizeof(s->username), 1);
2427 crWaitUntil(!ispkt);
2428 ret = process_userpass_input(ssh, in, inlen);
2432 c_write_str(ssh, "\r\n");
2435 strncpy(s->username, cfg.username, sizeof(s->username));
2436 s->username[sizeof(s->username)-1] = '\0';
2439 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, s->username, PKT_END);
2441 char userlog[22 + sizeof(s->username)];
2442 sprintf(userlog, "Sent username \"%s\"", s->username);
2444 if (flags & FLAG_INTERACTIVE &&
2445 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
2446 strcat(userlog, "\r\n");
2447 c_write_str(ssh, userlog);
2454 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA)) {
2455 /* We must not attempt PK auth. Pretend we've already tried it. */
2456 s->tried_publickey = s->tried_agent = 1;
2458 s->tried_publickey = s->tried_agent = 0;
2460 s->tis_auth_refused = s->ccard_auth_refused = 0;
2461 /* Load the public half of cfg.keyfile so we notice if it's in Pageant */
2463 if (!rsakey_pubblob(cfg.keyfile,
2464 &s->publickey_blob, &s->publickey_bloblen))
2465 s->publickey_blob = NULL;
2467 s->publickey_blob = NULL;
2469 while (ssh->pktin.type == SSH1_SMSG_FAILURE) {
2470 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
2472 if (agent_exists() && !s->tried_agent) {
2474 * Attempt RSA authentication using Pageant.
2480 logevent("Pageant is running. Requesting keys.");
2482 /* Request the keys held by the agent. */
2483 PUT_32BIT(s->request, 1);
2484 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
2485 agent_query(s->request, 5, &r, &s->responselen);
2486 s->response = (unsigned char *) r;
2487 if (s->response && s->responselen >= 5 &&
2488 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
2489 s->p = s->response + 5;
2490 s->nkeys = GET_32BIT(s->p);
2494 sprintf(buf, "Pageant has %d SSH1 keys", s->nkeys);
2497 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
2500 sprintf(buf, "Trying Pageant key #%d", s->keyi);
2503 if (s->publickey_blob &&
2504 !memcmp(s->p, s->publickey_blob,
2505 s->publickey_bloblen)) {
2506 logevent("This key matches configured key file");
2507 s->tried_publickey = 1;
2510 s->p += ssh1_read_bignum(s->p, &s->key.exponent);
2511 s->p += ssh1_read_bignum(s->p, &s->key.modulus);
2512 s->commentlen = GET_32BIT(s->p);
2515 s->p += s->commentlen;
2516 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
2517 PKT_BIGNUM, s->key.modulus, PKT_END);
2519 if (ssh->pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
2520 logevent("Key refused");
2523 logevent("Received RSA challenge");
2524 ssh1_read_bignum(ssh->pktin.body, &s->challenge);
2526 char *agentreq, *q, *ret;
2529 len = 1 + 4; /* message type, bit count */
2530 len += ssh1_bignum_length(s->key.exponent);
2531 len += ssh1_bignum_length(s->key.modulus);
2532 len += ssh1_bignum_length(s->challenge);
2533 len += 16; /* session id */
2534 len += 4; /* response format */
2535 agentreq = smalloc(4 + len);
2536 PUT_32BIT(agentreq, len);
2538 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
2539 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
2541 q += ssh1_write_bignum(q, s->key.exponent);
2542 q += ssh1_write_bignum(q, s->key.modulus);
2543 q += ssh1_write_bignum(q, s->challenge);
2544 memcpy(q, s->session_id, 16);
2546 PUT_32BIT(q, 1); /* response format */
2547 agent_query(agentreq, len + 4, &vret, &retlen);
2551 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
2552 logevent("Sending Pageant's response");
2553 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
2554 PKT_DATA, ret + 5, 16,
2558 if (ssh->pktin.type == SSH1_SMSG_SUCCESS) {
2560 ("Pageant's response accepted");
2561 if (flags & FLAG_VERBOSE) {
2562 c_write_str(ssh, "Authenticated using"
2564 c_write(ssh, s->commentp,
2566 c_write_str(ssh, "\" from agent\r\n");
2571 ("Pageant's response not accepted");
2574 ("Pageant failed to answer challenge");
2578 logevent("No reply received from Pageant");
2581 freebn(s->key.exponent);
2582 freebn(s->key.modulus);
2583 freebn(s->challenge);
2591 if (*cfg.keyfile && !s->tried_publickey)
2592 s->pwpkt_type = SSH1_CMSG_AUTH_RSA;
2594 if (cfg.try_tis_auth &&
2595 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
2596 !s->tis_auth_refused) {
2597 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
2598 logevent("Requested TIS authentication");
2599 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
2601 if (ssh->pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
2602 logevent("TIS authentication declined");
2603 if (flags & FLAG_INTERACTIVE)
2604 c_write_str(ssh, "TIS authentication refused.\r\n");
2605 s->tis_auth_refused = 1;
2608 int challengelen = GET_32BIT(ssh->pktin.body);
2609 logevent("Received TIS challenge");
2610 if (challengelen > sizeof(s->prompt) - 1)
2611 challengelen = sizeof(s->prompt) - 1;/* prevent overrun */
2612 memcpy(s->prompt, ssh->pktin.body + 4, challengelen);
2613 /* Prompt heuristic comes from OpenSSH */
2614 strncpy(s->prompt + challengelen,
2615 memchr(s->prompt, '\n', challengelen) ?
2616 "": "\r\nResponse: ",
2617 (sizeof s->prompt) - challengelen);
2618 s->prompt[(sizeof s->prompt) - 1] = '\0';
2621 if (cfg.try_tis_auth &&
2622 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
2623 !s->ccard_auth_refused) {
2624 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
2625 logevent("Requested CryptoCard authentication");
2626 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
2628 if (ssh->pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
2629 logevent("CryptoCard authentication declined");
2630 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
2631 s->ccard_auth_refused = 1;
2634 int challengelen = GET_32BIT(ssh->pktin.body);
2635 logevent("Received CryptoCard challenge");
2636 if (challengelen > sizeof(s->prompt) - 1)
2637 challengelen = sizeof(s->prompt) - 1;/* prevent overrun */
2638 memcpy(s->prompt, ssh->pktin.body + 4, challengelen);
2639 strncpy(s->prompt + challengelen,
2640 memchr(s->prompt, '\n', challengelen) ?
2641 "" : "\r\nResponse: ",
2642 sizeof(s->prompt) - challengelen);
2643 s->prompt[sizeof(s->prompt) - 1] = '\0';
2646 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
2647 sprintf(s->prompt, "%.90s@%.90s's password: ",
2648 s->username, ssh->savedhost);
2650 if (s->pwpkt_type == SSH1_CMSG_AUTH_RSA) {
2651 char *comment = NULL;
2654 if (flags & FLAG_VERBOSE)
2655 c_write_str(ssh, "Trying public key authentication.\r\n");
2656 sprintf(msgbuf, "Trying public key \"%.200s\"", cfg.keyfile);
2658 type = key_type(cfg.keyfile);
2659 if (type != SSH_KEYTYPE_SSH1) {
2660 sprintf(msgbuf, "Key is of wrong type (%s)",
2661 key_type_to_str(type));
2663 c_write_str(ssh, msgbuf);
2664 c_write_str(ssh, "\r\n");
2665 s->tried_publickey = 1;
2668 if (!rsakey_encrypted(cfg.keyfile, &comment)) {
2669 if (flags & FLAG_VERBOSE)
2670 c_write_str(ssh, "No passphrase required.\r\n");
2673 sprintf(s->prompt, "Passphrase for key \"%.100s\": ", comment);
2678 * Show password prompt, having first obtained it via a TIS
2679 * or CryptoCard exchange if we're doing TIS or CryptoCard
2683 if (!ssh_get_line(s->prompt, s->password,
2684 sizeof(s->password), TRUE)) {
2686 * get_line failed to get a password (for example
2687 * because one was supplied on the command line
2688 * which has already failed to work). Terminate.
2690 send_packet(ssh, SSH1_MSG_DISCONNECT,
2691 PKT_STR, "No more passwords available to try",
2693 logevent("Unable to authenticate");
2694 connection_fatal("Unable to authenticate");
2695 ssh->state = SSH_STATE_CLOSED;
2699 /* Prompt may have come from server. We've munged it a bit, so
2700 * we know it to be zero-terminated at least once. */
2701 int ret; /* need not be saved over crReturn */
2702 c_write_untrusted(ssh, s->prompt, strlen(s->prompt));
2705 setup_userpass_input(ssh, s->password, sizeof(s->password), 0);
2707 crWaitUntil(!ispkt);
2708 ret = process_userpass_input(ssh, in, inlen);
2712 c_write_str(ssh, "\r\n");
2716 if (s->pwpkt_type == SSH1_CMSG_AUTH_RSA) {
2718 * Try public key authentication with the specified
2721 s->tried_publickey = 1;
2724 int ret = loadrsakey(cfg.keyfile, &s->key, s->password);
2726 c_write_str(ssh, "Couldn't load private key from ");
2727 c_write_str(ssh, cfg.keyfile);
2728 c_write_str(ssh, ".\r\n");
2729 continue; /* go and try password */
2732 c_write_str(ssh, "Wrong passphrase.\r\n");
2733 s->tried_publickey = 0;
2734 continue; /* try again */
2739 * Send a public key attempt.
2741 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
2742 PKT_BIGNUM, s->key.modulus, PKT_END);
2745 if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
2746 c_write_str(ssh, "Server refused our public key.\r\n");
2747 continue; /* go and try password */
2749 if (ssh->pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
2750 bombout(("Bizarre response to offer of public key"));
2756 unsigned char buffer[32];
2757 Bignum challenge, response;
2759 ssh1_read_bignum(ssh->pktin.body, &challenge);
2760 response = rsadecrypt(challenge, &s->key);
2761 freebn(s->key.private_exponent);/* burn the evidence */
2763 for (i = 0; i < 32; i++) {
2764 buffer[i] = bignum_byte(response, 31 - i);
2768 MD5Update(&md5c, buffer, 32);
2769 MD5Update(&md5c, s->session_id, 16);
2770 MD5Final(buffer, &md5c);
2772 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
2773 PKT_DATA, buffer, 16, PKT_END);
2780 if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
2781 if (flags & FLAG_VERBOSE)
2782 c_write_str(ssh, "Failed to authenticate with"
2783 " our public key.\r\n");
2784 continue; /* go and try password */
2785 } else if (ssh->pktin.type != SSH1_SMSG_SUCCESS) {
2786 bombout(("Bizarre response to RSA authentication response"));
2790 break; /* we're through! */
2792 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
2794 * Defence against traffic analysis: we send a
2795 * whole bunch of packets containing strings of
2796 * different lengths. One of these strings is the
2797 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
2798 * The others are all random data in
2799 * SSH1_MSG_IGNORE packets. This way a passive
2800 * listener can't tell which is the password, and
2801 * hence can't deduce the password length.
2803 * Anybody with a password length greater than 16
2804 * bytes is going to have enough entropy in their
2805 * password that a listener won't find it _that_
2806 * much help to know how long it is. So what we'll
2809 * - if password length < 16, we send 15 packets
2810 * containing string lengths 1 through 15
2812 * - otherwise, we let N be the nearest multiple
2813 * of 8 below the password length, and send 8
2814 * packets containing string lengths N through
2815 * N+7. This won't obscure the order of
2816 * magnitude of the password length, but it will
2817 * introduce a bit of extra uncertainty.
2819 * A few servers (the old 1.2.18 through 1.2.22)
2820 * can't deal with SSH1_MSG_IGNORE. For these
2821 * servers, we need an alternative defence. We make
2822 * use of the fact that the password is interpreted
2823 * as a C string: so we can append a NUL, then some
2826 * One server (a Cisco one) can deal with neither
2827 * SSH1_MSG_IGNORE _nor_ a padded password string.
2828 * For this server we are left with no defences
2829 * against password length sniffing.
2831 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE)) {
2833 * The server can deal with SSH1_MSG_IGNORE, so
2834 * we can use the primary defence.
2836 int bottom, top, pwlen, i;
2839 pwlen = strlen(s->password);
2841 bottom = 0; /* zero length passwords are OK! :-) */
2844 bottom = pwlen & ~7;
2848 assert(pwlen >= bottom && pwlen <= top);
2850 randomstr = smalloc(top + 1);
2852 for (i = bottom; i <= top; i++) {
2854 defer_packet(ssh, s->pwpkt_type,
2855 PKT_STR, s->password, PKT_END);
2857 for (j = 0; j < i; j++) {
2859 randomstr[j] = random_byte();
2860 } while (randomstr[j] == '\0');
2862 randomstr[i] = '\0';
2863 defer_packet(ssh, SSH1_MSG_IGNORE,
2864 PKT_STR, randomstr, PKT_END);
2867 logevent("Sending password with camouflage packets");
2868 ssh_pkt_defersend(ssh);
2870 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
2872 * The server can't deal with SSH1_MSG_IGNORE
2873 * but can deal with padded passwords, so we
2874 * can use the secondary defence.
2880 len = strlen(s->password);
2881 if (len < sizeof(string)) {
2883 strcpy(string, s->password);
2884 len++; /* cover the zero byte */
2885 while (len < sizeof(string)) {
2886 string[len++] = (char) random_byte();
2891 logevent("Sending length-padded password");
2892 send_packet(ssh, s->pwpkt_type, PKT_INT, len,
2893 PKT_DATA, ss, len, PKT_END);
2896 * The server has _both_
2897 * BUG_CHOKES_ON_SSH1_IGNORE and
2898 * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
2899 * therefore nothing we can do.
2902 len = strlen(s->password);
2903 logevent("Sending unpadded password");
2904 send_packet(ssh, s->pwpkt_type, PKT_INT, len,
2905 PKT_DATA, s->password, len, PKT_END);
2908 send_packet(ssh, s->pwpkt_type, PKT_STR, s->password, PKT_END);
2911 logevent("Sent password");
2912 memset(s->password, 0, strlen(s->password));
2914 if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
2915 if (flags & FLAG_VERBOSE)
2916 c_write_str(ssh, "Access denied\r\n");
2917 logevent("Authentication refused");
2918 } else if (ssh->pktin.type != SSH1_SMSG_SUCCESS) {
2919 bombout(("Strange packet received, type %d", ssh->pktin.type));
2924 logevent("Authentication successful");
2929 void sshfwd_close(struct ssh_channel *c)
2933 if (c && !c->closes) {
2935 * If the channel's remoteid is -1, we have sent
2936 * CHANNEL_OPEN for this channel, but it hasn't even been
2937 * acknowledged by the server. So we must set a close flag
2938 * on it now, and then when the server acks the channel
2939 * open, we can close it then.
2941 if (((int)c->remoteid) != -1) {
2942 if (ssh->version == 1) {
2943 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
2946 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_CLOSE);
2947 ssh2_pkt_adduint32(ssh, c->remoteid);
2951 c->closes = 1; /* sent MSG_CLOSE */
2952 if (c->type == CHAN_X11) {
2954 logevent("Forwarded X11 connection terminated");
2955 } else if (c->type == CHAN_SOCKDATA ||
2956 c->type == CHAN_SOCKDATA_DORMANT) {
2958 logevent("Forwarded port closed");
2963 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
2967 if (ssh->version == 1) {
2968 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
2969 PKT_INT, c->remoteid,
2970 PKT_INT, len, PKT_DATA, buf, len, PKT_END);
2972 * In SSH1 we can return 0 here - implying that forwarded
2973 * connections are never individually throttled - because
2974 * the only circumstance that can cause throttling will be
2975 * the whole SSH connection backing up, in which case
2976 * _everything_ will be throttled as a whole.
2980 ssh2_add_channel_data(c, buf, len);
2981 return ssh2_try_send(c);
2985 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
2989 if (ssh->version == 1) {
2990 if (c->v.v1.throttling && bufsize < SSH1_BUFFER_LIMIT) {
2991 c->v.v1.throttling = 0;
2992 ssh1_throttle(ssh, -1);
2995 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
2999 static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
3001 crBegin(ssh->ssh1_protocol_crstate);
3005 while (!do_ssh1_login(ssh, in, inlen, ispkt)) {
3008 if (ssh->state == SSH_STATE_CLOSED)
3011 if (cfg.agentfwd && agent_exists()) {
3012 logevent("Requesting agent forwarding");
3013 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
3017 if (ssh->pktin.type != SSH1_SMSG_SUCCESS
3018 && ssh->pktin.type != SSH1_SMSG_FAILURE) {
3019 bombout(("Protocol confusion"));
3021 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
3022 logevent("Agent forwarding refused");
3024 logevent("Agent forwarding enabled");
3025 ssh->agentfwd_enabled = TRUE;
3029 if (cfg.x11_forward) {
3030 char proto[20], data[64];
3031 logevent("Requesting X11 forwarding");
3032 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
3033 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
3034 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
3035 PKT_STR, proto, PKT_STR, data,
3036 PKT_INT, 0, PKT_END);
3038 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
3039 PKT_STR, proto, PKT_STR, data, PKT_END);
3044 if (ssh->pktin.type != SSH1_SMSG_SUCCESS
3045 && ssh->pktin.type != SSH1_SMSG_FAILURE) {
3046 bombout(("Protocol confusion"));
3048 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
3049 logevent("X11 forwarding refused");
3051 logevent("X11 forwarding enabled");
3052 ssh->X11_fwd_enabled = TRUE;
3059 int sport,dport,sserv,dserv;
3060 char sports[256], dports[256], host[256];
3064 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
3065 /* Add port forwardings. */
3066 ssh->portfwd_strptr = cfg.portfwd;
3067 while (*ssh->portfwd_strptr) {
3068 type = *ssh->portfwd_strptr++;
3070 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != '\t')
3071 sports[n++] = *ssh->portfwd_strptr++;
3073 if (*ssh->portfwd_strptr == '\t')
3074 ssh->portfwd_strptr++;
3076 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != ':')
3077 host[n++] = *ssh->portfwd_strptr++;
3079 if (*ssh->portfwd_strptr == ':')
3080 ssh->portfwd_strptr++;
3082 while (*ssh->portfwd_strptr)
3083 dports[n++] = *ssh->portfwd_strptr++;
3085 ssh->portfwd_strptr++;
3086 dport = atoi(dports);
3090 se = getservbyname(dports, NULL);
3092 dport = ntohs(se->s_port);
3095 "Service lookup failed for destination port \"%s\"",
3100 sport = atoi(sports);
3104 se = getservbyname(sports, NULL);
3106 sport = ntohs(se->s_port);
3109 "Service lookup failed for source port \"%s\"",
3114 if (sport && dport) {
3116 pfd_addforward(host, dport, sport);
3117 sprintf(buf, "Local port %.*s%.*s%d%.*s forwarding to"
3118 " %s:%.*s%.*s%d%.*s",
3119 sserv ? strlen(sports) : 0, sports,
3120 sserv, "(", sport, sserv, ")",
3122 dserv ? strlen(dports) : 0, dports,
3123 dserv, "(", dport, dserv, ")");
3126 struct ssh_rportfwd *pf;
3127 pf = smalloc(sizeof(*pf));
3128 strcpy(pf->dhost, host);
3130 if (add234(ssh->rportfwds, pf) != pf) {
3132 "Duplicate remote port forwarding to %s:%d",
3137 sprintf(buf, "Requesting remote port %.*s%.*s%d%.*s"
3138 " forward to %s:%.*s%.*s%d%.*s",
3139 sserv ? strlen(sports) : 0, sports,
3140 sserv, "(", sport, sserv, ")",
3142 dserv ? strlen(dports) : 0, dports,
3143 dserv, "(", dport, dserv, ")");
3145 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
3153 if (ssh->pktin.type != SSH1_SMSG_SUCCESS
3154 && ssh->pktin.type != SSH1_SMSG_FAILURE) {
3155 bombout(("Protocol confusion"));
3157 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
3158 c_write_str(ssh, "Server refused port"
3161 logevent("Remote port forwarding enabled");
3169 send_packet(ssh, SSH1_CMSG_REQUEST_PTY,
3170 PKT_STR, cfg.termtype,
3171 PKT_INT, ssh->term_height,
3172 PKT_INT, ssh->term_width,
3173 PKT_INT, 0, PKT_INT, 0, PKT_CHAR, 0, PKT_END);
3174 ssh->state = SSH_STATE_INTERMED;
3178 if (ssh->pktin.type != SSH1_SMSG_SUCCESS
3179 && ssh->pktin.type != SSH1_SMSG_FAILURE) {
3180 bombout(("Protocol confusion"));
3182 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
3183 c_write_str(ssh, "Server refused to allocate pty\r\n");
3184 ssh->editing = ssh->echoing = 1;
3186 logevent("Allocated pty");
3188 ssh->editing = ssh->echoing = 1;
3191 if (cfg.compression) {
3192 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
3196 if (ssh->pktin.type != SSH1_SMSG_SUCCESS
3197 && ssh->pktin.type != SSH1_SMSG_FAILURE) {
3198 bombout(("Protocol confusion"));
3200 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
3201 c_write_str(ssh, "Server refused to compress\r\n");
3203 logevent("Started compression");
3204 ssh->v1_compressing = TRUE;
3205 ssh->cs_comp_ctx = zlib_compress_init();
3206 logevent("Initialised zlib (RFC1950) compression");
3207 ssh->sc_comp_ctx = zlib_decompress_init();
3208 logevent("Initialised zlib (RFC1950) decompression");
3212 * Start the shell or command.
3214 * Special case: if the first-choice command is an SSH2
3215 * subsystem (hence not usable here) and the second choice
3216 * exists, we fall straight back to that.
3219 char *cmd = cfg.remote_cmd_ptr;
3221 if (cfg.ssh_subsys && cfg.remote_cmd_ptr2) {
3222 cmd = cfg.remote_cmd_ptr2;
3223 ssh->fallback_cmd = TRUE;
3226 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
3228 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
3229 logevent("Started session");
3232 ssh->state = SSH_STATE_SESSION;
3233 if (ssh->size_needed)
3234 ssh_size(ssh, ssh->term_width, ssh->term_height);
3235 if (ssh->eof_needed)
3236 ssh_special(ssh, TS_EOF);
3239 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
3241 ssh->channels = newtree234(ssh_channelcmp);
3245 if (ssh->pktin.type == SSH1_SMSG_STDOUT_DATA ||
3246 ssh->pktin.type == SSH1_SMSG_STDERR_DATA) {
3247 long len = GET_32BIT(ssh->pktin.body);
3249 from_backend(ssh->frontend,
3250 ssh->pktin.type == SSH1_SMSG_STDERR_DATA,
3251 ssh->pktin.body + 4, len);
3252 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
3253 ssh->v1_stdout_throttling = 1;
3254 ssh1_throttle(ssh, +1);
3256 } else if (ssh->pktin.type == SSH1_MSG_DISCONNECT) {
3257 ssh->state = SSH_STATE_CLOSED;
3258 logevent("Received disconnect request");
3260 } else if (ssh->pktin.type == SSH1_SMSG_X11_OPEN) {
3261 /* Remote side is trying to open a channel to talk to our
3262 * X-Server. Give them back a local channel number. */
3263 struct ssh_channel *c;
3265 logevent("Received X11 connect request");
3266 /* Refuse if X11 forwarding is disabled. */
3267 if (!ssh->X11_fwd_enabled) {
3268 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3269 PKT_INT, GET_32BIT(ssh->pktin.body), PKT_END);
3270 logevent("Rejected X11 connect request");
3272 c = smalloc(sizeof(struct ssh_channel));
3275 if (x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL) {
3276 logevent("opening X11 forward connection failed");
3278 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3279 PKT_INT, GET_32BIT(ssh->pktin.body),
3283 ("opening X11 forward connection succeeded");
3284 c->remoteid = GET_32BIT(ssh->pktin.body);
3285 c->localid = alloc_channel_id(ssh);
3287 c->v.v1.throttling = 0;
3288 c->type = CHAN_X11; /* identify channel type */
3289 add234(ssh->channels, c);
3290 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3291 PKT_INT, c->remoteid, PKT_INT,
3292 c->localid, PKT_END);
3293 logevent("Opened X11 forward channel");
3296 } else if (ssh->pktin.type == SSH1_SMSG_AGENT_OPEN) {
3297 /* Remote side is trying to open a channel to talk to our
3298 * agent. Give them back a local channel number. */
3299 struct ssh_channel *c;
3301 /* Refuse if agent forwarding is disabled. */
3302 if (!ssh->agentfwd_enabled) {
3303 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3304 PKT_INT, GET_32BIT(ssh->pktin.body), PKT_END);
3306 c = smalloc(sizeof(struct ssh_channel));
3308 c->remoteid = GET_32BIT(ssh->pktin.body);
3309 c->localid = alloc_channel_id(ssh);
3311 c->v.v1.throttling = 0;
3312 c->type = CHAN_AGENT; /* identify channel type */
3313 c->u.a.lensofar = 0;
3314 add234(ssh->channels, c);
3315 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3316 PKT_INT, c->remoteid, PKT_INT, c->localid,
3319 } else if (ssh->pktin.type == SSH1_MSG_PORT_OPEN) {
3320 /* Remote side is trying to open a channel to talk to a
3321 * forwarded port. Give them back a local channel number. */
3322 struct ssh_channel *c;
3323 struct ssh_rportfwd pf;
3325 char host[256], buf[1024];
3327 c = smalloc(sizeof(struct ssh_channel));
3330 hostsize = GET_32BIT(ssh->pktin.body+4);
3331 for(h = host, p = ssh->pktin.body+8; hostsize != 0; hostsize--) {
3332 if (h+1 < host+sizeof(host))
3337 port = GET_32BIT(p);
3339 strcpy(pf.dhost, host);
3342 if (find234(ssh->rportfwds, &pf, NULL) == NULL) {
3343 sprintf(buf, "Rejected remote port open request for %s:%d",
3346 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3347 PKT_INT, GET_32BIT(ssh->pktin.body), PKT_END);
3349 sprintf(buf, "Received remote port open request for %s:%d",
3352 e = pfd_newconnect(&c->u.pfd.s, host, port, c);
3355 sprintf(buf, "Port open failed: %s", e);
3358 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3359 PKT_INT, GET_32BIT(ssh->pktin.body),
3362 c->remoteid = GET_32BIT(ssh->pktin.body);
3363 c->localid = alloc_channel_id(ssh);
3365 c->v.v1.throttling = 0;
3366 c->type = CHAN_SOCKDATA; /* identify channel type */
3367 add234(ssh->channels, c);
3368 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3369 PKT_INT, c->remoteid, PKT_INT,
3370 c->localid, PKT_END);
3371 logevent("Forwarded port opened successfully");
3375 } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_OPEN_CONFIRMATION) {
3376 unsigned int remoteid = GET_32BIT(ssh->pktin.body);
3377 unsigned int localid = GET_32BIT(ssh->pktin.body+4);
3378 struct ssh_channel *c;
3380 c = find234(ssh->channels, &remoteid, ssh_channelfind);
3381 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
3382 c->remoteid = localid;
3383 c->type = CHAN_SOCKDATA;
3384 c->v.v1.throttling = 0;
3385 pfd_confirm(c->u.pfd.s);
3388 if (c && c->closes) {
3390 * We have a pending close on this channel,
3391 * which we decided on before the server acked
3392 * the channel open. So now we know the
3393 * remoteid, we can close it again.
3395 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE,
3396 PKT_INT, c->remoteid, PKT_END);
3399 } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_OPEN_FAILURE) {
3400 unsigned int remoteid = GET_32BIT(ssh->pktin.body);
3401 unsigned int localid = GET_32BIT(ssh->pktin.body+4);
3402 struct ssh_channel *c;
3404 c = find234(ssh->channels, &remoteid, ssh_channelfind);
3405 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
3406 logevent("Forwarded connection refused by server");
3407 pfd_close(c->u.pfd.s);
3408 del234(ssh->channels, c);
3412 } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
3413 ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
3414 /* Remote side closes a channel. */
3415 unsigned i = GET_32BIT(ssh->pktin.body);
3416 struct ssh_channel *c;
3417 c = find234(ssh->channels, &i, ssh_channelfind);
3418 if (c && ((int)c->remoteid) != -1) {
3421 (ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
3423 if ((c->closes == 0) && (c->type == CHAN_X11)) {
3424 logevent("Forwarded X11 connection terminated");
3425 assert(c->u.x11.s != NULL);
3426 x11_close(c->u.x11.s);
3429 if ((c->closes == 0) && (c->type == CHAN_SOCKDATA)) {
3430 logevent("Forwarded port closed");
3431 assert(c->u.pfd.s != NULL);
3432 pfd_close(c->u.pfd.s);
3436 c->closes |= (closetype << 2); /* seen this message */
3437 if (!(c->closes & closetype)) {
3438 send_packet(ssh, ssh->pktin.type, PKT_INT, c->remoteid,
3440 c->closes |= closetype; /* sent it too */
3443 if (c->closes == 15) {
3444 del234(ssh->channels, c);
3448 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
3449 ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE ? "" :
3450 "_CONFIRMATION", c ? "half-open" : "nonexistent",
3453 } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_DATA) {
3454 /* Data sent down one of our channels. */
3455 int i = GET_32BIT(ssh->pktin.body);
3456 int len = GET_32BIT(ssh->pktin.body + 4);
3457 unsigned char *p = ssh->pktin.body + 8;
3458 struct ssh_channel *c;
3459 c = find234(ssh->channels, &i, ssh_channelfind);
3464 bufsize = x11_send(c->u.x11.s, p, len);
3467 bufsize = pfd_send(c->u.pfd.s, p, len);
3470 /* Data for an agent message. Buffer it. */
3472 if (c->u.a.lensofar < 4) {
3473 int l = min(4 - c->u.a.lensofar, len);
3474 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
3478 c->u.a.lensofar += l;
3480 if (c->u.a.lensofar == 4) {
3482 4 + GET_32BIT(c->u.a.msglen);
3483 c->u.a.message = smalloc(c->u.a.totallen);
3484 memcpy(c->u.a.message, c->u.a.msglen, 4);
3486 if (c->u.a.lensofar >= 4 && len > 0) {
3488 min(c->u.a.totallen - c->u.a.lensofar,
3490 memcpy(c->u.a.message + c->u.a.lensofar, p,
3494 c->u.a.lensofar += l;
3496 if (c->u.a.lensofar == c->u.a.totallen) {
3497 void *reply, *sentreply;
3499 agent_query(c->u.a.message,
3500 c->u.a.totallen, &reply,
3505 /* Fake SSH_AGENT_FAILURE. */
3506 sentreply = "\0\0\0\1\5";
3509 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3510 PKT_INT, c->remoteid,
3512 PKT_DATA, sentreply, replylen,
3516 sfree(c->u.a.message);
3517 c->u.a.lensofar = 0;
3520 bufsize = 0; /* agent channels never back up */
3523 if (!c->v.v1.throttling && bufsize > SSH1_BUFFER_LIMIT) {
3524 c->v.v1.throttling = 1;
3525 ssh1_throttle(ssh, +1);
3528 } else if (ssh->pktin.type == SSH1_SMSG_SUCCESS) {
3529 /* may be from EXEC_SHELL on some servers */
3530 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
3531 /* may be from EXEC_SHELL on some servers
3532 * if no pty is available or in other odd cases. Ignore */
3533 } else if (ssh->pktin.type == SSH1_SMSG_EXIT_STATUS) {
3535 ssh->exitcode = GET_32BIT(ssh->pktin.body);
3536 sprintf(buf, "Server sent command exit status %d",
3539 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
3541 * In case `helpful' firewalls or proxies tack
3542 * extra human-readable text on the end of the
3543 * session which we might mistake for another
3544 * encrypted packet, we close the session once
3545 * we've sent EXIT_CONFIRMATION.
3547 ssh->state = SSH_STATE_CLOSED;
3550 bombout(("Strange packet received: type %d", ssh->pktin.type));
3555 int len = min(inlen, 512);
3556 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
3557 PKT_INT, len, PKT_DATA, in, len, PKT_END);
3568 * Utility routine for decoding comma-separated strings in KEXINIT.
3570 static int in_commasep_string(char *needle, char *haystack, int haylen)
3572 int needlen = strlen(needle);
3575 * Is it at the start of the string?
3577 if (haylen >= needlen && /* haystack is long enough */
3578 !memcmp(needle, haystack, needlen) && /* initial match */
3579 (haylen == needlen || haystack[needlen] == ',')
3580 /* either , or EOS follows */
3584 * If not, search for the next comma and resume after that.
3585 * If no comma found, terminate.
3587 while (haylen > 0 && *haystack != ',')
3588 haylen--, haystack++;
3591 haylen--, haystack++; /* skip over comma itself */
3596 * SSH2 key creation method.
3598 static void ssh2_mkkey(Ssh ssh, Bignum K, char *H, char *sessid, char chr,
3602 /* First 20 bytes. */
3604 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
3606 SHA_Bytes(&s, H, 20);
3607 SHA_Bytes(&s, &chr, 1);
3608 SHA_Bytes(&s, sessid, 20);
3609 SHA_Final(&s, keyspace);
3610 /* Next 20 bytes. */
3612 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
3614 SHA_Bytes(&s, H, 20);
3615 SHA_Bytes(&s, keyspace, 20);
3616 SHA_Final(&s, keyspace + 20);
3620 * Handle the SSH2 transport layer.
3622 static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen, int ispkt)
3624 struct do_ssh2_transport_state {
3625 int nbits, pbits, warn;
3626 Bignum p, g, e, f, K;
3627 int kex_init_value, kex_reply_value;
3628 const struct ssh_mac **maclist;
3630 const struct ssh2_cipher *cscipher_tobe;
3631 const struct ssh2_cipher *sccipher_tobe;
3632 const struct ssh_mac *csmac_tobe;
3633 const struct ssh_mac *scmac_tobe;
3634 const struct ssh_compress *cscomp_tobe;
3635 const struct ssh_compress *sccomp_tobe;
3636 char *hostkeydata, *sigdata, *keystr, *fingerprint;
3637 int hostkeylen, siglen;
3638 void *hkey; /* actual host key */
3639 unsigned char exchange_hash[20];
3640 int n_preferred_ciphers;
3641 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
3642 const struct ssh_compress *preferred_comp;
3645 crState(do_ssh2_transport_state);
3647 crBegin(ssh->do_ssh2_transport_crstate);
3649 s->cscipher_tobe = s->sccipher_tobe = NULL;
3650 s->csmac_tobe = s->scmac_tobe = NULL;
3651 s->cscomp_tobe = s->sccomp_tobe = NULL;
3659 * Set up the preferred ciphers. (NULL => warn below here)
3661 s->n_preferred_ciphers = 0;
3662 for (i = 0; i < CIPHER_MAX; i++) {
3663 switch (cfg.ssh_cipherlist[i]) {
3664 case CIPHER_BLOWFISH:
3665 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
3668 if (cfg.ssh2_des_cbc) {
3669 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
3673 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
3676 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
3679 /* Flag for later. Don't bother if it's the last in
3681 if (i < CIPHER_MAX - 1) {
3682 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
3690 * Set up preferred compression.
3692 if (cfg.compression)
3693 s->preferred_comp = &ssh_zlib;
3695 s->preferred_comp = &ssh_comp_none;
3698 * Be prepared to work around the buggy MAC problem.
3700 if (ssh->remote_bugs & BUG_SSH2_HMAC)
3701 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
3703 s->maclist = macs, s->nmacs = lenof(macs);
3707 int i, j, cipherstr_started;
3710 * Construct and send our key exchange packet.
3712 ssh2_pkt_init(ssh, SSH2_MSG_KEXINIT);
3713 for (i = 0; i < 16; i++)
3714 ssh2_pkt_addbyte(ssh, (unsigned char) random_byte());
3715 /* List key exchange algorithms. */
3716 ssh2_pkt_addstring_start(ssh);
3717 for (i = 0; i < lenof(kex_algs); i++) {
3718 if (kex_algs[i] == &ssh_diffiehellman_gex &&
3719 (ssh->remote_bugs & BUG_SSH2_DH_GEX))
3721 ssh2_pkt_addstring_str(ssh, kex_algs[i]->name);
3722 if (i < lenof(kex_algs) - 1)
3723 ssh2_pkt_addstring_str(ssh, ",");
3725 /* List server host key algorithms. */
3726 ssh2_pkt_addstring_start(ssh);
3727 for (i = 0; i < lenof(hostkey_algs); i++) {
3728 ssh2_pkt_addstring_str(ssh, hostkey_algs[i]->name);
3729 if (i < lenof(hostkey_algs) - 1)
3730 ssh2_pkt_addstring_str(ssh, ",");
3732 /* List client->server encryption algorithms. */
3733 ssh2_pkt_addstring_start(ssh);
3734 cipherstr_started = 0;
3735 for (i = 0; i < s->n_preferred_ciphers; i++) {
3736 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
3737 if (!c) continue; /* warning flag */
3738 for (j = 0; j < c->nciphers; j++) {
3739 if (cipherstr_started)
3740 ssh2_pkt_addstring_str(ssh, ",");
3741 ssh2_pkt_addstring_str(ssh, c->list[j]->name);
3742 cipherstr_started = 1;
3745 /* List server->client encryption algorithms. */
3746 ssh2_pkt_addstring_start(ssh);
3747 cipherstr_started = 0;
3748 for (i = 0; i < s->n_preferred_ciphers; i++) {
3749 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
3750 if (!c) continue; /* warning flag */
3751 for (j = 0; j < c->nciphers; j++) {
3752 if (cipherstr_started)
3753 ssh2_pkt_addstring_str(ssh, ",");
3754 ssh2_pkt_addstring_str(ssh, c->list[j]->name);
3755 cipherstr_started = 1;
3758 /* List client->server MAC algorithms. */
3759 ssh2_pkt_addstring_start(ssh);
3760 for (i = 0; i < s->nmacs; i++) {
3761 ssh2_pkt_addstring_str(ssh, s->maclist[i]->name);
3762 if (i < s->nmacs - 1)
3763 ssh2_pkt_addstring_str(ssh, ",");
3765 /* List server->client MAC algorithms. */
3766 ssh2_pkt_addstring_start(ssh);
3767 for (i = 0; i < s->nmacs; i++) {
3768 ssh2_pkt_addstring_str(ssh, s->maclist[i]->name);
3769 if (i < s->nmacs - 1)
3770 ssh2_pkt_addstring_str(ssh, ",");
3772 /* List client->server compression algorithms. */
3773 ssh2_pkt_addstring_start(ssh);
3774 for (i = 0; i < lenof(compressions) + 1; i++) {
3775 const struct ssh_compress *c =
3776 i == 0 ? s->preferred_comp : compressions[i - 1];
3777 ssh2_pkt_addstring_str(ssh, c->name);
3778 if (i < lenof(compressions))
3779 ssh2_pkt_addstring_str(ssh, ",");
3781 /* List server->client compression algorithms. */
3782 ssh2_pkt_addstring_start(ssh);
3783 for (i = 0; i < lenof(compressions) + 1; i++) {
3784 const struct ssh_compress *c =
3785 i == 0 ? s->preferred_comp : compressions[i - 1];
3786 ssh2_pkt_addstring_str(ssh, c->name);
3787 if (i < lenof(compressions))
3788 ssh2_pkt_addstring_str(ssh, ",");
3790 /* List client->server languages. Empty list. */
3791 ssh2_pkt_addstring_start(ssh);
3792 /* List server->client languages. Empty list. */
3793 ssh2_pkt_addstring_start(ssh);
3794 /* First KEX packet does _not_ follow, because we're not that brave. */
3795 ssh2_pkt_addbool(ssh, FALSE);
3797 ssh2_pkt_adduint32(ssh, 0);
3800 ssh->exhash = ssh->exhashbase;
3801 sha_string(&ssh->exhash, ssh->pktout.data + 5, ssh->pktout.length - 5);
3807 sha_string(&ssh->exhash, ssh->pktin.data + 5, ssh->pktin.length - 5);
3810 * Now examine the other side's KEXINIT to see what we're up
3817 if (ssh->pktin.type != SSH2_MSG_KEXINIT) {
3818 bombout(("expected key exchange packet from server"));
3822 ssh->hostkey = NULL;
3823 s->cscipher_tobe = NULL;
3824 s->sccipher_tobe = NULL;
3825 s->csmac_tobe = NULL;
3826 s->scmac_tobe = NULL;
3827 s->cscomp_tobe = NULL;
3828 s->sccomp_tobe = NULL;
3829 ssh->pktin.savedpos += 16; /* skip garbage cookie */
3830 ssh2_pkt_getstring(ssh, &str, &len); /* key exchange algorithms */
3831 for (i = 0; i < lenof(kex_algs); i++) {
3832 if (kex_algs[i] == &ssh_diffiehellman_gex &&
3833 (ssh->remote_bugs & BUG_SSH2_DH_GEX))
3835 if (in_commasep_string(kex_algs[i]->name, str, len)) {
3836 ssh->kex = kex_algs[i];
3840 ssh2_pkt_getstring(ssh, &str, &len); /* host key algorithms */
3841 for (i = 0; i < lenof(hostkey_algs); i++) {
3842 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
3843 ssh->hostkey = hostkey_algs[i];
3847 ssh2_pkt_getstring(ssh, &str, &len); /* client->server cipher */
3849 for (i = 0; i < s->n_preferred_ciphers; i++) {
3850 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
3854 for (j = 0; j < c->nciphers; j++) {
3855 if (in_commasep_string(c->list[j]->name, str, len)) {
3856 s->cscipher_tobe = c->list[j];
3861 if (s->cscipher_tobe) {
3863 askcipher(s->cscipher_tobe->name, 1);
3867 if (!s->cscipher_tobe) {
3868 bombout(("Couldn't agree a client-to-server cipher (available: %s)", str));
3872 ssh2_pkt_getstring(ssh, &str, &len); /* server->client cipher */
3874 for (i = 0; i < s->n_preferred_ciphers; i++) {
3875 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
3879 for (j = 0; j < c->nciphers; j++) {
3880 if (in_commasep_string(c->list[j]->name, str, len)) {
3881 s->sccipher_tobe = c->list[j];
3886 if (s->sccipher_tobe) {
3888 askcipher(s->sccipher_tobe->name, 2);
3892 if (!s->sccipher_tobe) {
3893 bombout(("Couldn't agree a server-to-client cipher (available: %s)", str));
3897 ssh2_pkt_getstring(ssh, &str, &len); /* client->server mac */
3898 for (i = 0; i < s->nmacs; i++) {
3899 if (in_commasep_string(s->maclist[i]->name, str, len)) {
3900 s->csmac_tobe = s->maclist[i];
3904 ssh2_pkt_getstring(ssh, &str, &len); /* server->client mac */
3905 for (i = 0; i < s->nmacs; i++) {
3906 if (in_commasep_string(s->maclist[i]->name, str, len)) {
3907 s->scmac_tobe = s->maclist[i];
3911 ssh2_pkt_getstring(ssh, &str, &len); /* client->server compression */
3912 for (i = 0; i < lenof(compressions) + 1; i++) {
3913 const struct ssh_compress *c =
3914 i == 0 ? s->preferred_comp : compressions[i - 1];
3915 if (in_commasep_string(c->name, str, len)) {
3920 ssh2_pkt_getstring(ssh, &str, &len); /* server->client compression */
3921 for (i = 0; i < lenof(compressions) + 1; i++) {
3922 const struct ssh_compress *c =
3923 i == 0 ? s->preferred_comp : compressions[i - 1];
3924 if (in_commasep_string(c->name, str, len)) {
3932 * Work out the number of bits of key we will need from the key
3933 * exchange. We start with the maximum key length of either
3939 csbits = s->cscipher_tobe->keylen;
3940 scbits = s->sccipher_tobe->keylen;
3941 s->nbits = (csbits > scbits ? csbits : scbits);
3943 /* The keys only have 160-bit entropy, since they're based on
3944 * a SHA-1 hash. So cap the key size at 160 bits. */
3949 * If we're doing Diffie-Hellman group exchange, start by
3950 * requesting a group.
3952 if (ssh->kex == &ssh_diffiehellman_gex) {
3953 logevent("Doing Diffie-Hellman group exchange");
3954 ssh->pkt_ctx |= SSH2_PKTCTX_DHGEX;
3956 * Work out how big a DH group we will need to allow that
3959 s->pbits = 512 << ((s->nbits - 1) / 64);
3960 ssh2_pkt_init(ssh, SSH2_MSG_KEX_DH_GEX_REQUEST);
3961 ssh2_pkt_adduint32(ssh, s->pbits);
3965 if (ssh->pktin.type != SSH2_MSG_KEX_DH_GEX_GROUP) {
3966 bombout(("expected key exchange group packet from server"));
3969 s->p = ssh2_pkt_getmp(ssh);
3970 s->g = ssh2_pkt_getmp(ssh);
3971 ssh->kex_ctx = dh_setup_group(s->p, s->g);
3972 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
3973 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
3975 ssh->pkt_ctx |= SSH2_PKTCTX_DHGROUP1;
3976 ssh->kex_ctx = dh_setup_group1();
3977 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
3978 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
3981 logevent("Doing Diffie-Hellman key exchange");
3983 * Now generate and send e for Diffie-Hellman.
3985 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
3986 ssh2_pkt_init(ssh, s->kex_init_value);
3987 ssh2_pkt_addmp(ssh, s->e);
3991 if (ssh->pktin.type != s->kex_reply_value) {
3992 bombout(("expected key exchange reply packet from server"));
3995 ssh2_pkt_getstring(ssh, &s->hostkeydata, &s->hostkeylen);
3996 s->f = ssh2_pkt_getmp(ssh);
3997 ssh2_pkt_getstring(ssh, &s->sigdata, &s->siglen);
3999 s->K = dh_find_K(ssh->kex_ctx, s->f);
4001 sha_string(&ssh->exhash, s->hostkeydata, s->hostkeylen);
4002 if (ssh->kex == &ssh_diffiehellman_gex) {
4003 sha_uint32(&ssh->exhash, s->pbits);
4004 sha_mpint(&ssh->exhash, s->p);
4005 sha_mpint(&ssh->exhash, s->g);
4007 sha_mpint(&ssh->exhash, s->e);
4008 sha_mpint(&ssh->exhash, s->f);
4009 sha_mpint(&ssh->exhash, s->K);
4010 SHA_Final(&ssh->exhash, s->exchange_hash);
4012 dh_cleanup(ssh->kex_ctx);
4015 debug(("Exchange hash is:\n"));
4016 dmemdump(s->exchange_hash, 20);
4019 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
4021 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
4022 s->exchange_hash, 20)) {
4023 bombout(("Server's host key did not match the signature supplied"));
4028 * Authenticate remote host: verify host key. (We've already
4029 * checked the signature of the exchange hash.)
4031 s->keystr = ssh->hostkey->fmtkey(s->hkey);
4032 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
4033 verify_ssh_host_key(ssh->savedhost, ssh->savedport, ssh->hostkey->keytype,
4034 s->keystr, s->fingerprint);
4035 if (s->first_kex) { /* don't bother logging this in rekeys */
4036 logevent("Host key fingerprint is:");
4037 logevent(s->fingerprint);
4039 sfree(s->fingerprint);
4041 ssh->hostkey->freekey(s->hkey);
4044 * Send SSH2_MSG_NEWKEYS.
4046 ssh2_pkt_init(ssh, SSH2_MSG_NEWKEYS);
4050 * Expect SSH2_MSG_NEWKEYS from server.
4053 if (ssh->pktin.type != SSH2_MSG_NEWKEYS) {
4054 bombout(("expected new-keys packet from server"));
4059 * Create and initialise session keys.
4061 if (ssh->cs_cipher_ctx)
4062 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
4063 ssh->cscipher = s->cscipher_tobe;
4064 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
4066 if (ssh->sc_cipher_ctx)
4067 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
4068 ssh->sccipher = s->sccipher_tobe;
4069 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
4071 if (ssh->cs_mac_ctx)
4072 ssh->csmac->free_context(ssh->cs_mac_ctx);
4073 ssh->csmac = s->csmac_tobe;
4074 ssh->cs_mac_ctx = ssh->csmac->make_context();
4076 if (ssh->sc_mac_ctx)
4077 ssh->scmac->free_context(ssh->sc_mac_ctx);
4078 ssh->scmac = s->scmac_tobe;
4079 ssh->sc_mac_ctx = ssh->scmac->make_context();
4081 if (ssh->cs_comp_ctx)
4082 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
4083 ssh->cscomp = s->cscomp_tobe;
4084 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
4086 if (ssh->sc_comp_ctx)
4087 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
4088 ssh->sccomp = s->sccomp_tobe;
4089 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
4092 * Set IVs after keys. Here we use the exchange hash from the
4093 * _first_ key exchange.
4096 unsigned char keyspace[40];
4098 memcpy(ssh->v2_session_id, s->exchange_hash,
4099 sizeof(s->exchange_hash));
4100 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'C',keyspace);
4101 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
4102 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'D',keyspace);
4103 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
4104 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'A',keyspace);
4105 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
4106 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'B',keyspace);
4107 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
4108 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'E',keyspace);
4109 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
4110 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'F',keyspace);
4111 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
4115 sprintf(buf, "Initialised %.200s client->server encryption",
4116 ssh->cscipher->text_name);
4118 sprintf(buf, "Initialised %.200s server->client encryption",
4119 ssh->sccipher->text_name);
4121 if (ssh->cscomp->text_name) {
4122 sprintf(buf, "Initialised %.200s compression",
4123 ssh->cscomp->text_name);
4126 if (ssh->sccomp->text_name) {
4127 sprintf(buf, "Initialised %.200s decompression",
4128 ssh->sccomp->text_name);
4135 * If this is the first key exchange phase, we must pass the
4136 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
4137 * wants to see it but because it will need time to initialise
4138 * itself before it sees an actual packet. In subsequent key
4139 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
4140 * it would only confuse the layer above.
4142 if (!s->first_kex) {
4148 * Now we're encrypting. Begin returning 1 to the protocol main
4149 * function so that other things can run on top of the
4150 * transport. If we ever see a KEXINIT, we must go back to the
4153 while (!(ispkt && ssh->pktin.type == SSH2_MSG_KEXINIT)) {
4156 logevent("Server initiated key re-exchange");
4157 goto begin_key_exchange;
4163 * Add data to an SSH2 channel output buffer.
4165 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
4168 bufchain_add(&c->v.v2.outbuffer, buf, len);
4172 * Attempt to send data on an SSH2 channel.
4174 static int ssh2_try_send(struct ssh_channel *c)
4178 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
4181 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
4182 if ((unsigned)len > c->v.v2.remwindow)
4183 len = c->v.v2.remwindow;
4184 if ((unsigned)len > c->v.v2.remmaxpkt)
4185 len = c->v.v2.remmaxpkt;
4186 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_DATA);
4187 ssh2_pkt_adduint32(ssh, c->remoteid);
4188 ssh2_pkt_addstring_start(ssh);
4189 ssh2_pkt_addstring_data(ssh, data, len);
4191 bufchain_consume(&c->v.v2.outbuffer, len);
4192 c->v.v2.remwindow -= len;
4196 * After having sent as much data as we can, return the amount
4199 return bufchain_size(&c->v.v2.outbuffer);
4203 * Potentially enlarge the window on an SSH2 channel.
4205 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin)
4210 * Never send WINDOW_ADJUST for a channel that the remote side
4211 * already thinks it's closed; there's no point, since it won't
4212 * be sending any more data anyway.
4217 if (newwin > c->v.v2.locwindow) {
4218 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4219 ssh2_pkt_adduint32(ssh, c->remoteid);
4220 ssh2_pkt_adduint32(ssh, newwin - c->v.v2.locwindow);
4222 c->v.v2.locwindow = newwin;
4227 * Handle the SSH2 userauth and connection layers.
4229 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
4231 struct do_ssh2_authconn_state {
4233 AUTH_INVALID, AUTH_PUBLICKEY_AGENT, AUTH_PUBLICKEY_FILE,
4235 AUTH_KEYBOARD_INTERACTIVE
4239 AUTH_TYPE_PUBLICKEY,
4240 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
4241 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
4243 AUTH_TYPE_KEYBOARD_INTERACTIVE,
4244 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
4246 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
4247 int tried_pubkey_config, tried_agent, tried_keyb_inter;
4248 int kbd_inter_running;
4250 int num_prompts, curr_prompt, echo;
4255 void *publickey_blob;
4256 int publickey_bloblen;
4257 unsigned char request[5], *response, *p;
4261 char *pkblob, *alg, *commentp;
4262 int pklen, alglen, commentlen;
4263 int siglen, retlen, len;
4264 char *q, *agentreq, *ret;
4267 crState(do_ssh2_authconn_state);
4269 crBegin(ssh->do_ssh2_authconn_crstate);
4272 * Request userauth protocol, and await a response to it.
4274 ssh2_pkt_init(ssh, SSH2_MSG_SERVICE_REQUEST);
4275 ssh2_pkt_addstring(ssh, "ssh-userauth");
4277 crWaitUntilV(ispkt);
4278 if (ssh->pktin.type != SSH2_MSG_SERVICE_ACCEPT) {
4279 bombout(("Server refused user authentication protocol"));
4284 * We repeat this whole loop, including the username prompt,
4285 * until we manage a successful authentication. If the user
4286 * types the wrong _password_, they can be sent back to the
4287 * beginning to try another username, if this is configured on.
4288 * (If they specify a username in the config, they are never
4289 * asked, even if they do give a wrong password.)
4291 * I think this best serves the needs of
4293 * - the people who have no configuration, no keys, and just
4294 * want to try repeated (username,password) pairs until they
4295 * type both correctly
4297 * - people who have keys and configuration but occasionally
4298 * need to fall back to passwords
4300 * - people with a key held in Pageant, who might not have
4301 * logged in to a particular machine before; so they want to
4302 * type a username, and then _either_ their key will be
4303 * accepted, _or_ they will type a password. If they mistype
4304 * the username they will want to be able to get back and
4307 s->username[0] = '\0';
4308 s->got_username = FALSE;
4313 if (s->got_username && !cfg.change_username) {
4315 * We got a username last time round this loop, and
4316 * with change_username turned off we don't try to get
4319 } else if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
4320 if (ssh_get_line && !ssh_getline_pw_only) {
4321 if (!ssh_get_line("login as: ",
4322 s->username, sizeof(s->username), FALSE)) {
4324 * get_line failed to get a username.
4327 logevent("No username provided. Abandoning session.");
4328 ssh->state = SSH_STATE_CLOSED;
4332 int ret; /* need not be saved across crReturn */
4333 c_write_str(ssh, "login as: ");
4335 setup_userpass_input(ssh, s->username, sizeof(s->username), 1);
4337 crWaitUntilV(!ispkt);
4338 ret = process_userpass_input(ssh, in, inlen);
4343 c_write_str(ssh, "\r\n");
4344 s->username[strcspn(s->username, "\n\r")] = '\0';
4347 strncpy(s->username, cfg.username, sizeof(s->username));
4348 s->username[sizeof(s->username)-1] = '\0';
4349 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
4350 sprintf(stuff, "Using username \"%s\".\r\n", s->username);
4351 c_write_str(ssh, stuff);
4354 s->got_username = TRUE;
4357 * Send an authentication request using method "none": (a)
4358 * just in case it succeeds, and (b) so that we know what
4359 * authentication methods we can usefully try next.
4361 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4363 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4364 ssh2_pkt_addstring(ssh, s->username);
4365 ssh2_pkt_addstring(ssh, "ssh-connection");/* service requested */
4366 ssh2_pkt_addstring(ssh, "none"); /* method */
4368 s->type = AUTH_TYPE_NONE;
4370 s->we_are_in = FALSE;
4372 s->tried_pubkey_config = FALSE;
4373 s->tried_agent = FALSE;
4374 s->tried_keyb_inter = FALSE;
4375 s->kbd_inter_running = FALSE;
4376 /* Load the pub half of cfg.keyfile so we notice if it's in Pageant */
4379 logeventf("Reading private key file \"%.150s\"", cfg.keyfile);
4380 keytype = key_type(cfg.keyfile);
4381 if (keytype == SSH_KEYTYPE_SSH2) {
4383 ssh2_userkey_loadpub(cfg.keyfile, NULL,
4384 &s->publickey_bloblen);
4387 logeventf("Unable to use this key file (%s)",
4388 key_type_to_str(keytype));
4389 sprintf(msgbuf, "Unable to use key file \"%.150s\" (%s)\r\n",
4390 cfg.keyfile, key_type_to_str(keytype));
4391 c_write_str(ssh, msgbuf);
4392 s->publickey_blob = NULL;
4395 s->publickey_blob = NULL;
4399 * Wait for the result of the last authentication request.
4402 crWaitUntilV(ispkt);
4403 while (ssh->pktin.type == SSH2_MSG_USERAUTH_BANNER) {
4407 * Don't show the banner if we're operating in
4408 * non-verbose non-interactive mode. (It's probably
4409 * a script, which means nobody will read the
4410 * banner _anyway_, and moreover the printing of
4411 * the banner will screw up processing on the
4412 * output of (say) plink.)
4414 if (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE)) {
4415 ssh2_pkt_getstring(ssh, &banner, &size);
4417 c_write_untrusted(ssh, banner, size);
4419 crWaitUntilV(ispkt);
4421 if (ssh->pktin.type == SSH2_MSG_USERAUTH_SUCCESS) {
4422 logevent("Access granted");
4423 s->we_are_in = TRUE;
4427 if (s->kbd_inter_running &&
4428 ssh->pktin.type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
4430 * This is either a further set-of-prompts packet
4431 * in keyboard-interactive authentication, or it's
4432 * the same one and we came back here with `gotit'
4433 * set. In the former case, we must reset the
4434 * curr_prompt variable.
4438 } else if (ssh->pktin.type != SSH2_MSG_USERAUTH_FAILURE) {
4439 bombout(("Strange packet received during authentication: type %d",
4447 * OK, we're now sitting on a USERAUTH_FAILURE message, so
4448 * we can look at the string in it and know what we can
4449 * helpfully try next.
4451 if (ssh->pktin.type == SSH2_MSG_USERAUTH_FAILURE) {
4454 ssh2_pkt_getstring(ssh, &methods, &methlen);
4455 s->kbd_inter_running = FALSE;
4456 if (!ssh2_pkt_getbool(ssh)) {
4458 * We have received an unequivocal Access
4459 * Denied. This can translate to a variety of
4462 * - if we'd just tried "none" authentication,
4463 * it's not worth printing anything at all
4465 * - if we'd just tried a public key _offer_,
4466 * the message should be "Server refused our
4467 * key" (or no message at all if the key
4468 * came from Pageant)
4470 * - if we'd just tried anything else, the
4471 * message really should be "Access denied".
4473 * Additionally, if we'd just tried password
4474 * authentication, we should break out of this
4475 * whole loop so as to go back to the username
4478 if (s->type == AUTH_TYPE_NONE) {
4480 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
4481 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
4482 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
4483 c_write_str(ssh, "Server refused our key\r\n");
4484 logevent("Server refused public key");
4485 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
4486 /* server declined keyboard-interactive; ignore */
4488 c_write_str(ssh, "Access denied\r\n");
4489 logevent("Access denied");
4490 if (s->type == AUTH_TYPE_PASSWORD) {
4491 s->we_are_in = FALSE;
4496 c_write_str(ssh, "Further authentication required\r\n");
4497 logevent("Further authentication required");
4501 in_commasep_string("publickey", methods, methlen);
4503 in_commasep_string("password", methods, methlen);
4504 s->can_keyb_inter = cfg.try_ki_auth &&
4505 in_commasep_string("keyboard-interactive", methods, methlen);
4509 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4512 * Most password/passphrase prompts will be
4513 * non-echoing, so we set this to 0 by default.
4514 * Exception is that some keyboard-interactive prompts
4515 * can be echoing, in which case we'll set this to 1.
4519 if (!s->method && s->can_pubkey &&
4520 agent_exists() && !s->tried_agent) {
4522 * Attempt public-key authentication using Pageant.
4527 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4528 ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
4530 s->tried_agent = TRUE;
4532 logevent("Pageant is running. Requesting keys.");
4534 /* Request the keys held by the agent. */
4535 PUT_32BIT(s->request, 1);
4536 s->request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
4537 agent_query(s->request, 5, &r, &s->responselen);
4538 s->response = (unsigned char *) r;
4539 if (s->response && s->responselen >= 5 &&
4540 s->response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
4541 s->p = s->response + 5;
4542 s->nkeys = GET_32BIT(s->p);
4546 sprintf(buf, "Pageant has %d SSH2 keys", s->nkeys);
4549 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
4554 sprintf(buf, "Trying Pageant key #%d", s->keyi);
4557 s->pklen = GET_32BIT(s->p);
4559 if (s->publickey_blob &&
4560 s->pklen == s->publickey_bloblen &&
4561 !memcmp(s->p, s->publickey_blob,
4562 s->publickey_bloblen)) {
4563 logevent("This key matches configured key file");
4564 s->tried_pubkey_config = 1;
4568 s->alglen = GET_32BIT(s->pkblob);
4569 s->alg = s->pkblob + 4;
4570 s->commentlen = GET_32BIT(s->p);
4573 s->p += s->commentlen;
4574 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4575 ssh2_pkt_addstring(ssh, s->username);
4576 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4577 ssh2_pkt_addstring(ssh, "publickey"); /* method */
4578 ssh2_pkt_addbool(ssh, FALSE); /* no signature included */
4579 ssh2_pkt_addstring_start(ssh);
4580 ssh2_pkt_addstring_data(ssh, s->alg, s->alglen);
4581 ssh2_pkt_addstring_start(ssh);
4582 ssh2_pkt_addstring_data(ssh, s->pkblob, s->pklen);
4585 crWaitUntilV(ispkt);
4586 if (ssh->pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
4587 logevent("Key refused");
4591 if (flags & FLAG_VERBOSE) {
4592 c_write_str(ssh, "Authenticating with "
4594 c_write(ssh, s->commentp, s->commentlen);
4595 c_write_str(ssh, "\" from agent\r\n");
4599 * Server is willing to accept the key.
4600 * Construct a SIGN_REQUEST.
4602 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4603 ssh2_pkt_addstring(ssh, s->username);
4604 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4605 ssh2_pkt_addstring(ssh, "publickey"); /* method */
4606 ssh2_pkt_addbool(ssh, TRUE);
4607 ssh2_pkt_addstring_start(ssh);
4608 ssh2_pkt_addstring_data(ssh, s->alg, s->alglen);
4609 ssh2_pkt_addstring_start(ssh);
4610 ssh2_pkt_addstring_data(ssh, s->pkblob, s->pklen);
4612 s->siglen = ssh->pktout.length - 5 + 4 + 20;
4613 s->len = 1; /* message type */
4614 s->len += 4 + s->pklen; /* key blob */
4615 s->len += 4 + s->siglen; /* data to sign */
4616 s->len += 4; /* flags */
4617 s->agentreq = smalloc(4 + s->len);
4618 PUT_32BIT(s->agentreq, s->len);
4619 s->q = s->agentreq + 4;
4620 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
4621 PUT_32BIT(s->q, s->pklen);
4623 memcpy(s->q, s->pkblob, s->pklen);
4625 PUT_32BIT(s->q, s->siglen);
4627 /* Now the data to be signed... */
4628 PUT_32BIT(s->q, 20);
4630 memcpy(s->q, ssh->v2_session_id, 20);
4632 memcpy(s->q, ssh->pktout.data + 5,
4633 ssh->pktout.length - 5);
4634 s->q += ssh->pktout.length - 5;
4635 /* And finally the (zero) flags word. */
4637 agent_query(s->agentreq, s->len + 4, &vret, &s->retlen);
4641 if (s->ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
4642 logevent("Sending Pageant's response");
4643 ssh2_add_sigblob(ssh, s->pkblob, s->pklen,
4645 GET_32BIT(s->ret + 5));
4651 ("Pageant failed to answer challenge");
4661 if (!s->method && s->can_pubkey && s->publickey_blob
4662 && !s->tried_pubkey_config) {
4663 unsigned char *pub_blob;
4664 char *algorithm, *comment;
4667 s->tried_pubkey_config = TRUE;
4669 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4670 ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
4673 * Try the public key supplied in the configuration.
4675 * First, offer the public blob to see if the server is
4676 * willing to accept it.
4678 pub_blob = ssh2_userkey_loadpub(cfg.keyfile, &algorithm,
4681 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4682 ssh2_pkt_addstring(ssh, s->username);
4683 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4684 ssh2_pkt_addstring(ssh, "publickey"); /* method */
4685 ssh2_pkt_addbool(ssh, FALSE); /* no signature included */
4686 ssh2_pkt_addstring(ssh, algorithm);
4687 ssh2_pkt_addstring_start(ssh);
4688 ssh2_pkt_addstring_data(ssh, pub_blob, pub_blob_len);
4690 logevent("Offered public key"); /* FIXME */
4692 crWaitUntilV(ispkt);
4693 if (ssh->pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
4695 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
4696 continue; /* key refused; give up on it */
4699 logevent("Offer of public key accepted");
4701 * Actually attempt a serious authentication using
4704 if (ssh2_userkey_encrypted(cfg.keyfile, &comment)) {
4705 sprintf(s->pwprompt,
4706 "Passphrase for key \"%.100s\": ",
4712 c_write_str(ssh, "Authenticating with public key \"");
4713 c_write_str(ssh, comment);
4714 c_write_str(ssh, "\"\r\n");
4715 s->method = AUTH_PUBLICKEY_FILE;
4719 if (!s->method && s->can_keyb_inter && !s->tried_keyb_inter) {
4720 s->method = AUTH_KEYBOARD_INTERACTIVE;
4721 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4722 s->tried_keyb_inter = TRUE;
4724 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4725 ssh->pkt_ctx |= SSH2_PKTCTX_KBDINTER;
4727 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4728 ssh2_pkt_addstring(ssh, s->username);
4729 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4730 ssh2_pkt_addstring(ssh, "keyboard-interactive"); /* method */
4731 ssh2_pkt_addstring(ssh, ""); /* lang */
4732 ssh2_pkt_addstring(ssh, "");
4735 crWaitUntilV(ispkt);
4736 if (ssh->pktin.type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
4737 if (ssh->pktin.type == SSH2_MSG_USERAUTH_FAILURE)
4739 logevent("Keyboard-interactive authentication refused");
4740 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
4744 s->kbd_inter_running = TRUE;
4748 if (s->kbd_inter_running) {
4749 s->method = AUTH_KEYBOARD_INTERACTIVE;
4750 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4751 s->tried_keyb_inter = TRUE;
4753 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4754 ssh->pkt_ctx |= SSH2_PKTCTX_KBDINTER;
4756 if (s->curr_prompt == 0) {
4758 * We've got a fresh USERAUTH_INFO_REQUEST.
4759 * Display header data, and start going through
4762 char *name, *inst, *lang;
4763 int name_len, inst_len, lang_len;
4765 ssh2_pkt_getstring(ssh, &name, &name_len);
4766 ssh2_pkt_getstring(ssh, &inst, &inst_len);
4767 ssh2_pkt_getstring(ssh, &lang, &lang_len);
4769 c_write_untrusted(ssh, name, name_len);
4770 c_write_str(ssh, "\r\n");
4773 c_write_untrusted(ssh, inst, inst_len);
4774 c_write_str(ssh, "\r\n");
4776 s->num_prompts = ssh2_pkt_getuint32(ssh);
4780 * If there are prompts remaining in the packet,
4781 * display one and get a response.
4783 if (s->curr_prompt < s->num_prompts) {
4787 ssh2_pkt_getstring(ssh, &prompt, &prompt_len);
4788 if (prompt_len > 0) {
4789 strncpy(s->pwprompt, prompt, sizeof(s->pwprompt));
4790 s->pwprompt[prompt_len < sizeof(s->pwprompt) ?
4791 prompt_len : sizeof(s->pwprompt)-1] = '\0';
4794 "<server failed to send prompt>: ");
4796 s->echo = ssh2_pkt_getbool(ssh);
4802 if (!s->method && s->can_passwd) {
4803 s->method = AUTH_PASSWORD;
4804 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4805 ssh->pkt_ctx |= SSH2_PKTCTX_PASSWORD;
4806 sprintf(s->pwprompt, "%.90s@%.90s's password: ", s->username,
4813 if (!ssh_get_line(s->pwprompt, s->password,
4814 sizeof(s->password), TRUE)) {
4816 * get_line failed to get a password (for
4817 * example because one was supplied on the
4818 * command line which has already failed to
4821 ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
4822 ssh2_pkt_adduint32(ssh,SSH2_DISCONNECT_BY_APPLICATION);
4823 ssh2_pkt_addstring(ssh, "No more passwords available"
4825 ssh2_pkt_addstring(ssh, "en"); /* language tag */
4827 logevent("Unable to authenticate");
4828 connection_fatal("Unable to authenticate");
4829 ssh->state = SSH_STATE_CLOSED;
4833 int ret; /* need not be saved across crReturn */
4834 c_write_untrusted(ssh, s->pwprompt, strlen(s->pwprompt));
4837 setup_userpass_input(ssh, s->password,
4838 sizeof(s->password), s->echo);
4840 crWaitUntilV(!ispkt);
4841 ret = process_userpass_input(ssh, in, inlen);
4845 c_write_str(ssh, "\r\n");
4849 if (s->method == AUTH_PUBLICKEY_FILE) {
4851 * We have our passphrase. Now try the actual authentication.
4853 struct ssh2_userkey *key;
4855 key = ssh2_load_userkey(cfg.keyfile, s->password);
4856 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
4857 if (key == SSH2_WRONG_PASSPHRASE) {
4858 c_write_str(ssh, "Wrong passphrase\r\n");
4859 s->tried_pubkey_config = FALSE;
4861 c_write_str(ssh, "Unable to load private key\r\n");
4862 s->tried_pubkey_config = TRUE;
4864 /* Send a spurious AUTH_NONE to return to the top. */
4865 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4866 ssh2_pkt_addstring(ssh, s->username);
4867 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4868 ssh2_pkt_addstring(ssh, "none"); /* method */
4870 s->type = AUTH_TYPE_NONE;
4872 unsigned char *pkblob, *sigblob, *sigdata;
4873 int pkblob_len, sigblob_len, sigdata_len;
4876 * We have loaded the private key and the server
4877 * has announced that it's willing to accept it.
4878 * Hallelujah. Generate a signature and send it.
4880 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4881 ssh2_pkt_addstring(ssh, s->username);
4882 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4883 ssh2_pkt_addstring(ssh, "publickey"); /* method */
4884 ssh2_pkt_addbool(ssh, TRUE);
4885 ssh2_pkt_addstring(ssh, key->alg->name);
4886 pkblob = key->alg->public_blob(key->data, &pkblob_len);
4887 ssh2_pkt_addstring_start(ssh);
4888 ssh2_pkt_addstring_data(ssh, pkblob, pkblob_len);
4891 * The data to be signed is:
4895 * followed by everything so far placed in the
4898 sigdata_len = ssh->pktout.length - 5 + 4 + 20;
4899 sigdata = smalloc(sigdata_len);
4900 PUT_32BIT(sigdata, 20);
4901 memcpy(sigdata + 4, ssh->v2_session_id, 20);
4902 memcpy(sigdata + 24, ssh->pktout.data + 5,
4903 ssh->pktout.length - 5);
4904 sigblob = key->alg->sign(key->data, sigdata,
4905 sigdata_len, &sigblob_len);
4906 ssh2_add_sigblob(ssh, pkblob, pkblob_len,
4907 sigblob, sigblob_len);
4913 s->type = AUTH_TYPE_PUBLICKEY;
4915 } else if (s->method == AUTH_PASSWORD) {
4917 * We send the password packet lumped tightly together with
4918 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
4919 * string long enough to make the total length of the two
4920 * packets constant. This should ensure that a passive
4921 * listener doing traffic analyis can't work out the length
4924 * For this to work, we need an assumption about the
4925 * maximum length of the password packet. I think 256 is
4926 * pretty conservative. Anyone using a password longer than
4927 * that probably doesn't have much to worry about from
4928 * people who find out how long their password is!
4930 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4931 ssh2_pkt_addstring(ssh, s->username);
4932 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4933 ssh2_pkt_addstring(ssh, "password");
4934 ssh2_pkt_addbool(ssh, FALSE);
4935 ssh2_pkt_addstring(ssh, s->password);
4936 ssh2_pkt_defer(ssh);
4938 * We'll include a string that's an exact multiple of the
4939 * cipher block size. If the cipher is NULL for some
4940 * reason, we don't do this trick at all because we gain
4943 if (ssh->cscipher) {
4946 stringlen = (256 - ssh->deferred_len);
4947 stringlen += ssh->cscipher->blksize - 1;
4948 stringlen -= (stringlen % ssh->cscipher->blksize);
4951 * Temporarily disable actual compression,
4952 * so we can guarantee to get this string
4953 * exactly the length we want it. The
4954 * compression-disabling routine should
4955 * return an integer indicating how many
4956 * bytes we should adjust our string length
4960 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
4962 ssh2_pkt_init(ssh, SSH2_MSG_IGNORE);
4963 ssh2_pkt_addstring_start(ssh);
4964 for (i = 0; i < stringlen; i++) {
4965 char c = (char) random_byte();
4966 ssh2_pkt_addstring_data(ssh, &c, 1);
4968 ssh2_pkt_defer(ssh);
4970 ssh_pkt_defersend(ssh);
4971 logevent("Sent password");
4972 s->type = AUTH_TYPE_PASSWORD;
4973 } else if (s->method == AUTH_KEYBOARD_INTERACTIVE) {
4974 if (s->curr_prompt == 0) {
4975 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_INFO_RESPONSE);
4976 ssh2_pkt_adduint32(ssh, s->num_prompts);
4978 if (s->need_pw) { /* only add pw if we just got one! */
4979 ssh2_pkt_addstring(ssh, s->password);
4980 memset(s->password, 0, sizeof(s->password));
4983 if (s->curr_prompt >= s->num_prompts) {
4987 * If there are prompts remaining, we set
4988 * `gotit' so that we won't attempt to get
4989 * another packet. Then we go back round the
4990 * loop and will end up retrieving another
4991 * prompt out of the existing packet. Funky or
4996 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4998 c_write_str(ssh, "No supported authentication methods"
4999 " left to try!\r\n");
5000 logevent("No supported authentications offered."
5002 ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
5003 ssh2_pkt_adduint32(ssh, SSH2_DISCONNECT_BY_APPLICATION);
5004 ssh2_pkt_addstring(ssh, "No supported authentication"
5005 " methods available");
5006 ssh2_pkt_addstring(ssh, "en"); /* language tag */
5008 ssh->state = SSH_STATE_CLOSED;
5012 } while (!s->we_are_in);
5015 * Now we're authenticated for the connection protocol. The
5016 * connection protocol will automatically have started at this
5017 * point; there's no need to send SERVICE_REQUEST.
5021 * So now create a channel with a session in it.
5023 ssh->channels = newtree234(ssh_channelcmp);
5024 ssh->mainchan = smalloc(sizeof(struct ssh_channel));
5025 ssh->mainchan->ssh = ssh;
5026 ssh->mainchan->localid = alloc_channel_id(ssh);
5027 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_OPEN);
5028 ssh2_pkt_addstring(ssh, "session");
5029 ssh2_pkt_adduint32(ssh, ssh->mainchan->localid);
5030 ssh->mainchan->v.v2.locwindow = OUR_V2_WINSIZE;
5031 ssh2_pkt_adduint32(ssh, ssh->mainchan->v.v2.locwindow);/* our window size */
5032 ssh2_pkt_adduint32(ssh, 0x4000UL); /* our max pkt size */
5034 crWaitUntilV(ispkt);
5035 if (ssh->pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
5036 bombout(("Server refused to open a session"));
5038 /* FIXME: error data comes back in FAILURE packet */
5040 if (ssh2_pkt_getuint32(ssh) != ssh->mainchan->localid) {
5041 bombout(("Server's channel confirmation cited wrong channel"));
5044 ssh->mainchan->remoteid = ssh2_pkt_getuint32(ssh);
5045 ssh->mainchan->type = CHAN_MAINSESSION;
5046 ssh->mainchan->closes = 0;
5047 ssh->mainchan->v.v2.remwindow = ssh2_pkt_getuint32(ssh);
5048 ssh->mainchan->v.v2.remmaxpkt = ssh2_pkt_getuint32(ssh);
5049 bufchain_init(&ssh->mainchan->v.v2.outbuffer);
5050 add234(ssh->channels, ssh->mainchan);
5051 logevent("Opened channel for session");
5054 * Potentially enable X11 forwarding.
5056 if (cfg.x11_forward) {
5057 char proto[20], data[64];
5058 logevent("Requesting X11 forwarding");
5059 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
5060 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
5061 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
5062 ssh2_pkt_addstring(ssh, "x11-req");
5063 ssh2_pkt_addbool(ssh, 1); /* want reply */
5064 ssh2_pkt_addbool(ssh, 0); /* many connections */
5065 ssh2_pkt_addstring(ssh, proto);
5066 ssh2_pkt_addstring(ssh, data);
5067 ssh2_pkt_adduint32(ssh, 0); /* screen number */
5071 crWaitUntilV(ispkt);
5072 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5073 unsigned i = ssh2_pkt_getuint32(ssh);
5074 struct ssh_channel *c;
5075 c = find234(ssh->channels, &i, ssh_channelfind);
5077 continue; /* nonexistent channel */
5078 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5080 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5082 if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5083 if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5084 bombout(("Unexpected response to X11 forwarding request:"
5085 " packet type %d", ssh->pktin.type));
5088 logevent("X11 forwarding refused");
5090 logevent("X11 forwarding enabled");
5091 ssh->X11_fwd_enabled = TRUE;
5096 * Enable port forwardings.
5101 int sport,dport,sserv,dserv;
5102 char sports[256], dports[256], host[256];
5106 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5107 /* Add port forwardings. */
5108 ssh->portfwd_strptr = cfg.portfwd;
5109 while (*ssh->portfwd_strptr) {
5110 type = *ssh->portfwd_strptr++;
5112 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != '\t')
5113 sports[n++] = *ssh->portfwd_strptr++;
5115 if (*ssh->portfwd_strptr == '\t')
5116 ssh->portfwd_strptr++;
5118 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != ':')
5119 host[n++] = *ssh->portfwd_strptr++;
5121 if (*ssh->portfwd_strptr == ':')
5122 ssh->portfwd_strptr++;
5124 while (*ssh->portfwd_strptr)
5125 dports[n++] = *ssh->portfwd_strptr++;
5127 ssh->portfwd_strptr++;
5128 dport = atoi(dports);
5132 se = getservbyname(dports, NULL);
5134 dport = ntohs(se->s_port);
5137 "Service lookup failed for destination port \"%s\"",
5142 sport = atoi(sports);
5146 se = getservbyname(sports, NULL);
5148 sport = ntohs(se->s_port);
5151 "Service lookup failed for source port \"%s\"",
5156 if (sport && dport) {
5158 pfd_addforward(host, dport, sport);
5159 sprintf(buf, "Local port %.*s%.*s%d%.*s forwarding to"
5160 " %s:%.*s%.*s%d%.*s",
5161 sserv ? strlen(sports) : 0, sports,
5162 sserv, "(", sport, sserv, ")",
5164 dserv ? strlen(dports) : 0, dports,
5165 dserv, "(", dport, dserv, ")");
5168 struct ssh_rportfwd *pf;
5169 pf = smalloc(sizeof(*pf));
5170 strcpy(pf->dhost, host);
5173 if (add234(ssh->rportfwds, pf) != pf) {
5175 "Duplicate remote port forwarding to %s:%d",
5180 sprintf(buf, "Requesting remote port %.*s%.*s%d%.*s"
5181 " forward to %s:%.*s%.*s%d%.*s",
5182 sserv ? strlen(sports) : 0, sports,
5183 sserv, "(", sport, sserv, ")",
5185 dserv ? strlen(dports) : 0, dports,
5186 dserv, "(", dport, dserv, ")");
5188 ssh2_pkt_init(ssh, SSH2_MSG_GLOBAL_REQUEST);
5189 ssh2_pkt_addstring(ssh, "tcpip-forward");
5190 ssh2_pkt_addbool(ssh, 1);/* want reply */
5191 if (cfg.rport_acceptall)
5192 ssh2_pkt_addstring(ssh, "0.0.0.0");
5194 ssh2_pkt_addstring(ssh, "127.0.0.1");
5195 ssh2_pkt_adduint32(ssh, sport);
5199 crWaitUntilV(ispkt);
5200 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5201 unsigned i = ssh2_pkt_getuint32(ssh);
5202 struct ssh_channel *c;
5203 c = find234(ssh->channels, &i, ssh_channelfind);
5205 continue;/* nonexistent channel */
5206 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5208 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5210 if (ssh->pktin.type != SSH2_MSG_REQUEST_SUCCESS) {
5211 if (ssh->pktin.type != SSH2_MSG_REQUEST_FAILURE) {
5212 bombout(("Unexpected response to port "
5213 "forwarding request: packet type %d",
5217 logevent("Server refused this port forwarding");
5219 logevent("Remote port forwarding enabled");
5228 * Potentially enable agent forwarding.
5230 if (cfg.agentfwd && agent_exists()) {
5231 logevent("Requesting OpenSSH-style agent forwarding");
5232 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
5233 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
5234 ssh2_pkt_addstring(ssh, "auth-agent-req@openssh.com");
5235 ssh2_pkt_addbool(ssh, 1); /* want reply */
5239 crWaitUntilV(ispkt);
5240 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5241 unsigned i = ssh2_pkt_getuint32(ssh);
5242 struct ssh_channel *c;
5243 c = find234(ssh->channels, &i, ssh_channelfind);
5245 continue; /* nonexistent channel */
5246 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5248 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5250 if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5251 if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5252 bombout(("Unexpected response to agent forwarding request:"
5253 " packet type %d", ssh->pktin.type));
5256 logevent("Agent forwarding refused");
5258 logevent("Agent forwarding enabled");
5259 ssh->agentfwd_enabled = TRUE;
5264 * Now allocate a pty for the session.
5267 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
5268 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid); /* recipient channel */
5269 ssh2_pkt_addstring(ssh, "pty-req");
5270 ssh2_pkt_addbool(ssh, 1); /* want reply */
5271 ssh2_pkt_addstring(ssh, cfg.termtype);
5272 ssh2_pkt_adduint32(ssh, ssh->term_width);
5273 ssh2_pkt_adduint32(ssh, ssh->term_height);
5274 ssh2_pkt_adduint32(ssh, 0); /* pixel width */
5275 ssh2_pkt_adduint32(ssh, 0); /* pixel height */
5276 ssh2_pkt_addstring_start(ssh);
5277 ssh2_pkt_addstring_data(ssh, "\0", 1); /* TTY_OP_END, no special options */
5279 ssh->state = SSH_STATE_INTERMED;
5282 crWaitUntilV(ispkt);
5283 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5284 unsigned i = ssh2_pkt_getuint32(ssh);
5285 struct ssh_channel *c;
5286 c = find234(ssh->channels, &i, ssh_channelfind);
5288 continue; /* nonexistent channel */
5289 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5291 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5293 if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5294 if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5295 bombout(("Unexpected response to pty request:"
5296 " packet type %d", ssh->pktin.type));
5299 c_write_str(ssh, "Server refused to allocate pty\r\n");
5300 ssh->editing = ssh->echoing = 1;
5302 logevent("Allocated pty");
5305 ssh->editing = ssh->echoing = 1;
5309 * Start a shell or a remote command. We may have to attempt
5310 * this twice if the config data has provided a second choice
5317 if (ssh->fallback_cmd) {
5318 subsys = cfg.ssh_subsys2;
5319 cmd = cfg.remote_cmd_ptr2;
5321 subsys = cfg.ssh_subsys;
5322 cmd = cfg.remote_cmd_ptr;
5325 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
5326 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid); /* recipient channel */
5328 ssh2_pkt_addstring(ssh, "subsystem");
5329 ssh2_pkt_addbool(ssh, 1); /* want reply */
5330 ssh2_pkt_addstring(ssh, cmd);
5332 ssh2_pkt_addstring(ssh, "exec");
5333 ssh2_pkt_addbool(ssh, 1); /* want reply */
5334 ssh2_pkt_addstring(ssh, cmd);
5336 ssh2_pkt_addstring(ssh, "shell");
5337 ssh2_pkt_addbool(ssh, 1); /* want reply */
5341 crWaitUntilV(ispkt);
5342 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5343 unsigned i = ssh2_pkt_getuint32(ssh);
5344 struct ssh_channel *c;
5345 c = find234(ssh->channels, &i, ssh_channelfind);
5347 continue; /* nonexistent channel */
5348 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5350 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5351 if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5352 if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5353 bombout(("Unexpected response to shell/command request:"
5354 " packet type %d", ssh->pktin.type));
5358 * We failed to start the command. If this is the
5359 * fallback command, we really are finished; if it's
5360 * not, and if the fallback command exists, try falling
5361 * back to it before complaining.
5363 if (!ssh->fallback_cmd && cfg.remote_cmd_ptr2 != NULL) {
5364 logevent("Primary command failed; attempting fallback");
5365 ssh->fallback_cmd = TRUE;
5368 bombout(("Server refused to start a shell/command"));
5371 logevent("Started a shell/command");
5376 ssh->state = SSH_STATE_SESSION;
5377 if (ssh->size_needed)
5378 ssh_size(ssh, ssh->term_width, ssh->term_height);
5379 if (ssh->eof_needed)
5380 ssh_special(ssh, TS_EOF);
5386 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
5390 s->try_send = FALSE;
5392 if (ssh->pktin.type == SSH2_MSG_CHANNEL_DATA ||
5393 ssh->pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
5396 unsigned i = ssh2_pkt_getuint32(ssh);
5397 struct ssh_channel *c;
5398 c = find234(ssh->channels, &i, ssh_channelfind);
5400 continue; /* nonexistent channel */
5401 if (ssh->pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
5402 ssh2_pkt_getuint32(ssh) != SSH2_EXTENDED_DATA_STDERR)
5403 continue; /* extended but not stderr */
5404 ssh2_pkt_getstring(ssh, &data, &length);
5407 c->v.v2.locwindow -= length;
5409 case CHAN_MAINSESSION:
5411 from_backend(ssh->frontend, ssh->pktin.type ==
5412 SSH2_MSG_CHANNEL_EXTENDED_DATA,
5416 bufsize = x11_send(c->u.x11.s, data, length);
5419 bufsize = pfd_send(c->u.pfd.s, data, length);
5422 while (length > 0) {
5423 if (c->u.a.lensofar < 4) {
5424 int l = min(4 - c->u.a.lensofar, length);
5425 memcpy(c->u.a.msglen + c->u.a.lensofar,
5429 c->u.a.lensofar += l;
5431 if (c->u.a.lensofar == 4) {
5433 4 + GET_32BIT(c->u.a.msglen);
5434 c->u.a.message = smalloc(c->u.a.totallen);
5435 memcpy(c->u.a.message, c->u.a.msglen, 4);
5437 if (c->u.a.lensofar >= 4 && length > 0) {
5439 min(c->u.a.totallen - c->u.a.lensofar,
5441 memcpy(c->u.a.message + c->u.a.lensofar,
5445 c->u.a.lensofar += l;
5447 if (c->u.a.lensofar == c->u.a.totallen) {
5448 void *reply, *sentreply;
5450 agent_query(c->u.a.message,
5451 c->u.a.totallen, &reply,
5456 /* Fake SSH_AGENT_FAILURE. */
5457 sentreply = "\0\0\0\1\5";
5460 ssh2_add_channel_data(c, sentreply, replylen);
5464 sfree(c->u.a.message);
5465 c->u.a.lensofar = 0;
5472 * If we are not buffering too much data,
5473 * enlarge the window again at the remote side.
5475 if (bufsize < OUR_V2_WINSIZE)
5476 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
5478 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_EOF) {
5479 unsigned i = ssh2_pkt_getuint32(ssh);
5480 struct ssh_channel *c;
5482 c = find234(ssh->channels, &i, ssh_channelfind);
5484 continue; /* nonexistent channel */
5486 if (c->type == CHAN_X11) {
5488 * Remote EOF on an X11 channel means we should
5489 * wrap up and close the channel ourselves.
5491 x11_close(c->u.x11.s);
5493 } else if (c->type == CHAN_AGENT) {
5495 } else if (c->type == CHAN_SOCKDATA) {
5496 pfd_close(c->u.pfd.s);
5499 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
5500 unsigned i = ssh2_pkt_getuint32(ssh);
5501 struct ssh_channel *c;
5503 c = find234(ssh->channels, &i, ssh_channelfind);
5504 if (!c || ((int)c->remoteid) == -1) {
5505 bombout(("Received CHANNEL_CLOSE for %s channel %d\n",
5506 c ? "half-open" : "nonexistent", i));
5508 /* Do pre-close processing on the channel. */
5510 case CHAN_MAINSESSION:
5511 break; /* nothing to see here, move along */
5513 if (c->u.x11.s != NULL)
5514 x11_close(c->u.x11.s);
5521 if (c->u.pfd.s != NULL)
5522 pfd_close(c->u.pfd.s);
5526 if (c->closes == 0) {
5527 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_CLOSE);
5528 ssh2_pkt_adduint32(ssh, c->remoteid);
5531 del234(ssh->channels, c);
5532 bufchain_clear(&c->v.v2.outbuffer);
5536 * See if that was the last channel left open.
5538 if (count234(ssh->channels) == 0) {
5541 * We used to send SSH_MSG_DISCONNECT here,
5542 * because I'd believed that _every_ conforming
5543 * SSH2 connection had to end with a disconnect
5544 * being sent by at least one side; apparently
5545 * I was wrong and it's perfectly OK to
5546 * unceremoniously slam the connection shut
5547 * when you're done, and indeed OpenSSH feels
5548 * this is more polite than sending a
5549 * DISCONNECT. So now we don't.
5551 logevent("All channels closed. Disconnecting");
5552 ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
5553 ssh2_pkt_adduint32(ssh, SSH2_DISCONNECT_BY_APPLICATION);
5554 ssh2_pkt_addstring(ssh, "All open channels closed");
5555 ssh2_pkt_addstring(ssh, "en"); /* language tag */
5558 ssh->state = SSH_STATE_CLOSED;
5561 continue; /* remote sends close; ignore (FIXME) */
5562 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5563 unsigned i = ssh2_pkt_getuint32(ssh);
5564 struct ssh_channel *c;
5565 c = find234(ssh->channels, &i, ssh_channelfind);
5567 continue; /* nonexistent channel */
5568 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5570 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
5571 unsigned i = ssh2_pkt_getuint32(ssh);
5572 struct ssh_channel *c;
5573 c = find234(ssh->channels, &i, ssh_channelfind);
5575 continue; /* nonexistent channel */
5576 if (c->type != CHAN_SOCKDATA_DORMANT)
5577 continue; /* dunno why they're confirming this */
5578 c->remoteid = ssh2_pkt_getuint32(ssh);
5579 c->type = CHAN_SOCKDATA;
5580 c->v.v2.remwindow = ssh2_pkt_getuint32(ssh);
5581 c->v.v2.remmaxpkt = ssh2_pkt_getuint32(ssh);
5583 pfd_confirm(c->u.pfd.s);
5586 * We have a pending close on this channel,
5587 * which we decided on before the server acked
5588 * the channel open. So now we know the
5589 * remoteid, we can close it again.
5591 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_CLOSE);
5592 ssh2_pkt_adduint32(ssh, c->remoteid);
5595 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_OPEN_FAILURE) {
5596 unsigned i = ssh2_pkt_getuint32(ssh);
5597 struct ssh_channel *c;
5598 c = find234(ssh->channels, &i, ssh_channelfind);
5600 continue; /* nonexistent channel */
5601 if (c->type != CHAN_SOCKDATA_DORMANT)
5602 continue; /* dunno why they're failing this */
5604 logevent("Forwarded connection refused by server");
5606 pfd_close(c->u.pfd.s);
5608 del234(ssh->channels, c);
5610 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
5613 int typelen, want_reply;
5614 struct ssh_channel *c;
5616 localid = ssh2_pkt_getuint32(ssh);
5617 ssh2_pkt_getstring(ssh, &type, &typelen);
5618 want_reply = ssh2_pkt_getbool(ssh);
5621 * First, check that the channel exists. Otherwise,
5622 * we can instantly disconnect with a rude message.
5624 c = find234(ssh->channels, &localid, ssh_channelfind);
5627 sprintf(buf, "Received channel request for nonexistent"
5628 " channel %d", localid);
5630 ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
5631 ssh2_pkt_adduint32(ssh, SSH2_DISCONNECT_BY_APPLICATION);
5632 ssh2_pkt_addstring(ssh, buf);
5633 ssh2_pkt_addstring(ssh, "en"); /* language tag */
5635 connection_fatal("%s", buf);
5636 ssh->state = SSH_STATE_CLOSED;
5641 * Having got the channel number, we now look at
5642 * the request type string to see if it's something
5645 if (typelen == 11 && !memcmp(type, "exit-status", 11) &&
5646 c == ssh->mainchan) {
5647 /* We recognise "exit-status" on the primary channel. */
5649 ssh->exitcode = ssh2_pkt_getuint32(ssh);
5650 sprintf(buf, "Server sent command exit status %d",
5654 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_SUCCESS);
5655 ssh2_pkt_adduint32(ssh, c->remoteid);
5660 * This is a channel request we don't know
5661 * about, so we now either ignore the request
5662 * or respond with CHANNEL_FAILURE, depending
5666 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_FAILURE);
5667 ssh2_pkt_adduint32(ssh, c->remoteid);
5671 } else if (ssh->pktin.type == SSH2_MSG_GLOBAL_REQUEST) {
5673 int typelen, want_reply;
5675 ssh2_pkt_getstring(ssh, &type, &typelen);
5676 want_reply = ssh2_pkt_getbool(ssh);
5679 * We currently don't support any global requests
5680 * at all, so we either ignore the request or
5681 * respond with REQUEST_FAILURE, depending on
5685 ssh2_pkt_init(ssh, SSH2_MSG_REQUEST_FAILURE);
5688 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_OPEN) {
5692 struct ssh_channel *c;
5693 unsigned remid, winsize, pktsize;
5694 ssh2_pkt_getstring(ssh, &type, &typelen);
5695 c = smalloc(sizeof(struct ssh_channel));
5698 remid = ssh2_pkt_getuint32(ssh);
5699 winsize = ssh2_pkt_getuint32(ssh);
5700 pktsize = ssh2_pkt_getuint32(ssh);
5702 if (typelen == 3 && !memcmp(type, "x11", 3)) {
5703 if (!ssh->X11_fwd_enabled)
5704 error = "X11 forwarding is not enabled";
5705 else if (x11_init(&c->u.x11.s, cfg.x11_display, c) !=
5707 error = "Unable to open an X11 connection";
5711 } else if (typelen == 15 &&
5712 !memcmp(type, "forwarded-tcpip", 15)) {
5713 struct ssh_rportfwd pf, *realpf;
5716 ssh2_pkt_getstring(ssh, &dummy, &dummylen);/* skip address */
5717 pf.sport = ssh2_pkt_getuint32(ssh);
5718 realpf = find234(ssh->rportfwds, &pf, NULL);
5719 if (realpf == NULL) {
5720 error = "Remote port is not recognised";
5722 char *e = pfd_newconnect(&c->u.pfd.s, realpf->dhost,
5725 sprintf(buf, "Received remote port open request for %s:%d",
5726 realpf->dhost, realpf->dport);
5729 sprintf(buf, "Port open failed: %s", e);
5731 error = "Port open failed";
5733 logevent("Forwarded port opened successfully");
5734 c->type = CHAN_SOCKDATA;
5737 } else if (typelen == 22 &&
5738 !memcmp(type, "auth-agent@openssh.com", 3)) {
5739 if (!ssh->agentfwd_enabled)
5740 error = "Agent forwarding is not enabled";
5742 c->type = CHAN_AGENT; /* identify channel type */
5743 c->u.a.lensofar = 0;
5746 error = "Unsupported channel type requested";
5749 c->remoteid = remid;
5751 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE);
5752 ssh2_pkt_adduint32(ssh, c->remoteid);
5753 ssh2_pkt_adduint32(ssh, SSH2_OPEN_CONNECT_FAILED);
5754 ssh2_pkt_addstring(ssh, error);
5755 ssh2_pkt_addstring(ssh, "en"); /* language tag */
5759 c->localid = alloc_channel_id(ssh);
5761 c->v.v2.locwindow = OUR_V2_WINSIZE;
5762 c->v.v2.remwindow = winsize;
5763 c->v.v2.remmaxpkt = pktsize;
5764 bufchain_init(&c->v.v2.outbuffer);
5765 add234(ssh->channels, c);
5766 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
5767 ssh2_pkt_adduint32(ssh, c->remoteid);
5768 ssh2_pkt_adduint32(ssh, c->localid);
5769 ssh2_pkt_adduint32(ssh, c->v.v2.locwindow);
5770 ssh2_pkt_adduint32(ssh, 0x4000UL); /* our max pkt size */
5774 bombout(("Strange packet received: type %d", ssh->pktin.type));
5779 * We have spare data. Add it to the channel buffer.
5781 ssh2_add_channel_data(ssh->mainchan, in, inlen);
5786 struct ssh_channel *c;
5788 * Try to send data on all channels if we can.
5790 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
5791 int bufsize = ssh2_try_send(c);
5794 case CHAN_MAINSESSION:
5795 /* stdin need not receive an unthrottle
5796 * notification since it will be polled */
5799 x11_unthrottle(c->u.x11.s);
5802 /* agent sockets are request/response and need no
5803 * buffer management */
5806 pfd_unthrottle(c->u.pfd.s);
5818 * Handle the top-level SSH2 protocol.
5820 static void ssh2_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
5822 if (do_ssh2_transport(ssh, in, inlen, ispkt) == 0)
5824 do_ssh2_authconn(ssh, in, inlen, ispkt);
5828 * Called to set up the connection.
5830 * Returns an error message, or NULL on success.
5832 static char *ssh_init(void *frontend_handle, void **backend_handle,
5833 char *host, int port, char **realhost, int nodelay)
5838 ssh = smalloc(sizeof(*ssh));
5841 ssh->v1_cipher_ctx = NULL;
5842 ssh->crcda_ctx = NULL;
5843 ssh->cscipher = NULL;
5844 ssh->cs_cipher_ctx = NULL;
5845 ssh->sccipher = NULL;
5846 ssh->sc_cipher_ctx = NULL;
5848 ssh->sc_mac_ctx = NULL;
5850 ssh->sc_mac_ctx = NULL;
5852 ssh->cs_comp_ctx = NULL;
5854 ssh->sc_comp_ctx = NULL;
5856 ssh->hostkey = NULL;
5858 ssh->state = SSH_STATE_PREPACKET;
5859 ssh->size_needed = FALSE;
5860 ssh->eof_needed = FALSE;
5863 static const struct Packet empty = { 0, 0, NULL, NULL, 0 };
5864 ssh->pktin = ssh->pktout = empty;
5866 ssh->deferred_send_data = NULL;
5867 ssh->deferred_len = 0;
5868 ssh->deferred_size = 0;
5869 ssh->fallback_cmd = 0;
5871 ssh->v2_outgoing_sequence = 0;
5872 ssh->ssh1_rdpkt_crstate = 0;
5873 ssh->ssh2_rdpkt_crstate = 0;
5874 ssh->do_ssh_init_crstate = 0;
5875 ssh->ssh_gotdata_crstate = 0;
5876 ssh->ssh1_protocol_crstate = 0;
5877 ssh->do_ssh1_login_crstate = 0;
5878 ssh->do_ssh2_transport_crstate = 0;
5879 ssh->do_ssh2_authconn_crstate = 0;
5880 ssh->do_ssh_init_state = NULL;
5881 ssh->do_ssh1_login_state = NULL;
5882 ssh->do_ssh2_transport_state = NULL;
5883 ssh->do_ssh2_authconn_state = NULL;
5885 *backend_handle = ssh;
5888 if (crypto_startup() == 0)
5889 return "Microsoft high encryption pack not installed!";
5892 ssh->frontend = frontend_handle;
5893 ssh->term_width = cfg.width;
5894 ssh->term_height = cfg.height;
5899 ssh->v1_throttle_count = 0;
5900 ssh->overall_bufsize = 0;
5901 ssh->fallback_cmd = 0;
5903 p = connect_to_host(ssh, host, port, realhost, nodelay);
5911 * Called to send data down the Telnet connection.
5913 static int ssh_send(void *handle, char *buf, int len)
5915 Ssh ssh = (Ssh) handle;
5917 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
5920 ssh->protocol(ssh, buf, len, 0);
5922 return ssh_sendbuffer(ssh);
5926 * Called to query the current amount of buffered stdin data.
5928 static int ssh_sendbuffer(void *handle)
5930 Ssh ssh = (Ssh) handle;
5933 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
5937 * If the SSH socket itself has backed up, add the total backup
5938 * size on that to any individual buffer on the stdin channel.
5941 if (ssh->throttled_all)
5942 override_value = ssh->overall_bufsize;
5944 if (ssh->version == 1) {
5945 return override_value;
5946 } else if (ssh->version == 2) {
5947 if (!ssh->mainchan || ssh->mainchan->closes > 0)
5948 return override_value;
5950 return (override_value +
5951 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
5958 * Called to set the size of the window from SSH's POV.
5960 static void ssh_size(void *handle, int width, int height)
5962 Ssh ssh = (Ssh) handle;
5964 ssh->term_width = width;
5965 ssh->term_height = height;
5967 switch (ssh->state) {
5968 case SSH_STATE_BEFORE_SIZE:
5969 case SSH_STATE_PREPACKET:
5970 case SSH_STATE_CLOSED:
5971 break; /* do nothing */
5972 case SSH_STATE_INTERMED:
5973 ssh->size_needed = TRUE; /* buffer for later */
5975 case SSH_STATE_SESSION:
5979 if (ssh->version == 1) {
5980 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
5981 PKT_INT, ssh->term_height,
5982 PKT_INT, ssh->term_width,
5983 PKT_INT, 0, PKT_INT, 0, PKT_END);
5985 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
5986 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
5987 ssh2_pkt_addstring(ssh, "window-change");
5988 ssh2_pkt_addbool(ssh, 0);
5989 ssh2_pkt_adduint32(ssh, ssh->term_width);
5990 ssh2_pkt_adduint32(ssh, ssh->term_height);
5991 ssh2_pkt_adduint32(ssh, 0);
5992 ssh2_pkt_adduint32(ssh, 0);
6001 * Send Telnet special codes. TS_EOF is useful for `plink', so you
6002 * can send an EOF and collect resulting output (e.g. `plink
6005 static void ssh_special(void *handle, Telnet_Special code)
6007 Ssh ssh = (Ssh) handle;
6009 if (code == TS_EOF) {
6010 if (ssh->state != SSH_STATE_SESSION) {
6012 * Buffer the EOF in case we are pre-SESSION, so we can
6013 * send it as soon as we reach SESSION.
6016 ssh->eof_needed = TRUE;
6019 if (ssh->version == 1) {
6020 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
6022 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_EOF);
6023 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
6026 logevent("Sent EOF message");
6027 } else if (code == TS_PING) {
6028 if (ssh->state == SSH_STATE_CLOSED
6029 || ssh->state == SSH_STATE_PREPACKET) return;
6030 if (ssh->version == 1) {
6031 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
6032 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
6034 ssh2_pkt_init(ssh, SSH2_MSG_IGNORE);
6035 ssh2_pkt_addstring_start(ssh);
6043 void *new_sock_channel(void *handle, Socket s)
6045 Ssh ssh = (Ssh) handle;
6046 struct ssh_channel *c;
6047 c = smalloc(sizeof(struct ssh_channel));
6051 c->remoteid = -1; /* to be set when open confirmed */
6052 c->localid = alloc_channel_id(ssh);
6054 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
6056 bufchain_init(&c->v.v2.outbuffer);
6057 add234(ssh->channels, c);
6063 * This is called when stdout/stderr (the entity to which
6064 * from_backend sends data) manages to clear some backlog.
6066 void ssh_unthrottle(void *handle, int bufsize)
6068 Ssh ssh = (Ssh) handle;
6069 if (ssh->version == 1) {
6070 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
6071 ssh->v1_stdout_throttling = 0;
6072 ssh1_throttle(ssh, -1);
6075 if (ssh->mainchan && ssh->mainchan->closes == 0)
6076 ssh2_set_window(ssh->mainchan, OUR_V2_WINSIZE - bufsize);
6080 void ssh_send_port_open(void *handle, void *channel, char *hostname,
6081 int port, char *org)
6083 Ssh ssh = (Ssh) handle;
6084 struct ssh_channel *c = (struct ssh_channel *)channel;
6087 sprintf(buf, "Opening forwarded connection to %.512s:%d", hostname, port);
6090 if (ssh->version == 1) {
6091 send_packet(ssh, SSH1_MSG_PORT_OPEN,
6092 PKT_INT, c->localid,
6095 //PKT_STR, <org:orgport>,
6098 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_OPEN);
6099 ssh2_pkt_addstring(ssh, "direct-tcpip");
6100 ssh2_pkt_adduint32(ssh, c->localid);
6101 c->v.v2.locwindow = OUR_V2_WINSIZE;
6102 ssh2_pkt_adduint32(ssh, c->v.v2.locwindow);/* our window size */
6103 ssh2_pkt_adduint32(ssh, 0x4000UL); /* our max pkt size */
6104 ssh2_pkt_addstring(ssh, hostname);
6105 ssh2_pkt_adduint32(ssh, port);
6107 * We make up values for the originator data; partly it's
6108 * too much hassle to keep track, and partly I'm not
6109 * convinced the server should be told details like that
6110 * about my local network configuration.
6112 ssh2_pkt_addstring(ssh, "client-side-connection");
6113 ssh2_pkt_adduint32(ssh, 0);
6119 static Socket ssh_socket(void *handle)
6121 Ssh ssh = (Ssh) handle;
6125 static int ssh_sendok(void *handle)
6127 Ssh ssh = (Ssh) handle;
6128 return ssh->send_ok;
6131 static int ssh_ldisc(void *handle, int option)
6133 Ssh ssh = (Ssh) handle;
6134 if (option == LD_ECHO)
6135 return ssh->echoing;
6136 if (option == LD_EDIT)
6137 return ssh->editing;
6141 static void ssh_provide_ldisc(void *handle, void *ldisc)
6143 Ssh ssh = (Ssh) handle;
6147 static int ssh_return_exitcode(void *handle)
6149 Ssh ssh = (Ssh) handle;
6150 return ssh->exitcode;
6154 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
6155 * that fails. This variable is the means by which scp.c can reach
6156 * into the SSH code and find out which one it got.
6158 extern int ssh_fallback_cmd(void *handle)
6160 Ssh ssh = (Ssh) handle;
6161 return ssh->fallback_cmd;
6164 Backend ssh_backend = {
6171 ssh_return_exitcode,