17 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
18 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
19 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
20 #define SSH1_CMSG_USER 4 /* 0x4 */
21 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
22 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
23 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
24 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
25 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
26 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
27 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
28 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
29 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
30 #define SSH1_SMSG_FAILURE 15 /* 0xf */
31 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
32 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
33 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
34 #define SSH1_CMSG_EOF 19 /* 0x13 */
35 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
36 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
37 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
38 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
39 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
40 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
41 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
42 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
43 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
44 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
45 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
46 #define SSH1_MSG_IGNORE 32 /* 0x20 */
47 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
48 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
49 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
50 #define SSH1_MSG_DEBUG 36 /* 0x24 */
51 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
52 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
53 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
54 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
55 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
56 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
57 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
59 #define SSH1_AUTH_TIS 5 /* 0x5 */
60 #define SSH1_AUTH_CCARD 16 /* 0x10 */
62 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
63 /* Mask for protoflags we will echo back to server if seen */
64 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
66 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
67 #define SSH2_MSG_IGNORE 2 /* 0x2 */
68 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
69 #define SSH2_MSG_DEBUG 4 /* 0x4 */
70 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
71 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
72 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
73 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
74 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
75 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
76 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
77 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
78 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
79 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
80 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
81 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
82 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
83 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
84 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
85 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
86 #define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */
87 #define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */
88 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
89 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
90 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
91 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
92 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
93 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
94 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
95 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
96 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
97 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
98 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
99 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
100 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
101 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
104 * Packet type contexts, so that ssh2_pkt_type can correctly decode
105 * the ambiguous type numbers back into the correct type strings.
107 #define SSH2_PKTCTX_DHGROUP 0x0001
108 #define SSH2_PKTCTX_DHGEX 0x0002
109 #define SSH2_PKTCTX_PUBLICKEY 0x0010
110 #define SSH2_PKTCTX_PASSWORD 0x0020
111 #define SSH2_PKTCTX_KBDINTER 0x0040
112 #define SSH2_PKTCTX_AUTH_MASK 0x00F0
114 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
115 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
116 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
117 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
118 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
119 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
120 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
121 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
122 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
123 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
124 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
125 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
126 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
127 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
128 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
130 static const char *const ssh2_disconnect_reasons[] = {
132 "SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT",
133 "SSH_DISCONNECT_PROTOCOL_ERROR",
134 "SSH_DISCONNECT_KEY_EXCHANGE_FAILED",
135 "SSH_DISCONNECT_HOST_AUTHENTICATION_FAILED",
136 "SSH_DISCONNECT_MAC_ERROR",
137 "SSH_DISCONNECT_COMPRESSION_ERROR",
138 "SSH_DISCONNECT_SERVICE_NOT_AVAILABLE",
139 "SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED",
140 "SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE",
141 "SSH_DISCONNECT_CONNECTION_LOST",
142 "SSH_DISCONNECT_BY_APPLICATION",
143 "SSH_DISCONNECT_TOO_MANY_CONNECTIONS",
144 "SSH_DISCONNECT_AUTH_CANCELLED_BY_USER",
145 "SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE",
146 "SSH_DISCONNECT_ILLEGAL_USER_NAME",
149 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
150 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
151 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
152 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
154 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
157 * Various remote-bug flags.
159 #define BUG_CHOKES_ON_SSH1_IGNORE 1
160 #define BUG_SSH2_HMAC 2
161 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
162 #define BUG_CHOKES_ON_RSA 8
163 #define BUG_SSH2_RSA_PADDING 16
164 #define BUG_SSH2_DERIVEKEY 32
165 /* 64 was BUG_SSH2_DH_GEX, now spare */
166 #define BUG_SSH2_PK_SESSIONID 128
168 #define translate(x) if (type == x) return #x
169 #define translatec(x,ctx) if (type == x && (pkt_ctx & ctx)) return #x
170 static char *ssh1_pkt_type(int type)
172 translate(SSH1_MSG_DISCONNECT);
173 translate(SSH1_SMSG_PUBLIC_KEY);
174 translate(SSH1_CMSG_SESSION_KEY);
175 translate(SSH1_CMSG_USER);
176 translate(SSH1_CMSG_AUTH_RSA);
177 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
178 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
179 translate(SSH1_CMSG_AUTH_PASSWORD);
180 translate(SSH1_CMSG_REQUEST_PTY);
181 translate(SSH1_CMSG_WINDOW_SIZE);
182 translate(SSH1_CMSG_EXEC_SHELL);
183 translate(SSH1_CMSG_EXEC_CMD);
184 translate(SSH1_SMSG_SUCCESS);
185 translate(SSH1_SMSG_FAILURE);
186 translate(SSH1_CMSG_STDIN_DATA);
187 translate(SSH1_SMSG_STDOUT_DATA);
188 translate(SSH1_SMSG_STDERR_DATA);
189 translate(SSH1_CMSG_EOF);
190 translate(SSH1_SMSG_EXIT_STATUS);
191 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
192 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
193 translate(SSH1_MSG_CHANNEL_DATA);
194 translate(SSH1_MSG_CHANNEL_CLOSE);
195 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
196 translate(SSH1_SMSG_X11_OPEN);
197 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
198 translate(SSH1_MSG_PORT_OPEN);
199 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
200 translate(SSH1_SMSG_AGENT_OPEN);
201 translate(SSH1_MSG_IGNORE);
202 translate(SSH1_CMSG_EXIT_CONFIRMATION);
203 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
204 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
205 translate(SSH1_MSG_DEBUG);
206 translate(SSH1_CMSG_REQUEST_COMPRESSION);
207 translate(SSH1_CMSG_AUTH_TIS);
208 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
209 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
210 translate(SSH1_CMSG_AUTH_CCARD);
211 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
212 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
215 static char *ssh2_pkt_type(int pkt_ctx, int type)
217 translate(SSH2_MSG_DISCONNECT);
218 translate(SSH2_MSG_IGNORE);
219 translate(SSH2_MSG_UNIMPLEMENTED);
220 translate(SSH2_MSG_DEBUG);
221 translate(SSH2_MSG_SERVICE_REQUEST);
222 translate(SSH2_MSG_SERVICE_ACCEPT);
223 translate(SSH2_MSG_KEXINIT);
224 translate(SSH2_MSG_NEWKEYS);
225 translatec(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP);
226 translatec(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP);
227 translatec(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
228 translatec(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
229 translatec(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
230 translatec(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
231 translate(SSH2_MSG_USERAUTH_REQUEST);
232 translate(SSH2_MSG_USERAUTH_FAILURE);
233 translate(SSH2_MSG_USERAUTH_SUCCESS);
234 translate(SSH2_MSG_USERAUTH_BANNER);
235 translatec(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
236 translatec(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
237 translatec(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
238 translatec(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
239 translate(SSH2_MSG_GLOBAL_REQUEST);
240 translate(SSH2_MSG_REQUEST_SUCCESS);
241 translate(SSH2_MSG_REQUEST_FAILURE);
242 translate(SSH2_MSG_CHANNEL_OPEN);
243 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
244 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
245 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
246 translate(SSH2_MSG_CHANNEL_DATA);
247 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
248 translate(SSH2_MSG_CHANNEL_EOF);
249 translate(SSH2_MSG_CHANNEL_CLOSE);
250 translate(SSH2_MSG_CHANNEL_REQUEST);
251 translate(SSH2_MSG_CHANNEL_SUCCESS);
252 translate(SSH2_MSG_CHANNEL_FAILURE);
258 #define GET_32BIT(cp) \
259 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
260 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
261 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
262 ((unsigned long)(unsigned char)(cp)[3]))
264 #define PUT_32BIT(cp, value) { \
265 (cp)[0] = (unsigned char)((value) >> 24); \
266 (cp)[1] = (unsigned char)((value) >> 16); \
267 (cp)[2] = (unsigned char)((value) >> 8); \
268 (cp)[3] = (unsigned char)(value); }
270 /* Enumeration values for fields in SSH-1 packets */
272 PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
273 /* These values are for communicating relevant semantics of
274 * fields to the packet logging code. */
275 PKTT_OTHER, PKTT_PASSWORD, PKTT_DATA
279 * Coroutine mechanics for the sillier bits of the code. If these
280 * macros look impenetrable to you, you might find it helpful to
283 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
285 * which explains the theory behind these macros.
287 * In particular, if you are getting `case expression not constant'
288 * errors when building with MS Visual Studio, this is because MS's
289 * Edit and Continue debugging feature causes their compiler to
290 * violate ANSI C. To disable Edit and Continue debugging:
292 * - right-click ssh.c in the FileView
294 * - select the C/C++ tab and the General category
295 * - under `Debug info:', select anything _other_ than `Program
296 * Database for Edit and Continue'.
298 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
301 if (!ssh->t) ssh->t = snew(struct t); \
303 #define crFinish(z) } *crLine = 0; return (z); }
304 #define crFinishV } *crLine = 0; return; }
305 #define crReturn(z) \
307 *crLine =__LINE__; return (z); case __LINE__:;\
311 *crLine=__LINE__; return; case __LINE__:;\
313 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
314 #define crStopV do{ *crLine = 0; return; }while(0)
315 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
316 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
318 typedef struct ssh_tag *Ssh;
321 static struct Packet *ssh2_pkt_init(int pkt_type);
322 static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
323 static void ssh2_pkt_adduint32(struct Packet *, unsigned long value);
324 static void ssh2_pkt_addstring_start(struct Packet *);
325 static void ssh2_pkt_addstring_str(struct Packet *, char *data);
326 static void ssh2_pkt_addstring_data(struct Packet *, char *data, int len);
327 static void ssh2_pkt_addstring(struct Packet *, char *data);
328 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
329 static void ssh2_pkt_addmp(struct Packet *, Bignum b);
330 static int ssh2_pkt_construct(Ssh, struct Packet *);
331 static void ssh2_pkt_send(Ssh, struct Packet *);
332 static void ssh2_pkt_send_noqueue(Ssh, struct Packet *);
333 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
334 struct Packet *pktin);
335 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
336 struct Packet *pktin);
339 * Buffer management constants. There are several of these for
340 * various different purposes:
342 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
343 * on a local data stream before we throttle the whole SSH
344 * connection (in SSH1 only). Throttling the whole connection is
345 * pretty drastic so we set this high in the hope it won't
348 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
349 * on the SSH connection itself before we defensively throttle
350 * _all_ local data streams. This is pretty drastic too (though
351 * thankfully unlikely in SSH2 since the window mechanism should
352 * ensure that the server never has any need to throttle its end
353 * of the connection), so we set this high as well.
355 * - OUR_V2_WINSIZE is the maximum window size we present on SSH2
359 #define SSH1_BUFFER_LIMIT 32768
360 #define SSH_MAX_BACKLOG 32768
361 #define OUR_V2_WINSIZE 16384
363 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
365 static void *nullmac_make_context(void)
369 static void nullmac_free_context(void *handle)
372 static void nullmac_key(void *handle, unsigned char *key)
375 static void nullmac_generate(void *handle, unsigned char *blk, int len,
379 static int nullmac_verify(void *handle, unsigned char *blk, int len,
384 const static struct ssh_mac ssh_mac_none = {
385 nullmac_make_context, nullmac_free_context, nullmac_key,
386 nullmac_generate, nullmac_verify, "none", 0
388 const static struct ssh_mac *macs[] = {
389 &ssh_sha1, &ssh_md5, &ssh_mac_none
391 const static struct ssh_mac *buggymacs[] = {
392 &ssh_sha1_buggy, &ssh_md5, &ssh_mac_none
395 static void *ssh_comp_none_init(void)
399 static void ssh_comp_none_cleanup(void *handle)
402 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
403 unsigned char **outblock, int *outlen)
407 static int ssh_comp_none_disable(void *handle)
411 const static struct ssh_compress ssh_comp_none = {
413 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
414 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
415 ssh_comp_none_disable, NULL
417 extern const struct ssh_compress ssh_zlib;
418 const static struct ssh_compress *compressions[] = {
419 &ssh_zlib, &ssh_comp_none
422 enum { /* channel types */
427 CHAN_SOCKDATA_DORMANT /* one the remote hasn't confirmed */
431 * 2-3-4 tree storing channels.
434 Ssh ssh; /* pointer back to main context */
435 unsigned remoteid, localid;
438 * In SSH1, this value contains four bits:
440 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
441 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
442 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
443 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
445 * A channel is completely finished with when all four bits are set.
449 struct ssh1_data_channel {
452 struct ssh2_data_channel {
454 unsigned remwindow, remmaxpkt;
459 struct ssh_agent_channel {
460 unsigned char *message;
461 unsigned char msglen[4];
462 unsigned lensofar, totallen;
464 struct ssh_x11_channel {
467 struct ssh_pfd_channel {
474 * 2-3-4 tree storing remote->local port forwardings. SSH 1 and SSH
475 * 2 use this structure in different ways, reflecting SSH 2's
476 * altogether saner approach to port forwarding.
478 * In SSH 1, you arrange a remote forwarding by sending the server
479 * the remote port number, and the local destination host:port.
480 * When a connection comes in, the server sends you back that
481 * host:port pair, and you connect to it. This is a ready-made
482 * security hole if you're not on the ball: a malicious server
483 * could send you back _any_ host:port pair, so if you trustingly
484 * connect to the address it gives you then you've just opened the
485 * entire inside of your corporate network just by connecting
486 * through it to a dodgy SSH server. Hence, we must store a list of
487 * host:port pairs we _are_ trying to forward to, and reject a
488 * connection request from the server if it's not in the list.
490 * In SSH 2, each side of the connection minds its own business and
491 * doesn't send unnecessary information to the other. You arrange a
492 * remote forwarding by sending the server just the remote port
493 * number. When a connection comes in, the server tells you which
494 * of its ports was connected to; and _you_ have to remember what
495 * local host:port pair went with that port number.
497 * Hence, in SSH 1 this structure is indexed by destination
498 * host:port pair, whereas in SSH 2 it is indexed by source port.
500 struct ssh_portfwd; /* forward declaration */
502 struct ssh_rportfwd {
503 unsigned sport, dport;
506 struct ssh_portfwd *pfrec;
508 #define free_rportfwd(pf) ( \
509 ((pf) ? (sfree((pf)->sportdesc)) : (void)0 ), sfree(pf) )
512 * Separately to the rportfwd tree (which is for looking up port
513 * open requests from the server), a tree of _these_ structures is
514 * used to keep track of all the currently open port forwardings,
515 * so that we can reconfigure in mid-session if the user requests
521 unsigned sport, dport;
523 struct ssh_rportfwd *remote;
526 #define free_portfwd(pf) ( \
527 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr)) : (void)0 ), sfree(pf) )
532 unsigned long sequence;
537 long encrypted_len; /* for SSH2 total-size counting */
540 * State associated with packet logging
544 struct logblank_t *blanks;
547 static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen,
548 struct Packet *pktin);
549 static void ssh2_protocol(Ssh ssh, unsigned char *in, int inlen,
550 struct Packet *pktin);
551 static void ssh1_protocol_setup(Ssh ssh);
552 static void ssh2_protocol_setup(Ssh ssh);
553 static void ssh_size(void *handle, int width, int height);
554 static void ssh_special(void *handle, Telnet_Special);
555 static int ssh2_try_send(struct ssh_channel *c);
556 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
557 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
558 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin);
559 static int ssh_sendbuffer(void *handle);
560 static void ssh_do_close(Ssh ssh);
561 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
562 static int ssh2_pkt_getbool(struct Packet *pkt);
563 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
564 static void ssh2_timer(void *ctx, long now);
565 static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen,
566 struct Packet *pktin);
568 struct rdpkt1_state_tag {
569 long len, pad, biglen, to_read;
570 unsigned long realcrc, gotcrc;
574 struct Packet *pktin;
577 struct rdpkt2_state_tag {
578 long len, pad, payload, packetlen, maclen;
581 unsigned long incoming_sequence;
582 struct Packet *pktin;
585 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
586 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
588 struct queued_handler;
589 struct queued_handler {
591 chandler_fn_t handler;
593 struct queued_handler *next;
597 const struct plug_function_table *fn;
598 /* the above field _must_ be first in the structure */
600 SHA_State exhash, exhashbase;
607 unsigned char session_key[32];
609 int v1_remote_protoflags;
610 int v1_local_protoflags;
611 int agentfwd_enabled;
614 const struct ssh_cipher *cipher;
617 const struct ssh2_cipher *cscipher, *sccipher;
618 void *cs_cipher_ctx, *sc_cipher_ctx;
619 const struct ssh_mac *csmac, *scmac;
620 void *cs_mac_ctx, *sc_mac_ctx;
621 const struct ssh_compress *cscomp, *sccomp;
622 void *cs_comp_ctx, *sc_comp_ctx;
623 const struct ssh_kex *kex;
624 const struct ssh_signkey *hostkey;
625 unsigned char v2_session_id[20];
631 int echoing, editing;
635 int ospeed, ispeed; /* temporaries */
636 int term_width, term_height;
638 tree234 *channels; /* indexed by local id */
639 struct ssh_channel *mainchan; /* primary session channel */
642 tree234 *rportfwds, *portfwds;
646 SSH_STATE_BEFORE_SIZE,
652 int size_needed, eof_needed;
654 struct Packet **queue;
655 int queuelen, queuesize;
657 unsigned char *deferred_send_data;
658 int deferred_len, deferred_size;
661 * Gross hack: pscp will try to start SFTP but fall back to
662 * scp1 if that fails. This variable is the means by which
663 * scp.c can reach into the SSH code and find out which one it
669 * Used for username and password input.
671 char *userpass_input_buffer;
672 int userpass_input_buflen;
673 int userpass_input_bufpos;
674 int userpass_input_echo;
681 int v1_throttle_count;
684 int v1_stdout_throttling;
685 int v2_outgoing_sequence;
687 int ssh1_rdpkt_crstate;
688 int ssh2_rdpkt_crstate;
689 int do_ssh_init_crstate;
690 int ssh_gotdata_crstate;
691 int do_ssh1_login_crstate;
692 int do_ssh1_connection_crstate;
693 int do_ssh2_transport_crstate;
694 int do_ssh2_authconn_crstate;
696 void *do_ssh_init_state;
697 void *do_ssh1_login_state;
698 void *do_ssh2_transport_state;
699 void *do_ssh2_authconn_state;
701 struct rdpkt1_state_tag rdpkt1_state;
702 struct rdpkt2_state_tag rdpkt2_state;
704 /* ssh1 and ssh2 use this for different things, but both use it */
705 int protocol_initial_phase_done;
707 void (*protocol) (Ssh ssh, unsigned char *in, int inlen,
709 struct Packet *(*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
712 * We maintain a full _copy_ of a Config structure here, not
713 * merely a pointer to it. That way, when we're passed a new
714 * one for reconfiguration, we can check the differences and
715 * potentially reconfigure port forwardings etc in mid-session.
720 * Used to transfer data back from async agent callbacks.
722 void *agent_response;
723 int agent_response_len;
726 * Dispatch table for packet types that we may have to deal
729 handler_fn_t packet_dispatch[256];
732 * Queues of one-off handler functions for success/failure
733 * indications from a request.
735 struct queued_handler *qhead, *qtail;
738 * This module deals with sending keepalives.
743 * Track incoming and outgoing data sizes and time, for
746 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
747 unsigned long max_data_size;
749 long next_rekey, last_rekey;
752 #define logevent(s) logevent(ssh->frontend, s)
754 /* logevent, only printf-formatted. */
755 static void logeventf(Ssh ssh, const char *fmt, ...)
761 buf = dupvprintf(fmt, ap);
767 #define bombout(msg) \
769 char *text = dupprintf msg; \
772 connection_fatal(ssh->frontend, "%s", text); \
776 /* Functions to leave bits out of the SSH packet log file. */
778 static void dont_log_password(Ssh ssh, struct Packet *pkt, int blanktype)
780 if (ssh->cfg.logomitpass)
781 pkt->logmode = blanktype;
784 static void dont_log_data(Ssh ssh, struct Packet *pkt, int blanktype)
786 if (ssh->cfg.logomitdata)
787 pkt->logmode = blanktype;
790 static void end_log_omission(Ssh ssh, struct Packet *pkt)
792 pkt->logmode = PKTLOG_EMIT;
795 static int ssh_channelcmp(void *av, void *bv)
797 struct ssh_channel *a = (struct ssh_channel *) av;
798 struct ssh_channel *b = (struct ssh_channel *) bv;
799 if (a->localid < b->localid)
801 if (a->localid > b->localid)
805 static int ssh_channelfind(void *av, void *bv)
807 unsigned *a = (unsigned *) av;
808 struct ssh_channel *b = (struct ssh_channel *) bv;
816 static int ssh_rportcmp_ssh1(void *av, void *bv)
818 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
819 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
821 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
822 return i < 0 ? -1 : +1;
823 if (a->dport > b->dport)
825 if (a->dport < b->dport)
830 static int ssh_rportcmp_ssh2(void *av, void *bv)
832 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
833 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
835 if (a->sport > b->sport)
837 if (a->sport < b->sport)
843 * Special form of strcmp which can cope with NULL inputs. NULL is
844 * defined to sort before even the empty string.
846 static int nullstrcmp(const char *a, const char *b)
848 if (a == NULL && b == NULL)
857 static int ssh_portcmp(void *av, void *bv)
859 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
860 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
862 if (a->type > b->type)
864 if (a->type < b->type)
866 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
867 return i < 0 ? -1 : +1;
868 if (a->sport > b->sport)
870 if (a->sport < b->sport)
872 if (a->type != 'D') {
873 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
874 return i < 0 ? -1 : +1;
875 if (a->dport > b->dport)
877 if (a->dport < b->dport)
883 static int alloc_channel_id(Ssh ssh)
885 const unsigned CHANNEL_NUMBER_OFFSET = 256;
886 unsigned low, high, mid;
888 struct ssh_channel *c;
891 * First-fit allocation of channel numbers: always pick the
892 * lowest unused one. To do this, binary-search using the
893 * counted B-tree to find the largest channel ID which is in a
894 * contiguous sequence from the beginning. (Precisely
895 * everything in that sequence must have ID equal to its tree
896 * index plus CHANNEL_NUMBER_OFFSET.)
898 tsize = count234(ssh->channels);
902 while (high - low > 1) {
903 mid = (high + low) / 2;
904 c = index234(ssh->channels, mid);
905 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
906 low = mid; /* this one is fine */
908 high = mid; /* this one is past it */
911 * Now low points to either -1, or the tree index of the
912 * largest ID in the initial sequence.
915 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
916 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
918 return low + 1 + CHANNEL_NUMBER_OFFSET;
921 static void c_write(Ssh ssh, const char *buf, int len)
923 if ((flags & FLAG_STDERR)) {
925 for (i = 0; i < len; i++)
927 fputc(buf[i], stderr);
930 from_backend(ssh->frontend, 1, buf, len);
933 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
936 for (i = 0; i < len; i++) {
938 c_write(ssh, "\r\n", 2);
939 else if ((buf[i] & 0x60) || (buf[i] == '\r'))
940 c_write(ssh, buf + i, 1);
944 static void c_write_str(Ssh ssh, const char *buf)
946 c_write(ssh, buf, strlen(buf));
949 static void ssh_free_packet(struct Packet *pkt)
954 static struct Packet *ssh_new_packet(void)
956 struct Packet *pkt = snew(struct Packet);
960 pkt->logmode = PKTLOG_EMIT;
968 * Collect incoming data in the incoming packet buffer.
969 * Decipher and verify the packet when it is completely read.
970 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
971 * Update the *data and *datalen variables.
972 * Return a Packet structure when a packet is completed.
974 static struct Packet *ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
976 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
978 crBegin(ssh->ssh1_rdpkt_crstate);
980 st->pktin = ssh_new_packet();
983 st->pktin->length = 0;
985 for (st->i = st->len = 0; st->i < 4; st->i++) {
986 while ((*datalen) == 0)
988 st->len = (st->len << 8) + **data;
989 (*data)++, (*datalen)--;
992 st->pad = 8 - (st->len % 8);
993 st->biglen = st->len + st->pad;
994 st->pktin->length = st->len - 5;
996 if (st->biglen < 0) {
997 bombout(("Extremely large packet length from server suggests"
998 " data stream corruption"));
999 ssh_free_packet(st->pktin);
1003 st->pktin->maxlen = st->biglen;
1004 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1006 st->to_read = st->biglen;
1007 st->p = st->pktin->data;
1008 while (st->to_read > 0) {
1009 st->chunk = st->to_read;
1010 while ((*datalen) == 0)
1012 if (st->chunk > (*datalen))
1013 st->chunk = (*datalen);
1014 memcpy(st->p, *data, st->chunk);
1016 *datalen -= st->chunk;
1018 st->to_read -= st->chunk;
1021 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1022 st->biglen, NULL)) {
1023 bombout(("Network attack (CRC compensation) detected!"));
1024 ssh_free_packet(st->pktin);
1029 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1031 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1032 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1033 if (st->gotcrc != st->realcrc) {
1034 bombout(("Incorrect CRC received on packet"));
1035 ssh_free_packet(st->pktin);
1039 st->pktin->body = st->pktin->data + st->pad + 1;
1040 st->pktin->savedpos = 0;
1042 if (ssh->v1_compressing) {
1043 unsigned char *decompblk;
1045 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1046 st->pktin->body - 1, st->pktin->length + 1,
1047 &decompblk, &decomplen)) {
1048 bombout(("Zlib decompression encountered invalid data"));
1049 ssh_free_packet(st->pktin);
1053 if (st->pktin->maxlen < st->pad + decomplen) {
1054 st->pktin->maxlen = st->pad + decomplen;
1055 st->pktin->data = sresize(st->pktin->data,
1056 st->pktin->maxlen + APIEXTRA,
1058 st->pktin->body = st->pktin->data + st->pad + 1;
1061 memcpy(st->pktin->body - 1, decompblk, decomplen);
1063 st->pktin->length = decomplen - 1;
1066 st->pktin->type = st->pktin->body[-1];
1069 * Log incoming packet, possibly omitting sensitive fields.
1073 struct logblank_t blank;
1074 if (ssh->cfg.logomitdata) {
1075 int do_blank = FALSE, blank_prefix = 0;
1076 /* "Session data" packets - omit the data field */
1077 if ((st->pktin->type == SSH1_SMSG_STDOUT_DATA) ||
1078 (st->pktin->type == SSH1_SMSG_STDERR_DATA)) {
1079 do_blank = TRUE; blank_prefix = 0;
1080 } else if (st->pktin->type == SSH1_MSG_CHANNEL_DATA) {
1081 do_blank = TRUE; blank_prefix = 4;
1084 blank.offset = blank_prefix;
1085 blank.len = st->pktin->length;
1086 blank.type = PKTLOG_OMIT;
1090 log_packet(ssh->logctx,
1091 PKT_INCOMING, st->pktin->type,
1092 ssh1_pkt_type(st->pktin->type),
1093 st->pktin->body, st->pktin->length,
1097 crFinish(st->pktin);
1100 static struct Packet *ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1102 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1104 crBegin(ssh->ssh2_rdpkt_crstate);
1106 st->pktin = ssh_new_packet();
1108 st->pktin->type = 0;
1109 st->pktin->length = 0;
1111 st->cipherblk = ssh->sccipher->blksize;
1114 if (st->cipherblk < 8)
1117 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1120 * Acquire and decrypt the first block of the packet. This will
1121 * contain the length and padding details.
1123 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1124 while ((*datalen) == 0)
1126 st->pktin->data[st->i] = *(*data)++;
1131 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1132 st->pktin->data, st->cipherblk);
1135 * Now get the length and padding figures.
1137 st->len = GET_32BIT(st->pktin->data);
1138 st->pad = st->pktin->data[4];
1141 * _Completely_ silly lengths should be stomped on before they
1142 * do us any more damage.
1144 if (st->len < 0 || st->pad < 0 || st->len + st->pad < 0) {
1145 bombout(("Incoming packet was garbled on decryption"));
1146 ssh_free_packet(st->pktin);
1151 * This enables us to deduce the payload length.
1153 st->payload = st->len - st->pad - 1;
1155 st->pktin->length = st->payload + 5;
1158 * So now we can work out the total packet length.
1160 st->packetlen = st->len + 4;
1161 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1164 * Allocate memory for the rest of the packet.
1166 st->pktin->maxlen = st->packetlen + st->maclen;
1167 st->pktin->data = sresize(st->pktin->data,
1168 st->pktin->maxlen + APIEXTRA,
1172 * Read and decrypt the remainder of the packet.
1174 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1176 while ((*datalen) == 0)
1178 st->pktin->data[st->i] = *(*data)++;
1181 /* Decrypt everything _except_ the MAC. */
1183 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1184 st->pktin->data + st->cipherblk,
1185 st->packetlen - st->cipherblk);
1187 st->pktin->encrypted_len = st->packetlen;
1193 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data, st->len + 4,
1194 st->incoming_sequence)) {
1195 bombout(("Incorrect MAC received on packet"));
1196 ssh_free_packet(st->pktin);
1200 st->pktin->sequence = st->incoming_sequence++;
1203 * Decompress packet payload.
1206 unsigned char *newpayload;
1209 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1210 st->pktin->data + 5, st->pktin->length - 5,
1211 &newpayload, &newlen)) {
1212 if (st->pktin->maxlen < newlen + 5) {
1213 st->pktin->maxlen = newlen + 5;
1214 st->pktin->data = sresize(st->pktin->data,
1215 st->pktin->maxlen + APIEXTRA,
1218 st->pktin->length = 5 + newlen;
1219 memcpy(st->pktin->data + 5, newpayload, newlen);
1224 st->pktin->savedpos = 6;
1225 st->pktin->body = st->pktin->data;
1226 st->pktin->type = st->pktin->data[5];
1229 * Log incoming packet, possibly omitting sensitive fields.
1233 struct logblank_t blank;
1234 if (ssh->cfg.logomitdata) {
1235 int do_blank = FALSE, blank_prefix = 0;
1236 /* "Session data" packets - omit the data field */
1237 if (st->pktin->type == SSH2_MSG_CHANNEL_DATA) {
1238 do_blank = TRUE; blank_prefix = 4;
1239 } else if (st->pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
1240 do_blank = TRUE; blank_prefix = 8;
1243 blank.offset = blank_prefix;
1244 blank.len = (st->pktin->length-6) - blank_prefix;
1245 blank.type = PKTLOG_OMIT;
1249 log_packet(ssh->logctx, PKT_INCOMING, st->pktin->type,
1250 ssh2_pkt_type(ssh->pkt_ctx, st->pktin->type),
1251 st->pktin->data+6, st->pktin->length-6,
1255 crFinish(st->pktin);
1258 static void ssh1_pktout_size(struct Packet *pkt, int len)
1262 len += 5; /* type and CRC */
1263 pad = 8 - (len % 8);
1266 pkt->length = len - 5;
1267 if (pkt->maxlen < biglen) {
1268 pkt->maxlen = biglen;
1269 pkt->data = sresize(pkt->data, biglen + 4 + APIEXTRA, unsigned char);
1271 pkt->body = pkt->data + 4 + pad + 1;
1274 static struct Packet *s_wrpkt_start(int type, int len)
1276 struct Packet *pkt = ssh_new_packet();
1277 ssh1_pktout_size(pkt, len);
1279 /* Initialise log omission state */
1285 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt)
1291 * XXX various versions of SC (including 8.8.4) screw up the
1292 * register allocation in this function and use the same register
1293 * (D6) for len and as a temporary, with predictable results. The
1294 * following sledgehammer prevents this.
1300 pkt->body[-1] = pkt->type;
1303 log_packet(ssh->logctx, PKT_OUTGOING, pkt->type,
1304 ssh1_pkt_type(pkt->type),
1305 pkt->body, pkt->length,
1306 pkt->nblanks, pkt->blanks);
1307 sfree(pkt->blanks); pkt->blanks = NULL;
1310 if (ssh->v1_compressing) {
1311 unsigned char *compblk;
1313 zlib_compress_block(ssh->cs_comp_ctx,
1314 pkt->body - 1, pkt->length + 1,
1315 &compblk, &complen);
1316 ssh1_pktout_size(pkt, complen - 1);
1317 memcpy(pkt->body - 1, compblk, complen);
1321 len = pkt->length + 5; /* type and CRC */
1322 pad = 8 - (len % 8);
1325 for (i = 0; i < pad; i++)
1326 pkt->data[i + 4] = random_byte();
1327 crc = crc32_compute(pkt->data + 4, biglen - 4);
1328 PUT_32BIT(pkt->data + biglen, crc);
1329 PUT_32BIT(pkt->data, len);
1332 ssh->cipher->encrypt(ssh->v1_cipher_ctx, pkt->data + 4, biglen);
1337 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1340 len = s_wrpkt_prepare(ssh, pkt);
1341 backlog = sk_write(ssh->s, (char *)pkt->data, len);
1342 if (backlog > SSH_MAX_BACKLOG)
1343 ssh_throttle_all(ssh, 1, backlog);
1346 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1349 len = s_wrpkt_prepare(ssh, pkt);
1350 if (ssh->deferred_len + len > ssh->deferred_size) {
1351 ssh->deferred_size = ssh->deferred_len + len + 128;
1352 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1356 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->data, len);
1357 ssh->deferred_len += len;
1361 * Construct a packet with the specified contents.
1363 static struct Packet *construct_packet(Ssh ssh, int pkttype,
1364 va_list ap1, va_list ap2)
1366 unsigned char *p, *argp, argchar;
1367 unsigned long argint;
1368 int pktlen, argtype, arglen;
1373 while ((argtype = va_arg(ap1, int)) != PKT_END) {
1376 (void) va_arg(ap1, int);
1380 (void) va_arg(ap1, int);
1384 (void) va_arg(ap1, unsigned char *);
1385 arglen = va_arg(ap1, int);
1389 argp = va_arg(ap1, unsigned char *);
1390 arglen = strlen((char *)argp);
1391 pktlen += 4 + arglen;
1394 bn = va_arg(ap1, Bignum);
1395 pktlen += ssh1_bignum_length(bn);
1400 /* ignore this pass */
1407 pkt = s_wrpkt_start(pkttype, pktlen);
1410 while ((argtype = va_arg(ap2, int)) != PKT_END) {
1411 int offset = p - pkt->body, len = 0;
1413 /* Actual fields in the packet */
1415 argint = va_arg(ap2, int);
1416 PUT_32BIT(p, argint);
1420 argchar = (unsigned char) va_arg(ap2, int);
1425 argp = va_arg(ap2, unsigned char *);
1426 arglen = va_arg(ap2, int);
1427 memcpy(p, argp, arglen);
1431 argp = va_arg(ap2, unsigned char *);
1432 arglen = strlen((char *)argp);
1433 PUT_32BIT(p, arglen);
1434 memcpy(p + 4, argp, arglen);
1438 bn = va_arg(ap2, Bignum);
1439 len = ssh1_write_bignum(p, bn);
1441 /* Tokens for modifications to packet logging */
1443 dont_log_password(ssh, pkt, PKTLOG_BLANK);
1446 dont_log_data(ssh, pkt, PKTLOG_OMIT);
1449 end_log_omission(ssh, pkt);
1453 /* Deal with logfile omission, if required. */
1454 if (len && (pkt->logmode != PKTLOG_EMIT)) {
1456 pkt->blanks = sresize(pkt->blanks, pkt->nblanks,
1458 pkt->blanks[pkt->nblanks-1].offset = offset;
1459 pkt->blanks[pkt->nblanks-1].len = len;
1460 pkt->blanks[pkt->nblanks-1].type = pkt->logmode;
1467 static void send_packet(Ssh ssh, int pkttype, ...)
1471 va_start(ap1, pkttype);
1472 va_start(ap2, pkttype);
1473 pkt = construct_packet(ssh, pkttype, ap1, ap2);
1477 ssh_free_packet(pkt);
1480 static void defer_packet(Ssh ssh, int pkttype, ...)
1484 va_start(ap1, pkttype);
1485 va_start(ap2, pkttype);
1486 pkt = construct_packet(ssh, pkttype, ap1, ap2);
1489 s_wrpkt_defer(ssh, pkt);
1490 ssh_free_packet(pkt);
1493 static int ssh_versioncmp(char *a, char *b)
1496 unsigned long av, bv;
1498 av = strtoul(a, &ae, 10);
1499 bv = strtoul(b, &be, 10);
1501 return (av < bv ? -1 : +1);
1506 av = strtoul(ae, &ae, 10);
1507 bv = strtoul(be, &be, 10);
1509 return (av < bv ? -1 : +1);
1514 * Utility routines for putting an SSH-protocol `string' and
1515 * `uint32' into a SHA state.
1518 static void sha_string(SHA_State * s, void *str, int len)
1520 unsigned char lenblk[4];
1521 PUT_32BIT(lenblk, len);
1522 SHA_Bytes(s, lenblk, 4);
1523 SHA_Bytes(s, str, len);
1526 static void sha_uint32(SHA_State * s, unsigned i)
1528 unsigned char intblk[4];
1529 PUT_32BIT(intblk, i);
1530 SHA_Bytes(s, intblk, 4);
1534 * SSH2 packet construction functions.
1536 static void ssh2_pkt_ensure(struct Packet *pkt, int length)
1538 if (pkt->maxlen < length) {
1539 pkt->maxlen = length + 256;
1540 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
1543 static void ssh2_pkt_adddata(struct Packet *pkt, void *data, int len)
1545 if (pkt->logmode != PKTLOG_EMIT) {
1547 pkt->blanks = sresize(pkt->blanks, pkt->nblanks, struct logblank_t);
1548 pkt->blanks[pkt->nblanks-1].offset = pkt->length - 6;
1549 pkt->blanks[pkt->nblanks-1].len = len;
1550 pkt->blanks[pkt->nblanks-1].type = pkt->logmode;
1553 ssh2_pkt_ensure(pkt, pkt->length);
1554 memcpy(pkt->data + pkt->length - len, data, len);
1556 static void ssh2_pkt_addbyte(struct Packet *pkt, unsigned char byte)
1558 ssh2_pkt_adddata(pkt, &byte, 1);
1560 static struct Packet *ssh2_pkt_init(int pkt_type)
1562 struct Packet *pkt = ssh_new_packet();
1564 ssh2_pkt_addbyte(pkt, (unsigned char) pkt_type);
1567 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
1569 ssh2_pkt_adddata(pkt, &value, 1);
1571 static void ssh2_pkt_adduint32(struct Packet *pkt, unsigned long value)
1574 PUT_32BIT(x, value);
1575 ssh2_pkt_adddata(pkt, x, 4);
1577 static void ssh2_pkt_addstring_start(struct Packet *pkt)
1579 ssh2_pkt_adduint32(pkt, 0);
1580 pkt->savedpos = pkt->length;
1582 static void ssh2_pkt_addstring_str(struct Packet *pkt, char *data)
1584 ssh2_pkt_adddata(pkt, data, strlen(data));
1585 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1587 static void ssh2_pkt_addstring_data(struct Packet *pkt, char *data, int len)
1589 ssh2_pkt_adddata(pkt, data, len);
1590 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1592 static void ssh2_pkt_addstring(struct Packet *pkt, char *data)
1594 ssh2_pkt_addstring_start(pkt);
1595 ssh2_pkt_addstring_str(pkt, data);
1597 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
1600 int i, n = (bignum_bitcount(b) + 7) / 8;
1601 p = snewn(n + 1, unsigned char);
1603 fatalbox("out of memory");
1605 for (i = 1; i <= n; i++)
1606 p[i] = bignum_byte(b, n - i);
1608 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1610 memmove(p, p + i, n + 1 - i);
1614 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
1618 p = ssh2_mpint_fmt(b, &len);
1619 ssh2_pkt_addstring_start(pkt);
1620 ssh2_pkt_addstring_data(pkt, (char *)p, len);
1625 * Construct an SSH2 final-form packet: compress it, encrypt it,
1626 * put the MAC on it. Final packet, ready to be sent, is stored in
1627 * pkt->data. Total length is returned.
1629 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
1631 int cipherblk, maclen, padding, i;
1634 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1635 ssh2_pkt_type(ssh->pkt_ctx, pkt->data[5]),
1636 pkt->data + 6, pkt->length - 6,
1637 pkt->nblanks, pkt->blanks);
1638 sfree(pkt->blanks); pkt->blanks = NULL;
1642 * Compress packet payload.
1645 unsigned char *newpayload;
1648 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
1650 &newpayload, &newlen)) {
1652 ssh2_pkt_adddata(pkt, newpayload, newlen);
1658 * Add padding. At least four bytes, and must also bring total
1659 * length (minus MAC) up to a multiple of the block size.
1661 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
1662 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1665 (cipherblk - (pkt->length + padding) % cipherblk) % cipherblk;
1666 maclen = ssh->csmac ? ssh->csmac->len : 0;
1667 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
1668 pkt->data[4] = padding;
1669 for (i = 0; i < padding; i++)
1670 pkt->data[pkt->length + i] = random_byte();
1671 PUT_32BIT(pkt->data, pkt->length + padding - 4);
1673 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
1674 pkt->length + padding,
1675 ssh->v2_outgoing_sequence);
1676 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
1679 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
1680 pkt->data, pkt->length + padding);
1682 pkt->encrypted_len = pkt->length + padding;
1684 /* Ready-to-send packet starts at pkt->data. We return length. */
1685 return pkt->length + padding + maclen;
1689 * Routines called from the main SSH code to send packets. There
1690 * are quite a few of these, because we have two separate
1691 * mechanisms for delaying the sending of packets:
1693 * - In order to send an IGNORE message and a password message in
1694 * a single fixed-length blob, we require the ability to
1695 * concatenate the encrypted forms of those two packets _into_ a
1696 * single blob and then pass it to our <network.h> transport
1697 * layer in one go. Hence, there's a deferment mechanism which
1698 * works after packet encryption.
1700 * - In order to avoid sending any connection-layer messages
1701 * during repeat key exchange, we have to queue up any such
1702 * outgoing messages _before_ they are encrypted (and in
1703 * particular before they're allocated sequence numbers), and
1704 * then send them once we've finished.
1706 * I call these mechanisms `defer' and `queue' respectively, so as
1707 * to distinguish them reasonably easily.
1709 * The functions send_noqueue() and defer_noqueue() free the packet
1710 * structure they are passed. Every outgoing packet goes through
1711 * precisely one of these functions in its life; packets passed to
1712 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
1713 * these or get queued, and then when the queue is later emptied
1714 * the packets are all passed to defer_noqueue().
1718 * Send an SSH2 packet immediately, without queuing or deferring.
1720 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
1724 len = ssh2_pkt_construct(ssh, pkt);
1725 backlog = sk_write(ssh->s, (char *)pkt->data, len);
1726 if (backlog > SSH_MAX_BACKLOG)
1727 ssh_throttle_all(ssh, 1, backlog);
1729 ssh->outgoing_data_size += pkt->encrypted_len;
1730 if (!ssh->kex_in_progress &&
1731 ssh->max_data_size != 0 &&
1732 ssh->outgoing_data_size > ssh->max_data_size)
1733 do_ssh2_transport(ssh, "Initiating key re-exchange "
1734 "(too much data sent)", -1, NULL);
1736 ssh_free_packet(pkt);
1740 * Defer an SSH2 packet.
1742 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt)
1744 int len = ssh2_pkt_construct(ssh, pkt);
1745 if (ssh->deferred_len + len > ssh->deferred_size) {
1746 ssh->deferred_size = ssh->deferred_len + len + 128;
1747 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1751 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->data, len);
1752 ssh->deferred_len += len;
1753 ssh->deferred_data_size += pkt->encrypted_len;
1754 ssh_free_packet(pkt);
1758 * Queue an SSH2 packet.
1760 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
1762 assert(ssh->queueing);
1764 if (ssh->queuelen >= ssh->queuesize) {
1765 ssh->queuesize = ssh->queuelen + 32;
1766 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
1769 ssh->queue[ssh->queuelen++] = pkt;
1773 * Either queue or send a packet, depending on whether queueing is
1776 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
1779 ssh2_pkt_queue(ssh, pkt);
1781 ssh2_pkt_send_noqueue(ssh, pkt);
1785 * Either queue or defer a packet, depending on whether queueing is
1788 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
1791 ssh2_pkt_queue(ssh, pkt);
1793 ssh2_pkt_defer_noqueue(ssh, pkt);
1797 * Send the whole deferred data block constructed by
1798 * ssh2_pkt_defer() or SSH1's defer_packet().
1800 * The expected use of the defer mechanism is that you call
1801 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
1802 * not currently queueing, this simply sets up deferred_send_data
1803 * and then sends it. If we _are_ currently queueing, the calls to
1804 * ssh2_pkt_defer() put the deferred packets on to the queue
1805 * instead, and therefore ssh_pkt_defersend() has no deferred data
1806 * to send. Hence, there's no need to make it conditional on
1809 static void ssh_pkt_defersend(Ssh ssh)
1812 backlog = sk_write(ssh->s, (char *)ssh->deferred_send_data,
1814 ssh->deferred_len = ssh->deferred_size = 0;
1815 sfree(ssh->deferred_send_data);
1816 ssh->deferred_send_data = NULL;
1817 if (backlog > SSH_MAX_BACKLOG)
1818 ssh_throttle_all(ssh, 1, backlog);
1820 ssh->outgoing_data_size += ssh->deferred_data_size;
1821 if (!ssh->kex_in_progress &&
1822 ssh->max_data_size != 0 &&
1823 ssh->outgoing_data_size > ssh->max_data_size)
1824 do_ssh2_transport(ssh, "Initiating key re-exchange "
1825 "(too much data sent)", -1, NULL);
1826 ssh->deferred_data_size = 0;
1830 * Send all queued SSH2 packets. We send them by means of
1831 * ssh2_pkt_defer_noqueue(), in case they included a pair of
1832 * packets that needed to be lumped together.
1834 static void ssh2_pkt_queuesend(Ssh ssh)
1838 assert(!ssh->queueing);
1840 for (i = 0; i < ssh->queuelen; i++)
1841 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i]);
1844 ssh_pkt_defersend(ssh);
1848 void bndebug(char *string, Bignum b)
1852 p = ssh2_mpint_fmt(b, &len);
1853 debug(("%s", string));
1854 for (i = 0; i < len; i++)
1855 debug((" %02x", p[i]));
1861 static void sha_mpint(SHA_State * s, Bignum b)
1865 p = ssh2_mpint_fmt(b, &len);
1866 sha_string(s, p, len);
1871 * Packet decode functions for both SSH1 and SSH2.
1873 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
1875 unsigned long value;
1876 if (pkt->length - pkt->savedpos < 4)
1877 return 0; /* arrgh, no way to decline (FIXME?) */
1878 value = GET_32BIT(pkt->body + pkt->savedpos);
1882 static int ssh2_pkt_getbool(struct Packet *pkt)
1884 unsigned long value;
1885 if (pkt->length - pkt->savedpos < 1)
1886 return 0; /* arrgh, no way to decline (FIXME?) */
1887 value = pkt->body[pkt->savedpos] != 0;
1891 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
1896 if (pkt->length - pkt->savedpos < 4)
1898 len = GET_32BIT(pkt->body + pkt->savedpos);
1903 if (pkt->length - pkt->savedpos < *length)
1905 *p = (char *)(pkt->body + pkt->savedpos);
1906 pkt->savedpos += *length;
1908 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
1910 if (pkt->length - pkt->savedpos < length)
1912 pkt->savedpos += length;
1913 return pkt->body + (pkt->savedpos - length);
1915 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
1916 unsigned char **keystr)
1920 j = makekey(pkt->body + pkt->savedpos,
1921 pkt->length - pkt->savedpos,
1928 assert(pkt->savedpos < pkt->length);
1932 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
1937 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
1938 pkt->length - pkt->savedpos, &b);
1946 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
1952 ssh_pkt_getstring(pkt, &p, &length);
1957 b = bignum_from_bytes((unsigned char *)p, length);
1962 * Helper function to add an SSH2 signature blob to a packet.
1963 * Expects to be shown the public key blob as well as the signature
1964 * blob. Normally works just like ssh2_pkt_addstring, but will
1965 * fiddle with the signature packet if necessary for
1966 * BUG_SSH2_RSA_PADDING.
1968 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
1969 void *pkblob_v, int pkblob_len,
1970 void *sigblob_v, int sigblob_len)
1972 unsigned char *pkblob = (unsigned char *)pkblob_v;
1973 unsigned char *sigblob = (unsigned char *)sigblob_v;
1975 /* dmemdump(pkblob, pkblob_len); */
1976 /* dmemdump(sigblob, sigblob_len); */
1979 * See if this is in fact an ssh-rsa signature and a buggy
1980 * server; otherwise we can just do this the easy way.
1982 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) &&
1983 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
1984 int pos, len, siglen;
1987 * Find the byte length of the modulus.
1990 pos = 4+7; /* skip over "ssh-rsa" */
1991 pos += 4 + GET_32BIT(pkblob+pos); /* skip over exponent */
1992 len = GET_32BIT(pkblob+pos); /* find length of modulus */
1993 pos += 4; /* find modulus itself */
1994 while (len > 0 && pkblob[pos] == 0)
1996 /* debug(("modulus length is %d\n", len)); */
1999 * Now find the signature integer.
2001 pos = 4+7; /* skip over "ssh-rsa" */
2002 siglen = GET_32BIT(sigblob+pos);
2003 /* debug(("signature length is %d\n", siglen)); */
2005 if (len != siglen) {
2006 unsigned char newlen[4];
2007 ssh2_pkt_addstring_start(pkt);
2008 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2009 /* dmemdump(sigblob, pos); */
2010 pos += 4; /* point to start of actual sig */
2011 PUT_32BIT(newlen, len);
2012 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2013 /* dmemdump(newlen, 4); */
2015 while (len-- > siglen) {
2016 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2017 /* dmemdump(newlen, 1); */
2019 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2020 /* dmemdump(sigblob+pos, siglen); */
2024 /* Otherwise fall through and do it the easy way. */
2027 ssh2_pkt_addstring_start(pkt);
2028 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2032 * Examine the remote side's version string and compare it against
2033 * a list of known buggy implementations.
2035 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2037 char *imp; /* pointer to implementation part */
2039 imp += strcspn(imp, "-");
2041 imp += strcspn(imp, "-");
2044 ssh->remote_bugs = 0;
2046 if (ssh->cfg.sshbug_ignore1 == FORCE_ON ||
2047 (ssh->cfg.sshbug_ignore1 == AUTO &&
2048 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2049 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2050 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2051 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2053 * These versions don't support SSH1_MSG_IGNORE, so we have
2054 * to use a different defence against password length
2057 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2058 logevent("We believe remote version has SSH1 ignore bug");
2061 if (ssh->cfg.sshbug_plainpw1 == FORCE_ON ||
2062 (ssh->cfg.sshbug_plainpw1 == AUTO &&
2063 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2065 * These versions need a plain password sent; they can't
2066 * handle having a null and a random length of data after
2069 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2070 logevent("We believe remote version needs a plain SSH1 password");
2073 if (ssh->cfg.sshbug_rsa1 == FORCE_ON ||
2074 (ssh->cfg.sshbug_rsa1 == AUTO &&
2075 (!strcmp(imp, "Cisco-1.25")))) {
2077 * These versions apparently have no clue whatever about
2078 * RSA authentication and will panic and die if they see
2079 * an AUTH_RSA message.
2081 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2082 logevent("We believe remote version can't handle RSA authentication");
2085 if (ssh->cfg.sshbug_hmac2 == FORCE_ON ||
2086 (ssh->cfg.sshbug_hmac2 == AUTO &&
2087 !wc_match("* VShell", imp) &&
2088 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2089 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2090 wc_match("2.1 *", imp)))) {
2092 * These versions have the HMAC bug.
2094 ssh->remote_bugs |= BUG_SSH2_HMAC;
2095 logevent("We believe remote version has SSH2 HMAC bug");
2098 if (ssh->cfg.sshbug_derivekey2 == FORCE_ON ||
2099 (ssh->cfg.sshbug_derivekey2 == AUTO &&
2100 !wc_match("* VShell", imp) &&
2101 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2103 * These versions have the key-derivation bug (failing to
2104 * include the literal shared secret in the hashes that
2105 * generate the keys).
2107 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2108 logevent("We believe remote version has SSH2 key-derivation bug");
2111 if (ssh->cfg.sshbug_rsapad2 == FORCE_ON ||
2112 (ssh->cfg.sshbug_rsapad2 == AUTO &&
2113 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2114 wc_match("OpenSSH_3.[0-2]*", imp)))) {
2116 * These versions have the SSH2 RSA padding bug.
2118 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2119 logevent("We believe remote version has SSH2 RSA padding bug");
2122 if (ssh->cfg.sshbug_pksessid2 == FORCE_ON ||
2123 (ssh->cfg.sshbug_pksessid2 == AUTO &&
2124 wc_match("OpenSSH_2.[0-2]*", imp))) {
2126 * These versions have the SSH2 session-ID bug in
2127 * public-key authentication.
2129 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2130 logevent("We believe remote version has SSH2 public-key-session-ID bug");
2135 * The `software version' part of an SSH version string is required
2136 * to contain no spaces or minus signs.
2138 static void ssh_fix_verstring(char *str)
2140 /* Eat "SSH-<protoversion>-". */
2141 assert(*str == 'S'); str++;
2142 assert(*str == 'S'); str++;
2143 assert(*str == 'H'); str++;
2144 assert(*str == '-'); str++;
2145 while (*str && *str != '-') str++;
2146 assert(*str == '-'); str++;
2148 /* Convert minus signs and spaces in the remaining string into
2151 if (*str == '-' || *str == ' ')
2157 static int do_ssh_init(Ssh ssh, unsigned char c)
2159 struct do_ssh_init_state {
2167 crState(do_ssh_init_state);
2169 crBegin(ssh->do_ssh_init_crstate);
2171 /* Search for the string "SSH-" in the input. */
2174 static const int transS[] = { 1, 2, 2, 1 };
2175 static const int transH[] = { 0, 0, 3, 0 };
2176 static const int transminus[] = { 0, 0, 0, -1 };
2178 s->i = transS[s->i];
2180 s->i = transH[s->i];
2182 s->i = transminus[s->i];
2187 crReturn(1); /* get another character */
2191 s->vstring = snewn(s->vstrsize, char);
2192 strcpy(s->vstring, "SSH-");
2196 crReturn(1); /* get another char */
2197 if (s->vslen >= s->vstrsize - 1) {
2199 s->vstring = sresize(s->vstring, s->vstrsize, char);
2201 s->vstring[s->vslen++] = c;
2204 s->version[s->i] = '\0';
2206 } else if (s->i < sizeof(s->version) - 1)
2207 s->version[s->i++] = c;
2208 } else if (c == '\012')
2212 ssh->agentfwd_enabled = FALSE;
2213 ssh->rdpkt2_state.incoming_sequence = 0;
2215 s->vstring[s->vslen] = 0;
2216 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
2219 vlog = snewn(20 + s->vslen, char);
2220 sprintf(vlog, "Server version: %s", s->vstring);
2224 ssh_detect_bugs(ssh, s->vstring);
2227 * Decide which SSH protocol version to support.
2230 /* Anything strictly below "2.0" means protocol 1 is supported. */
2231 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
2232 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2233 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
2235 if (ssh->cfg.sshprot == 0 && !s->proto1) {
2236 bombout(("SSH protocol version 1 required by user but not provided by server"));
2239 if (ssh->cfg.sshprot == 3 && !s->proto2) {
2240 bombout(("SSH protocol version 2 required by user but not provided by server"));
2247 if (s->proto2 && (ssh->cfg.sshprot >= 2 || !s->proto1)) {
2249 * Construct a v2 version string.
2251 verstring = dupprintf("SSH-2.0-%s\015\012", sshver);
2255 * Construct a v1 version string.
2257 verstring = dupprintf("SSH-%s-%s\012",
2258 (ssh_versioncmp(s->version, "1.5") <= 0 ?
2259 s->version : "1.5"),
2264 ssh_fix_verstring(verstring);
2266 if (ssh->version == 2) {
2268 * Hash our version string and their version string.
2270 SHA_Init(&ssh->exhashbase);
2271 sha_string(&ssh->exhashbase, verstring,
2272 strcspn(verstring, "\015\012"));
2273 sha_string(&ssh->exhashbase, s->vstring,
2274 strcspn(s->vstring, "\015\012"));
2277 * Initialise SSHv2 protocol.
2279 ssh->protocol = ssh2_protocol;
2280 ssh2_protocol_setup(ssh);
2281 ssh->s_rdpkt = ssh2_rdpkt;
2284 * Initialise SSHv1 protocol.
2286 ssh->protocol = ssh1_protocol;
2287 ssh1_protocol_setup(ssh);
2288 ssh->s_rdpkt = ssh1_rdpkt;
2290 logeventf(ssh, "We claim version: %.*s",
2291 strcspn(verstring, "\015\012"), verstring);
2292 sk_write(ssh->s, verstring, strlen(verstring));
2296 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
2298 update_specials_menu(ssh->frontend);
2299 ssh->state = SSH_STATE_BEFORE_SIZE;
2300 ssh->pinger = pinger_new(&ssh->cfg, &ssh_backend, ssh);
2307 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
2309 crBegin(ssh->ssh_gotdata_crstate);
2312 * To begin with, feed the characters one by one to the
2313 * protocol initialisation / selection function do_ssh_init().
2314 * When that returns 0, we're done with the initial greeting
2315 * exchange and can move on to packet discipline.
2318 int ret; /* need not be kept across crReturn */
2320 crReturnV; /* more data please */
2321 ret = do_ssh_init(ssh, *data);
2329 * We emerge from that loop when the initial negotiation is
2330 * over and we have selected an s_rdpkt function. Now pass
2331 * everything to s_rdpkt, and then pass the resulting packets
2332 * to the proper protocol handler.
2337 while (datalen > 0) {
2338 struct Packet *pktin = ssh->s_rdpkt(ssh, &data, &datalen);
2340 ssh->protocol(ssh, NULL, 0, pktin);
2341 ssh_free_packet(pktin);
2343 if (ssh->state == SSH_STATE_CLOSED)
2351 static void ssh_do_close(Ssh ssh)
2354 struct ssh_channel *c;
2356 ssh->state = SSH_STATE_CLOSED;
2360 notify_remote_exit(ssh->frontend);
2363 * Now we must shut down any port and X forwardings going
2364 * through this connection.
2366 if (ssh->channels) {
2367 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
2370 x11_close(c->u.x11.s);
2373 pfd_close(c->u.pfd.s);
2376 del234(ssh->channels, c);
2377 if (ssh->version == 2)
2378 bufchain_clear(&c->v.v2.outbuffer);
2384 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
2387 Ssh ssh = (Ssh) plug;
2390 /* A socket error has occurred. */
2391 logevent(error_msg);
2392 connection_fatal(ssh->frontend, "%s", error_msg);
2394 /* Otherwise, the remote side closed the connection normally. */
2399 static int ssh_receive(Plug plug, int urgent, char *data, int len)
2401 Ssh ssh = (Ssh) plug;
2402 ssh_gotdata(ssh, (unsigned char *)data, len);
2403 if (ssh->state == SSH_STATE_CLOSED) {
2410 static void ssh_sent(Plug plug, int bufsize)
2412 Ssh ssh = (Ssh) plug;
2414 * If the send backlog on the SSH socket itself clears, we
2415 * should unthrottle the whole world if it was throttled.
2417 if (bufsize < SSH_MAX_BACKLOG)
2418 ssh_throttle_all(ssh, 0, bufsize);
2422 * Connect to specified host and port.
2423 * Returns an error message, or NULL on success.
2424 * Also places the canonical host name into `realhost'. It must be
2425 * freed by the caller.
2427 static const char *connect_to_host(Ssh ssh, char *host, int port,
2428 char **realhost, int nodelay, int keepalive)
2430 static const struct plug_function_table fn_table = {
2440 ssh->savedhost = snewn(1 + strlen(host), char);
2441 if (!ssh->savedhost)
2442 fatalbox("Out of memory");
2443 strcpy(ssh->savedhost, host);
2446 port = 22; /* default ssh port */
2447 ssh->savedport = port;
2452 logeventf(ssh, "Looking up host \"%s\"", host);
2453 addr = name_lookup(host, port, realhost, &ssh->cfg);
2454 if ((err = sk_addr_error(addr)) != NULL) {
2464 sk_getaddr(addr, addrbuf, 100);
2465 logeventf(ssh, "Connecting to %s port %d", addrbuf, port);
2467 ssh->fn = &fn_table;
2468 ssh->s = new_connection(addr, *realhost, port,
2469 0, 1, nodelay, keepalive, (Plug) ssh, &ssh->cfg);
2470 if ((err = sk_socket_error(ssh->s)) != NULL) {
2472 notify_remote_exit(ssh->frontend);
2480 * Throttle or unthrottle the SSH connection.
2482 static void ssh1_throttle(Ssh ssh, int adjust)
2484 int old_count = ssh->v1_throttle_count;
2485 ssh->v1_throttle_count += adjust;
2486 assert(ssh->v1_throttle_count >= 0);
2487 if (ssh->v1_throttle_count && !old_count) {
2488 sk_set_frozen(ssh->s, 1);
2489 } else if (!ssh->v1_throttle_count && old_count) {
2490 sk_set_frozen(ssh->s, 0);
2495 * Throttle or unthrottle _all_ local data streams (for when sends
2496 * on the SSH connection itself back up).
2498 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
2501 struct ssh_channel *c;
2503 if (enable == ssh->throttled_all)
2505 ssh->throttled_all = enable;
2506 ssh->overall_bufsize = bufsize;
2509 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
2511 case CHAN_MAINSESSION:
2513 * This is treated separately, outside the switch.
2517 x11_override_throttle(c->u.x11.s, enable);
2520 /* Agent channels require no buffer management. */
2523 pfd_override_throttle(c->u.pfd.s, enable);
2530 * Username and password input, abstracted off into routines
2531 * reusable in several places - even between SSH1 and SSH2.
2534 /* Set up a username or password input loop on a given buffer. */
2535 static void setup_userpass_input(Ssh ssh, char *buffer, int buflen, int echo)
2537 ssh->userpass_input_buffer = buffer;
2538 ssh->userpass_input_buflen = buflen;
2539 ssh->userpass_input_bufpos = 0;
2540 ssh->userpass_input_echo = echo;
2544 * Process some terminal data in the course of username/password
2545 * input. Returns >0 for success (line of input returned in
2546 * buffer), <0 for failure (user hit ^C/^D, bomb out and exit), 0
2547 * for inconclusive (keep waiting for more input please).
2549 static int process_userpass_input(Ssh ssh, unsigned char *in, int inlen)
2554 switch (c = *in++) {
2557 ssh->userpass_input_buffer[ssh->userpass_input_bufpos] = 0;
2558 ssh->userpass_input_buffer[ssh->userpass_input_buflen-1] = 0;
2563 if (ssh->userpass_input_bufpos > 0) {
2564 if (ssh->userpass_input_echo)
2565 c_write_str(ssh, "\b \b");
2566 ssh->userpass_input_bufpos--;
2571 while (ssh->userpass_input_bufpos > 0) {
2572 if (ssh->userpass_input_echo)
2573 c_write_str(ssh, "\b \b");
2574 ssh->userpass_input_bufpos--;
2583 * This simplistic check for printability is disabled
2584 * when we're doing password input, because some people
2585 * have control characters in their passwords.o
2587 if ((!ssh->userpass_input_echo ||
2588 (c >= ' ' && c <= '~') ||
2589 ((unsigned char) c >= 160))
2590 && ssh->userpass_input_bufpos < ssh->userpass_input_buflen-1) {
2591 ssh->userpass_input_buffer[ssh->userpass_input_bufpos++] = c;
2592 if (ssh->userpass_input_echo)
2593 c_write(ssh, &c, 1);
2601 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
2603 Ssh ssh = (Ssh) sshv;
2605 ssh->agent_response = reply;
2606 ssh->agent_response_len = replylen;
2608 if (ssh->version == 1)
2609 do_ssh1_login(ssh, NULL, -1, NULL);
2611 do_ssh2_authconn(ssh, NULL, -1, NULL);
2614 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
2616 struct ssh_channel *c = (struct ssh_channel *)cv;
2618 void *sentreply = reply;
2621 /* Fake SSH_AGENT_FAILURE. */
2622 sentreply = "\0\0\0\1\5";
2625 if (ssh->version == 2) {
2626 ssh2_add_channel_data(c, sentreply, replylen);
2629 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
2630 PKT_INT, c->remoteid,
2633 PKT_DATA, sentreply, replylen,
2642 * Handle the key exchange and user authentication phases.
2644 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
2645 struct Packet *pktin)
2648 unsigned char cookie[8], *ptr;
2649 struct RSAKey servkey, hostkey;
2650 struct MD5Context md5c;
2651 struct do_ssh1_login_state {
2653 unsigned char *rsabuf, *keystr1, *keystr2;
2654 unsigned long supported_ciphers_mask, supported_auths_mask;
2655 int tried_publickey, tried_agent;
2656 int tis_auth_refused, ccard_auth_refused;
2657 unsigned char session_id[16];
2660 void *publickey_blob;
2661 int publickey_bloblen;
2667 unsigned char request[5], *response, *p;
2676 crState(do_ssh1_login_state);
2678 crBegin(ssh->do_ssh1_login_crstate);
2683 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
2684 bombout(("Public key packet not received"));
2688 logevent("Received public keys");
2690 ptr = ssh_pkt_getdata(pktin, 8);
2692 bombout(("SSH1 public key packet stopped before random cookie"));
2695 memcpy(cookie, ptr, 8);
2697 if (!ssh1_pkt_getrsakey(pktin, &servkey, &s->keystr1) ||
2698 !ssh1_pkt_getrsakey(pktin, &hostkey, &s->keystr2)) {
2699 bombout(("Failed to read SSH1 public keys from public key packet"));
2704 * Log the host key fingerprint.
2708 logevent("Host key fingerprint is:");
2709 strcpy(logmsg, " ");
2710 hostkey.comment = NULL;
2711 rsa_fingerprint(logmsg + strlen(logmsg),
2712 sizeof(logmsg) - strlen(logmsg), &hostkey);
2716 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
2717 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
2718 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
2720 ssh->v1_local_protoflags =
2721 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
2722 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
2725 MD5Update(&md5c, s->keystr2, hostkey.bytes);
2726 MD5Update(&md5c, s->keystr1, servkey.bytes);
2727 MD5Update(&md5c, cookie, 8);
2728 MD5Final(s->session_id, &md5c);
2730 for (i = 0; i < 32; i++)
2731 ssh->session_key[i] = random_byte();
2734 * Verify that the `bits' and `bytes' parameters match.
2736 if (hostkey.bits > hostkey.bytes * 8 ||
2737 servkey.bits > servkey.bytes * 8) {
2738 bombout(("SSH1 public keys were badly formatted"));
2742 s->len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
2744 s->rsabuf = snewn(s->len, unsigned char);
2746 fatalbox("Out of memory");
2749 * Verify the host key.
2753 * First format the key into a string.
2755 int len = rsastr_len(&hostkey);
2756 char fingerprint[100];
2757 char *keystr = snewn(len, char);
2759 fatalbox("Out of memory");
2760 rsastr_fmt(keystr, &hostkey);
2761 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
2762 verify_ssh_host_key(ssh->frontend,
2763 ssh->savedhost, ssh->savedport, "rsa", keystr,
2768 for (i = 0; i < 32; i++) {
2769 s->rsabuf[i] = ssh->session_key[i];
2771 s->rsabuf[i] ^= s->session_id[i];
2774 if (hostkey.bytes > servkey.bytes) {
2775 ret = rsaencrypt(s->rsabuf, 32, &servkey);
2777 ret = rsaencrypt(s->rsabuf, servkey.bytes, &hostkey);
2779 ret = rsaencrypt(s->rsabuf, 32, &hostkey);
2781 ret = rsaencrypt(s->rsabuf, hostkey.bytes, &servkey);
2784 bombout(("SSH1 public key encryptions failed due to bad formatting"));
2788 logevent("Encrypted session key");
2791 int cipher_chosen = 0, warn = 0;
2792 char *cipher_string = NULL;
2794 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
2795 int next_cipher = ssh->cfg.ssh_cipherlist[i];
2796 if (next_cipher == CIPHER_WARN) {
2797 /* If/when we choose a cipher, warn about it */
2799 } else if (next_cipher == CIPHER_AES) {
2800 /* XXX Probably don't need to mention this. */
2801 logevent("AES not supported in SSH1, skipping");
2803 switch (next_cipher) {
2804 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
2805 cipher_string = "3DES"; break;
2806 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
2807 cipher_string = "Blowfish"; break;
2808 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
2809 cipher_string = "single-DES"; break;
2811 if (s->supported_ciphers_mask & (1 << s->cipher_type))
2815 if (!cipher_chosen) {
2816 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
2817 bombout(("Server violates SSH 1 protocol by not "
2818 "supporting 3DES encryption"));
2820 /* shouldn't happen */
2821 bombout(("No supported ciphers found"));
2825 /* Warn about chosen cipher if necessary. */
2827 askalg(ssh->frontend, "cipher", cipher_string);
2830 switch (s->cipher_type) {
2831 case SSH_CIPHER_3DES:
2832 logevent("Using 3DES encryption");
2834 case SSH_CIPHER_DES:
2835 logevent("Using single-DES encryption");
2837 case SSH_CIPHER_BLOWFISH:
2838 logevent("Using Blowfish encryption");
2842 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
2843 PKT_CHAR, s->cipher_type,
2844 PKT_DATA, cookie, 8,
2845 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
2846 PKT_DATA, s->rsabuf, s->len,
2847 PKT_INT, ssh->v1_local_protoflags, PKT_END);
2849 logevent("Trying to enable encryption...");
2853 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
2854 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
2856 ssh->v1_cipher_ctx = ssh->cipher->make_context();
2857 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
2858 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
2860 ssh->crcda_ctx = crcda_make_context();
2861 logevent("Installing CRC compensation attack detector");
2863 if (servkey.modulus) {
2864 sfree(servkey.modulus);
2865 servkey.modulus = NULL;
2867 if (servkey.exponent) {
2868 sfree(servkey.exponent);
2869 servkey.exponent = NULL;
2871 if (hostkey.modulus) {
2872 sfree(hostkey.modulus);
2873 hostkey.modulus = NULL;
2875 if (hostkey.exponent) {
2876 sfree(hostkey.exponent);
2877 hostkey.exponent = NULL;
2881 if (pktin->type != SSH1_SMSG_SUCCESS) {
2882 bombout(("Encryption not successfully enabled"));
2886 logevent("Successfully started encryption");
2890 if (!*ssh->cfg.username) {
2891 if (ssh_get_line && !ssh_getline_pw_only) {
2892 if (!ssh_get_line("login as: ",
2893 s->username, sizeof(s->username), FALSE)) {
2895 * get_line failed to get a username.
2898 logevent("No username provided. Abandoning session.");
2899 ssh_closing((Plug)ssh, NULL, 0, 0);
2903 int ret; /* need not be kept over crReturn */
2904 c_write_str(ssh, "login as: ");
2907 setup_userpass_input(ssh, s->username, sizeof(s->username), 1);
2909 crWaitUntil(!pktin);
2910 ret = process_userpass_input(ssh, in, inlen);
2914 c_write_str(ssh, "\r\n");
2917 strncpy(s->username, ssh->cfg.username, sizeof(s->username));
2918 s->username[sizeof(s->username)-1] = '\0';
2921 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, s->username, PKT_END);
2923 char userlog[22 + sizeof(s->username)];
2924 sprintf(userlog, "Sent username \"%s\"", s->username);
2926 if (flags & FLAG_INTERACTIVE &&
2927 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
2928 strcat(userlog, "\r\n");
2929 c_write_str(ssh, userlog);
2936 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA)) {
2937 /* We must not attempt PK auth. Pretend we've already tried it. */
2938 s->tried_publickey = s->tried_agent = 1;
2940 s->tried_publickey = s->tried_agent = 0;
2942 s->tis_auth_refused = s->ccard_auth_refused = 0;
2943 /* Load the public half of ssh->cfg.keyfile so we notice if it's in Pageant */
2944 if (!filename_is_null(ssh->cfg.keyfile)) {
2945 if (!rsakey_pubblob(&ssh->cfg.keyfile,
2946 &s->publickey_blob, &s->publickey_bloblen, NULL))
2947 s->publickey_blob = NULL;
2949 s->publickey_blob = NULL;
2951 while (pktin->type == SSH1_SMSG_FAILURE) {
2952 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
2954 if (agent_exists() && !s->tried_agent) {
2956 * Attempt RSA authentication using Pageant.
2962 logevent("Pageant is running. Requesting keys.");
2964 /* Request the keys held by the agent. */
2965 PUT_32BIT(s->request, 1);
2966 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
2967 if (!agent_query(s->request, 5, &r, &s->responselen,
2968 ssh_agent_callback, ssh)) {
2972 bombout(("Unexpected data from server while waiting"
2973 " for agent response"));
2976 } while (pktin || inlen > 0);
2977 r = ssh->agent_response;
2978 s->responselen = ssh->agent_response_len;
2980 s->response = (unsigned char *) r;
2981 if (s->response && s->responselen >= 5 &&
2982 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
2983 s->p = s->response + 5;
2984 s->nkeys = GET_32BIT(s->p);
2988 sprintf(buf, "Pageant has %d SSH1 keys", s->nkeys);
2991 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
2994 sprintf(buf, "Trying Pageant key #%d", s->keyi);
2997 if (s->publickey_blob &&
2998 !memcmp(s->p, s->publickey_blob,
2999 s->publickey_bloblen)) {
3000 logevent("This key matches configured key file");
3001 s->tried_publickey = 1;
3006 do { /* do while (0) to make breaking easy */
3007 n = ssh1_read_bignum
3008 (s->p, s->responselen-(s->p-s->response),
3013 n = ssh1_read_bignum
3014 (s->p, s->responselen-(s->p-s->response),
3019 if (s->responselen - (s->p-s->response) < 4)
3021 s->commentlen = GET_32BIT(s->p);
3023 if (s->responselen - (s->p-s->response) <
3026 s->commentp = (char *)s->p;
3027 s->p += s->commentlen;
3031 logevent("Pageant key list packet was truncated");
3035 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3036 PKT_BIGNUM, s->key.modulus, PKT_END);
3038 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3039 logevent("Key refused");
3042 logevent("Received RSA challenge");
3043 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3044 bombout(("Server's RSA challenge was badly formatted"));
3049 char *agentreq, *q, *ret;
3052 len = 1 + 4; /* message type, bit count */
3053 len += ssh1_bignum_length(s->key.exponent);
3054 len += ssh1_bignum_length(s->key.modulus);
3055 len += ssh1_bignum_length(s->challenge);
3056 len += 16; /* session id */
3057 len += 4; /* response format */
3058 agentreq = snewn(4 + len, char);
3059 PUT_32BIT(agentreq, len);
3061 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
3062 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
3064 q += ssh1_write_bignum(q, s->key.exponent);
3065 q += ssh1_write_bignum(q, s->key.modulus);
3066 q += ssh1_write_bignum(q, s->challenge);
3067 memcpy(q, s->session_id, 16);
3069 PUT_32BIT(q, 1); /* response format */
3070 if (!agent_query(agentreq, len + 4, &vret, &retlen,
3071 ssh_agent_callback, ssh)) {
3076 bombout(("Unexpected data from server"
3077 " while waiting for agent"
3081 } while (pktin || inlen > 0);
3082 vret = ssh->agent_response;
3083 retlen = ssh->agent_response_len;
3088 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
3089 logevent("Sending Pageant's response");
3090 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3091 PKT_DATA, ret + 5, 16,
3095 if (pktin->type == SSH1_SMSG_SUCCESS) {
3097 ("Pageant's response accepted");
3098 if (flags & FLAG_VERBOSE) {
3099 c_write_str(ssh, "Authenticated using"
3101 c_write(ssh, s->commentp,
3103 c_write_str(ssh, "\" from agent\r\n");
3108 ("Pageant's response not accepted");
3111 ("Pageant failed to answer challenge");
3115 logevent("No reply received from Pageant");
3118 freebn(s->key.exponent);
3119 freebn(s->key.modulus);
3120 freebn(s->challenge);
3129 if (!filename_is_null(ssh->cfg.keyfile) && !s->tried_publickey)
3130 s->pwpkt_type = SSH1_CMSG_AUTH_RSA;
3132 if (ssh->cfg.try_tis_auth &&
3133 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
3134 !s->tis_auth_refused) {
3135 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
3136 logevent("Requested TIS authentication");
3137 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
3139 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
3140 logevent("TIS authentication declined");
3141 if (flags & FLAG_INTERACTIVE)
3142 c_write_str(ssh, "TIS authentication refused.\r\n");
3143 s->tis_auth_refused = 1;
3149 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3151 bombout(("TIS challenge packet was badly formed"));
3154 logevent("Received TIS challenge");
3155 if (challengelen > sizeof(s->prompt) - 1)
3156 challengelen = sizeof(s->prompt) - 1;/* prevent overrun */
3157 memcpy(s->prompt, challenge, challengelen);
3158 /* Prompt heuristic comes from OpenSSH */
3159 strncpy(s->prompt + challengelen,
3160 memchr(s->prompt, '\n', challengelen) ?
3161 "": "\r\nResponse: ",
3162 (sizeof s->prompt) - challengelen);
3163 s->prompt[(sizeof s->prompt) - 1] = '\0';
3166 if (ssh->cfg.try_tis_auth &&
3167 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
3168 !s->ccard_auth_refused) {
3169 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
3170 logevent("Requested CryptoCard authentication");
3171 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
3173 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
3174 logevent("CryptoCard authentication declined");
3175 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
3176 s->ccard_auth_refused = 1;
3182 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3184 bombout(("CryptoCard challenge packet was badly formed"));
3187 logevent("Received CryptoCard challenge");
3188 if (challengelen > sizeof(s->prompt) - 1)
3189 challengelen = sizeof(s->prompt) - 1;/* prevent overrun */
3190 memcpy(s->prompt, challenge, challengelen);
3191 strncpy(s->prompt + challengelen,
3192 memchr(s->prompt, '\n', challengelen) ?
3193 "" : "\r\nResponse: ",
3194 sizeof(s->prompt) - challengelen);
3195 s->prompt[sizeof(s->prompt) - 1] = '\0';
3198 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
3199 sprintf(s->prompt, "%.90s@%.90s's password: ",
3200 s->username, ssh->savedhost);
3202 if (s->pwpkt_type == SSH1_CMSG_AUTH_RSA) {
3203 char *comment = NULL;
3206 if (flags & FLAG_VERBOSE)
3207 c_write_str(ssh, "Trying public key authentication.\r\n");
3208 logeventf(ssh, "Trying public key \"%s\"",
3209 filename_to_str(&ssh->cfg.keyfile));
3210 type = key_type(&ssh->cfg.keyfile);
3211 if (type != SSH_KEYTYPE_SSH1) {
3212 sprintf(msgbuf, "Key is of wrong type (%s)",
3213 key_type_to_str(type));
3215 c_write_str(ssh, msgbuf);
3216 c_write_str(ssh, "\r\n");
3217 s->tried_publickey = 1;
3220 if (!rsakey_encrypted(&ssh->cfg.keyfile, &comment)) {
3221 if (flags & FLAG_VERBOSE)
3222 c_write_str(ssh, "No passphrase required.\r\n");
3225 sprintf(s->prompt, "Passphrase for key \"%.100s\": ", comment);
3230 * Show password prompt, having first obtained it via a TIS
3231 * or CryptoCard exchange if we're doing TIS or CryptoCard
3235 if (!ssh_get_line(s->prompt, s->password,
3236 sizeof(s->password), TRUE)) {
3238 * get_line failed to get a password (for example
3239 * because one was supplied on the command line
3240 * which has already failed to work). Terminate.
3242 send_packet(ssh, SSH1_MSG_DISCONNECT,
3243 PKT_STR, "No more passwords available to try",
3245 logevent("Unable to authenticate");
3246 connection_fatal(ssh->frontend, "Unable to authenticate");
3247 ssh_closing((Plug)ssh, NULL, 0, 0);
3251 /* Prompt may have come from server. We've munged it a bit, so
3252 * we know it to be zero-terminated at least once. */
3253 int ret; /* need not be saved over crReturn */
3254 c_write_untrusted(ssh, s->prompt, strlen(s->prompt));
3257 setup_userpass_input(ssh, s->password, sizeof(s->password), 0);
3259 crWaitUntil(!pktin);
3260 ret = process_userpass_input(ssh, in, inlen);
3264 c_write_str(ssh, "\r\n");
3268 if (s->pwpkt_type == SSH1_CMSG_AUTH_RSA) {
3270 * Try public key authentication with the specified
3273 s->tried_publickey = 1;
3276 const char *error = NULL;
3277 int ret = loadrsakey(&ssh->cfg.keyfile, &s->key, s->password,
3280 c_write_str(ssh, "Couldn't load private key from ");
3281 c_write_str(ssh, filename_to_str(&ssh->cfg.keyfile));
3282 c_write_str(ssh, " (");
3283 c_write_str(ssh, error);
3284 c_write_str(ssh, ").\r\n");
3285 continue; /* go and try password */
3288 c_write_str(ssh, "Wrong passphrase.\r\n");
3289 s->tried_publickey = 0;
3290 continue; /* try again */
3295 * Send a public key attempt.
3297 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3298 PKT_BIGNUM, s->key.modulus, PKT_END);
3301 if (pktin->type == SSH1_SMSG_FAILURE) {
3302 c_write_str(ssh, "Server refused our public key.\r\n");
3303 continue; /* go and try password */
3305 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3306 bombout(("Bizarre response to offer of public key"));
3312 unsigned char buffer[32];
3313 Bignum challenge, response;
3315 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3316 bombout(("Server's RSA challenge was badly formatted"));
3319 response = rsadecrypt(challenge, &s->key);
3320 freebn(s->key.private_exponent);/* burn the evidence */
3322 for (i = 0; i < 32; i++) {
3323 buffer[i] = bignum_byte(response, 31 - i);
3327 MD5Update(&md5c, buffer, 32);
3328 MD5Update(&md5c, s->session_id, 16);
3329 MD5Final(buffer, &md5c);
3331 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3332 PKT_DATA, buffer, 16, PKT_END);
3339 if (pktin->type == SSH1_SMSG_FAILURE) {
3340 if (flags & FLAG_VERBOSE)
3341 c_write_str(ssh, "Failed to authenticate with"
3342 " our public key.\r\n");
3343 continue; /* go and try password */
3344 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
3345 bombout(("Bizarre response to RSA authentication response"));
3349 break; /* we're through! */
3351 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
3353 * Defence against traffic analysis: we send a
3354 * whole bunch of packets containing strings of
3355 * different lengths. One of these strings is the
3356 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
3357 * The others are all random data in
3358 * SSH1_MSG_IGNORE packets. This way a passive
3359 * listener can't tell which is the password, and
3360 * hence can't deduce the password length.
3362 * Anybody with a password length greater than 16
3363 * bytes is going to have enough entropy in their
3364 * password that a listener won't find it _that_
3365 * much help to know how long it is. So what we'll
3368 * - if password length < 16, we send 15 packets
3369 * containing string lengths 1 through 15
3371 * - otherwise, we let N be the nearest multiple
3372 * of 8 below the password length, and send 8
3373 * packets containing string lengths N through
3374 * N+7. This won't obscure the order of
3375 * magnitude of the password length, but it will
3376 * introduce a bit of extra uncertainty.
3378 * A few servers (the old 1.2.18 through 1.2.22)
3379 * can't deal with SSH1_MSG_IGNORE. For these
3380 * servers, we need an alternative defence. We make
3381 * use of the fact that the password is interpreted
3382 * as a C string: so we can append a NUL, then some
3385 * One server (a Cisco one) can deal with neither
3386 * SSH1_MSG_IGNORE _nor_ a padded password string.
3387 * For this server we are left with no defences
3388 * against password length sniffing.
3390 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE)) {
3392 * The server can deal with SSH1_MSG_IGNORE, so
3393 * we can use the primary defence.
3395 int bottom, top, pwlen, i;
3398 pwlen = strlen(s->password);
3400 bottom = 0; /* zero length passwords are OK! :-) */
3403 bottom = pwlen & ~7;
3407 assert(pwlen >= bottom && pwlen <= top);
3409 randomstr = snewn(top + 1, char);
3411 for (i = bottom; i <= top; i++) {
3413 defer_packet(ssh, s->pwpkt_type,
3414 PKTT_PASSWORD, PKT_STR, s->password,
3415 PKTT_OTHER, PKT_END);
3417 for (j = 0; j < i; j++) {
3419 randomstr[j] = random_byte();
3420 } while (randomstr[j] == '\0');
3422 randomstr[i] = '\0';
3423 defer_packet(ssh, SSH1_MSG_IGNORE,
3424 PKT_STR, randomstr, PKT_END);
3427 logevent("Sending password with camouflage packets");
3428 ssh_pkt_defersend(ssh);
3431 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
3433 * The server can't deal with SSH1_MSG_IGNORE
3434 * but can deal with padded passwords, so we
3435 * can use the secondary defence.
3441 len = strlen(s->password);
3442 if (len < sizeof(string)) {
3444 strcpy(string, s->password);
3445 len++; /* cover the zero byte */
3446 while (len < sizeof(string)) {
3447 string[len++] = (char) random_byte();
3452 logevent("Sending length-padded password");
3453 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
3454 PKT_INT, len, PKT_DATA, ss, len,
3455 PKTT_OTHER, PKT_END);
3458 * The server has _both_
3459 * BUG_CHOKES_ON_SSH1_IGNORE and
3460 * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
3461 * therefore nothing we can do.
3464 len = strlen(s->password);
3465 logevent("Sending unpadded password");
3466 send_packet(ssh, s->pwpkt_type,
3467 PKTT_PASSWORD, PKT_INT, len,
3468 PKT_DATA, s->password, len,
3469 PKTT_OTHER, PKT_END);
3472 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
3473 PKT_STR, s->password, PKTT_OTHER, PKT_END);
3476 logevent("Sent password");
3477 memset(s->password, 0, strlen(s->password));
3479 if (pktin->type == SSH1_SMSG_FAILURE) {
3480 if (flags & FLAG_VERBOSE)
3481 c_write_str(ssh, "Access denied\r\n");
3482 logevent("Authentication refused");
3483 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
3484 bombout(("Strange packet received, type %d", pktin->type));
3489 logevent("Authentication successful");
3494 void sshfwd_close(struct ssh_channel *c)
3498 if (ssh->state != SSH_STATE_SESSION) {
3499 assert(ssh->state == SSH_STATE_CLOSED);
3503 if (c && !c->closes) {
3505 * If the channel's remoteid is -1, we have sent
3506 * CHANNEL_OPEN for this channel, but it hasn't even been
3507 * acknowledged by the server. So we must set a close flag
3508 * on it now, and then when the server acks the channel
3509 * open, we can close it then.
3511 if (((int)c->remoteid) != -1) {
3512 if (ssh->version == 1) {
3513 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
3516 struct Packet *pktout;
3517 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
3518 ssh2_pkt_adduint32(pktout, c->remoteid);
3519 ssh2_pkt_send(ssh, pktout);
3522 c->closes = 1; /* sent MSG_CLOSE */
3523 if (c->type == CHAN_X11) {
3525 logevent("Forwarded X11 connection terminated");
3526 } else if (c->type == CHAN_SOCKDATA ||
3527 c->type == CHAN_SOCKDATA_DORMANT) {
3529 logevent("Forwarded port closed");
3534 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
3538 if (ssh->state != SSH_STATE_SESSION) {
3539 assert(ssh->state == SSH_STATE_CLOSED);
3543 if (ssh->version == 1) {
3544 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3545 PKT_INT, c->remoteid,
3547 PKT_INT, len, PKT_DATA, buf, len,
3548 PKTT_OTHER, PKT_END);
3550 * In SSH1 we can return 0 here - implying that forwarded
3551 * connections are never individually throttled - because
3552 * the only circumstance that can cause throttling will be
3553 * the whole SSH connection backing up, in which case
3554 * _everything_ will be throttled as a whole.
3558 ssh2_add_channel_data(c, buf, len);
3559 return ssh2_try_send(c);
3563 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
3567 if (ssh->state != SSH_STATE_SESSION) {
3568 assert(ssh->state == SSH_STATE_CLOSED);
3572 if (ssh->version == 1) {
3573 if (c->v.v1.throttling && bufsize < SSH1_BUFFER_LIMIT) {
3574 c->v.v1.throttling = 0;
3575 ssh1_throttle(ssh, -1);
3578 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
3582 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
3584 struct queued_handler *qh = ssh->qhead;
3588 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
3591 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
3592 ssh->packet_dispatch[qh->msg1] = NULL;
3595 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
3596 ssh->packet_dispatch[qh->msg2] = NULL;
3600 ssh->qhead = qh->next;
3602 if (ssh->qhead->msg1 > 0) {
3603 assert(ssh->packet_dispatch[ssh->qhead->msg1] == NULL);
3604 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
3606 if (ssh->qhead->msg2 > 0) {
3607 assert(ssh->packet_dispatch[ssh->qhead->msg2] == NULL);
3608 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
3611 ssh->qhead = ssh->qtail = NULL;
3612 ssh->packet_dispatch[pktin->type] = NULL;
3615 qh->handler(ssh, pktin, qh->ctx);
3620 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
3621 chandler_fn_t handler, void *ctx)
3623 struct queued_handler *qh;
3625 qh = snew(struct queued_handler);
3628 qh->handler = handler;
3632 if (ssh->qtail == NULL) {
3636 assert(ssh->packet_dispatch[qh->msg1] == NULL);
3637 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
3640 assert(ssh->packet_dispatch[qh->msg2] == NULL);
3641 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
3644 ssh->qtail->next = qh;
3649 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
3651 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
3653 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
3654 SSH2_MSG_REQUEST_SUCCESS)) {
3655 logeventf(ssh, "Remote port forwarding from %s enabled",
3658 logeventf(ssh, "Remote port forwarding from %s refused",
3661 rpf = del234(ssh->rportfwds, pf);
3667 static void ssh_setup_portfwd(Ssh ssh, const Config *cfg)
3671 int sport,dport,sserv,dserv;
3672 char sports[256], dports[256], saddr[256], host[256];
3673 const char *portfwd_strptr;
3675 portfwd_strptr = cfg->portfwd;
3677 if (!ssh->portfwds) {
3678 ssh->portfwds = newtree234(ssh_portcmp);
3681 * Go through the existing port forwardings and tag them
3682 * with keep==FALSE. Any that we want to keep will be
3683 * re-enabled as we go through the configuration and find
3684 * out which bits are the same as they were before.
3686 struct ssh_portfwd *epf;
3688 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
3692 while (*portfwd_strptr) {
3693 type = *portfwd_strptr++;
3696 while (*portfwd_strptr && *portfwd_strptr != '\t') {
3697 if (*portfwd_strptr == ':') {
3699 * We've seen a colon in the middle of the
3700 * source port number. This means that
3701 * everything we've seen until now is the
3702 * source _address_, so we'll move it into
3703 * saddr and start sports from the beginning
3708 if (ssh->version == 1 && type == 'R') {
3709 logeventf(ssh, "SSH1 cannot handle remote source address "
3710 "spec \"%s\"; ignoring", sports);
3712 strcpy(saddr, sports);
3715 if (n < 255) sports[n++] = *portfwd_strptr++;
3719 if (*portfwd_strptr == '\t')
3722 while (*portfwd_strptr && *portfwd_strptr != ':') {
3723 if (n < 255) host[n++] = *portfwd_strptr++;
3726 if (*portfwd_strptr == ':')
3729 while (*portfwd_strptr) {
3730 if (n < 255) dports[n++] = *portfwd_strptr++;
3734 dport = atoi(dports);
3738 dport = net_service_lookup(dports);
3740 logeventf(ssh, "Service lookup failed for destination"
3741 " port \"%s\"", dports);
3745 while (*portfwd_strptr) portfwd_strptr++;
3747 portfwd_strptr++; /* eat the NUL and move to next one */
3749 sport = atoi(sports);
3753 sport = net_service_lookup(sports);
3755 logeventf(ssh, "Service lookup failed for source"
3756 " port \"%s\"", sports);
3759 if (sport && dport) {
3760 /* Set up a description of the source port. */
3761 struct ssh_portfwd *pfrec, *epfrec;
3763 sportdesc = dupprintf("%.*s%.*s%.*s%.*s%d%.*s",
3764 (int)(*saddr?strlen(saddr):0), *saddr?saddr:NULL,
3765 (int)(*saddr?1:0), ":",
3766 (int)(sserv ? strlen(sports) : 0), sports,
3767 sserv, "(", sport, sserv, ")");
3769 pfrec = snew(struct ssh_portfwd);
3771 pfrec->saddr = *saddr ? dupstr(saddr) : NULL;
3772 pfrec->sport = sport;
3773 pfrec->daddr = dupstr(host);
3774 pfrec->dport = dport;
3775 pfrec->local = NULL;
3776 pfrec->remote = NULL;
3778 epfrec = add234(ssh->portfwds, pfrec);
3779 if (epfrec != pfrec) {
3781 * We already have a port forwarding with precisely
3782 * these parameters. Hence, no need to do anything;
3783 * simply tag the existing one as `keep'.
3785 epfrec->keep = TRUE;
3786 free_portfwd(pfrec);
3787 } else if (type == 'L') {
3788 /* Verbose description of the destination port */
3789 char *dportdesc = dupprintf("%s:%.*s%.*s%d%.*s",
3791 (int)(dserv ? strlen(dports) : 0), dports,
3792 dserv, "(", dport, dserv, ")");
3793 const char *err = pfd_addforward(host, dport,
3794 *saddr ? saddr : NULL,
3795 sport, ssh, &ssh->cfg,
3798 logeventf(ssh, "Local port %s forward to %s"
3799 " failed: %s", sportdesc, dportdesc, err);
3801 logeventf(ssh, "Local port %s forwarding to %s",
3802 sportdesc, dportdesc);
3805 } else if (type == 'D') {
3806 const char *err = pfd_addforward(NULL, -1,
3807 *saddr ? saddr : NULL,
3808 sport, ssh, &ssh->cfg,
3811 logeventf(ssh, "Local port %s SOCKS dynamic forward"
3812 " setup failed: %s", sportdesc, err);
3814 logeventf(ssh, "Local port %s doing SOCKS"
3815 " dynamic forwarding", sportdesc);
3818 struct ssh_rportfwd *pf;
3821 * Ensure the remote port forwardings tree exists.
3823 if (!ssh->rportfwds) {
3824 if (ssh->version == 1)
3825 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
3827 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
3830 pf = snew(struct ssh_rportfwd);
3831 strcpy(pf->dhost, host);
3834 if (add234(ssh->rportfwds, pf) != pf) {
3835 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
3839 logeventf(ssh, "Requesting remote port %s"
3840 " forward to %s:%.*s%.*s%d%.*s",
3842 (int)(dserv ? strlen(dports) : 0), dports,
3843 dserv, "(", dport, dserv, ")");
3845 pf->sportdesc = sportdesc;
3850 if (ssh->version == 1) {
3851 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
3856 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
3858 ssh_rportfwd_succfail, pf);
3860 struct Packet *pktout;
3861 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
3862 ssh2_pkt_addstring(pktout, "tcpip-forward");
3863 ssh2_pkt_addbool(pktout, 1);/* want reply */
3865 ssh2_pkt_addstring(pktout, saddr);
3866 } else if (ssh->cfg.rport_acceptall) {
3867 ssh2_pkt_addstring(pktout, "0.0.0.0");
3869 ssh2_pkt_addstring(pktout, "127.0.0.1");
3871 ssh2_pkt_adduint32(pktout, sport);
3872 ssh2_pkt_send(ssh, pktout);
3874 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
3875 SSH2_MSG_REQUEST_FAILURE,
3876 ssh_rportfwd_succfail, pf);
3885 * Now go through and destroy any port forwardings which were
3889 struct ssh_portfwd *epf;
3891 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
3895 message = dupprintf("%s port forwarding from %s%s%d",
3896 epf->type == 'L' ? "local" :
3897 epf->type == 'R' ? "remote" : "dynamic",
3898 epf->saddr ? epf->saddr : "",
3899 epf->saddr ? ":" : "",
3902 if (epf->type != 'D') {
3903 char *msg2 = dupprintf("%s to %s:%d", message,
3904 epf->daddr, epf->dport);
3909 logeventf(ssh, "Cancelling %s", message);
3913 struct ssh_rportfwd *rpf = epf->remote;
3914 struct Packet *pktout;
3917 * Cancel the port forwarding at the server
3920 if (ssh->version == 1) {
3922 * We cannot cancel listening ports on the
3923 * server side in SSH1! There's no message
3924 * to support it. Instead, we simply remove
3925 * the rportfwd record from the local end
3926 * so that any connections the server tries
3927 * to make on it are rejected.
3930 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
3931 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
3932 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
3934 ssh2_pkt_addstring(pktout, epf->saddr);
3935 } else if (ssh->cfg.rport_acceptall) {
3936 ssh2_pkt_addstring(pktout, "0.0.0.0");
3938 ssh2_pkt_addstring(pktout, "127.0.0.1");
3940 ssh2_pkt_adduint32(pktout, epf->sport);
3941 ssh2_pkt_send(ssh, pktout);
3944 del234(ssh->rportfwds, rpf);
3946 } else if (epf->local) {
3947 pfd_terminate(epf->local);
3950 delpos234(ssh->portfwds, i);
3952 i--; /* so we don't skip one in the list */
3957 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
3960 int stringlen, bufsize;
3962 ssh_pkt_getstring(pktin, &string, &stringlen);
3963 if (string == NULL) {
3964 bombout(("Incoming terminal data packet was badly formed"));
3968 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
3970 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
3971 ssh->v1_stdout_throttling = 1;
3972 ssh1_throttle(ssh, +1);
3976 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
3978 /* Remote side is trying to open a channel to talk to our
3979 * X-Server. Give them back a local channel number. */
3980 struct ssh_channel *c;
3981 int remoteid = ssh_pkt_getuint32(pktin);
3983 logevent("Received X11 connect request");
3984 /* Refuse if X11 forwarding is disabled. */
3985 if (!ssh->X11_fwd_enabled) {
3986 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3987 PKT_INT, remoteid, PKT_END);
3988 logevent("Rejected X11 connect request");
3990 c = snew(struct ssh_channel);
3993 if (x11_init(&c->u.x11.s, ssh->cfg.x11_display, c,
3994 ssh->x11auth, NULL, -1, &ssh->cfg) != NULL) {
3995 logevent("Opening X11 forward connection failed");
3997 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3998 PKT_INT, remoteid, PKT_END);
4001 ("Opening X11 forward connection succeeded");
4002 c->remoteid = remoteid;
4003 c->localid = alloc_channel_id(ssh);
4005 c->v.v1.throttling = 0;
4006 c->type = CHAN_X11; /* identify channel type */
4007 add234(ssh->channels, c);
4008 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4009 PKT_INT, c->remoteid, PKT_INT,
4010 c->localid, PKT_END);
4011 logevent("Opened X11 forward channel");
4016 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
4018 /* Remote side is trying to open a channel to talk to our
4019 * agent. Give them back a local channel number. */
4020 struct ssh_channel *c;
4021 int remoteid = ssh_pkt_getuint32(pktin);
4023 /* Refuse if agent forwarding is disabled. */
4024 if (!ssh->agentfwd_enabled) {
4025 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4026 PKT_INT, remoteid, PKT_END);
4028 c = snew(struct ssh_channel);
4030 c->remoteid = remoteid;
4031 c->localid = alloc_channel_id(ssh);
4033 c->v.v1.throttling = 0;
4034 c->type = CHAN_AGENT; /* identify channel type */
4035 c->u.a.lensofar = 0;
4036 add234(ssh->channels, c);
4037 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4038 PKT_INT, c->remoteid, PKT_INT, c->localid,
4043 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
4045 /* Remote side is trying to open a channel to talk to a
4046 * forwarded port. Give them back a local channel number. */
4047 struct ssh_channel *c;
4048 struct ssh_rportfwd pf;
4051 char *host, buf[1024];
4053 c = snew(struct ssh_channel);
4056 remoteid = ssh_pkt_getuint32(pktin);
4057 ssh_pkt_getstring(pktin, &host, &hostsize);
4058 port = ssh_pkt_getuint32(pktin);
4060 if (hostsize >= lenof(pf.dhost))
4061 hostsize = lenof(pf.dhost)-1;
4062 memcpy(pf.dhost, host, hostsize);
4063 pf.dhost[hostsize] = '\0';
4066 if (find234(ssh->rportfwds, &pf, NULL) == NULL) {
4067 sprintf(buf, "Rejected remote port open request for %s:%d",
4070 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4071 PKT_INT, remoteid, PKT_END);
4073 sprintf(buf, "Received remote port open request for %s:%d",
4076 e = pfd_newconnect(&c->u.pfd.s, pf.dhost, port,
4080 sprintf(buf, "Port open failed: %s", e);
4083 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4084 PKT_INT, remoteid, PKT_END);
4086 c->remoteid = remoteid;
4087 c->localid = alloc_channel_id(ssh);
4089 c->v.v1.throttling = 0;
4090 c->type = CHAN_SOCKDATA; /* identify channel type */
4091 add234(ssh->channels, c);
4092 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4093 PKT_INT, c->remoteid, PKT_INT,
4094 c->localid, PKT_END);
4095 logevent("Forwarded port opened successfully");
4100 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
4102 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4103 unsigned int localid = ssh_pkt_getuint32(pktin);
4104 struct ssh_channel *c;
4106 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4107 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4108 c->remoteid = localid;
4109 c->type = CHAN_SOCKDATA;
4110 c->v.v1.throttling = 0;
4111 pfd_confirm(c->u.pfd.s);
4114 if (c && c->closes) {
4116 * We have a pending close on this channel,
4117 * which we decided on before the server acked
4118 * the channel open. So now we know the
4119 * remoteid, we can close it again.
4121 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE,
4122 PKT_INT, c->remoteid, PKT_END);
4126 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
4128 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4129 struct ssh_channel *c;
4131 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4132 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4133 logevent("Forwarded connection refused by server");
4134 pfd_close(c->u.pfd.s);
4135 del234(ssh->channels, c);
4140 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
4142 /* Remote side closes a channel. */
4143 unsigned i = ssh_pkt_getuint32(pktin);
4144 struct ssh_channel *c;
4145 c = find234(ssh->channels, &i, ssh_channelfind);
4146 if (c && ((int)c->remoteid) != -1) {
4149 (pktin->type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
4151 if ((c->closes == 0) && (c->type == CHAN_X11)) {
4152 logevent("Forwarded X11 connection terminated");
4153 assert(c->u.x11.s != NULL);
4154 x11_close(c->u.x11.s);
4157 if ((c->closes == 0) && (c->type == CHAN_SOCKDATA)) {
4158 logevent("Forwarded port closed");
4159 assert(c->u.pfd.s != NULL);
4160 pfd_close(c->u.pfd.s);
4164 c->closes |= (closetype << 2); /* seen this message */
4165 if (!(c->closes & closetype)) {
4166 send_packet(ssh, pktin->type, PKT_INT, c->remoteid,
4168 c->closes |= closetype; /* sent it too */
4171 if (c->closes == 15) {
4172 del234(ssh->channels, c);
4176 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
4177 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
4178 "_CONFIRMATION", c ? "half-open" : "nonexistent",
4183 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
4185 /* Data sent down one of our channels. */
4186 int i = ssh_pkt_getuint32(pktin);
4189 struct ssh_channel *c;
4191 ssh_pkt_getstring(pktin, &p, &len);
4193 c = find234(ssh->channels, &i, ssh_channelfind);
4198 bufsize = x11_send(c->u.x11.s, p, len);
4201 bufsize = pfd_send(c->u.pfd.s, p, len);
4204 /* Data for an agent message. Buffer it. */
4206 if (c->u.a.lensofar < 4) {
4207 unsigned int l = min(4 - c->u.a.lensofar, len);
4208 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
4212 c->u.a.lensofar += l;
4214 if (c->u.a.lensofar == 4) {
4216 4 + GET_32BIT(c->u.a.msglen);
4217 c->u.a.message = snewn(c->u.a.totallen,
4219 memcpy(c->u.a.message, c->u.a.msglen, 4);
4221 if (c->u.a.lensofar >= 4 && len > 0) {
4223 min(c->u.a.totallen - c->u.a.lensofar,
4225 memcpy(c->u.a.message + c->u.a.lensofar, p,
4229 c->u.a.lensofar += l;
4231 if (c->u.a.lensofar == c->u.a.totallen) {
4234 if (agent_query(c->u.a.message,
4237 ssh_agentf_callback, c))
4238 ssh_agentf_callback(c, reply, replylen);
4239 sfree(c->u.a.message);
4240 c->u.a.lensofar = 0;
4243 bufsize = 0; /* agent channels never back up */
4246 if (!c->v.v1.throttling && bufsize > SSH1_BUFFER_LIMIT) {
4247 c->v.v1.throttling = 1;
4248 ssh1_throttle(ssh, +1);
4253 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
4256 ssh->exitcode = ssh_pkt_getuint32(pktin);
4257 sprintf(buf, "Server sent command exit status %d",
4260 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
4262 * In case `helpful' firewalls or proxies tack
4263 * extra human-readable text on the end of the
4264 * session which we might mistake for another
4265 * encrypted packet, we close the session once
4266 * we've sent EXIT_CONFIRMATION.
4268 ssh_closing((Plug)ssh, NULL, 0, 0);
4271 static void do_ssh1_connection(Ssh ssh, unsigned char *in, int inlen,
4272 struct Packet *pktin)
4274 crBegin(ssh->do_ssh1_connection_crstate);
4276 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
4277 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
4278 ssh1_smsg_stdout_stderr_data;
4280 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
4281 ssh1_msg_channel_open_confirmation;
4282 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
4283 ssh1_msg_channel_open_failure;
4284 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
4285 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
4286 ssh1_msg_channel_close;
4287 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
4288 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
4290 if (ssh->cfg.agentfwd && agent_exists()) {
4291 logevent("Requesting agent forwarding");
4292 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
4296 if (pktin->type != SSH1_SMSG_SUCCESS
4297 && pktin->type != SSH1_SMSG_FAILURE) {
4298 bombout(("Protocol confusion"));
4300 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4301 logevent("Agent forwarding refused");
4303 logevent("Agent forwarding enabled");
4304 ssh->agentfwd_enabled = TRUE;
4305 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
4309 if (ssh->cfg.x11_forward) {
4310 char proto[20], data[64];
4311 logevent("Requesting X11 forwarding");
4312 ssh->x11auth = x11_invent_auth(proto, sizeof(proto),
4313 data, sizeof(data), ssh->cfg.x11_auth);
4314 x11_get_real_auth(ssh->x11auth, ssh->cfg.x11_display);
4315 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
4316 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
4317 PKT_STR, proto, PKT_STR, data,
4318 PKT_INT, x11_get_screen_number(ssh->cfg.x11_display),
4321 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
4322 PKT_STR, proto, PKT_STR, data, PKT_END);
4327 if (pktin->type != SSH1_SMSG_SUCCESS
4328 && pktin->type != SSH1_SMSG_FAILURE) {
4329 bombout(("Protocol confusion"));
4331 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4332 logevent("X11 forwarding refused");
4334 logevent("X11 forwarding enabled");
4335 ssh->X11_fwd_enabled = TRUE;
4336 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
4340 ssh_setup_portfwd(ssh, &ssh->cfg);
4341 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
4343 if (!ssh->cfg.nopty) {
4344 /* Unpick the terminal-speed string. */
4345 /* XXX perhaps we should allow no speeds to be sent. */
4346 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
4347 sscanf(ssh->cfg.termspeed, "%d,%d", &ssh->ospeed, &ssh->ispeed);
4348 /* Send the pty request. */
4349 send_packet(ssh, SSH1_CMSG_REQUEST_PTY,
4350 PKT_STR, ssh->cfg.termtype,
4351 PKT_INT, ssh->term_height,
4352 PKT_INT, ssh->term_width,
4353 PKT_INT, 0, PKT_INT, 0, /* width,height in pixels */
4354 PKT_CHAR, 192, PKT_INT, ssh->ispeed, /* TTY_OP_ISPEED */
4355 PKT_CHAR, 193, PKT_INT, ssh->ospeed, /* TTY_OP_OSPEED */
4356 PKT_CHAR, 0, PKT_END);
4357 ssh->state = SSH_STATE_INTERMED;
4361 if (pktin->type != SSH1_SMSG_SUCCESS
4362 && pktin->type != SSH1_SMSG_FAILURE) {
4363 bombout(("Protocol confusion"));
4365 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4366 c_write_str(ssh, "Server refused to allocate pty\r\n");
4367 ssh->editing = ssh->echoing = 1;
4369 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
4370 ssh->ospeed, ssh->ispeed);
4372 ssh->editing = ssh->echoing = 1;
4375 if (ssh->cfg.compression) {
4376 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
4380 if (pktin->type != SSH1_SMSG_SUCCESS
4381 && pktin->type != SSH1_SMSG_FAILURE) {
4382 bombout(("Protocol confusion"));
4384 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4385 c_write_str(ssh, "Server refused to compress\r\n");
4387 logevent("Started compression");
4388 ssh->v1_compressing = TRUE;
4389 ssh->cs_comp_ctx = zlib_compress_init();
4390 logevent("Initialised zlib (RFC1950) compression");
4391 ssh->sc_comp_ctx = zlib_decompress_init();
4392 logevent("Initialised zlib (RFC1950) decompression");
4396 * Start the shell or command.
4398 * Special case: if the first-choice command is an SSH2
4399 * subsystem (hence not usable here) and the second choice
4400 * exists, we fall straight back to that.
4403 char *cmd = ssh->cfg.remote_cmd_ptr;
4405 if (ssh->cfg.ssh_subsys && ssh->cfg.remote_cmd_ptr2) {
4406 cmd = ssh->cfg.remote_cmd_ptr2;
4407 ssh->fallback_cmd = TRUE;
4410 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
4412 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
4413 logevent("Started session");
4416 ssh->state = SSH_STATE_SESSION;
4417 if (ssh->size_needed)
4418 ssh_size(ssh, ssh->term_width, ssh->term_height);
4419 if (ssh->eof_needed)
4420 ssh_special(ssh, TS_EOF);
4423 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
4425 ssh->channels = newtree234(ssh_channelcmp);
4429 * By this point, most incoming packets are already being
4430 * handled by the dispatch table, and we need only pay
4431 * attention to the unusual ones.
4436 if (pktin->type == SSH1_SMSG_SUCCESS) {
4437 /* may be from EXEC_SHELL on some servers */
4438 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4439 /* may be from EXEC_SHELL on some servers
4440 * if no pty is available or in other odd cases. Ignore */
4442 bombout(("Strange packet received: type %d", pktin->type));
4447 int len = min(inlen, 512);
4448 send_packet(ssh, SSH1_CMSG_STDIN_DATA, PKTT_DATA,
4449 PKT_INT, len, PKT_DATA, in, len,
4450 PKTT_OTHER, PKT_END);
4461 * Handle the top-level SSH2 protocol.
4463 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
4468 ssh_pkt_getstring(pktin, &msg, &msglen);
4469 buf = dupprintf("Remote debug message: %.*s", msglen, msg);
4474 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
4476 /* log reason code in disconnect message */
4480 ssh_pkt_getstring(pktin, &msg, &msglen);
4481 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
4484 void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
4486 /* Do nothing, because we're ignoring it! Duhh. */
4489 static void ssh1_protocol_setup(Ssh ssh)
4494 * Most messages are handled by the coroutines.
4496 for (i = 0; i < 256; i++)
4497 ssh->packet_dispatch[i] = NULL;
4500 * These special message types we install handlers for.
4502 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
4503 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
4504 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
4507 static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen,
4508 struct Packet *pktin)
4510 if (ssh->state == SSH_STATE_CLOSED)
4513 if (pktin && ssh->packet_dispatch[pktin->type]) {
4514 ssh->packet_dispatch[pktin->type](ssh, pktin);
4518 if (!ssh->protocol_initial_phase_done) {
4519 if (do_ssh1_login(ssh, in, inlen, pktin))
4520 ssh->protocol_initial_phase_done = TRUE;
4525 do_ssh1_connection(ssh, in, inlen, pktin);
4529 * Utility routine for decoding comma-separated strings in KEXINIT.
4531 static int in_commasep_string(char *needle, char *haystack, int haylen)
4534 if (!needle || !haystack) /* protect against null pointers */
4536 needlen = strlen(needle);
4539 * Is it at the start of the string?
4541 if (haylen >= needlen && /* haystack is long enough */
4542 !memcmp(needle, haystack, needlen) && /* initial match */
4543 (haylen == needlen || haystack[needlen] == ',')
4544 /* either , or EOS follows */
4548 * If not, search for the next comma and resume after that.
4549 * If no comma found, terminate.
4551 while (haylen > 0 && *haystack != ',')
4552 haylen--, haystack++;
4555 haylen--, haystack++; /* skip over comma itself */
4560 * SSH2 key creation method.
4562 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H,
4563 unsigned char *sessid, char chr,
4564 unsigned char *keyspace)
4567 /* First 20 bytes. */
4569 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
4571 SHA_Bytes(&s, H, 20);
4572 SHA_Bytes(&s, &chr, 1);
4573 SHA_Bytes(&s, sessid, 20);
4574 SHA_Final(&s, keyspace);
4575 /* Next 20 bytes. */
4577 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
4579 SHA_Bytes(&s, H, 20);
4580 SHA_Bytes(&s, keyspace, 20);
4581 SHA_Final(&s, keyspace + 20);
4585 * Handle the SSH2 transport layer.
4587 static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen,
4588 struct Packet *pktin)
4590 struct do_ssh2_transport_state {
4591 int nbits, pbits, warn;
4592 Bignum p, g, e, f, K;
4593 int kex_init_value, kex_reply_value;
4594 const struct ssh_mac **maclist;
4596 const struct ssh2_cipher *cscipher_tobe;
4597 const struct ssh2_cipher *sccipher_tobe;
4598 const struct ssh_mac *csmac_tobe;
4599 const struct ssh_mac *scmac_tobe;
4600 const struct ssh_compress *cscomp_tobe;
4601 const struct ssh_compress *sccomp_tobe;
4602 char *hostkeydata, *sigdata, *keystr, *fingerprint;
4603 int hostkeylen, siglen;
4604 void *hkey; /* actual host key */
4605 unsigned char exchange_hash[20];
4606 int n_preferred_kex;
4607 const struct ssh_kex *preferred_kex[KEX_MAX];
4608 int n_preferred_ciphers;
4609 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
4610 const struct ssh_compress *preferred_comp;
4612 struct Packet *pktout;
4614 crState(do_ssh2_transport_state);
4616 crBegin(ssh->do_ssh2_transport_crstate);
4618 s->cscipher_tobe = s->sccipher_tobe = NULL;
4619 s->csmac_tobe = s->scmac_tobe = NULL;
4620 s->cscomp_tobe = s->sccomp_tobe = NULL;
4627 * Set up the preferred key exchange. (NULL => warn below here)
4629 s->n_preferred_kex = 0;
4630 for (i = 0; i < KEX_MAX; i++) {
4631 switch (ssh->cfg.ssh_kexlist[i]) {
4633 s->preferred_kex[s->n_preferred_kex++] =
4634 &ssh_diffiehellman_gex;
4637 s->preferred_kex[s->n_preferred_kex++] =
4638 &ssh_diffiehellman_group14;
4641 s->preferred_kex[s->n_preferred_kex++] =
4642 &ssh_diffiehellman_group1;
4645 /* Flag for later. Don't bother if it's the last in
4647 if (i < KEX_MAX - 1) {
4648 s->preferred_kex[s->n_preferred_kex++] = NULL;
4658 * Set up the preferred ciphers. (NULL => warn below here)
4660 s->n_preferred_ciphers = 0;
4661 for (i = 0; i < CIPHER_MAX; i++) {
4662 switch (ssh->cfg.ssh_cipherlist[i]) {
4663 case CIPHER_BLOWFISH:
4664 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
4667 if (ssh->cfg.ssh2_des_cbc) {
4668 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
4672 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
4675 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
4678 /* Flag for later. Don't bother if it's the last in
4680 if (i < CIPHER_MAX - 1) {
4681 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
4689 * Set up preferred compression.
4691 if (ssh->cfg.compression)
4692 s->preferred_comp = &ssh_zlib;
4694 s->preferred_comp = &ssh_comp_none;
4697 * Be prepared to work around the buggy MAC problem.
4699 if (ssh->remote_bugs & BUG_SSH2_HMAC)
4700 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
4702 s->maclist = macs, s->nmacs = lenof(macs);
4706 int i, j, commalist_started;
4709 * Enable queueing of outgoing auth- or connection-layer
4710 * packets while we are in the middle of a key exchange.
4712 ssh->queueing = TRUE;
4715 * Flag that KEX is in progress.
4717 ssh->kex_in_progress = TRUE;
4720 * Construct and send our key exchange packet.
4722 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
4723 for (i = 0; i < 16; i++)
4724 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
4725 /* List key exchange algorithms. */
4726 ssh2_pkt_addstring_start(s->pktout);
4727 commalist_started = 0;
4728 for (i = 0; i < s->n_preferred_kex; i++) {
4729 const struct ssh_kex *k = s->preferred_kex[i];
4730 if (!k) continue; /* warning flag */
4731 if (commalist_started)
4732 ssh2_pkt_addstring_str(s->pktout, ",");
4733 ssh2_pkt_addstring_str(s->pktout, s->preferred_kex[i]->name);
4734 commalist_started = 1;
4736 /* List server host key algorithms. */
4737 ssh2_pkt_addstring_start(s->pktout);
4738 for (i = 0; i < lenof(hostkey_algs); i++) {
4739 ssh2_pkt_addstring_str(s->pktout, hostkey_algs[i]->name);
4740 if (i < lenof(hostkey_algs) - 1)
4741 ssh2_pkt_addstring_str(s->pktout, ",");
4743 /* List client->server encryption algorithms. */
4744 ssh2_pkt_addstring_start(s->pktout);
4745 commalist_started = 0;
4746 for (i = 0; i < s->n_preferred_ciphers; i++) {
4747 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
4748 if (!c) continue; /* warning flag */
4749 for (j = 0; j < c->nciphers; j++) {
4750 if (commalist_started)
4751 ssh2_pkt_addstring_str(s->pktout, ",");
4752 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
4753 commalist_started = 1;
4756 /* List server->client encryption algorithms. */
4757 ssh2_pkt_addstring_start(s->pktout);
4758 commalist_started = 0;
4759 for (i = 0; i < s->n_preferred_ciphers; i++) {
4760 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
4761 if (!c) continue; /* warning flag */
4762 for (j = 0; j < c->nciphers; j++) {
4763 if (commalist_started)
4764 ssh2_pkt_addstring_str(s->pktout, ",");
4765 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
4766 commalist_started = 1;
4769 /* List client->server MAC algorithms. */
4770 ssh2_pkt_addstring_start(s->pktout);
4771 for (i = 0; i < s->nmacs; i++) {
4772 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
4773 if (i < s->nmacs - 1)
4774 ssh2_pkt_addstring_str(s->pktout, ",");
4776 /* List server->client MAC algorithms. */
4777 ssh2_pkt_addstring_start(s->pktout);
4778 for (i = 0; i < s->nmacs; i++) {
4779 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
4780 if (i < s->nmacs - 1)
4781 ssh2_pkt_addstring_str(s->pktout, ",");
4783 /* List client->server compression algorithms. */
4784 ssh2_pkt_addstring_start(s->pktout);
4785 assert(lenof(compressions) > 1);
4786 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
4787 for (i = 0; i < lenof(compressions); i++) {
4788 const struct ssh_compress *c = compressions[i];
4789 if (c != s->preferred_comp) {
4790 ssh2_pkt_addstring_str(s->pktout, ",");
4791 ssh2_pkt_addstring_str(s->pktout, c->name);
4794 /* List server->client compression algorithms. */
4795 ssh2_pkt_addstring_start(s->pktout);
4796 assert(lenof(compressions) > 1);
4797 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
4798 for (i = 0; i < lenof(compressions); i++) {
4799 const struct ssh_compress *c = compressions[i];
4800 if (c != s->preferred_comp) {
4801 ssh2_pkt_addstring_str(s->pktout, ",");
4802 ssh2_pkt_addstring_str(s->pktout, c->name);
4805 /* List client->server languages. Empty list. */
4806 ssh2_pkt_addstring_start(s->pktout);
4807 /* List server->client languages. Empty list. */
4808 ssh2_pkt_addstring_start(s->pktout);
4809 /* First KEX packet does _not_ follow, because we're not that brave. */
4810 ssh2_pkt_addbool(s->pktout, FALSE);
4812 ssh2_pkt_adduint32(s->pktout, 0);
4815 ssh->exhash = ssh->exhashbase;
4816 sha_string(&ssh->exhash, s->pktout->data + 5, s->pktout->length - 5);
4818 ssh2_pkt_send_noqueue(ssh, s->pktout);
4822 if (pktin->length > 5)
4823 sha_string(&ssh->exhash, pktin->data + 5, pktin->length - 5);
4826 * Now examine the other side's KEXINIT to see what we're up
4833 if (pktin->type != SSH2_MSG_KEXINIT) {
4834 bombout(("expected key exchange packet from server"));
4838 ssh->hostkey = NULL;
4839 s->cscipher_tobe = NULL;
4840 s->sccipher_tobe = NULL;
4841 s->csmac_tobe = NULL;
4842 s->scmac_tobe = NULL;
4843 s->cscomp_tobe = NULL;
4844 s->sccomp_tobe = NULL;
4845 pktin->savedpos += 16; /* skip garbage cookie */
4846 ssh_pkt_getstring(pktin, &str, &len); /* key exchange algorithms */
4848 for (i = 0; i < s->n_preferred_kex; i++) {
4849 const struct ssh_kex *k = s->preferred_kex[i];
4852 } else if (in_commasep_string(k->name, str, len)) {
4857 askalg(ssh->frontend, "key-exchange algorithm",
4863 bombout(("Couldn't agree a key exchange algorithm (available: %s)",
4864 str ? str : "(null)"));
4867 ssh_pkt_getstring(pktin, &str, &len); /* host key algorithms */
4868 for (i = 0; i < lenof(hostkey_algs); i++) {
4869 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
4870 ssh->hostkey = hostkey_algs[i];
4874 ssh_pkt_getstring(pktin, &str, &len); /* client->server cipher */
4876 for (i = 0; i < s->n_preferred_ciphers; i++) {
4877 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
4881 for (j = 0; j < c->nciphers; j++) {
4882 if (in_commasep_string(c->list[j]->name, str, len)) {
4883 s->cscipher_tobe = c->list[j];
4888 if (s->cscipher_tobe) {
4890 askalg(ssh->frontend, "client-to-server cipher",
4891 s->cscipher_tobe->name);
4895 if (!s->cscipher_tobe) {
4896 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
4897 str ? str : "(null)"));
4901 ssh_pkt_getstring(pktin, &str, &len); /* server->client cipher */
4903 for (i = 0; i < s->n_preferred_ciphers; i++) {
4904 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
4908 for (j = 0; j < c->nciphers; j++) {
4909 if (in_commasep_string(c->list[j]->name, str, len)) {
4910 s->sccipher_tobe = c->list[j];
4915 if (s->sccipher_tobe) {
4917 askalg(ssh->frontend, "server-to-client cipher",
4918 s->sccipher_tobe->name);
4922 if (!s->sccipher_tobe) {
4923 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
4924 str ? str : "(null)"));
4928 ssh_pkt_getstring(pktin, &str, &len); /* client->server mac */
4929 for (i = 0; i < s->nmacs; i++) {
4930 if (in_commasep_string(s->maclist[i]->name, str, len)) {
4931 s->csmac_tobe = s->maclist[i];
4935 ssh_pkt_getstring(pktin, &str, &len); /* server->client mac */
4936 for (i = 0; i < s->nmacs; i++) {
4937 if (in_commasep_string(s->maclist[i]->name, str, len)) {
4938 s->scmac_tobe = s->maclist[i];
4942 ssh_pkt_getstring(pktin, &str, &len); /* client->server compression */
4943 for (i = 0; i < lenof(compressions) + 1; i++) {
4944 const struct ssh_compress *c =
4945 i == 0 ? s->preferred_comp : compressions[i - 1];
4946 if (in_commasep_string(c->name, str, len)) {
4951 ssh_pkt_getstring(pktin, &str, &len); /* server->client compression */
4952 for (i = 0; i < lenof(compressions) + 1; i++) {
4953 const struct ssh_compress *c =
4954 i == 0 ? s->preferred_comp : compressions[i - 1];
4955 if (in_commasep_string(c->name, str, len)) {
4963 * Work out the number of bits of key we will need from the key
4964 * exchange. We start with the maximum key length of either
4970 csbits = s->cscipher_tobe->keylen;
4971 scbits = s->sccipher_tobe->keylen;
4972 s->nbits = (csbits > scbits ? csbits : scbits);
4974 /* The keys only have 160-bit entropy, since they're based on
4975 * a SHA-1 hash. So cap the key size at 160 bits. */
4980 * If we're doing Diffie-Hellman group exchange, start by
4981 * requesting a group.
4983 if (!ssh->kex->pdata) {
4984 logevent("Doing Diffie-Hellman group exchange");
4985 ssh->pkt_ctx |= SSH2_PKTCTX_DHGEX;
4987 * Work out how big a DH group we will need to allow that
4990 s->pbits = 512 << ((s->nbits - 1) / 64);
4991 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
4992 ssh2_pkt_adduint32(s->pktout, s->pbits);
4993 ssh2_pkt_send_noqueue(ssh, s->pktout);
4996 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
4997 bombout(("expected key exchange group packet from server"));
5000 s->p = ssh2_pkt_getmp(pktin);
5001 s->g = ssh2_pkt_getmp(pktin);
5002 if (!s->p || !s->g) {
5003 bombout(("unable to read mp-ints from incoming group packet"));
5006 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
5007 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
5008 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
5010 ssh->pkt_ctx |= SSH2_PKTCTX_DHGROUP;
5011 ssh->kex_ctx = dh_setup_group(ssh->kex);
5012 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
5013 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
5014 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
5015 ssh->kex->groupname);
5018 logevent("Doing Diffie-Hellman key exchange");
5020 * Now generate and send e for Diffie-Hellman.
5022 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
5023 s->pktout = ssh2_pkt_init(s->kex_init_value);
5024 ssh2_pkt_addmp(s->pktout, s->e);
5025 ssh2_pkt_send_noqueue(ssh, s->pktout);
5028 if (pktin->type != s->kex_reply_value) {
5029 bombout(("expected key exchange reply packet from server"));
5032 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
5033 s->f = ssh2_pkt_getmp(pktin);
5035 bombout(("unable to parse key exchange reply packet"));
5038 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
5040 s->K = dh_find_K(ssh->kex_ctx, s->f);
5042 sha_string(&ssh->exhash, s->hostkeydata, s->hostkeylen);
5043 if (ssh->kex == &ssh_diffiehellman_gex) {
5044 sha_uint32(&ssh->exhash, s->pbits);
5045 sha_mpint(&ssh->exhash, s->p);
5046 sha_mpint(&ssh->exhash, s->g);
5048 sha_mpint(&ssh->exhash, s->e);
5049 sha_mpint(&ssh->exhash, s->f);
5050 sha_mpint(&ssh->exhash, s->K);
5051 SHA_Final(&ssh->exhash, s->exchange_hash);
5053 dh_cleanup(ssh->kex_ctx);
5054 ssh->kex_ctx = NULL;
5057 debug(("Exchange hash is:\n"));
5058 dmemdump(s->exchange_hash, 20);
5061 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
5063 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
5064 (char *)s->exchange_hash, 20)) {
5065 bombout(("Server's host key did not match the signature supplied"));
5070 * Authenticate remote host: verify host key. (We've already
5071 * checked the signature of the exchange hash.)
5073 s->keystr = ssh->hostkey->fmtkey(s->hkey);
5074 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
5075 verify_ssh_host_key(ssh->frontend,
5076 ssh->savedhost, ssh->savedport, ssh->hostkey->keytype,
5077 s->keystr, s->fingerprint);
5078 if (s->first_kex) { /* don't bother logging this in rekeys */
5079 logevent("Host key fingerprint is:");
5080 logevent(s->fingerprint);
5082 sfree(s->fingerprint);
5084 ssh->hostkey->freekey(s->hkey);
5087 * The exchange hash from the very first key exchange is also
5088 * the session id, used in session key construction and
5092 memcpy(ssh->v2_session_id, s->exchange_hash,
5093 sizeof(s->exchange_hash));
5096 * Send SSH2_MSG_NEWKEYS.
5098 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
5099 ssh2_pkt_send_noqueue(ssh, s->pktout);
5100 ssh->outgoing_data_size = 0; /* start counting from here */
5103 * We've sent client NEWKEYS, so create and initialise
5104 * client-to-server session keys.
5106 if (ssh->cs_cipher_ctx)
5107 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
5108 ssh->cscipher = s->cscipher_tobe;
5109 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
5111 if (ssh->cs_mac_ctx)
5112 ssh->csmac->free_context(ssh->cs_mac_ctx);
5113 ssh->csmac = s->csmac_tobe;
5114 ssh->cs_mac_ctx = ssh->csmac->make_context();
5116 if (ssh->cs_comp_ctx)
5117 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
5118 ssh->cscomp = s->cscomp_tobe;
5119 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
5122 * Set IVs on client-to-server keys. Here we use the exchange
5123 * hash from the _first_ key exchange.
5126 unsigned char keyspace[40];
5127 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'C',keyspace);
5128 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
5129 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'A',keyspace);
5130 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
5131 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'E',keyspace);
5132 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
5135 logeventf(ssh, "Initialised %.200s client->server encryption",
5136 ssh->cscipher->text_name);
5137 logeventf(ssh, "Initialised %.200s client->server MAC algorithm",
5138 ssh->csmac->text_name);
5139 if (ssh->cscomp->text_name)
5140 logeventf(ssh, "Initialised %s compression",
5141 ssh->cscomp->text_name);
5144 * Now our end of the key exchange is complete, we can send all
5145 * our queued higher-layer packets.
5147 ssh->queueing = FALSE;
5148 ssh2_pkt_queuesend(ssh);
5151 * Expect SSH2_MSG_NEWKEYS from server.
5154 if (pktin->type != SSH2_MSG_NEWKEYS) {
5155 bombout(("expected new-keys packet from server"));
5158 ssh->incoming_data_size = 0; /* start counting from here */
5161 * We've seen server NEWKEYS, so create and initialise
5162 * server-to-client session keys.
5164 if (ssh->sc_cipher_ctx)
5165 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
5166 ssh->sccipher = s->sccipher_tobe;
5167 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
5169 if (ssh->sc_mac_ctx)
5170 ssh->scmac->free_context(ssh->sc_mac_ctx);
5171 ssh->scmac = s->scmac_tobe;
5172 ssh->sc_mac_ctx = ssh->scmac->make_context();
5174 if (ssh->sc_comp_ctx)
5175 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
5176 ssh->sccomp = s->sccomp_tobe;
5177 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
5180 * Set IVs on server-to-client keys. Here we use the exchange
5181 * hash from the _first_ key exchange.
5184 unsigned char keyspace[40];
5185 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'D',keyspace);
5186 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
5187 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'B',keyspace);
5188 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
5189 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'F',keyspace);
5190 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
5192 logeventf(ssh, "Initialised %.200s server->client encryption",
5193 ssh->sccipher->text_name);
5194 logeventf(ssh, "Initialised %.200s server->client MAC algorithm",
5195 ssh->scmac->text_name);
5196 if (ssh->sccomp->text_name)
5197 logeventf(ssh, "Initialised %s decompression",
5198 ssh->sccomp->text_name);
5201 * Free key exchange data.
5205 if (ssh->kex == &ssh_diffiehellman_gex) {
5211 * Key exchange is over. Schedule a timer for our next rekey.
5213 ssh->kex_in_progress = FALSE;
5214 ssh->last_rekey = GETTICKCOUNT();
5215 if (ssh->cfg.ssh_rekey_time != 0)
5216 ssh->next_rekey = schedule_timer(ssh->cfg.ssh_rekey_time*60*TICKSPERSEC,
5220 * If this is the first key exchange phase, we must pass the
5221 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
5222 * wants to see it but because it will need time to initialise
5223 * itself before it sees an actual packet. In subsequent key
5224 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
5225 * it would only confuse the layer above.
5227 if (!s->first_kex) {
5233 * Now we're encrypting. Begin returning 1 to the protocol main
5234 * function so that other things can run on top of the
5235 * transport. If we ever see a KEXINIT, we must go back to the
5238 * We _also_ go back to the start if we see pktin==NULL and
5239 * inlen==-1, because this is a special signal meaning
5240 * `initiate client-driven rekey', and `in' contains a message
5241 * giving the reason for the rekey.
5243 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
5244 (!pktin && inlen == -1))) {
5248 logevent("Server initiated key re-exchange");
5250 logevent((char *)in);
5252 goto begin_key_exchange;
5258 * Add data to an SSH2 channel output buffer.
5260 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
5263 bufchain_add(&c->v.v2.outbuffer, buf, len);
5267 * Attempt to send data on an SSH2 channel.
5269 static int ssh2_try_send(struct ssh_channel *c)
5272 struct Packet *pktout;
5274 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
5277 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
5278 if ((unsigned)len > c->v.v2.remwindow)
5279 len = c->v.v2.remwindow;
5280 if ((unsigned)len > c->v.v2.remmaxpkt)
5281 len = c->v.v2.remmaxpkt;
5282 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
5283 ssh2_pkt_adduint32(pktout, c->remoteid);
5284 dont_log_data(ssh, pktout, PKTLOG_OMIT);
5285 ssh2_pkt_addstring_start(pktout);
5286 ssh2_pkt_addstring_data(pktout, data, len);
5287 end_log_omission(ssh, pktout);
5288 ssh2_pkt_send(ssh, pktout);
5289 bufchain_consume(&c->v.v2.outbuffer, len);
5290 c->v.v2.remwindow -= len;
5294 * After having sent as much data as we can, return the amount
5297 return bufchain_size(&c->v.v2.outbuffer);
5301 * Potentially enlarge the window on an SSH2 channel.
5303 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin)
5308 * Never send WINDOW_ADJUST for a channel that the remote side
5309 * already thinks it's closed; there's no point, since it won't
5310 * be sending any more data anyway.
5315 if (newwin > c->v.v2.locwindow) {
5316 struct Packet *pktout;
5318 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5319 ssh2_pkt_adduint32(pktout, c->remoteid);
5320 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
5321 ssh2_pkt_send(ssh, pktout);
5322 c->v.v2.locwindow = newwin;
5326 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
5328 unsigned i = ssh_pkt_getuint32(pktin);
5329 struct ssh_channel *c;
5330 c = find234(ssh->channels, &i, ssh_channelfind);
5331 if (c && !c->closes)
5332 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
5335 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
5338 unsigned int length;
5339 unsigned i = ssh_pkt_getuint32(pktin);
5340 struct ssh_channel *c;
5341 c = find234(ssh->channels, &i, ssh_channelfind);
5343 return; /* nonexistent channel */
5344 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
5345 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
5346 return; /* extended but not stderr */
5347 ssh_pkt_getstring(pktin, &data, &length);
5350 c->v.v2.locwindow -= length;
5352 case CHAN_MAINSESSION:
5354 from_backend(ssh->frontend, pktin->type ==
5355 SSH2_MSG_CHANNEL_EXTENDED_DATA,
5359 bufsize = x11_send(c->u.x11.s, data, length);
5362 bufsize = pfd_send(c->u.pfd.s, data, length);
5365 while (length > 0) {
5366 if (c->u.a.lensofar < 4) {
5367 unsigned int l = min(4 - c->u.a.lensofar, length);
5368 memcpy(c->u.a.msglen + c->u.a.lensofar,
5372 c->u.a.lensofar += l;
5374 if (c->u.a.lensofar == 4) {
5376 4 + GET_32BIT(c->u.a.msglen);
5377 c->u.a.message = snewn(c->u.a.totallen,
5379 memcpy(c->u.a.message, c->u.a.msglen, 4);
5381 if (c->u.a.lensofar >= 4 && length > 0) {
5383 min(c->u.a.totallen - c->u.a.lensofar,
5385 memcpy(c->u.a.message + c->u.a.lensofar,
5389 c->u.a.lensofar += l;
5391 if (c->u.a.lensofar == c->u.a.totallen) {
5394 if (agent_query(c->u.a.message,
5397 ssh_agentf_callback, c))
5398 ssh_agentf_callback(c, reply, replylen);
5399 sfree(c->u.a.message);
5400 c->u.a.lensofar = 0;
5407 * If we are not buffering too much data,
5408 * enlarge the window again at the remote side.
5410 if (bufsize < OUR_V2_WINSIZE)
5411 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
5415 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
5417 unsigned i = ssh_pkt_getuint32(pktin);
5418 struct ssh_channel *c;
5420 c = find234(ssh->channels, &i, ssh_channelfind);
5422 return; /* nonexistent channel */
5424 if (c->type == CHAN_X11) {
5426 * Remote EOF on an X11 channel means we should
5427 * wrap up and close the channel ourselves.
5429 x11_close(c->u.x11.s);
5431 } else if (c->type == CHAN_AGENT) {
5433 } else if (c->type == CHAN_SOCKDATA) {
5434 pfd_close(c->u.pfd.s);
5439 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
5441 unsigned i = ssh_pkt_getuint32(pktin);
5442 struct ssh_channel *c;
5443 struct Packet *pktout;
5445 c = find234(ssh->channels, &i, ssh_channelfind);
5446 if (!c || ((int)c->remoteid) == -1) {
5447 bombout(("Received CHANNEL_CLOSE for %s channel %d\n",
5448 c ? "half-open" : "nonexistent", i));
5451 /* Do pre-close processing on the channel. */
5453 case CHAN_MAINSESSION:
5454 ssh->mainchan = NULL;
5455 update_specials_menu(ssh->frontend);
5458 if (c->u.x11.s != NULL)
5459 x11_close(c->u.x11.s);
5466 if (c->u.pfd.s != NULL)
5467 pfd_close(c->u.pfd.s);
5471 if (c->closes == 0) {
5472 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
5473 ssh2_pkt_adduint32(pktout, c->remoteid);
5474 ssh2_pkt_send(ssh, pktout);
5476 del234(ssh->channels, c);
5477 bufchain_clear(&c->v.v2.outbuffer);
5481 * See if that was the last channel left open.
5482 * (This is only our termination condition if we're
5483 * not running in -N mode.)
5485 if (!ssh->cfg.ssh_no_shell && count234(ssh->channels) == 0) {
5486 logevent("All channels closed. Disconnecting");
5489 * We used to send SSH_MSG_DISCONNECT here,
5490 * because I'd believed that _every_ conforming
5491 * SSH2 connection had to end with a disconnect
5492 * being sent by at least one side; apparently
5493 * I was wrong and it's perfectly OK to
5494 * unceremoniously slam the connection shut
5495 * when you're done, and indeed OpenSSH feels
5496 * this is more polite than sending a
5497 * DISCONNECT. So now we don't.
5499 s->pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
5500 ssh2_pkt_adduint32(s->pktout, SSH2_DISCONNECT_BY_APPLICATION);
5501 ssh2_pkt_addstring(s->pktout, "All open channels closed");
5502 ssh2_pkt_addstring(s->pktout, "en"); /* language tag */
5503 ssh2_pkt_send_noqueue(ssh, s->pktout);
5505 ssh_closing((Plug)ssh, NULL, 0, 0);
5509 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
5511 unsigned i = ssh_pkt_getuint32(pktin);
5512 struct ssh_channel *c;
5513 struct Packet *pktout;
5515 c = find234(ssh->channels, &i, ssh_channelfind);
5517 return; /* nonexistent channel */
5518 if (c->type != CHAN_SOCKDATA_DORMANT)
5519 return; /* dunno why they're confirming this */
5520 c->remoteid = ssh_pkt_getuint32(pktin);
5521 c->type = CHAN_SOCKDATA;
5522 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
5523 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
5525 pfd_confirm(c->u.pfd.s);
5528 * We have a pending close on this channel,
5529 * which we decided on before the server acked
5530 * the channel open. So now we know the
5531 * remoteid, we can close it again.
5533 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
5534 ssh2_pkt_adduint32(pktout, c->remoteid);
5535 ssh2_pkt_send(ssh, pktout);
5539 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
5541 static const char *const reasons[] = {
5542 "<unknown reason code>",
5543 "Administratively prohibited",
5545 "Unknown channel type",
5546 "Resource shortage",
5548 unsigned i = ssh_pkt_getuint32(pktin);
5549 unsigned reason_code;
5550 char *reason_string;
5553 struct ssh_channel *c;
5554 c = find234(ssh->channels, &i, ssh_channelfind);
5556 return; /* nonexistent channel */
5557 if (c->type != CHAN_SOCKDATA_DORMANT)
5558 return; /* dunno why they're failing this */
5560 reason_code = ssh_pkt_getuint32(pktin);
5561 if (reason_code >= lenof(reasons))
5562 reason_code = 0; /* ensure reasons[reason_code] in range */
5563 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
5564 message = dupprintf("Forwarded connection refused by"
5565 " server: %s [%.*s]", reasons[reason_code],
5566 reason_length, reason_string);
5570 pfd_close(c->u.pfd.s);
5572 del234(ssh->channels, c);
5576 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
5580 int typelen, want_reply;
5581 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
5582 struct ssh_channel *c;
5583 struct Packet *pktout;
5585 localid = ssh_pkt_getuint32(pktin);
5586 ssh_pkt_getstring(pktin, &type, &typelen);
5587 want_reply = ssh2_pkt_getbool(pktin);
5590 * First, check that the channel exists. Otherwise,
5591 * we can instantly disconnect with a rude message.
5593 c = find234(ssh->channels, &localid, ssh_channelfind);
5596 sprintf(buf, "Received channel request for nonexistent"
5597 " channel %d", localid);
5599 pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
5600 ssh2_pkt_adduint32(pktout, SSH2_DISCONNECT_BY_APPLICATION);
5601 ssh2_pkt_addstring(pktout, buf);
5602 ssh2_pkt_addstring(pktout, "en"); /* language tag */
5603 ssh2_pkt_send_noqueue(ssh, pktout);
5604 connection_fatal(ssh->frontend, "%s", buf);
5605 ssh_closing((Plug)ssh, NULL, 0, 0);
5610 * Having got the channel number, we now look at
5611 * the request type string to see if it's something
5614 if (c == ssh->mainchan) {
5616 * We recognise "exit-status" and "exit-signal" on
5617 * the primary channel.
5619 if (typelen == 11 &&
5620 !memcmp(type, "exit-status", 11)) {
5622 ssh->exitcode = ssh_pkt_getuint32(pktin);
5623 logeventf(ssh, "Server sent command exit status %d",
5625 reply = SSH2_MSG_CHANNEL_SUCCESS;
5627 } else if (typelen == 11 &&
5628 !memcmp(type, "exit-signal", 11)) {
5630 int is_plausible = TRUE, is_int = FALSE;
5631 char *fmt_sig = "", *fmt_msg = "";
5633 int msglen = 0, core = FALSE;
5634 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
5635 * provide an `int' for the signal, despite its
5636 * having been a `string' in the drafts since at
5637 * least 2001. (Fixed in session.c 1.147.) Try to
5638 * infer which we can safely parse it as. */
5640 unsigned char *p = pktin->body +
5642 long len = pktin->length - pktin->savedpos;
5643 unsigned long num = GET_32BIT(p); /* what is it? */
5644 /* If it's 0, it hardly matters; assume string */
5648 int maybe_int = FALSE, maybe_str = FALSE;
5649 #define CHECK_HYPOTHESIS(offset, result) \
5652 if (q >= 0 && q+4 <= len) { \
5653 q = q + 4 + GET_32BIT(p+q); \
5654 if (q >= 0 && q+4 <= len && \
5655 (q = q + 4 + GET_32BIT(p+q)) && q == len) \
5659 CHECK_HYPOTHESIS(4+1, maybe_int);
5660 CHECK_HYPOTHESIS(4+num+1, maybe_str);
5661 #undef CHECK_HYPOTHESIS
5662 if (maybe_int && !maybe_str)
5664 else if (!maybe_int && maybe_str)
5667 /* Crikey. Either or neither. Panic. */
5668 is_plausible = FALSE;
5673 /* Old non-standard OpenSSH. */
5674 int signum = ssh_pkt_getuint32(pktin);
5675 fmt_sig = dupprintf(" %d", signum);
5677 /* As per the drafts. */
5680 ssh_pkt_getstring(pktin, &sig, &siglen);
5681 /* Signal name isn't supposed to be blank, but
5682 * let's cope gracefully if it is. */
5684 fmt_sig = dupprintf(" \"%.*s\"",
5688 core = ssh2_pkt_getbool(pktin);
5689 ssh_pkt_getstring(pktin, &msg, &msglen);
5691 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
5693 /* ignore lang tag */
5694 } /* else don't attempt to parse */
5695 logeventf(ssh, "Server exited on signal%s%s%s",
5696 fmt_sig, core ? " (core dumped)" : "",
5698 if (*fmt_sig) sfree(fmt_sig);
5699 if (*fmt_msg) sfree(fmt_msg);
5700 reply = SSH2_MSG_CHANNEL_SUCCESS;
5705 * This is a channel request we don't know
5706 * about, so we now either ignore the request
5707 * or respond with CHANNEL_FAILURE, depending
5710 reply = SSH2_MSG_CHANNEL_FAILURE;
5713 pktout = ssh2_pkt_init(reply);
5714 ssh2_pkt_adduint32(pktout, c->remoteid);
5715 ssh2_pkt_send(ssh, pktout);
5719 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
5722 int typelen, want_reply;
5723 struct Packet *pktout;
5725 ssh_pkt_getstring(pktin, &type, &typelen);
5726 want_reply = ssh2_pkt_getbool(pktin);
5729 * We currently don't support any global requests
5730 * at all, so we either ignore the request or
5731 * respond with REQUEST_FAILURE, depending on
5735 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
5736 ssh2_pkt_send(ssh, pktout);
5740 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
5748 struct ssh_channel *c;
5749 unsigned remid, winsize, pktsize;
5750 struct Packet *pktout;
5752 ssh_pkt_getstring(pktin, &type, &typelen);
5753 c = snew(struct ssh_channel);
5756 remid = ssh_pkt_getuint32(pktin);
5757 winsize = ssh_pkt_getuint32(pktin);
5758 pktsize = ssh_pkt_getuint32(pktin);
5760 if (typelen == 3 && !memcmp(type, "x11", 3)) {
5763 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
5764 addrstr = snewn(peeraddrlen+1, char);
5765 memcpy(addrstr, peeraddr, peeraddrlen);
5766 addrstr[peeraddrlen] = '\0';
5767 peerport = ssh_pkt_getuint32(pktin);
5769 logeventf(ssh, "Received X11 connect request from %s:%d",
5772 if (!ssh->X11_fwd_enabled)
5773 error = "X11 forwarding is not enabled";
5774 else if (x11_init(&c->u.x11.s, ssh->cfg.x11_display, c,
5775 ssh->x11auth, addrstr, peerport,
5776 &ssh->cfg) != NULL) {
5777 error = "Unable to open an X11 connection";
5779 logevent("Opening X11 forward connection succeeded");
5784 } else if (typelen == 15 &&
5785 !memcmp(type, "forwarded-tcpip", 15)) {
5786 struct ssh_rportfwd pf, *realpf;
5789 ssh_pkt_getstring(pktin, &dummy, &dummylen);/* skip address */
5790 pf.sport = ssh_pkt_getuint32(pktin);
5791 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
5792 peerport = ssh_pkt_getuint32(pktin);
5793 realpf = find234(ssh->rportfwds, &pf, NULL);
5794 logeventf(ssh, "Received remote port %d open request "
5795 "from %s:%d", pf.sport, peeraddr, peerport);
5796 if (realpf == NULL) {
5797 error = "Remote port is not recognised";
5799 const char *e = pfd_newconnect(&c->u.pfd.s,
5803 logeventf(ssh, "Attempting to forward remote port to "
5804 "%s:%d", realpf->dhost, realpf->dport);
5806 logeventf(ssh, "Port open failed: %s", e);
5807 error = "Port open failed";
5809 logevent("Forwarded port opened successfully");
5810 c->type = CHAN_SOCKDATA;
5813 } else if (typelen == 22 &&
5814 !memcmp(type, "auth-agent@openssh.com", 3)) {
5815 if (!ssh->agentfwd_enabled)
5816 error = "Agent forwarding is not enabled";
5818 c->type = CHAN_AGENT; /* identify channel type */
5819 c->u.a.lensofar = 0;
5822 error = "Unsupported channel type requested";
5825 c->remoteid = remid;
5827 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
5828 ssh2_pkt_adduint32(pktout, c->remoteid);
5829 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
5830 ssh2_pkt_addstring(pktout, error);
5831 ssh2_pkt_addstring(pktout, "en"); /* language tag */
5832 ssh2_pkt_send(ssh, pktout);
5833 logeventf(ssh, "Rejected channel open: %s", error);
5836 c->localid = alloc_channel_id(ssh);
5838 c->v.v2.locwindow = OUR_V2_WINSIZE;
5839 c->v.v2.remwindow = winsize;
5840 c->v.v2.remmaxpkt = pktsize;
5841 bufchain_init(&c->v.v2.outbuffer);
5842 add234(ssh->channels, c);
5843 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
5844 ssh2_pkt_adduint32(pktout, c->remoteid);
5845 ssh2_pkt_adduint32(pktout, c->localid);
5846 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
5847 ssh2_pkt_adduint32(pktout, 0x4000UL); /* our max pkt size */
5848 ssh2_pkt_send(ssh, pktout);
5853 * Handle the SSH2 userauth and connection layers.
5855 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
5856 struct Packet *pktin)
5858 struct do_ssh2_authconn_state {
5860 AUTH_INVALID, AUTH_PUBLICKEY_AGENT, AUTH_PUBLICKEY_FILE,
5862 AUTH_KEYBOARD_INTERACTIVE
5866 AUTH_TYPE_PUBLICKEY,
5867 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
5868 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
5870 AUTH_TYPE_KEYBOARD_INTERACTIVE,
5871 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
5873 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
5874 int tried_pubkey_config, tried_agent, tried_keyb_inter;
5875 int kbd_inter_running;
5877 int num_prompts, curr_prompt, echo;
5882 void *publickey_blob;
5883 int publickey_bloblen;
5884 unsigned char request[5], *response, *p;
5888 char *pkblob, *alg, *commentp;
5889 int pklen, alglen, commentlen;
5890 int siglen, retlen, len;
5891 char *q, *agentreq, *ret;
5893 int num_env, env_left, env_ok;
5894 struct Packet *pktout;
5896 crState(do_ssh2_authconn_state);
5898 crBegin(ssh->do_ssh2_authconn_crstate);
5901 * Request userauth protocol, and await a response to it.
5903 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
5904 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
5905 ssh2_pkt_send(ssh, s->pktout);
5906 crWaitUntilV(pktin);
5907 if (pktin->type != SSH2_MSG_SERVICE_ACCEPT) {
5908 bombout(("Server refused user authentication protocol"));
5913 * We repeat this whole loop, including the username prompt,
5914 * until we manage a successful authentication. If the user
5915 * types the wrong _password_, they can be sent back to the
5916 * beginning to try another username, if this is configured on.
5917 * (If they specify a username in the config, they are never
5918 * asked, even if they do give a wrong password.)
5920 * I think this best serves the needs of
5922 * - the people who have no configuration, no keys, and just
5923 * want to try repeated (username,password) pairs until they
5924 * type both correctly
5926 * - people who have keys and configuration but occasionally
5927 * need to fall back to passwords
5929 * - people with a key held in Pageant, who might not have
5930 * logged in to a particular machine before; so they want to
5931 * type a username, and then _either_ their key will be
5932 * accepted, _or_ they will type a password. If they mistype
5933 * the username they will want to be able to get back and
5936 s->username[0] = '\0';
5937 s->got_username = FALSE;
5942 if (s->got_username && !ssh->cfg.change_username) {
5944 * We got a username last time round this loop, and
5945 * with change_username turned off we don't try to get
5948 } else if (!*ssh->cfg.username) {
5949 if (ssh_get_line && !ssh_getline_pw_only) {
5950 if (!ssh_get_line("login as: ",
5951 s->username, sizeof(s->username), FALSE)) {
5953 * get_line failed to get a username.
5956 logevent("No username provided. Abandoning session.");
5957 ssh_closing((Plug)ssh, NULL, 0, 0);
5961 int ret; /* need not be saved across crReturn */
5962 c_write_str(ssh, "login as: ");
5964 setup_userpass_input(ssh, s->username, sizeof(s->username), 1);
5966 crWaitUntilV(!pktin);
5967 ret = process_userpass_input(ssh, in, inlen);
5971 c_write_str(ssh, "\r\n");
5973 s->username[strcspn(s->username, "\n\r")] = '\0';
5976 strncpy(s->username, ssh->cfg.username, sizeof(s->username));
5977 s->username[sizeof(s->username)-1] = '\0';
5978 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
5979 stuff = dupprintf("Using username \"%s\".\r\n", s->username);
5980 c_write_str(ssh, stuff);
5984 s->got_username = TRUE;
5987 * Send an authentication request using method "none": (a)
5988 * just in case it succeeds, and (b) so that we know what
5989 * authentication methods we can usefully try next.
5991 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
5993 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
5994 ssh2_pkt_addstring(s->pktout, s->username);
5995 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
5996 ssh2_pkt_addstring(s->pktout, "none"); /* method */
5997 ssh2_pkt_send(ssh, s->pktout);
5998 s->type = AUTH_TYPE_NONE;
6000 s->we_are_in = FALSE;
6002 s->tried_pubkey_config = FALSE;
6003 s->tried_agent = FALSE;
6004 s->tried_keyb_inter = FALSE;
6005 s->kbd_inter_running = FALSE;
6006 /* Load the pub half of ssh->cfg.keyfile so we notice if it's in Pageant */
6007 if (!filename_is_null(ssh->cfg.keyfile)) {
6009 logeventf(ssh, "Reading private key file \"%.150s\"",
6010 filename_to_str(&ssh->cfg.keyfile));
6011 keytype = key_type(&ssh->cfg.keyfile);
6012 if (keytype == SSH_KEYTYPE_SSH2) {
6014 ssh2_userkey_loadpub(&ssh->cfg.keyfile, NULL,
6015 &s->publickey_bloblen, NULL);
6018 logeventf(ssh, "Unable to use this key file (%s)",
6019 key_type_to_str(keytype));
6020 msgbuf = dupprintf("Unable to use key file \"%.150s\""
6022 filename_to_str(&ssh->cfg.keyfile),
6023 key_type_to_str(keytype));
6024 c_write_str(ssh, msgbuf);
6026 s->publickey_blob = NULL;
6029 s->publickey_blob = NULL;
6033 * Wait for the result of the last authentication request.
6036 crWaitUntilV(pktin);
6037 while (pktin->type == SSH2_MSG_USERAUTH_BANNER) {
6041 * Don't show the banner if we're operating in
6042 * non-verbose non-interactive mode. (It's probably
6043 * a script, which means nobody will read the
6044 * banner _anyway_, and moreover the printing of
6045 * the banner will screw up processing on the
6046 * output of (say) plink.)
6048 if (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE)) {
6049 ssh_pkt_getstring(pktin, &banner, &size);
6051 c_write_untrusted(ssh, banner, size);
6053 crWaitUntilV(pktin);
6055 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
6056 logevent("Access granted");
6057 s->we_are_in = TRUE;
6061 if (s->kbd_inter_running &&
6062 pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
6064 * This is either a further set-of-prompts packet
6065 * in keyboard-interactive authentication, or it's
6066 * the same one and we came back here with `gotit'
6067 * set. In the former case, we must reset the
6068 * curr_prompt variable.
6072 } else if (pktin->type != SSH2_MSG_USERAUTH_FAILURE) {
6073 bombout(("Strange packet received during authentication: type %d",
6081 * OK, we're now sitting on a USERAUTH_FAILURE message, so
6082 * we can look at the string in it and know what we can
6083 * helpfully try next.
6085 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
6088 ssh_pkt_getstring(pktin, &methods, &methlen);
6089 s->kbd_inter_running = FALSE;
6090 if (!ssh2_pkt_getbool(pktin)) {
6092 * We have received an unequivocal Access
6093 * Denied. This can translate to a variety of
6096 * - if we'd just tried "none" authentication,
6097 * it's not worth printing anything at all
6099 * - if we'd just tried a public key _offer_,
6100 * the message should be "Server refused our
6101 * key" (or no message at all if the key
6102 * came from Pageant)
6104 * - if we'd just tried anything else, the
6105 * message really should be "Access denied".
6107 * Additionally, if we'd just tried password
6108 * authentication, we should break out of this
6109 * whole loop so as to go back to the username
6110 * prompt (iff we're configured to allow
6111 * username change attempts).
6113 if (s->type == AUTH_TYPE_NONE) {
6115 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
6116 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
6117 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
6118 c_write_str(ssh, "Server refused our key\r\n");
6119 logevent("Server refused public key");
6120 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
6121 /* server declined keyboard-interactive; ignore */
6123 c_write_str(ssh, "Access denied\r\n");
6124 logevent("Access denied");
6125 if (s->type == AUTH_TYPE_PASSWORD &&
6126 ssh->cfg.change_username) {
6127 /* XXX perhaps we should allow
6128 * keyboard-interactive to do this too? */
6129 s->we_are_in = FALSE;
6134 c_write_str(ssh, "Further authentication required\r\n");
6135 logevent("Further authentication required");
6139 in_commasep_string("publickey", methods, methlen);
6141 in_commasep_string("password", methods, methlen);
6142 s->can_keyb_inter = ssh->cfg.try_ki_auth &&
6143 in_commasep_string("keyboard-interactive", methods, methlen);
6147 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6151 * Most password/passphrase prompts will be
6152 * non-echoing, so we set this to 0 by default.
6153 * Exception is that some keyboard-interactive prompts
6154 * can be echoing, in which case we'll set this to 1.
6158 if (!s->method && s->can_pubkey &&
6159 agent_exists() && !s->tried_agent) {
6161 * Attempt public-key authentication using Pageant.
6166 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6167 ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
6169 s->tried_agent = TRUE;
6171 logevent("Pageant is running. Requesting keys.");
6173 /* Request the keys held by the agent. */
6174 PUT_32BIT(s->request, 1);
6175 s->request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
6176 if (!agent_query(s->request, 5, &r, &s->responselen,
6177 ssh_agent_callback, ssh)) {
6181 bombout(("Unexpected data from server while"
6182 " waiting for agent response"));
6185 } while (pktin || inlen > 0);
6186 r = ssh->agent_response;
6187 s->responselen = ssh->agent_response_len;
6189 s->response = (unsigned char *) r;
6190 if (s->response && s->responselen >= 5 &&
6191 s->response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
6192 s->p = s->response + 5;
6193 s->nkeys = GET_32BIT(s->p);
6197 sprintf(buf, "Pageant has %d SSH2 keys", s->nkeys);
6200 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
6205 sprintf(buf, "Trying Pageant key #%d", s->keyi);
6208 s->pklen = GET_32BIT(s->p);
6210 if (s->publickey_blob &&
6211 s->pklen == s->publickey_bloblen &&
6212 !memcmp(s->p, s->publickey_blob,
6213 s->publickey_bloblen)) {
6214 logevent("This key matches configured key file");
6215 s->tried_pubkey_config = 1;
6217 s->pkblob = (char *)s->p;
6219 s->alglen = GET_32BIT(s->pkblob);
6220 s->alg = s->pkblob + 4;
6221 s->commentlen = GET_32BIT(s->p);
6223 s->commentp = (char *)s->p;
6224 s->p += s->commentlen;
6225 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6226 ssh2_pkt_addstring(s->pktout, s->username);
6227 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
6228 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
6229 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
6230 ssh2_pkt_addstring_start(s->pktout);
6231 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
6232 ssh2_pkt_addstring_start(s->pktout);
6233 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
6234 ssh2_pkt_send(ssh, s->pktout);
6236 crWaitUntilV(pktin);
6237 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
6238 logevent("Key refused");
6242 if (flags & FLAG_VERBOSE) {
6243 c_write_str(ssh, "Authenticating with "
6245 c_write(ssh, s->commentp, s->commentlen);
6246 c_write_str(ssh, "\" from agent\r\n");
6250 * Server is willing to accept the key.
6251 * Construct a SIGN_REQUEST.
6253 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6254 ssh2_pkt_addstring(s->pktout, s->username);
6255 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
6256 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
6257 ssh2_pkt_addbool(s->pktout, TRUE);
6258 ssh2_pkt_addstring_start(s->pktout);
6259 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
6260 ssh2_pkt_addstring_start(s->pktout);
6261 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
6263 s->siglen = s->pktout->length - 5 + 4 + 20;
6264 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
6266 s->len = 1; /* message type */
6267 s->len += 4 + s->pklen; /* key blob */
6268 s->len += 4 + s->siglen; /* data to sign */
6269 s->len += 4; /* flags */
6270 s->agentreq = snewn(4 + s->len, char);
6271 PUT_32BIT(s->agentreq, s->len);
6272 s->q = s->agentreq + 4;
6273 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
6274 PUT_32BIT(s->q, s->pklen);
6276 memcpy(s->q, s->pkblob, s->pklen);
6278 PUT_32BIT(s->q, s->siglen);
6280 /* Now the data to be signed... */
6281 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
6282 PUT_32BIT(s->q, 20);
6285 memcpy(s->q, ssh->v2_session_id, 20);
6287 memcpy(s->q, s->pktout->data + 5,
6288 s->pktout->length - 5);
6289 s->q += s->pktout->length - 5;
6290 /* And finally the (zero) flags word. */
6292 if (!agent_query(s->agentreq, s->len + 4,
6294 ssh_agent_callback, ssh)) {
6298 bombout(("Unexpected data from server"
6299 " while waiting for agent"
6303 } while (pktin || inlen > 0);
6304 vret = ssh->agent_response;
6305 s->retlen = ssh->agent_response_len;
6310 if (s->ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
6311 logevent("Sending Pageant's response");
6312 ssh2_add_sigblob(ssh, s->pktout,
6313 s->pkblob, s->pklen,
6315 GET_32BIT(s->ret + 5));
6316 ssh2_pkt_send(ssh, s->pktout);
6321 ("Pageant failed to answer challenge");
6332 if (!s->method && s->can_pubkey && s->publickey_blob
6333 && !s->tried_pubkey_config) {
6334 unsigned char *pub_blob;
6335 char *algorithm, *comment;
6338 s->tried_pubkey_config = TRUE;
6340 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6341 ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
6344 * Try the public key supplied in the configuration.
6346 * First, offer the public blob to see if the server is
6347 * willing to accept it.
6350 (unsigned char *)ssh2_userkey_loadpub(&ssh->cfg.keyfile,
6355 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6356 ssh2_pkt_addstring(s->pktout, s->username);
6357 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
6358 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
6359 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
6360 ssh2_pkt_addstring(s->pktout, algorithm);
6361 ssh2_pkt_addstring_start(s->pktout);
6362 ssh2_pkt_addstring_data(s->pktout, (char *)pub_blob,
6364 ssh2_pkt_send(ssh, s->pktout);
6365 logevent("Offered public key");
6367 crWaitUntilV(pktin);
6368 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
6370 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
6371 continue; /* key refused; give up on it */
6374 logevent("Offer of public key accepted");
6376 * Actually attempt a serious authentication using
6379 if (ssh2_userkey_encrypted(&ssh->cfg.keyfile, &comment)) {
6380 sprintf(s->pwprompt,
6381 "Passphrase for key \"%.100s\": ",
6387 if (flags & FLAG_VERBOSE) {
6388 c_write_str(ssh, "Authenticating with public key \"");
6389 c_write_str(ssh, comment);
6390 c_write_str(ssh, "\"\r\n");
6392 s->method = AUTH_PUBLICKEY_FILE;
6396 if (!s->method && s->can_keyb_inter && !s->tried_keyb_inter) {
6397 s->method = AUTH_KEYBOARD_INTERACTIVE;
6398 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
6399 s->tried_keyb_inter = TRUE;
6401 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6402 ssh->pkt_ctx |= SSH2_PKTCTX_KBDINTER;
6404 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6405 ssh2_pkt_addstring(s->pktout, s->username);
6406 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
6407 ssh2_pkt_addstring(s->pktout, "keyboard-interactive"); /* method */
6408 ssh2_pkt_addstring(s->pktout, ""); /* lang */
6409 ssh2_pkt_addstring(s->pktout, "");
6410 ssh2_pkt_send(ssh, s->pktout);
6412 crWaitUntilV(pktin);
6413 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
6414 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE)
6416 logevent("Keyboard-interactive authentication refused");
6417 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
6421 s->kbd_inter_running = TRUE;
6425 if (s->kbd_inter_running) {
6426 s->method = AUTH_KEYBOARD_INTERACTIVE;
6427 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
6428 s->tried_keyb_inter = TRUE;
6430 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6431 ssh->pkt_ctx |= SSH2_PKTCTX_KBDINTER;
6433 if (s->curr_prompt == 0) {
6435 * We've got a fresh USERAUTH_INFO_REQUEST.
6436 * Display header data, and start going through
6439 char *name, *inst, *lang;
6440 int name_len, inst_len, lang_len;
6442 ssh_pkt_getstring(pktin, &name, &name_len);
6443 ssh_pkt_getstring(pktin, &inst, &inst_len);
6444 ssh_pkt_getstring(pktin, &lang, &lang_len);
6446 c_write_untrusted(ssh, name, name_len);
6447 c_write_str(ssh, "\r\n");
6450 c_write_untrusted(ssh, inst, inst_len);
6451 c_write_str(ssh, "\r\n");
6453 s->num_prompts = ssh_pkt_getuint32(pktin);
6457 * If there are prompts remaining in the packet,
6458 * display one and get a response.
6460 if (s->curr_prompt < s->num_prompts) {
6464 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
6465 if (prompt_len > 0) {
6466 static const char trunc[] = "<prompt truncated>: ";
6467 static const int prlen = sizeof(s->pwprompt) -
6469 if (prompt_len > prlen) {
6470 memcpy(s->pwprompt, prompt, prlen);
6471 strcpy(s->pwprompt + prlen, trunc);
6473 memcpy(s->pwprompt, prompt, prompt_len);
6474 s->pwprompt[prompt_len] = '\0';
6478 "<server failed to send prompt>: ");
6480 s->echo = ssh2_pkt_getbool(pktin);
6486 if (!s->method && s->can_passwd) {
6487 s->method = AUTH_PASSWORD;
6488 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6489 ssh->pkt_ctx |= SSH2_PKTCTX_PASSWORD;
6490 sprintf(s->pwprompt, "%.90s@%.90s's password: ", s->username,
6497 if (!ssh_get_line(s->pwprompt, s->password,
6498 sizeof(s->password), TRUE)) {
6500 * get_line failed to get a password (for
6501 * example because one was supplied on the
6502 * command line which has already failed to
6505 s->pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
6506 ssh2_pkt_adduint32(s->pktout,SSH2_DISCONNECT_BY_APPLICATION);
6507 ssh2_pkt_addstring(s->pktout, "No more passwords available"
6509 ssh2_pkt_addstring(s->pktout, "en"); /* language tag */
6510 ssh2_pkt_send_noqueue(ssh, s->pktout);
6511 logevent("Unable to authenticate");
6512 connection_fatal(ssh->frontend,
6513 "Unable to authenticate");
6514 ssh_closing((Plug)ssh, NULL, 0, 0);
6518 int ret; /* need not be saved across crReturn */
6519 c_write_untrusted(ssh, s->pwprompt, strlen(s->pwprompt));
6522 setup_userpass_input(ssh, s->password,
6523 sizeof(s->password), s->echo);
6525 crWaitUntilV(!pktin);
6526 ret = process_userpass_input(ssh, in, inlen);
6530 c_write_str(ssh, "\r\n");
6534 if (s->method == AUTH_PUBLICKEY_FILE) {
6536 * We have our passphrase. Now try the actual authentication.
6538 struct ssh2_userkey *key;
6539 const char *error = NULL;
6541 key = ssh2_load_userkey(&ssh->cfg.keyfile, s->password,
6543 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
6544 if (key == SSH2_WRONG_PASSPHRASE) {
6545 c_write_str(ssh, "Wrong passphrase\r\n");
6546 s->tried_pubkey_config = FALSE;
6548 c_write_str(ssh, "Unable to load private key (");
6549 c_write_str(ssh, error);
6550 c_write_str(ssh, ")\r\n");
6551 s->tried_pubkey_config = TRUE;
6553 /* Send a spurious AUTH_NONE to return to the top. */
6554 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6555 ssh2_pkt_addstring(s->pktout, s->username);
6556 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
6557 ssh2_pkt_addstring(s->pktout, "none"); /* method */
6558 ssh2_pkt_send(ssh, s->pktout);
6559 s->type = AUTH_TYPE_NONE;
6561 unsigned char *pkblob, *sigblob, *sigdata;
6562 int pkblob_len, sigblob_len, sigdata_len;
6566 * We have loaded the private key and the server
6567 * has announced that it's willing to accept it.
6568 * Hallelujah. Generate a signature and send it.
6570 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6571 ssh2_pkt_addstring(s->pktout, s->username);
6572 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
6573 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
6574 ssh2_pkt_addbool(s->pktout, TRUE);
6575 ssh2_pkt_addstring(s->pktout, key->alg->name);
6576 pkblob = key->alg->public_blob(key->data, &pkblob_len);
6577 ssh2_pkt_addstring_start(s->pktout);
6578 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob, pkblob_len);
6581 * The data to be signed is:
6585 * followed by everything so far placed in the
6588 sigdata_len = s->pktout->length - 5 + 4 + 20;
6589 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
6591 sigdata = snewn(sigdata_len, unsigned char);
6593 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
6594 PUT_32BIT(sigdata+p, 20);
6597 memcpy(sigdata+p, ssh->v2_session_id, 20); p += 20;
6598 memcpy(sigdata+p, s->pktout->data + 5,
6599 s->pktout->length - 5);
6600 p += s->pktout->length - 5;
6601 assert(p == sigdata_len);
6602 sigblob = key->alg->sign(key->data, (char *)sigdata,
6603 sigdata_len, &sigblob_len);
6604 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
6605 sigblob, sigblob_len);
6610 ssh2_pkt_send(ssh, s->pktout);
6611 s->type = AUTH_TYPE_PUBLICKEY;
6612 key->alg->freekey(key->data);
6614 } else if (s->method == AUTH_PASSWORD) {
6616 * We send the password packet lumped tightly together with
6617 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
6618 * string long enough to make the total length of the two
6619 * packets constant. This should ensure that a passive
6620 * listener doing traffic analyis can't work out the length
6623 * For this to work, we need an assumption about the
6624 * maximum length of the password packet. I think 256 is
6625 * pretty conservative. Anyone using a password longer than
6626 * that probably doesn't have much to worry about from
6627 * people who find out how long their password is!
6629 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6630 ssh2_pkt_addstring(s->pktout, s->username);
6631 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
6632 ssh2_pkt_addstring(s->pktout, "password");
6633 ssh2_pkt_addbool(s->pktout, FALSE);
6634 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
6635 ssh2_pkt_addstring(s->pktout, s->password);
6636 memset(s->password, 0, sizeof(s->password));
6637 end_log_omission(ssh, s->pktout);
6638 ssh2_pkt_defer(ssh, s->pktout);
6640 * We'll include a string that's an exact multiple of the
6641 * cipher block size. If the cipher is NULL for some
6642 * reason, we don't do this trick at all because we gain
6645 if (ssh->cscipher) {
6648 stringlen = (256 - ssh->deferred_len);
6649 stringlen += ssh->cscipher->blksize - 1;
6650 stringlen -= (stringlen % ssh->cscipher->blksize);
6653 * Temporarily disable actual compression,
6654 * so we can guarantee to get this string
6655 * exactly the length we want it. The
6656 * compression-disabling routine should
6657 * return an integer indicating how many
6658 * bytes we should adjust our string length
6662 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
6664 s->pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
6665 ssh2_pkt_addstring_start(s->pktout);
6666 for (i = 0; i < stringlen; i++) {
6667 char c = (char) random_byte();
6668 ssh2_pkt_addstring_data(s->pktout, &c, 1);
6670 ssh2_pkt_defer(ssh, s->pktout);
6672 ssh_pkt_defersend(ssh);
6673 logevent("Sent password");
6674 s->type = AUTH_TYPE_PASSWORD;
6675 } else if (s->method == AUTH_KEYBOARD_INTERACTIVE) {
6676 if (s->curr_prompt == 0) {
6677 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
6678 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
6680 if (s->need_pw) { /* only add pw if we just got one! */
6681 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
6682 ssh2_pkt_addstring(s->pktout, s->password);
6683 memset(s->password, 0, sizeof(s->password));
6684 end_log_omission(ssh, s->pktout);
6687 if (s->curr_prompt >= s->num_prompts) {
6688 ssh2_pkt_send(ssh, s->pktout);
6691 * If there are prompts remaining, we set
6692 * `gotit' so that we won't attempt to get
6693 * another packet. Then we go back round the
6694 * loop and will end up retrieving another
6695 * prompt out of the existing packet. Funky or
6700 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
6702 c_write_str(ssh, "No supported authentication methods"
6703 " left to try!\r\n");
6704 logevent("No supported authentications offered."
6706 s->pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
6707 ssh2_pkt_adduint32(s->pktout, SSH2_DISCONNECT_BY_APPLICATION);
6708 ssh2_pkt_addstring(s->pktout, "No supported authentication"
6709 " methods available");
6710 ssh2_pkt_addstring(s->pktout, "en"); /* language tag */
6711 ssh2_pkt_send_noqueue(ssh, s->pktout);
6712 ssh_closing((Plug)ssh, NULL, 0, 0);
6716 } while (!s->we_are_in);
6719 * Now we're authenticated for the connection protocol. The
6720 * connection protocol will automatically have started at this
6721 * point; there's no need to send SERVICE_REQUEST.
6724 ssh->channels = newtree234(ssh_channelcmp);
6727 * Set up handlers for some connection protocol messages, so we
6728 * don't have to handle them repeatedly in this coroutine.
6730 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
6731 ssh2_msg_channel_window_adjust;
6732 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
6733 ssh2_msg_global_request;
6736 * Create the main session channel.
6738 if (!ssh->cfg.ssh_no_shell) {
6739 ssh->mainchan = snew(struct ssh_channel);
6740 ssh->mainchan->ssh = ssh;
6741 ssh->mainchan->localid = alloc_channel_id(ssh);
6742 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
6743 ssh2_pkt_addstring(s->pktout, "session");
6744 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
6745 ssh->mainchan->v.v2.locwindow = OUR_V2_WINSIZE;
6746 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
6747 ssh2_pkt_adduint32(s->pktout, 0x4000UL); /* our max pkt size */
6748 ssh2_pkt_send(ssh, s->pktout);
6749 crWaitUntilV(pktin);
6750 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
6751 bombout(("Server refused to open a session"));
6753 /* FIXME: error data comes back in FAILURE packet */
6755 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
6756 bombout(("Server's channel confirmation cited wrong channel"));
6759 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
6760 ssh->mainchan->type = CHAN_MAINSESSION;
6761 ssh->mainchan->closes = 0;
6762 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
6763 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
6764 bufchain_init(&ssh->mainchan->v.v2.outbuffer);
6765 add234(ssh->channels, ssh->mainchan);
6766 update_specials_menu(ssh->frontend);
6767 logevent("Opened channel for session");
6769 ssh->mainchan = NULL;
6772 * Now we have a channel, make dispatch table entries for
6773 * general channel-based messages.
6775 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
6776 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
6777 ssh2_msg_channel_data;
6778 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
6779 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
6780 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
6781 ssh2_msg_channel_open_confirmation;
6782 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
6783 ssh2_msg_channel_open_failure;
6784 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
6785 ssh2_msg_channel_request;
6786 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
6787 ssh2_msg_channel_open;
6790 * Potentially enable X11 forwarding.
6792 if (ssh->mainchan && ssh->cfg.x11_forward) {
6793 char proto[20], data[64];
6794 logevent("Requesting X11 forwarding");
6795 ssh->x11auth = x11_invent_auth(proto, sizeof(proto),
6796 data, sizeof(data), ssh->cfg.x11_auth);
6797 x11_get_real_auth(ssh->x11auth, ssh->cfg.x11_display);
6798 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6799 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
6800 ssh2_pkt_addstring(s->pktout, "x11-req");
6801 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
6802 ssh2_pkt_addbool(s->pktout, 0); /* many connections */
6803 ssh2_pkt_addstring(s->pktout, proto);
6804 ssh2_pkt_addstring(s->pktout, data);
6805 ssh2_pkt_adduint32(s->pktout, x11_get_screen_number(ssh->cfg.x11_display));
6806 ssh2_pkt_send(ssh, s->pktout);
6808 crWaitUntilV(pktin);
6810 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
6811 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
6812 bombout(("Unexpected response to X11 forwarding request:"
6813 " packet type %d", pktin->type));
6816 logevent("X11 forwarding refused");
6818 logevent("X11 forwarding enabled");
6819 ssh->X11_fwd_enabled = TRUE;
6824 * Enable port forwardings.
6826 ssh_setup_portfwd(ssh, &ssh->cfg);
6829 * Potentially enable agent forwarding.
6831 if (ssh->mainchan && ssh->cfg.agentfwd && agent_exists()) {
6832 logevent("Requesting OpenSSH-style agent forwarding");
6833 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6834 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
6835 ssh2_pkt_addstring(s->pktout, "auth-agent-req@openssh.com");
6836 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
6837 ssh2_pkt_send(ssh, s->pktout);
6839 crWaitUntilV(pktin);
6841 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
6842 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
6843 bombout(("Unexpected response to agent forwarding request:"
6844 " packet type %d", pktin->type));
6847 logevent("Agent forwarding refused");
6849 logevent("Agent forwarding enabled");
6850 ssh->agentfwd_enabled = TRUE;
6855 * Now allocate a pty for the session.
6857 if (ssh->mainchan && !ssh->cfg.nopty) {
6858 /* Unpick the terminal-speed string. */
6859 /* XXX perhaps we should allow no speeds to be sent. */
6860 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
6861 sscanf(ssh->cfg.termspeed, "%d,%d", &ssh->ospeed, &ssh->ispeed);
6862 /* Build the pty request. */
6863 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6864 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
6865 ssh2_pkt_addstring(s->pktout, "pty-req");
6866 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
6867 ssh2_pkt_addstring(s->pktout, ssh->cfg.termtype);
6868 ssh2_pkt_adduint32(s->pktout, ssh->term_width);
6869 ssh2_pkt_adduint32(s->pktout, ssh->term_height);
6870 ssh2_pkt_adduint32(s->pktout, 0); /* pixel width */
6871 ssh2_pkt_adduint32(s->pktout, 0); /* pixel height */
6872 ssh2_pkt_addstring_start(s->pktout);
6873 ssh2_pkt_addbyte(s->pktout, 128); /* TTY_OP_ISPEED */
6874 ssh2_pkt_adduint32(s->pktout, ssh->ispeed);
6875 ssh2_pkt_addbyte(s->pktout, 129); /* TTY_OP_OSPEED */
6876 ssh2_pkt_adduint32(s->pktout, ssh->ospeed);
6877 ssh2_pkt_addstring_data(s->pktout, "\0", 1); /* TTY_OP_END */
6878 ssh2_pkt_send(ssh, s->pktout);
6879 ssh->state = SSH_STATE_INTERMED;
6881 crWaitUntilV(pktin);
6883 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
6884 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
6885 bombout(("Unexpected response to pty request:"
6886 " packet type %d", pktin->type));
6889 c_write_str(ssh, "Server refused to allocate pty\r\n");
6890 ssh->editing = ssh->echoing = 1;
6892 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
6893 ssh->ospeed, ssh->ispeed);
6896 ssh->editing = ssh->echoing = 1;
6900 * Send environment variables.
6902 * Simplest thing here is to send all the requests at once, and
6903 * then wait for a whole bunch of successes or failures.
6905 if (ssh->mainchan && *ssh->cfg.environmt) {
6906 char *e = ssh->cfg.environmt;
6907 char *var, *varend, *val;
6913 while (*e && *e != '\t') e++;
6915 if (*e == '\t') e++;
6920 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6921 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
6922 ssh2_pkt_addstring(s->pktout, "env");
6923 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
6924 ssh2_pkt_addstring_start(s->pktout);
6925 ssh2_pkt_addstring_data(s->pktout, var, varend-var);
6926 ssh2_pkt_addstring(s->pktout, val);
6927 ssh2_pkt_send(ssh, s->pktout);
6932 logeventf(ssh, "Sent %d environment variables", s->num_env);
6935 s->env_left = s->num_env;
6937 while (s->env_left > 0) {
6938 crWaitUntilV(pktin);
6940 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
6941 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
6942 bombout(("Unexpected response to environment request:"
6943 " packet type %d", pktin->type));
6953 if (s->env_ok == s->num_env) {
6954 logevent("All environment variables successfully set");
6955 } else if (s->env_ok == 0) {
6956 logevent("All environment variables refused");
6957 c_write_str(ssh, "Server refused to set environment variables\r\n");
6959 logeventf(ssh, "%d environment variables refused",
6960 s->num_env - s->env_ok);
6961 c_write_str(ssh, "Server refused to set all environment variables\r\n");
6966 * Start a shell or a remote command. We may have to attempt
6967 * this twice if the config data has provided a second choice
6970 if (ssh->mainchan) while (1) {
6974 if (ssh->fallback_cmd) {
6975 subsys = ssh->cfg.ssh_subsys2;
6976 cmd = ssh->cfg.remote_cmd_ptr2;
6978 subsys = ssh->cfg.ssh_subsys;
6979 cmd = ssh->cfg.remote_cmd_ptr;
6982 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6983 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
6985 ssh2_pkt_addstring(s->pktout, "subsystem");
6986 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
6987 ssh2_pkt_addstring(s->pktout, cmd);
6989 ssh2_pkt_addstring(s->pktout, "exec");
6990 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
6991 ssh2_pkt_addstring(s->pktout, cmd);
6993 ssh2_pkt_addstring(s->pktout, "shell");
6994 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
6996 ssh2_pkt_send(ssh, s->pktout);
6998 crWaitUntilV(pktin);
7000 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
7001 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
7002 bombout(("Unexpected response to shell/command request:"
7003 " packet type %d", pktin->type));
7007 * We failed to start the command. If this is the
7008 * fallback command, we really are finished; if it's
7009 * not, and if the fallback command exists, try falling
7010 * back to it before complaining.
7012 if (!ssh->fallback_cmd && ssh->cfg.remote_cmd_ptr2 != NULL) {
7013 logevent("Primary command failed; attempting fallback");
7014 ssh->fallback_cmd = TRUE;
7017 bombout(("Server refused to start a shell/command"));
7020 logevent("Started a shell/command");
7025 ssh->state = SSH_STATE_SESSION;
7026 if (ssh->size_needed)
7027 ssh_size(ssh, ssh->term_width, ssh->term_height);
7028 if (ssh->eof_needed)
7029 ssh_special(ssh, TS_EOF);
7035 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
7040 s->try_send = FALSE;
7044 * _All_ the connection-layer packets we expect to
7045 * receive are now handled by the dispatch table.
7046 * Anything that reaches here must be bogus.
7049 bombout(("Strange packet received: type %d", pktin->type));
7051 } else if (ssh->mainchan) {
7053 * We have spare data. Add it to the channel buffer.
7055 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
7060 struct ssh_channel *c;
7062 * Try to send data on all channels if we can.
7064 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
7067 continue; /* don't send on closing channels */
7068 bufsize = ssh2_try_send(c);
7071 case CHAN_MAINSESSION:
7072 /* stdin need not receive an unthrottle
7073 * notification since it will be polled */
7076 x11_unthrottle(c->u.x11.s);
7079 /* agent sockets are request/response and need no
7080 * buffer management */
7083 pfd_unthrottle(c->u.pfd.s);
7095 * Handlers for SSH2 messages that might arrive at any moment.
7097 void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
7099 /* log reason code in disconnect message */
7101 int nowlen, reason, msglen;
7103 reason = ssh_pkt_getuint32(pktin);
7104 ssh_pkt_getstring(pktin, &msg, &msglen);
7106 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
7107 buf = dupprintf("Received disconnect message (%s)",
7108 ssh2_disconnect_reasons[reason]);
7110 buf = dupprintf("Received disconnect message (unknown"
7111 " type %d)", reason);
7115 buf = dupprintf("Disconnection message text: %n%.*s",
7116 &nowlen, msglen, msg);
7118 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
7120 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
7121 ssh2_disconnect_reasons[reason] : "unknown",
7126 void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
7128 /* log the debug message */
7133 /* XXX maybe we should actually take notice of this */
7134 always_display = ssh2_pkt_getbool(pktin);
7135 ssh_pkt_getstring(pktin, &msg, &msglen);
7137 buf = dupprintf("Remote debug message: %.*s", msglen, msg);
7142 void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
7144 struct Packet *pktout;
7145 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
7146 ssh2_pkt_adduint32(pktout, pktin->sequence);
7148 * UNIMPLEMENTED messages MUST appear in the same order as the
7149 * messages they respond to. Hence, never queue them.
7151 ssh2_pkt_send_noqueue(ssh, pktout);
7155 * Handle the top-level SSH2 protocol.
7157 static void ssh2_protocol_setup(Ssh ssh)
7162 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
7164 for (i = 0; i < 256; i++)
7165 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
7168 * Any message we actually understand, we set to NULL so that
7169 * the coroutines will get it.
7171 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = NULL;
7172 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = NULL;
7173 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = NULL;
7174 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = NULL;
7175 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = NULL;
7176 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = NULL;
7177 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = NULL;
7178 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = NULL; duplicate case value */
7179 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = NULL; duplicate case value */
7180 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = NULL;
7181 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = NULL;
7182 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = NULL;
7183 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = NULL;
7184 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = NULL;
7185 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
7186 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = NULL;
7187 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = NULL; duplicate case value */
7188 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = NULL; duplicate case value */
7189 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = NULL;
7190 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = NULL;
7191 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = NULL;
7192 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = NULL;
7193 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = NULL;
7194 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = NULL;
7195 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = NULL;
7196 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = NULL;
7197 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = NULL;
7198 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = NULL;
7199 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = NULL;
7200 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = NULL;
7201 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = NULL;
7202 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = NULL;
7203 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = NULL;
7206 * These special message types we install handlers for.
7208 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
7209 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with ssh1 */
7210 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
7213 static void ssh2_timer(void *ctx, long now)
7217 if (!ssh->kex_in_progress && ssh->cfg.ssh_rekey_time != 0 &&
7218 now - ssh->next_rekey >= 0) {
7219 do_ssh2_transport(ssh, "Initiating key re-exchange (timeout)",
7224 static void ssh2_protocol(Ssh ssh, unsigned char *in, int inlen,
7225 struct Packet *pktin)
7227 if (ssh->state == SSH_STATE_CLOSED)
7231 ssh->incoming_data_size += pktin->encrypted_len;
7232 if (!ssh->kex_in_progress &&
7233 ssh->max_data_size != 0 &&
7234 ssh->incoming_data_size > ssh->max_data_size)
7235 do_ssh2_transport(ssh, "Initiating key re-exchange "
7236 "(too much data received)", -1, NULL);
7239 if (pktin && ssh->packet_dispatch[pktin->type]) {
7240 ssh->packet_dispatch[pktin->type](ssh, pktin);
7244 if (!ssh->protocol_initial_phase_done ||
7245 (pktin && pktin->type >= 20 && pktin->type < 50)) {
7246 if (do_ssh2_transport(ssh, in, inlen, pktin) &&
7247 !ssh->protocol_initial_phase_done) {
7248 ssh->protocol_initial_phase_done = TRUE;
7250 * Allow authconn to initialise itself.
7252 do_ssh2_authconn(ssh, NULL, 0, NULL);
7255 do_ssh2_authconn(ssh, in, inlen, pktin);
7260 * Called to set up the connection.
7262 * Returns an error message, or NULL on success.
7264 static const char *ssh_init(void *frontend_handle, void **backend_handle,
7266 char *host, int port, char **realhost, int nodelay,
7272 ssh = snew(struct ssh_tag);
7273 ssh->cfg = *cfg; /* STRUCTURE COPY */
7274 ssh->version = 0; /* when not ready yet */
7277 ssh->v1_cipher_ctx = NULL;
7278 ssh->crcda_ctx = NULL;
7279 ssh->cscipher = NULL;
7280 ssh->cs_cipher_ctx = NULL;
7281 ssh->sccipher = NULL;
7282 ssh->sc_cipher_ctx = NULL;
7284 ssh->cs_mac_ctx = NULL;
7286 ssh->sc_mac_ctx = NULL;
7288 ssh->cs_comp_ctx = NULL;
7290 ssh->sc_comp_ctx = NULL;
7292 ssh->kex_ctx = NULL;
7293 ssh->hostkey = NULL;
7295 ssh->state = SSH_STATE_PREPACKET;
7296 ssh->size_needed = FALSE;
7297 ssh->eof_needed = FALSE;
7300 ssh->deferred_send_data = NULL;
7301 ssh->deferred_len = 0;
7302 ssh->deferred_size = 0;
7303 ssh->fallback_cmd = 0;
7305 ssh->x11auth = NULL;
7306 ssh->v1_compressing = FALSE;
7307 ssh->v2_outgoing_sequence = 0;
7308 ssh->ssh1_rdpkt_crstate = 0;
7309 ssh->ssh2_rdpkt_crstate = 0;
7310 ssh->do_ssh_init_crstate = 0;
7311 ssh->ssh_gotdata_crstate = 0;
7312 ssh->do_ssh1_connection_crstate = 0;
7313 ssh->do_ssh1_login_crstate = 0;
7314 ssh->do_ssh2_transport_crstate = 0;
7315 ssh->do_ssh2_authconn_crstate = 0;
7316 ssh->do_ssh_init_state = NULL;
7317 ssh->do_ssh1_login_state = NULL;
7318 ssh->do_ssh2_transport_state = NULL;
7319 ssh->do_ssh2_authconn_state = NULL;
7320 ssh->mainchan = NULL;
7321 ssh->throttled_all = 0;
7322 ssh->v1_stdout_throttling = 0;
7324 ssh->queuelen = ssh->queuesize = 0;
7325 ssh->queueing = FALSE;
7326 ssh->qhead = ssh->qtail = NULL;
7328 *backend_handle = ssh;
7331 if (crypto_startup() == 0)
7332 return "Microsoft high encryption pack not installed!";
7335 ssh->frontend = frontend_handle;
7336 ssh->term_width = ssh->cfg.width;
7337 ssh->term_height = ssh->cfg.height;
7339 ssh->channels = NULL;
7340 ssh->rportfwds = NULL;
7341 ssh->portfwds = NULL;
7346 ssh->v1_throttle_count = 0;
7347 ssh->overall_bufsize = 0;
7348 ssh->fallback_cmd = 0;
7350 ssh->protocol = NULL;
7352 ssh->protocol_initial_phase_done = FALSE;
7356 ssh->incoming_data_size = ssh->outgoing_data_size =
7357 ssh->deferred_data_size = 0L;
7358 ssh->max_data_size = parse_blocksize(ssh->cfg.ssh_rekey_data);
7359 ssh->kex_in_progress = FALSE;
7361 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
7370 static void ssh_free(void *handle)
7372 Ssh ssh = (Ssh) handle;
7373 struct ssh_channel *c;
7374 struct ssh_rportfwd *pf;
7376 if (ssh->v1_cipher_ctx)
7377 ssh->cipher->free_context(ssh->v1_cipher_ctx);
7378 if (ssh->cs_cipher_ctx)
7379 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
7380 if (ssh->sc_cipher_ctx)
7381 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
7382 if (ssh->cs_mac_ctx)
7383 ssh->csmac->free_context(ssh->cs_mac_ctx);
7384 if (ssh->sc_mac_ctx)
7385 ssh->scmac->free_context(ssh->sc_mac_ctx);
7386 if (ssh->cs_comp_ctx) {
7388 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
7390 zlib_compress_cleanup(ssh->cs_comp_ctx);
7392 if (ssh->sc_comp_ctx) {
7394 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
7396 zlib_decompress_cleanup(ssh->sc_comp_ctx);
7399 dh_cleanup(ssh->kex_ctx);
7400 sfree(ssh->savedhost);
7402 while (ssh->queuelen-- > 0)
7403 ssh_free_packet(ssh->queue[ssh->queuelen]);
7406 while (ssh->qhead) {
7407 struct queued_handler *qh = ssh->qhead;
7408 ssh->qhead = qh->next;
7411 ssh->qhead = ssh->qtail = NULL;
7413 if (ssh->channels) {
7414 while ((c = delpos234(ssh->channels, 0)) != NULL) {
7417 if (c->u.x11.s != NULL)
7418 x11_close(c->u.x11.s);
7421 if (c->u.pfd.s != NULL)
7422 pfd_close(c->u.pfd.s);
7427 freetree234(ssh->channels);
7428 ssh->channels = NULL;
7431 if (ssh->rportfwds) {
7432 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
7434 freetree234(ssh->rportfwds);
7435 ssh->rportfwds = NULL;
7437 sfree(ssh->deferred_send_data);
7439 x11_free_auth(ssh->x11auth);
7440 sfree(ssh->do_ssh_init_state);
7441 sfree(ssh->do_ssh1_login_state);
7442 sfree(ssh->do_ssh2_transport_state);
7443 sfree(ssh->do_ssh2_authconn_state);
7444 if (ssh->crcda_ctx) {
7445 crcda_free_context(ssh->crcda_ctx);
7446 ssh->crcda_ctx = NULL;
7450 expire_timer_context(ssh);
7452 pinger_free(ssh->pinger);
7459 * Reconfigure the SSH backend.
7461 static void ssh_reconfig(void *handle, Config *cfg)
7463 Ssh ssh = (Ssh) handle;
7464 char *rekeying = NULL;
7465 unsigned long old_max_data_size;
7467 pinger_reconfig(ssh->pinger, &ssh->cfg, cfg);
7468 ssh_setup_portfwd(ssh, cfg);
7470 if (ssh->cfg.ssh_rekey_time != cfg->ssh_rekey_time &&
7471 cfg->ssh_rekey_time != 0) {
7472 long new_next = ssh->last_rekey + cfg->ssh_rekey_time*60*TICKSPERSEC;
7473 long now = GETTICKCOUNT();
7475 if (new_next - now < 0) {
7476 rekeying = "Initiating key re-exchange (timeout shortened)";
7478 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
7482 old_max_data_size = ssh->max_data_size;
7483 ssh->max_data_size = parse_blocksize(cfg->ssh_rekey_data);
7484 if (old_max_data_size != ssh->max_data_size &&
7485 ssh->max_data_size != 0) {
7486 if (ssh->outgoing_data_size > ssh->max_data_size ||
7487 ssh->incoming_data_size > ssh->max_data_size)
7488 rekeying = "Initiating key re-exchange (data limit lowered)";
7491 if (rekeying && !ssh->kex_in_progress) {
7492 do_ssh2_transport(ssh, rekeying, -1, NULL);
7495 ssh->cfg = *cfg; /* STRUCTURE COPY */
7499 * Called to send data down the Telnet connection.
7501 static int ssh_send(void *handle, char *buf, int len)
7503 Ssh ssh = (Ssh) handle;
7505 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
7508 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
7510 return ssh_sendbuffer(ssh);
7514 * Called to query the current amount of buffered stdin data.
7516 static int ssh_sendbuffer(void *handle)
7518 Ssh ssh = (Ssh) handle;
7521 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
7525 * If the SSH socket itself has backed up, add the total backup
7526 * size on that to any individual buffer on the stdin channel.
7529 if (ssh->throttled_all)
7530 override_value = ssh->overall_bufsize;
7532 if (ssh->version == 1) {
7533 return override_value;
7534 } else if (ssh->version == 2) {
7535 if (!ssh->mainchan || ssh->mainchan->closes > 0)
7536 return override_value;
7538 return (override_value +
7539 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
7546 * Called to set the size of the window from SSH's POV.
7548 static void ssh_size(void *handle, int width, int height)
7550 Ssh ssh = (Ssh) handle;
7551 struct Packet *pktout;
7553 ssh->term_width = width;
7554 ssh->term_height = height;
7556 switch (ssh->state) {
7557 case SSH_STATE_BEFORE_SIZE:
7558 case SSH_STATE_PREPACKET:
7559 case SSH_STATE_CLOSED:
7560 break; /* do nothing */
7561 case SSH_STATE_INTERMED:
7562 ssh->size_needed = TRUE; /* buffer for later */
7564 case SSH_STATE_SESSION:
7565 if (!ssh->cfg.nopty) {
7566 if (ssh->version == 1) {
7567 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
7568 PKT_INT, ssh->term_height,
7569 PKT_INT, ssh->term_width,
7570 PKT_INT, 0, PKT_INT, 0, PKT_END);
7571 } else if (ssh->mainchan) {
7572 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7573 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
7574 ssh2_pkt_addstring(pktout, "window-change");
7575 ssh2_pkt_addbool(pktout, 0);
7576 ssh2_pkt_adduint32(pktout, ssh->term_width);
7577 ssh2_pkt_adduint32(pktout, ssh->term_height);
7578 ssh2_pkt_adduint32(pktout, 0);
7579 ssh2_pkt_adduint32(pktout, 0);
7580 ssh2_pkt_send(ssh, pktout);
7588 * Return a list of the special codes that make sense in this
7591 static const struct telnet_special *ssh_get_specials(void *handle)
7593 static const struct telnet_special ssh1_ignore_special[] = {
7594 {"IGNORE message", TS_NOP}
7596 static const struct telnet_special ssh2_transport_specials[] = {
7597 {"IGNORE message", TS_NOP},
7598 {"Repeat key exchange", TS_REKEY},
7600 static const struct telnet_special ssh2_session_specials[] = {
7603 /* These are the signal names defined by draft-ietf-secsh-connect-23.
7604 * They include all the ISO C signals, but are a subset of the POSIX
7605 * required signals. */
7606 {"SIGINT (Interrupt)", TS_SIGINT},
7607 {"SIGTERM (Terminate)", TS_SIGTERM},
7608 {"SIGKILL (Kill)", TS_SIGKILL},
7609 {"SIGQUIT (Quit)", TS_SIGQUIT},
7610 {"SIGHUP (Hangup)", TS_SIGHUP},
7611 {"More signals", TS_SUBMENU},
7612 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
7613 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
7614 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
7615 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
7618 static const struct telnet_special specials_end[] = {
7621 /* XXX review this length for any changes: */
7622 static struct telnet_special ssh_specials[lenof(ssh2_transport_specials) +
7623 lenof(ssh2_session_specials) +
7624 lenof(specials_end)];
7625 Ssh ssh = (Ssh) handle;
7627 #define ADD_SPECIALS(name) \
7629 assert((i + lenof(name)) <= lenof(ssh_specials)); \
7630 memcpy(&ssh_specials[i], name, sizeof name); \
7634 if (ssh->version == 1) {
7635 /* Don't bother offering IGNORE if we've decided the remote
7636 * won't cope with it, since we wouldn't bother sending it if
7638 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
7639 ADD_SPECIALS(ssh1_ignore_special);
7640 } else if (ssh->version == 2) {
7641 ADD_SPECIALS(ssh2_transport_specials);
7643 ADD_SPECIALS(ssh2_session_specials);
7644 } /* else we're not ready yet */
7647 ADD_SPECIALS(specials_end);
7648 return ssh_specials;
7656 * Send Telnet special codes. TS_EOF is useful for `plink', so you
7657 * can send an EOF and collect resulting output (e.g. `plink
7660 static void ssh_special(void *handle, Telnet_Special code)
7662 Ssh ssh = (Ssh) handle;
7663 struct Packet *pktout;
7665 if (code == TS_EOF) {
7666 if (ssh->state != SSH_STATE_SESSION) {
7668 * Buffer the EOF in case we are pre-SESSION, so we can
7669 * send it as soon as we reach SESSION.
7672 ssh->eof_needed = TRUE;
7675 if (ssh->version == 1) {
7676 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
7677 } else if (ssh->mainchan) {
7678 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
7679 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
7680 ssh2_pkt_send(ssh, pktout);
7682 logevent("Sent EOF message");
7683 } else if (code == TS_PING || code == TS_NOP) {
7684 if (ssh->state == SSH_STATE_CLOSED
7685 || ssh->state == SSH_STATE_PREPACKET) return;
7686 if (ssh->version == 1) {
7687 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
7688 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
7690 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
7691 ssh2_pkt_addstring_start(pktout);
7692 ssh2_pkt_send_noqueue(ssh, pktout);
7694 } else if (code == TS_REKEY) {
7695 if (!ssh->kex_in_progress && ssh->version == 2) {
7696 do_ssh2_transport(ssh, "Initiating key re-exchange at"
7697 " user request", -1, NULL);
7699 } else if (code == TS_BRK) {
7700 if (ssh->state == SSH_STATE_CLOSED
7701 || ssh->state == SSH_STATE_PREPACKET) return;
7702 if (ssh->version == 1) {
7703 logevent("Unable to send BREAK signal in SSH1");
7704 } else if (ssh->mainchan) {
7705 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7706 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
7707 ssh2_pkt_addstring(pktout, "break");
7708 ssh2_pkt_addbool(pktout, 0);
7709 ssh2_pkt_adduint32(pktout, 0); /* default break length */
7710 ssh2_pkt_send(ssh, pktout);
7713 /* Is is a POSIX signal? */
7714 char *signame = NULL;
7715 if (code == TS_SIGABRT) signame = "ABRT";
7716 if (code == TS_SIGALRM) signame = "ALRM";
7717 if (code == TS_SIGFPE) signame = "FPE";
7718 if (code == TS_SIGHUP) signame = "HUP";
7719 if (code == TS_SIGILL) signame = "ILL";
7720 if (code == TS_SIGINT) signame = "INT";
7721 if (code == TS_SIGKILL) signame = "KILL";
7722 if (code == TS_SIGPIPE) signame = "PIPE";
7723 if (code == TS_SIGQUIT) signame = "QUIT";
7724 if (code == TS_SIGSEGV) signame = "SEGV";
7725 if (code == TS_SIGTERM) signame = "TERM";
7726 if (code == TS_SIGUSR1) signame = "USR1";
7727 if (code == TS_SIGUSR2) signame = "USR2";
7728 /* The SSH-2 protocol does in principle support arbitrary named
7729 * signals, including signame@domain, but we don't support those. */
7731 /* It's a signal. */
7732 if (ssh->version == 2 && ssh->mainchan) {
7733 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7734 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
7735 ssh2_pkt_addstring(pktout, "signal");
7736 ssh2_pkt_addbool(pktout, 0);
7737 ssh2_pkt_addstring(pktout, signame);
7738 ssh2_pkt_send(ssh, pktout);
7739 logeventf(ssh, "Sent signal SIG%s", signame);
7742 /* Never heard of it. Do nothing */
7747 void *new_sock_channel(void *handle, Socket s)
7749 Ssh ssh = (Ssh) handle;
7750 struct ssh_channel *c;
7751 c = snew(struct ssh_channel);
7755 c->remoteid = -1; /* to be set when open confirmed */
7756 c->localid = alloc_channel_id(ssh);
7758 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
7760 bufchain_init(&c->v.v2.outbuffer);
7761 add234(ssh->channels, c);
7767 * This is called when stdout/stderr (the entity to which
7768 * from_backend sends data) manages to clear some backlog.
7770 static void ssh_unthrottle(void *handle, int bufsize)
7772 Ssh ssh = (Ssh) handle;
7773 if (ssh->version == 1) {
7774 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
7775 ssh->v1_stdout_throttling = 0;
7776 ssh1_throttle(ssh, -1);
7779 if (ssh->mainchan && ssh->mainchan->closes == 0)
7780 ssh2_set_window(ssh->mainchan, OUR_V2_WINSIZE - bufsize);
7784 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
7786 struct ssh_channel *c = (struct ssh_channel *)channel;
7788 struct Packet *pktout;
7790 logeventf(ssh, "Opening forwarded connection to %s:%d", hostname, port);
7792 if (ssh->version == 1) {
7793 send_packet(ssh, SSH1_MSG_PORT_OPEN,
7794 PKT_INT, c->localid,
7797 //PKT_STR, <org:orgport>,
7800 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7801 ssh2_pkt_addstring(pktout, "direct-tcpip");
7802 ssh2_pkt_adduint32(pktout, c->localid);
7803 c->v.v2.locwindow = OUR_V2_WINSIZE;
7804 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
7805 ssh2_pkt_adduint32(pktout, 0x4000UL); /* our max pkt size */
7806 ssh2_pkt_addstring(pktout, hostname);
7807 ssh2_pkt_adduint32(pktout, port);
7809 * We make up values for the originator data; partly it's
7810 * too much hassle to keep track, and partly I'm not
7811 * convinced the server should be told details like that
7812 * about my local network configuration.
7814 ssh2_pkt_addstring(pktout, "client-side-connection");
7815 ssh2_pkt_adduint32(pktout, 0);
7816 ssh2_pkt_send(ssh, pktout);
7820 static Socket ssh_socket(void *handle)
7822 Ssh ssh = (Ssh) handle;
7826 static int ssh_sendok(void *handle)
7828 Ssh ssh = (Ssh) handle;
7829 return ssh->send_ok;
7832 static int ssh_ldisc(void *handle, int option)
7834 Ssh ssh = (Ssh) handle;
7835 if (option == LD_ECHO)
7836 return ssh->echoing;
7837 if (option == LD_EDIT)
7838 return ssh->editing;
7842 static void ssh_provide_ldisc(void *handle, void *ldisc)
7844 Ssh ssh = (Ssh) handle;
7848 static void ssh_provide_logctx(void *handle, void *logctx)
7850 Ssh ssh = (Ssh) handle;
7851 ssh->logctx = logctx;
7854 static int ssh_return_exitcode(void *handle)
7856 Ssh ssh = (Ssh) handle;
7860 return (ssh->exitcode >= 0 ? ssh->exitcode : 0);
7864 * cfg_info for SSH is the currently running version of the
7865 * protocol. (1 for 1; 2 for 2; 0 for not-decided-yet.)
7867 static int ssh_cfg_info(void *handle)
7869 Ssh ssh = (Ssh) handle;
7870 return ssh->version;
7874 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
7875 * that fails. This variable is the means by which scp.c can reach
7876 * into the SSH code and find out which one it got.
7878 extern int ssh_fallback_cmd(void *handle)
7880 Ssh ssh = (Ssh) handle;
7881 return ssh->fallback_cmd;
7884 Backend ssh_backend = {
7894 ssh_return_exitcode,