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;
527 #define free_portfwd(pf) ( \
528 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr)) : (void)0 ), sfree(pf) )
533 unsigned long sequence;
538 long encrypted_len; /* for SSH2 total-size counting */
541 * State associated with packet logging
545 struct logblank_t *blanks;
548 static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen,
549 struct Packet *pktin);
550 static void ssh2_protocol(Ssh ssh, unsigned char *in, int inlen,
551 struct Packet *pktin);
552 static void ssh1_protocol_setup(Ssh ssh);
553 static void ssh2_protocol_setup(Ssh ssh);
554 static void ssh_size(void *handle, int width, int height);
555 static void ssh_special(void *handle, Telnet_Special);
556 static int ssh2_try_send(struct ssh_channel *c);
557 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
558 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
559 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin);
560 static int ssh_sendbuffer(void *handle);
561 static void ssh_do_close(Ssh ssh);
562 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
563 static int ssh2_pkt_getbool(struct Packet *pkt);
564 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
565 static void ssh2_timer(void *ctx, long now);
566 static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen,
567 struct Packet *pktin);
569 struct rdpkt1_state_tag {
570 long len, pad, biglen, to_read;
571 unsigned long realcrc, gotcrc;
575 struct Packet *pktin;
578 struct rdpkt2_state_tag {
579 long len, pad, payload, packetlen, maclen;
582 unsigned long incoming_sequence;
583 struct Packet *pktin;
586 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
587 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
589 struct queued_handler;
590 struct queued_handler {
592 chandler_fn_t handler;
594 struct queued_handler *next;
598 const struct plug_function_table *fn;
599 /* the above field _must_ be first in the structure */
601 SHA_State exhash, exhashbase;
608 unsigned char session_key[32];
610 int v1_remote_protoflags;
611 int v1_local_protoflags;
612 int agentfwd_enabled;
615 const struct ssh_cipher *cipher;
618 const struct ssh2_cipher *cscipher, *sccipher;
619 void *cs_cipher_ctx, *sc_cipher_ctx;
620 const struct ssh_mac *csmac, *scmac;
621 void *cs_mac_ctx, *sc_mac_ctx;
622 const struct ssh_compress *cscomp, *sccomp;
623 void *cs_comp_ctx, *sc_comp_ctx;
624 const struct ssh_kex *kex;
625 const struct ssh_signkey *hostkey;
626 unsigned char v2_session_id[20];
632 int echoing, editing;
636 int ospeed, ispeed; /* temporaries */
637 int term_width, term_height;
639 tree234 *channels; /* indexed by local id */
640 struct ssh_channel *mainchan; /* primary session channel */
643 tree234 *rportfwds, *portfwds;
647 SSH_STATE_BEFORE_SIZE,
653 int size_needed, eof_needed;
655 struct Packet **queue;
656 int queuelen, queuesize;
658 unsigned char *deferred_send_data;
659 int deferred_len, deferred_size;
662 * Gross hack: pscp will try to start SFTP but fall back to
663 * scp1 if that fails. This variable is the means by which
664 * scp.c can reach into the SSH code and find out which one it
670 * Used for username and password input.
672 char *userpass_input_buffer;
673 int userpass_input_buflen;
674 int userpass_input_bufpos;
675 int userpass_input_echo;
682 int v1_throttle_count;
685 int v1_stdout_throttling;
686 int v2_outgoing_sequence;
688 int ssh1_rdpkt_crstate;
689 int ssh2_rdpkt_crstate;
690 int do_ssh_init_crstate;
691 int ssh_gotdata_crstate;
692 int do_ssh1_login_crstate;
693 int do_ssh1_connection_crstate;
694 int do_ssh2_transport_crstate;
695 int do_ssh2_authconn_crstate;
697 void *do_ssh_init_state;
698 void *do_ssh1_login_state;
699 void *do_ssh2_transport_state;
700 void *do_ssh2_authconn_state;
702 struct rdpkt1_state_tag rdpkt1_state;
703 struct rdpkt2_state_tag rdpkt2_state;
705 /* ssh1 and ssh2 use this for different things, but both use it */
706 int protocol_initial_phase_done;
708 void (*protocol) (Ssh ssh, unsigned char *in, int inlen,
710 struct Packet *(*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
713 * We maintain a full _copy_ of a Config structure here, not
714 * merely a pointer to it. That way, when we're passed a new
715 * one for reconfiguration, we can check the differences and
716 * potentially reconfigure port forwardings etc in mid-session.
721 * Used to transfer data back from async agent callbacks.
723 void *agent_response;
724 int agent_response_len;
727 * Dispatch table for packet types that we may have to deal
730 handler_fn_t packet_dispatch[256];
733 * Queues of one-off handler functions for success/failure
734 * indications from a request.
736 struct queued_handler *qhead, *qtail;
739 * This module deals with sending keepalives.
744 * Track incoming and outgoing data sizes and time, for
747 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
748 unsigned long max_data_size;
750 long next_rekey, last_rekey;
753 #define logevent(s) logevent(ssh->frontend, s)
755 /* logevent, only printf-formatted. */
756 static void logeventf(Ssh ssh, const char *fmt, ...)
762 buf = dupvprintf(fmt, ap);
768 #define bombout(msg) \
770 char *text = dupprintf msg; \
773 connection_fatal(ssh->frontend, "%s", text); \
777 /* Functions to leave bits out of the SSH packet log file. */
779 static void dont_log_password(Ssh ssh, struct Packet *pkt, int blanktype)
781 if (ssh->cfg.logomitpass)
782 pkt->logmode = blanktype;
785 static void dont_log_data(Ssh ssh, struct Packet *pkt, int blanktype)
787 if (ssh->cfg.logomitdata)
788 pkt->logmode = blanktype;
791 static void end_log_omission(Ssh ssh, struct Packet *pkt)
793 pkt->logmode = PKTLOG_EMIT;
796 static int ssh_channelcmp(void *av, void *bv)
798 struct ssh_channel *a = (struct ssh_channel *) av;
799 struct ssh_channel *b = (struct ssh_channel *) bv;
800 if (a->localid < b->localid)
802 if (a->localid > b->localid)
806 static int ssh_channelfind(void *av, void *bv)
808 unsigned *a = (unsigned *) av;
809 struct ssh_channel *b = (struct ssh_channel *) bv;
817 static int ssh_rportcmp_ssh1(void *av, void *bv)
819 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
820 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
822 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
823 return i < 0 ? -1 : +1;
824 if (a->dport > b->dport)
826 if (a->dport < b->dport)
831 static int ssh_rportcmp_ssh2(void *av, void *bv)
833 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
834 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
836 if (a->sport > b->sport)
838 if (a->sport < b->sport)
844 * Special form of strcmp which can cope with NULL inputs. NULL is
845 * defined to sort before even the empty string.
847 static int nullstrcmp(const char *a, const char *b)
849 if (a == NULL && b == NULL)
858 static int ssh_portcmp(void *av, void *bv)
860 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
861 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
863 if (a->type > b->type)
865 if (a->type < b->type)
867 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
868 return i < 0 ? -1 : +1;
869 if (a->sport > b->sport)
871 if (a->sport < b->sport)
873 if (a->type != 'D') {
874 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
875 return i < 0 ? -1 : +1;
876 if (a->dport > b->dport)
878 if (a->dport < b->dport)
884 static int alloc_channel_id(Ssh ssh)
886 const unsigned CHANNEL_NUMBER_OFFSET = 256;
887 unsigned low, high, mid;
889 struct ssh_channel *c;
892 * First-fit allocation of channel numbers: always pick the
893 * lowest unused one. To do this, binary-search using the
894 * counted B-tree to find the largest channel ID which is in a
895 * contiguous sequence from the beginning. (Precisely
896 * everything in that sequence must have ID equal to its tree
897 * index plus CHANNEL_NUMBER_OFFSET.)
899 tsize = count234(ssh->channels);
903 while (high - low > 1) {
904 mid = (high + low) / 2;
905 c = index234(ssh->channels, mid);
906 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
907 low = mid; /* this one is fine */
909 high = mid; /* this one is past it */
912 * Now low points to either -1, or the tree index of the
913 * largest ID in the initial sequence.
916 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
917 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
919 return low + 1 + CHANNEL_NUMBER_OFFSET;
922 static void c_write(Ssh ssh, const char *buf, int len)
924 if ((flags & FLAG_STDERR)) {
926 for (i = 0; i < len; i++)
928 fputc(buf[i], stderr);
931 from_backend(ssh->frontend, 1, buf, len);
934 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
937 for (i = 0; i < len; i++) {
939 c_write(ssh, "\r\n", 2);
940 else if ((buf[i] & 0x60) || (buf[i] == '\r'))
941 c_write(ssh, buf + i, 1);
945 static void c_write_str(Ssh ssh, const char *buf)
947 c_write(ssh, buf, strlen(buf));
950 static void ssh_free_packet(struct Packet *pkt)
955 static struct Packet *ssh_new_packet(void)
957 struct Packet *pkt = snew(struct Packet);
961 pkt->logmode = PKTLOG_EMIT;
969 * Collect incoming data in the incoming packet buffer.
970 * Decipher and verify the packet when it is completely read.
971 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
972 * Update the *data and *datalen variables.
973 * Return a Packet structure when a packet is completed.
975 static struct Packet *ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
977 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
979 crBegin(ssh->ssh1_rdpkt_crstate);
981 st->pktin = ssh_new_packet();
984 st->pktin->length = 0;
986 for (st->i = st->len = 0; st->i < 4; st->i++) {
987 while ((*datalen) == 0)
989 st->len = (st->len << 8) + **data;
990 (*data)++, (*datalen)--;
993 st->pad = 8 - (st->len % 8);
994 st->biglen = st->len + st->pad;
995 st->pktin->length = st->len - 5;
997 if (st->biglen < 0) {
998 bombout(("Extremely large packet length from server suggests"
999 " data stream corruption"));
1000 ssh_free_packet(st->pktin);
1004 st->pktin->maxlen = st->biglen;
1005 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1007 st->to_read = st->biglen;
1008 st->p = st->pktin->data;
1009 while (st->to_read > 0) {
1010 st->chunk = st->to_read;
1011 while ((*datalen) == 0)
1013 if (st->chunk > (*datalen))
1014 st->chunk = (*datalen);
1015 memcpy(st->p, *data, st->chunk);
1017 *datalen -= st->chunk;
1019 st->to_read -= st->chunk;
1022 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1023 st->biglen, NULL)) {
1024 bombout(("Network attack (CRC compensation) detected!"));
1025 ssh_free_packet(st->pktin);
1030 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1032 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1033 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1034 if (st->gotcrc != st->realcrc) {
1035 bombout(("Incorrect CRC received on packet"));
1036 ssh_free_packet(st->pktin);
1040 st->pktin->body = st->pktin->data + st->pad + 1;
1041 st->pktin->savedpos = 0;
1043 if (ssh->v1_compressing) {
1044 unsigned char *decompblk;
1046 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1047 st->pktin->body - 1, st->pktin->length + 1,
1048 &decompblk, &decomplen)) {
1049 bombout(("Zlib decompression encountered invalid data"));
1050 ssh_free_packet(st->pktin);
1054 if (st->pktin->maxlen < st->pad + decomplen) {
1055 st->pktin->maxlen = st->pad + decomplen;
1056 st->pktin->data = sresize(st->pktin->data,
1057 st->pktin->maxlen + APIEXTRA,
1059 st->pktin->body = st->pktin->data + st->pad + 1;
1062 memcpy(st->pktin->body - 1, decompblk, decomplen);
1064 st->pktin->length = decomplen - 1;
1067 st->pktin->type = st->pktin->body[-1];
1070 * Log incoming packet, possibly omitting sensitive fields.
1074 struct logblank_t blank;
1075 if (ssh->cfg.logomitdata) {
1076 int do_blank = FALSE, blank_prefix = 0;
1077 /* "Session data" packets - omit the data field */
1078 if ((st->pktin->type == SSH1_SMSG_STDOUT_DATA) ||
1079 (st->pktin->type == SSH1_SMSG_STDERR_DATA)) {
1080 do_blank = TRUE; blank_prefix = 0;
1081 } else if (st->pktin->type == SSH1_MSG_CHANNEL_DATA) {
1082 do_blank = TRUE; blank_prefix = 4;
1085 blank.offset = blank_prefix;
1086 blank.len = st->pktin->length;
1087 blank.type = PKTLOG_OMIT;
1091 log_packet(ssh->logctx,
1092 PKT_INCOMING, st->pktin->type,
1093 ssh1_pkt_type(st->pktin->type),
1094 st->pktin->body, st->pktin->length,
1098 crFinish(st->pktin);
1101 static struct Packet *ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1103 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1105 crBegin(ssh->ssh2_rdpkt_crstate);
1107 st->pktin = ssh_new_packet();
1109 st->pktin->type = 0;
1110 st->pktin->length = 0;
1112 st->cipherblk = ssh->sccipher->blksize;
1115 if (st->cipherblk < 8)
1118 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1121 * Acquire and decrypt the first block of the packet. This will
1122 * contain the length and padding details.
1124 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1125 while ((*datalen) == 0)
1127 st->pktin->data[st->i] = *(*data)++;
1132 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1133 st->pktin->data, st->cipherblk);
1136 * Now get the length and padding figures.
1138 st->len = GET_32BIT(st->pktin->data);
1139 st->pad = st->pktin->data[4];
1142 * _Completely_ silly lengths should be stomped on before they
1143 * do us any more damage.
1145 if (st->len < 0 || st->pad < 0 || st->len + st->pad < 0) {
1146 bombout(("Incoming packet was garbled on decryption"));
1147 ssh_free_packet(st->pktin);
1152 * This enables us to deduce the payload length.
1154 st->payload = st->len - st->pad - 1;
1156 st->pktin->length = st->payload + 5;
1159 * So now we can work out the total packet length.
1161 st->packetlen = st->len + 4;
1162 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1165 * Allocate memory for the rest of the packet.
1167 st->pktin->maxlen = st->packetlen + st->maclen;
1168 st->pktin->data = sresize(st->pktin->data,
1169 st->pktin->maxlen + APIEXTRA,
1173 * Read and decrypt the remainder of the packet.
1175 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1177 while ((*datalen) == 0)
1179 st->pktin->data[st->i] = *(*data)++;
1182 /* Decrypt everything _except_ the MAC. */
1184 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1185 st->pktin->data + st->cipherblk,
1186 st->packetlen - st->cipherblk);
1188 st->pktin->encrypted_len = st->packetlen;
1194 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data, st->len + 4,
1195 st->incoming_sequence)) {
1196 bombout(("Incorrect MAC received on packet"));
1197 ssh_free_packet(st->pktin);
1201 st->pktin->sequence = st->incoming_sequence++;
1204 * Decompress packet payload.
1207 unsigned char *newpayload;
1210 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1211 st->pktin->data + 5, st->pktin->length - 5,
1212 &newpayload, &newlen)) {
1213 if (st->pktin->maxlen < newlen + 5) {
1214 st->pktin->maxlen = newlen + 5;
1215 st->pktin->data = sresize(st->pktin->data,
1216 st->pktin->maxlen + APIEXTRA,
1219 st->pktin->length = 5 + newlen;
1220 memcpy(st->pktin->data + 5, newpayload, newlen);
1225 st->pktin->savedpos = 6;
1226 st->pktin->body = st->pktin->data;
1227 st->pktin->type = st->pktin->data[5];
1230 * Log incoming packet, possibly omitting sensitive fields.
1234 struct logblank_t blank;
1235 if (ssh->cfg.logomitdata) {
1236 int do_blank = FALSE, blank_prefix = 0;
1237 /* "Session data" packets - omit the data field */
1238 if (st->pktin->type == SSH2_MSG_CHANNEL_DATA) {
1239 do_blank = TRUE; blank_prefix = 4;
1240 } else if (st->pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
1241 do_blank = TRUE; blank_prefix = 8;
1244 blank.offset = blank_prefix;
1245 blank.len = (st->pktin->length-6) - blank_prefix;
1246 blank.type = PKTLOG_OMIT;
1250 log_packet(ssh->logctx, PKT_INCOMING, st->pktin->type,
1251 ssh2_pkt_type(ssh->pkt_ctx, st->pktin->type),
1252 st->pktin->data+6, st->pktin->length-6,
1256 crFinish(st->pktin);
1259 static void ssh1_pktout_size(struct Packet *pkt, int len)
1263 len += 5; /* type and CRC */
1264 pad = 8 - (len % 8);
1267 pkt->length = len - 5;
1268 if (pkt->maxlen < biglen) {
1269 pkt->maxlen = biglen;
1270 pkt->data = sresize(pkt->data, biglen + 4 + APIEXTRA, unsigned char);
1272 pkt->body = pkt->data + 4 + pad + 1;
1275 static struct Packet *s_wrpkt_start(int type, int len)
1277 struct Packet *pkt = ssh_new_packet();
1278 ssh1_pktout_size(pkt, len);
1280 /* Initialise log omission state */
1286 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt)
1292 * XXX various versions of SC (including 8.8.4) screw up the
1293 * register allocation in this function and use the same register
1294 * (D6) for len and as a temporary, with predictable results. The
1295 * following sledgehammer prevents this.
1301 pkt->body[-1] = pkt->type;
1304 log_packet(ssh->logctx, PKT_OUTGOING, pkt->type,
1305 ssh1_pkt_type(pkt->type),
1306 pkt->body, pkt->length,
1307 pkt->nblanks, pkt->blanks);
1308 sfree(pkt->blanks); pkt->blanks = NULL;
1311 if (ssh->v1_compressing) {
1312 unsigned char *compblk;
1314 zlib_compress_block(ssh->cs_comp_ctx,
1315 pkt->body - 1, pkt->length + 1,
1316 &compblk, &complen);
1317 ssh1_pktout_size(pkt, complen - 1);
1318 memcpy(pkt->body - 1, compblk, complen);
1322 len = pkt->length + 5; /* type and CRC */
1323 pad = 8 - (len % 8);
1326 for (i = 0; i < pad; i++)
1327 pkt->data[i + 4] = random_byte();
1328 crc = crc32_compute(pkt->data + 4, biglen - 4);
1329 PUT_32BIT(pkt->data + biglen, crc);
1330 PUT_32BIT(pkt->data, len);
1333 ssh->cipher->encrypt(ssh->v1_cipher_ctx, pkt->data + 4, biglen);
1338 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1341 len = s_wrpkt_prepare(ssh, pkt);
1342 backlog = sk_write(ssh->s, (char *)pkt->data, len);
1343 if (backlog > SSH_MAX_BACKLOG)
1344 ssh_throttle_all(ssh, 1, backlog);
1347 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1350 len = s_wrpkt_prepare(ssh, pkt);
1351 if (ssh->deferred_len + len > ssh->deferred_size) {
1352 ssh->deferred_size = ssh->deferred_len + len + 128;
1353 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1357 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->data, len);
1358 ssh->deferred_len += len;
1362 * Construct a packet with the specified contents.
1364 static struct Packet *construct_packet(Ssh ssh, int pkttype,
1365 va_list ap1, va_list ap2)
1367 unsigned char *p, *argp, argchar;
1368 unsigned long argint;
1369 int pktlen, argtype, arglen;
1374 while ((argtype = va_arg(ap1, int)) != PKT_END) {
1377 (void) va_arg(ap1, int);
1381 (void) va_arg(ap1, int);
1385 (void) va_arg(ap1, unsigned char *);
1386 arglen = va_arg(ap1, int);
1390 argp = va_arg(ap1, unsigned char *);
1391 arglen = strlen((char *)argp);
1392 pktlen += 4 + arglen;
1395 bn = va_arg(ap1, Bignum);
1396 pktlen += ssh1_bignum_length(bn);
1401 /* ignore this pass */
1408 pkt = s_wrpkt_start(pkttype, pktlen);
1411 while ((argtype = va_arg(ap2, int)) != PKT_END) {
1412 int offset = p - pkt->body, len = 0;
1414 /* Actual fields in the packet */
1416 argint = va_arg(ap2, int);
1417 PUT_32BIT(p, argint);
1421 argchar = (unsigned char) va_arg(ap2, int);
1426 argp = va_arg(ap2, unsigned char *);
1427 arglen = va_arg(ap2, int);
1428 memcpy(p, argp, arglen);
1432 argp = va_arg(ap2, unsigned char *);
1433 arglen = strlen((char *)argp);
1434 PUT_32BIT(p, arglen);
1435 memcpy(p + 4, argp, arglen);
1439 bn = va_arg(ap2, Bignum);
1440 len = ssh1_write_bignum(p, bn);
1442 /* Tokens for modifications to packet logging */
1444 dont_log_password(ssh, pkt, PKTLOG_BLANK);
1447 dont_log_data(ssh, pkt, PKTLOG_OMIT);
1450 end_log_omission(ssh, pkt);
1454 /* Deal with logfile omission, if required. */
1455 if (len && (pkt->logmode != PKTLOG_EMIT)) {
1457 pkt->blanks = sresize(pkt->blanks, pkt->nblanks,
1459 pkt->blanks[pkt->nblanks-1].offset = offset;
1460 pkt->blanks[pkt->nblanks-1].len = len;
1461 pkt->blanks[pkt->nblanks-1].type = pkt->logmode;
1468 static void send_packet(Ssh ssh, int pkttype, ...)
1472 va_start(ap1, pkttype);
1473 va_start(ap2, pkttype);
1474 pkt = construct_packet(ssh, pkttype, ap1, ap2);
1478 ssh_free_packet(pkt);
1481 static void defer_packet(Ssh ssh, int pkttype, ...)
1485 va_start(ap1, pkttype);
1486 va_start(ap2, pkttype);
1487 pkt = construct_packet(ssh, pkttype, ap1, ap2);
1490 s_wrpkt_defer(ssh, pkt);
1491 ssh_free_packet(pkt);
1494 static int ssh_versioncmp(char *a, char *b)
1497 unsigned long av, bv;
1499 av = strtoul(a, &ae, 10);
1500 bv = strtoul(b, &be, 10);
1502 return (av < bv ? -1 : +1);
1507 av = strtoul(ae, &ae, 10);
1508 bv = strtoul(be, &be, 10);
1510 return (av < bv ? -1 : +1);
1515 * Utility routines for putting an SSH-protocol `string' and
1516 * `uint32' into a SHA state.
1519 static void sha_string(SHA_State * s, void *str, int len)
1521 unsigned char lenblk[4];
1522 PUT_32BIT(lenblk, len);
1523 SHA_Bytes(s, lenblk, 4);
1524 SHA_Bytes(s, str, len);
1527 static void sha_uint32(SHA_State * s, unsigned i)
1529 unsigned char intblk[4];
1530 PUT_32BIT(intblk, i);
1531 SHA_Bytes(s, intblk, 4);
1535 * SSH2 packet construction functions.
1537 static void ssh2_pkt_ensure(struct Packet *pkt, int length)
1539 if (pkt->maxlen < length) {
1540 pkt->maxlen = length + 256;
1541 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
1544 static void ssh2_pkt_adddata(struct Packet *pkt, void *data, int len)
1546 if (pkt->logmode != PKTLOG_EMIT) {
1548 pkt->blanks = sresize(pkt->blanks, pkt->nblanks, struct logblank_t);
1549 pkt->blanks[pkt->nblanks-1].offset = pkt->length - 6;
1550 pkt->blanks[pkt->nblanks-1].len = len;
1551 pkt->blanks[pkt->nblanks-1].type = pkt->logmode;
1554 ssh2_pkt_ensure(pkt, pkt->length);
1555 memcpy(pkt->data + pkt->length - len, data, len);
1557 static void ssh2_pkt_addbyte(struct Packet *pkt, unsigned char byte)
1559 ssh2_pkt_adddata(pkt, &byte, 1);
1561 static struct Packet *ssh2_pkt_init(int pkt_type)
1563 struct Packet *pkt = ssh_new_packet();
1565 ssh2_pkt_addbyte(pkt, (unsigned char) pkt_type);
1568 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
1570 ssh2_pkt_adddata(pkt, &value, 1);
1572 static void ssh2_pkt_adduint32(struct Packet *pkt, unsigned long value)
1575 PUT_32BIT(x, value);
1576 ssh2_pkt_adddata(pkt, x, 4);
1578 static void ssh2_pkt_addstring_start(struct Packet *pkt)
1580 ssh2_pkt_adduint32(pkt, 0);
1581 pkt->savedpos = pkt->length;
1583 static void ssh2_pkt_addstring_str(struct Packet *pkt, char *data)
1585 ssh2_pkt_adddata(pkt, data, strlen(data));
1586 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1588 static void ssh2_pkt_addstring_data(struct Packet *pkt, char *data, int len)
1590 ssh2_pkt_adddata(pkt, data, len);
1591 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1593 static void ssh2_pkt_addstring(struct Packet *pkt, char *data)
1595 ssh2_pkt_addstring_start(pkt);
1596 ssh2_pkt_addstring_str(pkt, data);
1598 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
1601 int i, n = (bignum_bitcount(b) + 7) / 8;
1602 p = snewn(n + 1, unsigned char);
1604 fatalbox("out of memory");
1606 for (i = 1; i <= n; i++)
1607 p[i] = bignum_byte(b, n - i);
1609 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1611 memmove(p, p + i, n + 1 - i);
1615 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
1619 p = ssh2_mpint_fmt(b, &len);
1620 ssh2_pkt_addstring_start(pkt);
1621 ssh2_pkt_addstring_data(pkt, (char *)p, len);
1626 * Construct an SSH2 final-form packet: compress it, encrypt it,
1627 * put the MAC on it. Final packet, ready to be sent, is stored in
1628 * pkt->data. Total length is returned.
1630 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
1632 int cipherblk, maclen, padding, i;
1635 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1636 ssh2_pkt_type(ssh->pkt_ctx, pkt->data[5]),
1637 pkt->data + 6, pkt->length - 6,
1638 pkt->nblanks, pkt->blanks);
1639 sfree(pkt->blanks); pkt->blanks = NULL;
1643 * Compress packet payload.
1646 unsigned char *newpayload;
1649 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
1651 &newpayload, &newlen)) {
1653 ssh2_pkt_adddata(pkt, newpayload, newlen);
1659 * Add padding. At least four bytes, and must also bring total
1660 * length (minus MAC) up to a multiple of the block size.
1662 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
1663 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1666 (cipherblk - (pkt->length + padding) % cipherblk) % cipherblk;
1667 maclen = ssh->csmac ? ssh->csmac->len : 0;
1668 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
1669 pkt->data[4] = padding;
1670 for (i = 0; i < padding; i++)
1671 pkt->data[pkt->length + i] = random_byte();
1672 PUT_32BIT(pkt->data, pkt->length + padding - 4);
1674 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
1675 pkt->length + padding,
1676 ssh->v2_outgoing_sequence);
1677 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
1680 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
1681 pkt->data, pkt->length + padding);
1683 pkt->encrypted_len = pkt->length + padding;
1685 /* Ready-to-send packet starts at pkt->data. We return length. */
1686 return pkt->length + padding + maclen;
1690 * Routines called from the main SSH code to send packets. There
1691 * are quite a few of these, because we have two separate
1692 * mechanisms for delaying the sending of packets:
1694 * - In order to send an IGNORE message and a password message in
1695 * a single fixed-length blob, we require the ability to
1696 * concatenate the encrypted forms of those two packets _into_ a
1697 * single blob and then pass it to our <network.h> transport
1698 * layer in one go. Hence, there's a deferment mechanism which
1699 * works after packet encryption.
1701 * - In order to avoid sending any connection-layer messages
1702 * during repeat key exchange, we have to queue up any such
1703 * outgoing messages _before_ they are encrypted (and in
1704 * particular before they're allocated sequence numbers), and
1705 * then send them once we've finished.
1707 * I call these mechanisms `defer' and `queue' respectively, so as
1708 * to distinguish them reasonably easily.
1710 * The functions send_noqueue() and defer_noqueue() free the packet
1711 * structure they are passed. Every outgoing packet goes through
1712 * precisely one of these functions in its life; packets passed to
1713 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
1714 * these or get queued, and then when the queue is later emptied
1715 * the packets are all passed to defer_noqueue().
1719 * Send an SSH2 packet immediately, without queuing or deferring.
1721 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
1725 len = ssh2_pkt_construct(ssh, pkt);
1726 backlog = sk_write(ssh->s, (char *)pkt->data, len);
1727 if (backlog > SSH_MAX_BACKLOG)
1728 ssh_throttle_all(ssh, 1, backlog);
1730 ssh->outgoing_data_size += pkt->encrypted_len;
1731 if (!ssh->kex_in_progress &&
1732 ssh->max_data_size != 0 &&
1733 ssh->outgoing_data_size > ssh->max_data_size)
1734 do_ssh2_transport(ssh, "Initiating key re-exchange "
1735 "(too much data sent)", -1, NULL);
1737 ssh_free_packet(pkt);
1741 * Defer an SSH2 packet.
1743 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt)
1745 int len = ssh2_pkt_construct(ssh, pkt);
1746 if (ssh->deferred_len + len > ssh->deferred_size) {
1747 ssh->deferred_size = ssh->deferred_len + len + 128;
1748 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1752 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->data, len);
1753 ssh->deferred_len += len;
1754 ssh->deferred_data_size += pkt->encrypted_len;
1755 ssh_free_packet(pkt);
1759 * Queue an SSH2 packet.
1761 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
1763 assert(ssh->queueing);
1765 if (ssh->queuelen >= ssh->queuesize) {
1766 ssh->queuesize = ssh->queuelen + 32;
1767 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
1770 ssh->queue[ssh->queuelen++] = pkt;
1774 * Either queue or send a packet, depending on whether queueing is
1777 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
1780 ssh2_pkt_queue(ssh, pkt);
1782 ssh2_pkt_send_noqueue(ssh, pkt);
1786 * Either queue or defer a packet, depending on whether queueing is
1789 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
1792 ssh2_pkt_queue(ssh, pkt);
1794 ssh2_pkt_defer_noqueue(ssh, pkt);
1798 * Send the whole deferred data block constructed by
1799 * ssh2_pkt_defer() or SSH1's defer_packet().
1801 * The expected use of the defer mechanism is that you call
1802 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
1803 * not currently queueing, this simply sets up deferred_send_data
1804 * and then sends it. If we _are_ currently queueing, the calls to
1805 * ssh2_pkt_defer() put the deferred packets on to the queue
1806 * instead, and therefore ssh_pkt_defersend() has no deferred data
1807 * to send. Hence, there's no need to make it conditional on
1810 static void ssh_pkt_defersend(Ssh ssh)
1813 backlog = sk_write(ssh->s, (char *)ssh->deferred_send_data,
1815 ssh->deferred_len = ssh->deferred_size = 0;
1816 sfree(ssh->deferred_send_data);
1817 ssh->deferred_send_data = NULL;
1818 if (backlog > SSH_MAX_BACKLOG)
1819 ssh_throttle_all(ssh, 1, backlog);
1821 ssh->outgoing_data_size += ssh->deferred_data_size;
1822 if (!ssh->kex_in_progress &&
1823 ssh->max_data_size != 0 &&
1824 ssh->outgoing_data_size > ssh->max_data_size)
1825 do_ssh2_transport(ssh, "Initiating key re-exchange "
1826 "(too much data sent)", -1, NULL);
1827 ssh->deferred_data_size = 0;
1831 * Send all queued SSH2 packets. We send them by means of
1832 * ssh2_pkt_defer_noqueue(), in case they included a pair of
1833 * packets that needed to be lumped together.
1835 static void ssh2_pkt_queuesend(Ssh ssh)
1839 assert(!ssh->queueing);
1841 for (i = 0; i < ssh->queuelen; i++)
1842 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i]);
1845 ssh_pkt_defersend(ssh);
1849 void bndebug(char *string, Bignum b)
1853 p = ssh2_mpint_fmt(b, &len);
1854 debug(("%s", string));
1855 for (i = 0; i < len; i++)
1856 debug((" %02x", p[i]));
1862 static void sha_mpint(SHA_State * s, Bignum b)
1866 p = ssh2_mpint_fmt(b, &len);
1867 sha_string(s, p, len);
1872 * Packet decode functions for both SSH1 and SSH2.
1874 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
1876 unsigned long value;
1877 if (pkt->length - pkt->savedpos < 4)
1878 return 0; /* arrgh, no way to decline (FIXME?) */
1879 value = GET_32BIT(pkt->body + pkt->savedpos);
1883 static int ssh2_pkt_getbool(struct Packet *pkt)
1885 unsigned long value;
1886 if (pkt->length - pkt->savedpos < 1)
1887 return 0; /* arrgh, no way to decline (FIXME?) */
1888 value = pkt->body[pkt->savedpos] != 0;
1892 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
1897 if (pkt->length - pkt->savedpos < 4)
1899 len = GET_32BIT(pkt->body + pkt->savedpos);
1904 if (pkt->length - pkt->savedpos < *length)
1906 *p = (char *)(pkt->body + pkt->savedpos);
1907 pkt->savedpos += *length;
1909 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
1911 if (pkt->length - pkt->savedpos < length)
1913 pkt->savedpos += length;
1914 return pkt->body + (pkt->savedpos - length);
1916 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
1917 unsigned char **keystr)
1921 j = makekey(pkt->body + pkt->savedpos,
1922 pkt->length - pkt->savedpos,
1929 assert(pkt->savedpos < pkt->length);
1933 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
1938 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
1939 pkt->length - pkt->savedpos, &b);
1947 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
1953 ssh_pkt_getstring(pkt, &p, &length);
1958 b = bignum_from_bytes((unsigned char *)p, length);
1963 * Helper function to add an SSH2 signature blob to a packet.
1964 * Expects to be shown the public key blob as well as the signature
1965 * blob. Normally works just like ssh2_pkt_addstring, but will
1966 * fiddle with the signature packet if necessary for
1967 * BUG_SSH2_RSA_PADDING.
1969 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
1970 void *pkblob_v, int pkblob_len,
1971 void *sigblob_v, int sigblob_len)
1973 unsigned char *pkblob = (unsigned char *)pkblob_v;
1974 unsigned char *sigblob = (unsigned char *)sigblob_v;
1976 /* dmemdump(pkblob, pkblob_len); */
1977 /* dmemdump(sigblob, sigblob_len); */
1980 * See if this is in fact an ssh-rsa signature and a buggy
1981 * server; otherwise we can just do this the easy way.
1983 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) &&
1984 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
1985 int pos, len, siglen;
1988 * Find the byte length of the modulus.
1991 pos = 4+7; /* skip over "ssh-rsa" */
1992 pos += 4 + GET_32BIT(pkblob+pos); /* skip over exponent */
1993 len = GET_32BIT(pkblob+pos); /* find length of modulus */
1994 pos += 4; /* find modulus itself */
1995 while (len > 0 && pkblob[pos] == 0)
1997 /* debug(("modulus length is %d\n", len)); */
2000 * Now find the signature integer.
2002 pos = 4+7; /* skip over "ssh-rsa" */
2003 siglen = GET_32BIT(sigblob+pos);
2004 /* debug(("signature length is %d\n", siglen)); */
2006 if (len != siglen) {
2007 unsigned char newlen[4];
2008 ssh2_pkt_addstring_start(pkt);
2009 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2010 /* dmemdump(sigblob, pos); */
2011 pos += 4; /* point to start of actual sig */
2012 PUT_32BIT(newlen, len);
2013 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2014 /* dmemdump(newlen, 4); */
2016 while (len-- > siglen) {
2017 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2018 /* dmemdump(newlen, 1); */
2020 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2021 /* dmemdump(sigblob+pos, siglen); */
2025 /* Otherwise fall through and do it the easy way. */
2028 ssh2_pkt_addstring_start(pkt);
2029 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2033 * Examine the remote side's version string and compare it against
2034 * a list of known buggy implementations.
2036 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2038 char *imp; /* pointer to implementation part */
2040 imp += strcspn(imp, "-");
2042 imp += strcspn(imp, "-");
2045 ssh->remote_bugs = 0;
2047 if (ssh->cfg.sshbug_ignore1 == FORCE_ON ||
2048 (ssh->cfg.sshbug_ignore1 == AUTO &&
2049 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2050 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2051 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2052 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2054 * These versions don't support SSH1_MSG_IGNORE, so we have
2055 * to use a different defence against password length
2058 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2059 logevent("We believe remote version has SSH1 ignore bug");
2062 if (ssh->cfg.sshbug_plainpw1 == FORCE_ON ||
2063 (ssh->cfg.sshbug_plainpw1 == AUTO &&
2064 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2066 * These versions need a plain password sent; they can't
2067 * handle having a null and a random length of data after
2070 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2071 logevent("We believe remote version needs a plain SSH1 password");
2074 if (ssh->cfg.sshbug_rsa1 == FORCE_ON ||
2075 (ssh->cfg.sshbug_rsa1 == AUTO &&
2076 (!strcmp(imp, "Cisco-1.25")))) {
2078 * These versions apparently have no clue whatever about
2079 * RSA authentication and will panic and die if they see
2080 * an AUTH_RSA message.
2082 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2083 logevent("We believe remote version can't handle RSA authentication");
2086 if (ssh->cfg.sshbug_hmac2 == FORCE_ON ||
2087 (ssh->cfg.sshbug_hmac2 == AUTO &&
2088 !wc_match("* VShell", imp) &&
2089 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2090 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2091 wc_match("2.1 *", imp)))) {
2093 * These versions have the HMAC bug.
2095 ssh->remote_bugs |= BUG_SSH2_HMAC;
2096 logevent("We believe remote version has SSH2 HMAC bug");
2099 if (ssh->cfg.sshbug_derivekey2 == FORCE_ON ||
2100 (ssh->cfg.sshbug_derivekey2 == AUTO &&
2101 !wc_match("* VShell", imp) &&
2102 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2104 * These versions have the key-derivation bug (failing to
2105 * include the literal shared secret in the hashes that
2106 * generate the keys).
2108 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2109 logevent("We believe remote version has SSH2 key-derivation bug");
2112 if (ssh->cfg.sshbug_rsapad2 == FORCE_ON ||
2113 (ssh->cfg.sshbug_rsapad2 == AUTO &&
2114 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2115 wc_match("OpenSSH_3.[0-2]*", imp)))) {
2117 * These versions have the SSH2 RSA padding bug.
2119 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2120 logevent("We believe remote version has SSH2 RSA padding bug");
2123 if (ssh->cfg.sshbug_pksessid2 == FORCE_ON ||
2124 (ssh->cfg.sshbug_pksessid2 == AUTO &&
2125 wc_match("OpenSSH_2.[0-2]*", imp))) {
2127 * These versions have the SSH2 session-ID bug in
2128 * public-key authentication.
2130 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2131 logevent("We believe remote version has SSH2 public-key-session-ID bug");
2136 * The `software version' part of an SSH version string is required
2137 * to contain no spaces or minus signs.
2139 static void ssh_fix_verstring(char *str)
2141 /* Eat "SSH-<protoversion>-". */
2142 assert(*str == 'S'); str++;
2143 assert(*str == 'S'); str++;
2144 assert(*str == 'H'); str++;
2145 assert(*str == '-'); str++;
2146 while (*str && *str != '-') str++;
2147 assert(*str == '-'); str++;
2149 /* Convert minus signs and spaces in the remaining string into
2152 if (*str == '-' || *str == ' ')
2158 static int do_ssh_init(Ssh ssh, unsigned char c)
2160 struct do_ssh_init_state {
2168 crState(do_ssh_init_state);
2170 crBegin(ssh->do_ssh_init_crstate);
2172 /* Search for the string "SSH-" in the input. */
2175 static const int transS[] = { 1, 2, 2, 1 };
2176 static const int transH[] = { 0, 0, 3, 0 };
2177 static const int transminus[] = { 0, 0, 0, -1 };
2179 s->i = transS[s->i];
2181 s->i = transH[s->i];
2183 s->i = transminus[s->i];
2188 crReturn(1); /* get another character */
2192 s->vstring = snewn(s->vstrsize, char);
2193 strcpy(s->vstring, "SSH-");
2197 crReturn(1); /* get another char */
2198 if (s->vslen >= s->vstrsize - 1) {
2200 s->vstring = sresize(s->vstring, s->vstrsize, char);
2202 s->vstring[s->vslen++] = c;
2205 s->version[s->i] = '\0';
2207 } else if (s->i < sizeof(s->version) - 1)
2208 s->version[s->i++] = c;
2209 } else if (c == '\012')
2213 ssh->agentfwd_enabled = FALSE;
2214 ssh->rdpkt2_state.incoming_sequence = 0;
2216 s->vstring[s->vslen] = 0;
2217 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
2220 vlog = snewn(20 + s->vslen, char);
2221 sprintf(vlog, "Server version: %s", s->vstring);
2225 ssh_detect_bugs(ssh, s->vstring);
2228 * Decide which SSH protocol version to support.
2231 /* Anything strictly below "2.0" means protocol 1 is supported. */
2232 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
2233 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2234 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
2236 if (ssh->cfg.sshprot == 0 && !s->proto1) {
2237 bombout(("SSH protocol version 1 required by user but not provided by server"));
2240 if (ssh->cfg.sshprot == 3 && !s->proto2) {
2241 bombout(("SSH protocol version 2 required by user but not provided by server"));
2248 if (s->proto2 && (ssh->cfg.sshprot >= 2 || !s->proto1)) {
2250 * Construct a v2 version string.
2252 verstring = dupprintf("SSH-2.0-%s\015\012", sshver);
2256 * Construct a v1 version string.
2258 verstring = dupprintf("SSH-%s-%s\012",
2259 (ssh_versioncmp(s->version, "1.5") <= 0 ?
2260 s->version : "1.5"),
2265 ssh_fix_verstring(verstring);
2267 if (ssh->version == 2) {
2269 * Hash our version string and their version string.
2271 SHA_Init(&ssh->exhashbase);
2272 sha_string(&ssh->exhashbase, verstring,
2273 strcspn(verstring, "\015\012"));
2274 sha_string(&ssh->exhashbase, s->vstring,
2275 strcspn(s->vstring, "\015\012"));
2278 * Initialise SSHv2 protocol.
2280 ssh->protocol = ssh2_protocol;
2281 ssh2_protocol_setup(ssh);
2282 ssh->s_rdpkt = ssh2_rdpkt;
2285 * Initialise SSHv1 protocol.
2287 ssh->protocol = ssh1_protocol;
2288 ssh1_protocol_setup(ssh);
2289 ssh->s_rdpkt = ssh1_rdpkt;
2291 logeventf(ssh, "We claim version: %.*s",
2292 strcspn(verstring, "\015\012"), verstring);
2293 sk_write(ssh->s, verstring, strlen(verstring));
2297 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
2299 update_specials_menu(ssh->frontend);
2300 ssh->state = SSH_STATE_BEFORE_SIZE;
2301 ssh->pinger = pinger_new(&ssh->cfg, &ssh_backend, ssh);
2308 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
2310 crBegin(ssh->ssh_gotdata_crstate);
2313 * To begin with, feed the characters one by one to the
2314 * protocol initialisation / selection function do_ssh_init().
2315 * When that returns 0, we're done with the initial greeting
2316 * exchange and can move on to packet discipline.
2319 int ret; /* need not be kept across crReturn */
2321 crReturnV; /* more data please */
2322 ret = do_ssh_init(ssh, *data);
2330 * We emerge from that loop when the initial negotiation is
2331 * over and we have selected an s_rdpkt function. Now pass
2332 * everything to s_rdpkt, and then pass the resulting packets
2333 * to the proper protocol handler.
2338 while (datalen > 0) {
2339 struct Packet *pktin = ssh->s_rdpkt(ssh, &data, &datalen);
2341 ssh->protocol(ssh, NULL, 0, pktin);
2342 ssh_free_packet(pktin);
2344 if (ssh->state == SSH_STATE_CLOSED)
2352 static void ssh_do_close(Ssh ssh)
2355 struct ssh_channel *c;
2357 ssh->state = SSH_STATE_CLOSED;
2361 notify_remote_exit(ssh->frontend);
2364 * Now we must shut down any port and X forwardings going
2365 * through this connection.
2367 if (ssh->channels) {
2368 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
2371 x11_close(c->u.x11.s);
2374 pfd_close(c->u.pfd.s);
2377 del234(ssh->channels, c);
2378 if (ssh->version == 2)
2379 bufchain_clear(&c->v.v2.outbuffer);
2385 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
2388 Ssh ssh = (Ssh) plug;
2391 /* A socket error has occurred. */
2392 logevent(error_msg);
2393 connection_fatal(ssh->frontend, "%s", error_msg);
2395 /* Otherwise, the remote side closed the connection normally. */
2400 static int ssh_receive(Plug plug, int urgent, char *data, int len)
2402 Ssh ssh = (Ssh) plug;
2403 ssh_gotdata(ssh, (unsigned char *)data, len);
2404 if (ssh->state == SSH_STATE_CLOSED) {
2411 static void ssh_sent(Plug plug, int bufsize)
2413 Ssh ssh = (Ssh) plug;
2415 * If the send backlog on the SSH socket itself clears, we
2416 * should unthrottle the whole world if it was throttled.
2418 if (bufsize < SSH_MAX_BACKLOG)
2419 ssh_throttle_all(ssh, 0, bufsize);
2423 * Connect to specified host and port.
2424 * Returns an error message, or NULL on success.
2425 * Also places the canonical host name into `realhost'. It must be
2426 * freed by the caller.
2428 static const char *connect_to_host(Ssh ssh, char *host, int port,
2429 char **realhost, int nodelay, int keepalive)
2431 static const struct plug_function_table fn_table = {
2441 ssh->savedhost = snewn(1 + strlen(host), char);
2442 if (!ssh->savedhost)
2443 fatalbox("Out of memory");
2444 strcpy(ssh->savedhost, host);
2447 port = 22; /* default ssh port */
2448 ssh->savedport = port;
2453 logeventf(ssh, "Looking up host \"%s\"%s", host,
2454 (ssh->cfg.addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
2455 (ssh->cfg.addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" : "")));
2456 addr = name_lookup(host, port, realhost, &ssh->cfg,
2457 ssh->cfg.addressfamily);
2458 if ((err = sk_addr_error(addr)) != NULL) {
2468 sk_getaddr(addr, addrbuf, 100);
2469 logeventf(ssh, "Connecting to %s port %d", addrbuf, port);
2471 ssh->fn = &fn_table;
2472 ssh->s = new_connection(addr, *realhost, port,
2473 0, 1, nodelay, keepalive, (Plug) ssh, &ssh->cfg);
2474 if ((err = sk_socket_error(ssh->s)) != NULL) {
2476 notify_remote_exit(ssh->frontend);
2484 * Throttle or unthrottle the SSH connection.
2486 static void ssh1_throttle(Ssh ssh, int adjust)
2488 int old_count = ssh->v1_throttle_count;
2489 ssh->v1_throttle_count += adjust;
2490 assert(ssh->v1_throttle_count >= 0);
2491 if (ssh->v1_throttle_count && !old_count) {
2492 sk_set_frozen(ssh->s, 1);
2493 } else if (!ssh->v1_throttle_count && old_count) {
2494 sk_set_frozen(ssh->s, 0);
2499 * Throttle or unthrottle _all_ local data streams (for when sends
2500 * on the SSH connection itself back up).
2502 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
2505 struct ssh_channel *c;
2507 if (enable == ssh->throttled_all)
2509 ssh->throttled_all = enable;
2510 ssh->overall_bufsize = bufsize;
2513 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
2515 case CHAN_MAINSESSION:
2517 * This is treated separately, outside the switch.
2521 x11_override_throttle(c->u.x11.s, enable);
2524 /* Agent channels require no buffer management. */
2527 pfd_override_throttle(c->u.pfd.s, enable);
2534 * Username and password input, abstracted off into routines
2535 * reusable in several places - even between SSH1 and SSH2.
2538 /* Set up a username or password input loop on a given buffer. */
2539 static void setup_userpass_input(Ssh ssh, char *buffer, int buflen, int echo)
2541 ssh->userpass_input_buffer = buffer;
2542 ssh->userpass_input_buflen = buflen;
2543 ssh->userpass_input_bufpos = 0;
2544 ssh->userpass_input_echo = echo;
2548 * Process some terminal data in the course of username/password
2549 * input. Returns >0 for success (line of input returned in
2550 * buffer), <0 for failure (user hit ^C/^D, bomb out and exit), 0
2551 * for inconclusive (keep waiting for more input please).
2553 static int process_userpass_input(Ssh ssh, unsigned char *in, int inlen)
2558 switch (c = *in++) {
2561 ssh->userpass_input_buffer[ssh->userpass_input_bufpos] = 0;
2562 ssh->userpass_input_buffer[ssh->userpass_input_buflen-1] = 0;
2567 if (ssh->userpass_input_bufpos > 0) {
2568 if (ssh->userpass_input_echo)
2569 c_write_str(ssh, "\b \b");
2570 ssh->userpass_input_bufpos--;
2575 while (ssh->userpass_input_bufpos > 0) {
2576 if (ssh->userpass_input_echo)
2577 c_write_str(ssh, "\b \b");
2578 ssh->userpass_input_bufpos--;
2587 * This simplistic check for printability is disabled
2588 * when we're doing password input, because some people
2589 * have control characters in their passwords.o
2591 if ((!ssh->userpass_input_echo ||
2592 (c >= ' ' && c <= '~') ||
2593 ((unsigned char) c >= 160))
2594 && ssh->userpass_input_bufpos < ssh->userpass_input_buflen-1) {
2595 ssh->userpass_input_buffer[ssh->userpass_input_bufpos++] = c;
2596 if (ssh->userpass_input_echo)
2597 c_write(ssh, &c, 1);
2605 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
2607 Ssh ssh = (Ssh) sshv;
2609 ssh->agent_response = reply;
2610 ssh->agent_response_len = replylen;
2612 if (ssh->version == 1)
2613 do_ssh1_login(ssh, NULL, -1, NULL);
2615 do_ssh2_authconn(ssh, NULL, -1, NULL);
2618 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
2620 struct ssh_channel *c = (struct ssh_channel *)cv;
2622 void *sentreply = reply;
2625 /* Fake SSH_AGENT_FAILURE. */
2626 sentreply = "\0\0\0\1\5";
2629 if (ssh->version == 2) {
2630 ssh2_add_channel_data(c, sentreply, replylen);
2633 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
2634 PKT_INT, c->remoteid,
2637 PKT_DATA, sentreply, replylen,
2646 * Handle the key exchange and user authentication phases.
2648 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
2649 struct Packet *pktin)
2652 unsigned char cookie[8], *ptr;
2653 struct RSAKey servkey, hostkey;
2654 struct MD5Context md5c;
2655 struct do_ssh1_login_state {
2657 unsigned char *rsabuf, *keystr1, *keystr2;
2658 unsigned long supported_ciphers_mask, supported_auths_mask;
2659 int tried_publickey, tried_agent;
2660 int tis_auth_refused, ccard_auth_refused;
2661 unsigned char session_id[16];
2664 void *publickey_blob;
2665 int publickey_bloblen;
2671 unsigned char request[5], *response, *p;
2680 crState(do_ssh1_login_state);
2682 crBegin(ssh->do_ssh1_login_crstate);
2687 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
2688 bombout(("Public key packet not received"));
2692 logevent("Received public keys");
2694 ptr = ssh_pkt_getdata(pktin, 8);
2696 bombout(("SSH1 public key packet stopped before random cookie"));
2699 memcpy(cookie, ptr, 8);
2701 if (!ssh1_pkt_getrsakey(pktin, &servkey, &s->keystr1) ||
2702 !ssh1_pkt_getrsakey(pktin, &hostkey, &s->keystr2)) {
2703 bombout(("Failed to read SSH1 public keys from public key packet"));
2708 * Log the host key fingerprint.
2712 logevent("Host key fingerprint is:");
2713 strcpy(logmsg, " ");
2714 hostkey.comment = NULL;
2715 rsa_fingerprint(logmsg + strlen(logmsg),
2716 sizeof(logmsg) - strlen(logmsg), &hostkey);
2720 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
2721 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
2722 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
2724 ssh->v1_local_protoflags =
2725 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
2726 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
2729 MD5Update(&md5c, s->keystr2, hostkey.bytes);
2730 MD5Update(&md5c, s->keystr1, servkey.bytes);
2731 MD5Update(&md5c, cookie, 8);
2732 MD5Final(s->session_id, &md5c);
2734 for (i = 0; i < 32; i++)
2735 ssh->session_key[i] = random_byte();
2738 * Verify that the `bits' and `bytes' parameters match.
2740 if (hostkey.bits > hostkey.bytes * 8 ||
2741 servkey.bits > servkey.bytes * 8) {
2742 bombout(("SSH1 public keys were badly formatted"));
2746 s->len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
2748 s->rsabuf = snewn(s->len, unsigned char);
2750 fatalbox("Out of memory");
2753 * Verify the host key.
2757 * First format the key into a string.
2759 int len = rsastr_len(&hostkey);
2760 char fingerprint[100];
2761 char *keystr = snewn(len, char);
2763 fatalbox("Out of memory");
2764 rsastr_fmt(keystr, &hostkey);
2765 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
2766 verify_ssh_host_key(ssh->frontend,
2767 ssh->savedhost, ssh->savedport, "rsa", keystr,
2772 for (i = 0; i < 32; i++) {
2773 s->rsabuf[i] = ssh->session_key[i];
2775 s->rsabuf[i] ^= s->session_id[i];
2778 if (hostkey.bytes > servkey.bytes) {
2779 ret = rsaencrypt(s->rsabuf, 32, &servkey);
2781 ret = rsaencrypt(s->rsabuf, servkey.bytes, &hostkey);
2783 ret = rsaencrypt(s->rsabuf, 32, &hostkey);
2785 ret = rsaencrypt(s->rsabuf, hostkey.bytes, &servkey);
2788 bombout(("SSH1 public key encryptions failed due to bad formatting"));
2792 logevent("Encrypted session key");
2795 int cipher_chosen = 0, warn = 0;
2796 char *cipher_string = NULL;
2798 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
2799 int next_cipher = ssh->cfg.ssh_cipherlist[i];
2800 if (next_cipher == CIPHER_WARN) {
2801 /* If/when we choose a cipher, warn about it */
2803 } else if (next_cipher == CIPHER_AES) {
2804 /* XXX Probably don't need to mention this. */
2805 logevent("AES not supported in SSH1, skipping");
2807 switch (next_cipher) {
2808 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
2809 cipher_string = "3DES"; break;
2810 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
2811 cipher_string = "Blowfish"; break;
2812 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
2813 cipher_string = "single-DES"; break;
2815 if (s->supported_ciphers_mask & (1 << s->cipher_type))
2819 if (!cipher_chosen) {
2820 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
2821 bombout(("Server violates SSH 1 protocol by not "
2822 "supporting 3DES encryption"));
2824 /* shouldn't happen */
2825 bombout(("No supported ciphers found"));
2829 /* Warn about chosen cipher if necessary. */
2831 askalg(ssh->frontend, "cipher", cipher_string);
2834 switch (s->cipher_type) {
2835 case SSH_CIPHER_3DES:
2836 logevent("Using 3DES encryption");
2838 case SSH_CIPHER_DES:
2839 logevent("Using single-DES encryption");
2841 case SSH_CIPHER_BLOWFISH:
2842 logevent("Using Blowfish encryption");
2846 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
2847 PKT_CHAR, s->cipher_type,
2848 PKT_DATA, cookie, 8,
2849 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
2850 PKT_DATA, s->rsabuf, s->len,
2851 PKT_INT, ssh->v1_local_protoflags, PKT_END);
2853 logevent("Trying to enable encryption...");
2857 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
2858 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
2860 ssh->v1_cipher_ctx = ssh->cipher->make_context();
2861 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
2862 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
2864 ssh->crcda_ctx = crcda_make_context();
2865 logevent("Installing CRC compensation attack detector");
2867 if (servkey.modulus) {
2868 sfree(servkey.modulus);
2869 servkey.modulus = NULL;
2871 if (servkey.exponent) {
2872 sfree(servkey.exponent);
2873 servkey.exponent = NULL;
2875 if (hostkey.modulus) {
2876 sfree(hostkey.modulus);
2877 hostkey.modulus = NULL;
2879 if (hostkey.exponent) {
2880 sfree(hostkey.exponent);
2881 hostkey.exponent = NULL;
2885 if (pktin->type != SSH1_SMSG_SUCCESS) {
2886 bombout(("Encryption not successfully enabled"));
2890 logevent("Successfully started encryption");
2894 if (!*ssh->cfg.username) {
2895 if (ssh_get_line && !ssh_getline_pw_only) {
2896 if (!ssh_get_line("login as: ",
2897 s->username, sizeof(s->username), FALSE)) {
2899 * get_line failed to get a username.
2902 logevent("No username provided. Abandoning session.");
2903 ssh_closing((Plug)ssh, NULL, 0, 0);
2907 int ret; /* need not be kept over crReturn */
2908 c_write_str(ssh, "login as: ");
2911 setup_userpass_input(ssh, s->username, sizeof(s->username), 1);
2913 crWaitUntil(!pktin);
2914 ret = process_userpass_input(ssh, in, inlen);
2918 c_write_str(ssh, "\r\n");
2921 strncpy(s->username, ssh->cfg.username, sizeof(s->username));
2922 s->username[sizeof(s->username)-1] = '\0';
2925 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, s->username, PKT_END);
2927 char userlog[22 + sizeof(s->username)];
2928 sprintf(userlog, "Sent username \"%s\"", s->username);
2930 if (flags & FLAG_INTERACTIVE &&
2931 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
2932 strcat(userlog, "\r\n");
2933 c_write_str(ssh, userlog);
2940 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA)) {
2941 /* We must not attempt PK auth. Pretend we've already tried it. */
2942 s->tried_publickey = s->tried_agent = 1;
2944 s->tried_publickey = s->tried_agent = 0;
2946 s->tis_auth_refused = s->ccard_auth_refused = 0;
2947 /* Load the public half of ssh->cfg.keyfile so we notice if it's in Pageant */
2948 if (!filename_is_null(ssh->cfg.keyfile)) {
2949 if (!rsakey_pubblob(&ssh->cfg.keyfile,
2950 &s->publickey_blob, &s->publickey_bloblen, NULL))
2951 s->publickey_blob = NULL;
2953 s->publickey_blob = NULL;
2955 while (pktin->type == SSH1_SMSG_FAILURE) {
2956 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
2958 if (agent_exists() && !s->tried_agent) {
2960 * Attempt RSA authentication using Pageant.
2966 logevent("Pageant is running. Requesting keys.");
2968 /* Request the keys held by the agent. */
2969 PUT_32BIT(s->request, 1);
2970 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
2971 if (!agent_query(s->request, 5, &r, &s->responselen,
2972 ssh_agent_callback, ssh)) {
2976 bombout(("Unexpected data from server while waiting"
2977 " for agent response"));
2980 } while (pktin || inlen > 0);
2981 r = ssh->agent_response;
2982 s->responselen = ssh->agent_response_len;
2984 s->response = (unsigned char *) r;
2985 if (s->response && s->responselen >= 5 &&
2986 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
2987 s->p = s->response + 5;
2988 s->nkeys = GET_32BIT(s->p);
2992 sprintf(buf, "Pageant has %d SSH1 keys", s->nkeys);
2995 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
2998 sprintf(buf, "Trying Pageant key #%d", s->keyi);
3001 if (s->publickey_blob &&
3002 !memcmp(s->p, s->publickey_blob,
3003 s->publickey_bloblen)) {
3004 logevent("This key matches configured key file");
3005 s->tried_publickey = 1;
3010 do { /* do while (0) to make breaking easy */
3011 n = ssh1_read_bignum
3012 (s->p, s->responselen-(s->p-s->response),
3017 n = ssh1_read_bignum
3018 (s->p, s->responselen-(s->p-s->response),
3023 if (s->responselen - (s->p-s->response) < 4)
3025 s->commentlen = GET_32BIT(s->p);
3027 if (s->responselen - (s->p-s->response) <
3030 s->commentp = (char *)s->p;
3031 s->p += s->commentlen;
3035 logevent("Pageant key list packet was truncated");
3039 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3040 PKT_BIGNUM, s->key.modulus, PKT_END);
3042 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3043 logevent("Key refused");
3046 logevent("Received RSA challenge");
3047 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3048 bombout(("Server's RSA challenge was badly formatted"));
3053 char *agentreq, *q, *ret;
3056 len = 1 + 4; /* message type, bit count */
3057 len += ssh1_bignum_length(s->key.exponent);
3058 len += ssh1_bignum_length(s->key.modulus);
3059 len += ssh1_bignum_length(s->challenge);
3060 len += 16; /* session id */
3061 len += 4; /* response format */
3062 agentreq = snewn(4 + len, char);
3063 PUT_32BIT(agentreq, len);
3065 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
3066 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
3068 q += ssh1_write_bignum(q, s->key.exponent);
3069 q += ssh1_write_bignum(q, s->key.modulus);
3070 q += ssh1_write_bignum(q, s->challenge);
3071 memcpy(q, s->session_id, 16);
3073 PUT_32BIT(q, 1); /* response format */
3074 if (!agent_query(agentreq, len + 4, &vret, &retlen,
3075 ssh_agent_callback, ssh)) {
3080 bombout(("Unexpected data from server"
3081 " while waiting for agent"
3085 } while (pktin || inlen > 0);
3086 vret = ssh->agent_response;
3087 retlen = ssh->agent_response_len;
3092 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
3093 logevent("Sending Pageant's response");
3094 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3095 PKT_DATA, ret + 5, 16,
3099 if (pktin->type == SSH1_SMSG_SUCCESS) {
3101 ("Pageant's response accepted");
3102 if (flags & FLAG_VERBOSE) {
3103 c_write_str(ssh, "Authenticated using"
3105 c_write(ssh, s->commentp,
3107 c_write_str(ssh, "\" from agent\r\n");
3112 ("Pageant's response not accepted");
3115 ("Pageant failed to answer challenge");
3119 logevent("No reply received from Pageant");
3122 freebn(s->key.exponent);
3123 freebn(s->key.modulus);
3124 freebn(s->challenge);
3133 if (!filename_is_null(ssh->cfg.keyfile) && !s->tried_publickey)
3134 s->pwpkt_type = SSH1_CMSG_AUTH_RSA;
3136 if (ssh->cfg.try_tis_auth &&
3137 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
3138 !s->tis_auth_refused) {
3139 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
3140 logevent("Requested TIS authentication");
3141 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
3143 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
3144 logevent("TIS authentication declined");
3145 if (flags & FLAG_INTERACTIVE)
3146 c_write_str(ssh, "TIS authentication refused.\r\n");
3147 s->tis_auth_refused = 1;
3153 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3155 bombout(("TIS challenge packet was badly formed"));
3158 logevent("Received TIS challenge");
3159 if (challengelen > sizeof(s->prompt) - 1)
3160 challengelen = sizeof(s->prompt) - 1;/* prevent overrun */
3161 memcpy(s->prompt, challenge, challengelen);
3162 /* Prompt heuristic comes from OpenSSH */
3163 strncpy(s->prompt + challengelen,
3164 memchr(s->prompt, '\n', challengelen) ?
3165 "": "\r\nResponse: ",
3166 (sizeof s->prompt) - challengelen);
3167 s->prompt[(sizeof s->prompt) - 1] = '\0';
3170 if (ssh->cfg.try_tis_auth &&
3171 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
3172 !s->ccard_auth_refused) {
3173 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
3174 logevent("Requested CryptoCard authentication");
3175 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
3177 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
3178 logevent("CryptoCard authentication declined");
3179 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
3180 s->ccard_auth_refused = 1;
3186 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3188 bombout(("CryptoCard challenge packet was badly formed"));
3191 logevent("Received CryptoCard challenge");
3192 if (challengelen > sizeof(s->prompt) - 1)
3193 challengelen = sizeof(s->prompt) - 1;/* prevent overrun */
3194 memcpy(s->prompt, challenge, challengelen);
3195 strncpy(s->prompt + challengelen,
3196 memchr(s->prompt, '\n', challengelen) ?
3197 "" : "\r\nResponse: ",
3198 sizeof(s->prompt) - challengelen);
3199 s->prompt[sizeof(s->prompt) - 1] = '\0';
3202 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
3203 sprintf(s->prompt, "%.90s@%.90s's password: ",
3204 s->username, ssh->savedhost);
3206 if (s->pwpkt_type == SSH1_CMSG_AUTH_RSA) {
3207 char *comment = NULL;
3210 if (flags & FLAG_VERBOSE)
3211 c_write_str(ssh, "Trying public key authentication.\r\n");
3212 logeventf(ssh, "Trying public key \"%s\"",
3213 filename_to_str(&ssh->cfg.keyfile));
3214 type = key_type(&ssh->cfg.keyfile);
3215 if (type != SSH_KEYTYPE_SSH1) {
3216 sprintf(msgbuf, "Key is of wrong type (%s)",
3217 key_type_to_str(type));
3219 c_write_str(ssh, msgbuf);
3220 c_write_str(ssh, "\r\n");
3221 s->tried_publickey = 1;
3224 if (!rsakey_encrypted(&ssh->cfg.keyfile, &comment)) {
3225 if (flags & FLAG_VERBOSE)
3226 c_write_str(ssh, "No passphrase required.\r\n");
3229 sprintf(s->prompt, "Passphrase for key \"%.100s\": ", comment);
3234 * Show password prompt, having first obtained it via a TIS
3235 * or CryptoCard exchange if we're doing TIS or CryptoCard
3239 if (!ssh_get_line(s->prompt, s->password,
3240 sizeof(s->password), TRUE)) {
3242 * get_line failed to get a password (for example
3243 * because one was supplied on the command line
3244 * which has already failed to work). Terminate.
3246 send_packet(ssh, SSH1_MSG_DISCONNECT,
3247 PKT_STR, "No more passwords available to try",
3249 logevent("Unable to authenticate");
3250 connection_fatal(ssh->frontend, "Unable to authenticate");
3251 ssh_closing((Plug)ssh, NULL, 0, 0);
3255 /* Prompt may have come from server. We've munged it a bit, so
3256 * we know it to be zero-terminated at least once. */
3257 int ret; /* need not be saved over crReturn */
3258 c_write_untrusted(ssh, s->prompt, strlen(s->prompt));
3261 setup_userpass_input(ssh, s->password, sizeof(s->password), 0);
3263 crWaitUntil(!pktin);
3264 ret = process_userpass_input(ssh, in, inlen);
3268 c_write_str(ssh, "\r\n");
3272 if (s->pwpkt_type == SSH1_CMSG_AUTH_RSA) {
3274 * Try public key authentication with the specified
3277 s->tried_publickey = 1;
3280 const char *error = NULL;
3281 int ret = loadrsakey(&ssh->cfg.keyfile, &s->key, s->password,
3284 c_write_str(ssh, "Couldn't load private key from ");
3285 c_write_str(ssh, filename_to_str(&ssh->cfg.keyfile));
3286 c_write_str(ssh, " (");
3287 c_write_str(ssh, error);
3288 c_write_str(ssh, ").\r\n");
3289 continue; /* go and try password */
3292 c_write_str(ssh, "Wrong passphrase.\r\n");
3293 s->tried_publickey = 0;
3294 continue; /* try again */
3299 * Send a public key attempt.
3301 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3302 PKT_BIGNUM, s->key.modulus, PKT_END);
3305 if (pktin->type == SSH1_SMSG_FAILURE) {
3306 c_write_str(ssh, "Server refused our public key.\r\n");
3307 continue; /* go and try password */
3309 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3310 bombout(("Bizarre response to offer of public key"));
3316 unsigned char buffer[32];
3317 Bignum challenge, response;
3319 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3320 bombout(("Server's RSA challenge was badly formatted"));
3323 response = rsadecrypt(challenge, &s->key);
3324 freebn(s->key.private_exponent);/* burn the evidence */
3326 for (i = 0; i < 32; i++) {
3327 buffer[i] = bignum_byte(response, 31 - i);
3331 MD5Update(&md5c, buffer, 32);
3332 MD5Update(&md5c, s->session_id, 16);
3333 MD5Final(buffer, &md5c);
3335 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3336 PKT_DATA, buffer, 16, PKT_END);
3343 if (pktin->type == SSH1_SMSG_FAILURE) {
3344 if (flags & FLAG_VERBOSE)
3345 c_write_str(ssh, "Failed to authenticate with"
3346 " our public key.\r\n");
3347 continue; /* go and try password */
3348 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
3349 bombout(("Bizarre response to RSA authentication response"));
3353 break; /* we're through! */
3355 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
3357 * Defence against traffic analysis: we send a
3358 * whole bunch of packets containing strings of
3359 * different lengths. One of these strings is the
3360 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
3361 * The others are all random data in
3362 * SSH1_MSG_IGNORE packets. This way a passive
3363 * listener can't tell which is the password, and
3364 * hence can't deduce the password length.
3366 * Anybody with a password length greater than 16
3367 * bytes is going to have enough entropy in their
3368 * password that a listener won't find it _that_
3369 * much help to know how long it is. So what we'll
3372 * - if password length < 16, we send 15 packets
3373 * containing string lengths 1 through 15
3375 * - otherwise, we let N be the nearest multiple
3376 * of 8 below the password length, and send 8
3377 * packets containing string lengths N through
3378 * N+7. This won't obscure the order of
3379 * magnitude of the password length, but it will
3380 * introduce a bit of extra uncertainty.
3382 * A few servers (the old 1.2.18 through 1.2.22)
3383 * can't deal with SSH1_MSG_IGNORE. For these
3384 * servers, we need an alternative defence. We make
3385 * use of the fact that the password is interpreted
3386 * as a C string: so we can append a NUL, then some
3389 * One server (a Cisco one) can deal with neither
3390 * SSH1_MSG_IGNORE _nor_ a padded password string.
3391 * For this server we are left with no defences
3392 * against password length sniffing.
3394 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE)) {
3396 * The server can deal with SSH1_MSG_IGNORE, so
3397 * we can use the primary defence.
3399 int bottom, top, pwlen, i;
3402 pwlen = strlen(s->password);
3404 bottom = 0; /* zero length passwords are OK! :-) */
3407 bottom = pwlen & ~7;
3411 assert(pwlen >= bottom && pwlen <= top);
3413 randomstr = snewn(top + 1, char);
3415 for (i = bottom; i <= top; i++) {
3417 defer_packet(ssh, s->pwpkt_type,
3418 PKTT_PASSWORD, PKT_STR, s->password,
3419 PKTT_OTHER, PKT_END);
3421 for (j = 0; j < i; j++) {
3423 randomstr[j] = random_byte();
3424 } while (randomstr[j] == '\0');
3426 randomstr[i] = '\0';
3427 defer_packet(ssh, SSH1_MSG_IGNORE,
3428 PKT_STR, randomstr, PKT_END);
3431 logevent("Sending password with camouflage packets");
3432 ssh_pkt_defersend(ssh);
3435 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
3437 * The server can't deal with SSH1_MSG_IGNORE
3438 * but can deal with padded passwords, so we
3439 * can use the secondary defence.
3445 len = strlen(s->password);
3446 if (len < sizeof(string)) {
3448 strcpy(string, s->password);
3449 len++; /* cover the zero byte */
3450 while (len < sizeof(string)) {
3451 string[len++] = (char) random_byte();
3456 logevent("Sending length-padded password");
3457 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
3458 PKT_INT, len, PKT_DATA, ss, len,
3459 PKTT_OTHER, PKT_END);
3462 * The server has _both_
3463 * BUG_CHOKES_ON_SSH1_IGNORE and
3464 * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
3465 * therefore nothing we can do.
3468 len = strlen(s->password);
3469 logevent("Sending unpadded password");
3470 send_packet(ssh, s->pwpkt_type,
3471 PKTT_PASSWORD, PKT_INT, len,
3472 PKT_DATA, s->password, len,
3473 PKTT_OTHER, PKT_END);
3476 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
3477 PKT_STR, s->password, PKTT_OTHER, PKT_END);
3480 logevent("Sent password");
3481 memset(s->password, 0, strlen(s->password));
3483 if (pktin->type == SSH1_SMSG_FAILURE) {
3484 if (flags & FLAG_VERBOSE)
3485 c_write_str(ssh, "Access denied\r\n");
3486 logevent("Authentication refused");
3487 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
3488 bombout(("Strange packet received, type %d", pktin->type));
3493 logevent("Authentication successful");
3498 void sshfwd_close(struct ssh_channel *c)
3502 if (ssh->state != SSH_STATE_SESSION) {
3503 assert(ssh->state == SSH_STATE_CLOSED);
3507 if (c && !c->closes) {
3509 * If the channel's remoteid is -1, we have sent
3510 * CHANNEL_OPEN for this channel, but it hasn't even been
3511 * acknowledged by the server. So we must set a close flag
3512 * on it now, and then when the server acks the channel
3513 * open, we can close it then.
3515 if (((int)c->remoteid) != -1) {
3516 if (ssh->version == 1) {
3517 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
3520 struct Packet *pktout;
3521 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
3522 ssh2_pkt_adduint32(pktout, c->remoteid);
3523 ssh2_pkt_send(ssh, pktout);
3526 c->closes = 1; /* sent MSG_CLOSE */
3527 if (c->type == CHAN_X11) {
3529 logevent("Forwarded X11 connection terminated");
3530 } else if (c->type == CHAN_SOCKDATA ||
3531 c->type == CHAN_SOCKDATA_DORMANT) {
3533 logevent("Forwarded port closed");
3538 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
3542 if (ssh->state != SSH_STATE_SESSION) {
3543 assert(ssh->state == SSH_STATE_CLOSED);
3547 if (ssh->version == 1) {
3548 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3549 PKT_INT, c->remoteid,
3551 PKT_INT, len, PKT_DATA, buf, len,
3552 PKTT_OTHER, PKT_END);
3554 * In SSH1 we can return 0 here - implying that forwarded
3555 * connections are never individually throttled - because
3556 * the only circumstance that can cause throttling will be
3557 * the whole SSH connection backing up, in which case
3558 * _everything_ will be throttled as a whole.
3562 ssh2_add_channel_data(c, buf, len);
3563 return ssh2_try_send(c);
3567 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
3571 if (ssh->state != SSH_STATE_SESSION) {
3572 assert(ssh->state == SSH_STATE_CLOSED);
3576 if (ssh->version == 1) {
3577 if (c->v.v1.throttling && bufsize < SSH1_BUFFER_LIMIT) {
3578 c->v.v1.throttling = 0;
3579 ssh1_throttle(ssh, -1);
3582 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
3586 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
3588 struct queued_handler *qh = ssh->qhead;
3592 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
3595 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
3596 ssh->packet_dispatch[qh->msg1] = NULL;
3599 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
3600 ssh->packet_dispatch[qh->msg2] = NULL;
3604 ssh->qhead = qh->next;
3606 if (ssh->qhead->msg1 > 0) {
3607 assert(ssh->packet_dispatch[ssh->qhead->msg1] == NULL);
3608 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
3610 if (ssh->qhead->msg2 > 0) {
3611 assert(ssh->packet_dispatch[ssh->qhead->msg2] == NULL);
3612 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
3615 ssh->qhead = ssh->qtail = NULL;
3616 ssh->packet_dispatch[pktin->type] = NULL;
3619 qh->handler(ssh, pktin, qh->ctx);
3624 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
3625 chandler_fn_t handler, void *ctx)
3627 struct queued_handler *qh;
3629 qh = snew(struct queued_handler);
3632 qh->handler = handler;
3636 if (ssh->qtail == NULL) {
3640 assert(ssh->packet_dispatch[qh->msg1] == NULL);
3641 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
3644 assert(ssh->packet_dispatch[qh->msg2] == NULL);
3645 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
3648 ssh->qtail->next = qh;
3653 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
3655 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
3657 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
3658 SSH2_MSG_REQUEST_SUCCESS)) {
3659 logeventf(ssh, "Remote port forwarding from %s enabled",
3662 logeventf(ssh, "Remote port forwarding from %s refused",
3665 rpf = del234(ssh->rportfwds, pf);
3671 static void ssh_setup_portfwd(Ssh ssh, const Config *cfg)
3673 char address_family, type;
3675 int sport,dport,sserv,dserv;
3676 char sports[256], dports[256], saddr[256], host[256];
3677 const char *portfwd_strptr;
3679 portfwd_strptr = cfg->portfwd;
3681 if (!ssh->portfwds) {
3682 ssh->portfwds = newtree234(ssh_portcmp);
3685 * Go through the existing port forwardings and tag them
3686 * with keep==FALSE. Any that we want to keep will be
3687 * re-enabled as we go through the configuration and find
3688 * out which bits are the same as they were before.
3690 struct ssh_portfwd *epf;
3692 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
3696 while (*portfwd_strptr) {
3697 address_family = 'A';
3699 while (*portfwd_strptr && *portfwd_strptr != '\t') {
3700 if (*portfwd_strptr == 'A' ||
3701 *portfwd_strptr == '4' ||
3702 *portfwd_strptr == '6')
3703 address_family = *portfwd_strptr;
3704 else if (*portfwd_strptr == 'L' ||
3705 *portfwd_strptr == 'R' ||
3706 *portfwd_strptr == 'D')
3707 type = *portfwd_strptr;
3714 while (*portfwd_strptr && *portfwd_strptr != '\t') {
3715 if (*portfwd_strptr == ':') {
3717 * We've seen a colon in the middle of the
3718 * source port number. This means that
3719 * everything we've seen until now is the
3720 * source _address_, so we'll move it into
3721 * saddr and start sports from the beginning
3726 if (ssh->version == 1 && type == 'R') {
3727 logeventf(ssh, "SSH1 cannot handle remote source address "
3728 "spec \"%s\"; ignoring", sports);
3730 strcpy(saddr, sports);
3733 if (n < 255) sports[n++] = *portfwd_strptr++;
3737 if (*portfwd_strptr == '\t')
3740 while (*portfwd_strptr && *portfwd_strptr != ':') {
3741 if (n < 255) host[n++] = *portfwd_strptr++;
3744 if (*portfwd_strptr == ':')
3747 while (*portfwd_strptr) {
3748 if (n < 255) dports[n++] = *portfwd_strptr++;
3752 dport = atoi(dports);
3756 dport = net_service_lookup(dports);
3758 logeventf(ssh, "Service lookup failed for destination"
3759 " port \"%s\"", dports);
3763 while (*portfwd_strptr) portfwd_strptr++;
3765 portfwd_strptr++; /* eat the NUL and move to next one */
3767 sport = atoi(sports);
3771 sport = net_service_lookup(sports);
3773 logeventf(ssh, "Service lookup failed for source"
3774 " port \"%s\"", sports);
3777 if (sport && dport) {
3778 /* Set up a description of the source port. */
3779 struct ssh_portfwd *pfrec, *epfrec;
3781 sportdesc = dupprintf("%.*s%.*s%.*s%.*s%d%.*s",
3782 (int)(*saddr?strlen(saddr):0), *saddr?saddr:NULL,
3783 (int)(*saddr?1:0), ":",
3784 (int)(sserv ? strlen(sports) : 0), sports,
3785 sserv, "(", sport, sserv, ")");
3787 pfrec = snew(struct ssh_portfwd);
3789 pfrec->saddr = *saddr ? dupstr(saddr) : NULL;
3790 pfrec->sport = sport;
3791 pfrec->daddr = dupstr(host);
3792 pfrec->dport = dport;
3793 pfrec->local = NULL;
3794 pfrec->remote = NULL;
3795 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
3796 address_family == '6' ? ADDRTYPE_IPV6 :
3799 epfrec = add234(ssh->portfwds, pfrec);
3800 if (epfrec != pfrec) {
3802 * We already have a port forwarding with precisely
3803 * these parameters. Hence, no need to do anything;
3804 * simply tag the existing one as `keep'.
3806 epfrec->keep = TRUE;
3807 free_portfwd(pfrec);
3808 } else if (type == 'L') {
3809 /* Verbose description of the destination port */
3810 char *dportdesc = dupprintf("%s:%.*s%.*s%d%.*s",
3812 (int)(dserv ? strlen(dports) : 0), dports,
3813 dserv, "(", dport, dserv, ")");
3814 const char *err = pfd_addforward(host, dport,
3815 *saddr ? saddr : NULL,
3816 sport, ssh, &ssh->cfg,
3818 pfrec->addressfamily);
3820 logeventf(ssh, "Local %sport %s forward to %s%s%s",
3821 pfrec->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
3822 pfrec->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
3823 sportdesc, dportdesc,
3824 err ? " failed: " : "", err);
3827 } else if (type == 'D') {
3828 const char *err = pfd_addforward(NULL, -1,
3829 *saddr ? saddr : NULL,
3830 sport, ssh, &ssh->cfg,
3832 pfrec->addressfamily);
3834 logeventf(ssh, "Local %sport %s SOCKS dynamic forward%s%s",
3835 pfrec->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
3836 pfrec->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
3838 err ? " setup failed: " : "", err);
3840 struct ssh_rportfwd *pf;
3843 * Ensure the remote port forwardings tree exists.
3845 if (!ssh->rportfwds) {
3846 if (ssh->version == 1)
3847 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
3849 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
3852 pf = snew(struct ssh_rportfwd);
3853 strcpy(pf->dhost, host);
3856 if (add234(ssh->rportfwds, pf) != pf) {
3857 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
3861 logeventf(ssh, "Requesting remote port %s"
3862 " forward to %s:%.*s%.*s%d%.*s",
3864 (int)(dserv ? strlen(dports) : 0), dports,
3865 dserv, "(", dport, dserv, ")");
3867 pf->sportdesc = sportdesc;
3872 if (ssh->version == 1) {
3873 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
3878 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
3880 ssh_rportfwd_succfail, pf);
3882 struct Packet *pktout;
3883 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
3884 ssh2_pkt_addstring(pktout, "tcpip-forward");
3885 ssh2_pkt_addbool(pktout, 1);/* want reply */
3887 ssh2_pkt_addstring(pktout, saddr);
3888 } else if (ssh->cfg.rport_acceptall) {
3889 ssh2_pkt_addstring(pktout, "0.0.0.0");
3891 ssh2_pkt_addstring(pktout, "127.0.0.1");
3893 ssh2_pkt_adduint32(pktout, sport);
3894 ssh2_pkt_send(ssh, pktout);
3896 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
3897 SSH2_MSG_REQUEST_FAILURE,
3898 ssh_rportfwd_succfail, pf);
3907 * Now go through and destroy any port forwardings which were
3911 struct ssh_portfwd *epf;
3913 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
3917 message = dupprintf("%s port forwarding from %s%s%d",
3918 epf->type == 'L' ? "local" :
3919 epf->type == 'R' ? "remote" : "dynamic",
3920 epf->saddr ? epf->saddr : "",
3921 epf->saddr ? ":" : "",
3924 if (epf->type != 'D') {
3925 char *msg2 = dupprintf("%s to %s:%d", message,
3926 epf->daddr, epf->dport);
3931 logeventf(ssh, "Cancelling %s", message);
3935 struct ssh_rportfwd *rpf = epf->remote;
3936 struct Packet *pktout;
3939 * Cancel the port forwarding at the server
3942 if (ssh->version == 1) {
3944 * We cannot cancel listening ports on the
3945 * server side in SSH1! There's no message
3946 * to support it. Instead, we simply remove
3947 * the rportfwd record from the local end
3948 * so that any connections the server tries
3949 * to make on it are rejected.
3952 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
3953 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
3954 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
3956 ssh2_pkt_addstring(pktout, epf->saddr);
3957 } else if (ssh->cfg.rport_acceptall) {
3958 ssh2_pkt_addstring(pktout, "0.0.0.0");
3960 ssh2_pkt_addstring(pktout, "127.0.0.1");
3962 ssh2_pkt_adduint32(pktout, epf->sport);
3963 ssh2_pkt_send(ssh, pktout);
3966 del234(ssh->rportfwds, rpf);
3968 } else if (epf->local) {
3969 pfd_terminate(epf->local);
3972 delpos234(ssh->portfwds, i);
3974 i--; /* so we don't skip one in the list */
3979 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
3982 int stringlen, bufsize;
3984 ssh_pkt_getstring(pktin, &string, &stringlen);
3985 if (string == NULL) {
3986 bombout(("Incoming terminal data packet was badly formed"));
3990 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
3992 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
3993 ssh->v1_stdout_throttling = 1;
3994 ssh1_throttle(ssh, +1);
3998 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
4000 /* Remote side is trying to open a channel to talk to our
4001 * X-Server. Give them back a local channel number. */
4002 struct ssh_channel *c;
4003 int remoteid = ssh_pkt_getuint32(pktin);
4005 logevent("Received X11 connect request");
4006 /* Refuse if X11 forwarding is disabled. */
4007 if (!ssh->X11_fwd_enabled) {
4008 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4009 PKT_INT, remoteid, PKT_END);
4010 logevent("Rejected X11 connect request");
4012 c = snew(struct ssh_channel);
4015 if (x11_init(&c->u.x11.s, ssh->cfg.x11_display, c,
4016 ssh->x11auth, NULL, -1, &ssh->cfg) != NULL) {
4017 logevent("Opening X11 forward connection failed");
4019 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4020 PKT_INT, remoteid, PKT_END);
4023 ("Opening X11 forward connection succeeded");
4024 c->remoteid = remoteid;
4025 c->localid = alloc_channel_id(ssh);
4027 c->v.v1.throttling = 0;
4028 c->type = CHAN_X11; /* identify channel type */
4029 add234(ssh->channels, c);
4030 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4031 PKT_INT, c->remoteid, PKT_INT,
4032 c->localid, PKT_END);
4033 logevent("Opened X11 forward channel");
4038 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
4040 /* Remote side is trying to open a channel to talk to our
4041 * agent. Give them back a local channel number. */
4042 struct ssh_channel *c;
4043 int remoteid = ssh_pkt_getuint32(pktin);
4045 /* Refuse if agent forwarding is disabled. */
4046 if (!ssh->agentfwd_enabled) {
4047 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4048 PKT_INT, remoteid, PKT_END);
4050 c = snew(struct ssh_channel);
4052 c->remoteid = remoteid;
4053 c->localid = alloc_channel_id(ssh);
4055 c->v.v1.throttling = 0;
4056 c->type = CHAN_AGENT; /* identify channel type */
4057 c->u.a.lensofar = 0;
4058 add234(ssh->channels, c);
4059 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4060 PKT_INT, c->remoteid, PKT_INT, c->localid,
4065 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
4067 /* Remote side is trying to open a channel to talk to a
4068 * forwarded port. Give them back a local channel number. */
4069 struct ssh_channel *c;
4070 struct ssh_rportfwd pf, *pfp;
4073 char *host, buf[1024];
4075 c = snew(struct ssh_channel);
4078 remoteid = ssh_pkt_getuint32(pktin);
4079 ssh_pkt_getstring(pktin, &host, &hostsize);
4080 port = ssh_pkt_getuint32(pktin);
4082 if (hostsize >= lenof(pf.dhost))
4083 hostsize = lenof(pf.dhost)-1;
4084 memcpy(pf.dhost, host, hostsize);
4085 pf.dhost[hostsize] = '\0';
4087 pfp = find234(ssh->rportfwds, &pf, NULL);
4090 sprintf(buf, "Rejected remote port open request for %s:%d",
4093 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4094 PKT_INT, remoteid, PKT_END);
4096 sprintf(buf, "Received remote port open request for %s:%d",
4099 e = pfd_newconnect(&c->u.pfd.s, pf.dhost, port,
4100 c, &ssh->cfg, pfp->pfrec->addressfamily);
4103 sprintf(buf, "Port open failed: %s", e);
4106 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4107 PKT_INT, remoteid, PKT_END);
4109 c->remoteid = remoteid;
4110 c->localid = alloc_channel_id(ssh);
4112 c->v.v1.throttling = 0;
4113 c->type = CHAN_SOCKDATA; /* identify channel type */
4114 add234(ssh->channels, c);
4115 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4116 PKT_INT, c->remoteid, PKT_INT,
4117 c->localid, PKT_END);
4118 logevent("Forwarded port opened successfully");
4123 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
4125 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4126 unsigned int localid = ssh_pkt_getuint32(pktin);
4127 struct ssh_channel *c;
4129 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4130 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4131 c->remoteid = localid;
4132 c->type = CHAN_SOCKDATA;
4133 c->v.v1.throttling = 0;
4134 pfd_confirm(c->u.pfd.s);
4137 if (c && c->closes) {
4139 * We have a pending close on this channel,
4140 * which we decided on before the server acked
4141 * the channel open. So now we know the
4142 * remoteid, we can close it again.
4144 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE,
4145 PKT_INT, c->remoteid, PKT_END);
4149 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
4151 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4152 struct ssh_channel *c;
4154 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4155 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4156 logevent("Forwarded connection refused by server");
4157 pfd_close(c->u.pfd.s);
4158 del234(ssh->channels, c);
4163 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
4165 /* Remote side closes a channel. */
4166 unsigned i = ssh_pkt_getuint32(pktin);
4167 struct ssh_channel *c;
4168 c = find234(ssh->channels, &i, ssh_channelfind);
4169 if (c && ((int)c->remoteid) != -1) {
4172 (pktin->type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
4174 if ((c->closes == 0) && (c->type == CHAN_X11)) {
4175 logevent("Forwarded X11 connection terminated");
4176 assert(c->u.x11.s != NULL);
4177 x11_close(c->u.x11.s);
4180 if ((c->closes == 0) && (c->type == CHAN_SOCKDATA)) {
4181 logevent("Forwarded port closed");
4182 assert(c->u.pfd.s != NULL);
4183 pfd_close(c->u.pfd.s);
4187 c->closes |= (closetype << 2); /* seen this message */
4188 if (!(c->closes & closetype)) {
4189 send_packet(ssh, pktin->type, PKT_INT, c->remoteid,
4191 c->closes |= closetype; /* sent it too */
4194 if (c->closes == 15) {
4195 del234(ssh->channels, c);
4199 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
4200 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
4201 "_CONFIRMATION", c ? "half-open" : "nonexistent",
4206 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
4208 /* Data sent down one of our channels. */
4209 int i = ssh_pkt_getuint32(pktin);
4212 struct ssh_channel *c;
4214 ssh_pkt_getstring(pktin, &p, &len);
4216 c = find234(ssh->channels, &i, ssh_channelfind);
4221 bufsize = x11_send(c->u.x11.s, p, len);
4224 bufsize = pfd_send(c->u.pfd.s, p, len);
4227 /* Data for an agent message. Buffer it. */
4229 if (c->u.a.lensofar < 4) {
4230 unsigned int l = min(4 - c->u.a.lensofar, len);
4231 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
4235 c->u.a.lensofar += l;
4237 if (c->u.a.lensofar == 4) {
4239 4 + GET_32BIT(c->u.a.msglen);
4240 c->u.a.message = snewn(c->u.a.totallen,
4242 memcpy(c->u.a.message, c->u.a.msglen, 4);
4244 if (c->u.a.lensofar >= 4 && len > 0) {
4246 min(c->u.a.totallen - c->u.a.lensofar,
4248 memcpy(c->u.a.message + c->u.a.lensofar, p,
4252 c->u.a.lensofar += l;
4254 if (c->u.a.lensofar == c->u.a.totallen) {
4257 if (agent_query(c->u.a.message,
4260 ssh_agentf_callback, c))
4261 ssh_agentf_callback(c, reply, replylen);
4262 sfree(c->u.a.message);
4263 c->u.a.lensofar = 0;
4266 bufsize = 0; /* agent channels never back up */
4269 if (!c->v.v1.throttling && bufsize > SSH1_BUFFER_LIMIT) {
4270 c->v.v1.throttling = 1;
4271 ssh1_throttle(ssh, +1);
4276 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
4279 ssh->exitcode = ssh_pkt_getuint32(pktin);
4280 sprintf(buf, "Server sent command exit status %d",
4283 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
4285 * In case `helpful' firewalls or proxies tack
4286 * extra human-readable text on the end of the
4287 * session which we might mistake for another
4288 * encrypted packet, we close the session once
4289 * we've sent EXIT_CONFIRMATION.
4291 ssh_closing((Plug)ssh, NULL, 0, 0);
4294 static void do_ssh1_connection(Ssh ssh, unsigned char *in, int inlen,
4295 struct Packet *pktin)
4297 crBegin(ssh->do_ssh1_connection_crstate);
4299 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
4300 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
4301 ssh1_smsg_stdout_stderr_data;
4303 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
4304 ssh1_msg_channel_open_confirmation;
4305 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
4306 ssh1_msg_channel_open_failure;
4307 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
4308 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
4309 ssh1_msg_channel_close;
4310 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
4311 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
4313 if (ssh->cfg.agentfwd && agent_exists()) {
4314 logevent("Requesting agent forwarding");
4315 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
4319 if (pktin->type != SSH1_SMSG_SUCCESS
4320 && pktin->type != SSH1_SMSG_FAILURE) {
4321 bombout(("Protocol confusion"));
4323 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4324 logevent("Agent forwarding refused");
4326 logevent("Agent forwarding enabled");
4327 ssh->agentfwd_enabled = TRUE;
4328 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
4332 if (ssh->cfg.x11_forward) {
4333 char proto[20], data[64];
4334 logevent("Requesting X11 forwarding");
4335 ssh->x11auth = x11_invent_auth(proto, sizeof(proto),
4336 data, sizeof(data), ssh->cfg.x11_auth);
4337 x11_get_real_auth(ssh->x11auth, ssh->cfg.x11_display);
4338 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
4339 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
4340 PKT_STR, proto, PKT_STR, data,
4341 PKT_INT, x11_get_screen_number(ssh->cfg.x11_display),
4344 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
4345 PKT_STR, proto, PKT_STR, data, PKT_END);
4350 if (pktin->type != SSH1_SMSG_SUCCESS
4351 && pktin->type != SSH1_SMSG_FAILURE) {
4352 bombout(("Protocol confusion"));
4354 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4355 logevent("X11 forwarding refused");
4357 logevent("X11 forwarding enabled");
4358 ssh->X11_fwd_enabled = TRUE;
4359 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
4363 ssh_setup_portfwd(ssh, &ssh->cfg);
4364 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
4366 if (!ssh->cfg.nopty) {
4367 /* Unpick the terminal-speed string. */
4368 /* XXX perhaps we should allow no speeds to be sent. */
4369 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
4370 sscanf(ssh->cfg.termspeed, "%d,%d", &ssh->ospeed, &ssh->ispeed);
4371 /* Send the pty request. */
4372 send_packet(ssh, SSH1_CMSG_REQUEST_PTY,
4373 PKT_STR, ssh->cfg.termtype,
4374 PKT_INT, ssh->term_height,
4375 PKT_INT, ssh->term_width,
4376 PKT_INT, 0, PKT_INT, 0, /* width,height in pixels */
4377 PKT_CHAR, 192, PKT_INT, ssh->ispeed, /* TTY_OP_ISPEED */
4378 PKT_CHAR, 193, PKT_INT, ssh->ospeed, /* TTY_OP_OSPEED */
4379 PKT_CHAR, 0, PKT_END);
4380 ssh->state = SSH_STATE_INTERMED;
4384 if (pktin->type != SSH1_SMSG_SUCCESS
4385 && pktin->type != SSH1_SMSG_FAILURE) {
4386 bombout(("Protocol confusion"));
4388 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4389 c_write_str(ssh, "Server refused to allocate pty\r\n");
4390 ssh->editing = ssh->echoing = 1;
4392 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
4393 ssh->ospeed, ssh->ispeed);
4395 ssh->editing = ssh->echoing = 1;
4398 if (ssh->cfg.compression) {
4399 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
4403 if (pktin->type != SSH1_SMSG_SUCCESS
4404 && pktin->type != SSH1_SMSG_FAILURE) {
4405 bombout(("Protocol confusion"));
4407 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4408 c_write_str(ssh, "Server refused to compress\r\n");
4410 logevent("Started compression");
4411 ssh->v1_compressing = TRUE;
4412 ssh->cs_comp_ctx = zlib_compress_init();
4413 logevent("Initialised zlib (RFC1950) compression");
4414 ssh->sc_comp_ctx = zlib_decompress_init();
4415 logevent("Initialised zlib (RFC1950) decompression");
4419 * Start the shell or command.
4421 * Special case: if the first-choice command is an SSH2
4422 * subsystem (hence not usable here) and the second choice
4423 * exists, we fall straight back to that.
4426 char *cmd = ssh->cfg.remote_cmd_ptr;
4428 if (ssh->cfg.ssh_subsys && ssh->cfg.remote_cmd_ptr2) {
4429 cmd = ssh->cfg.remote_cmd_ptr2;
4430 ssh->fallback_cmd = TRUE;
4433 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
4435 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
4436 logevent("Started session");
4439 ssh->state = SSH_STATE_SESSION;
4440 if (ssh->size_needed)
4441 ssh_size(ssh, ssh->term_width, ssh->term_height);
4442 if (ssh->eof_needed)
4443 ssh_special(ssh, TS_EOF);
4446 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
4448 ssh->channels = newtree234(ssh_channelcmp);
4452 * By this point, most incoming packets are already being
4453 * handled by the dispatch table, and we need only pay
4454 * attention to the unusual ones.
4459 if (pktin->type == SSH1_SMSG_SUCCESS) {
4460 /* may be from EXEC_SHELL on some servers */
4461 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4462 /* may be from EXEC_SHELL on some servers
4463 * if no pty is available or in other odd cases. Ignore */
4465 bombout(("Strange packet received: type %d", pktin->type));
4470 int len = min(inlen, 512);
4471 send_packet(ssh, SSH1_CMSG_STDIN_DATA, PKTT_DATA,
4472 PKT_INT, len, PKT_DATA, in, len,
4473 PKTT_OTHER, PKT_END);
4484 * Handle the top-level SSH2 protocol.
4486 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
4491 ssh_pkt_getstring(pktin, &msg, &msglen);
4492 buf = dupprintf("Remote debug message: %.*s", msglen, msg);
4497 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
4499 /* log reason code in disconnect message */
4503 ssh_pkt_getstring(pktin, &msg, &msglen);
4504 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
4507 void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
4509 /* Do nothing, because we're ignoring it! Duhh. */
4512 static void ssh1_protocol_setup(Ssh ssh)
4517 * Most messages are handled by the coroutines.
4519 for (i = 0; i < 256; i++)
4520 ssh->packet_dispatch[i] = NULL;
4523 * These special message types we install handlers for.
4525 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
4526 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
4527 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
4530 static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen,
4531 struct Packet *pktin)
4533 if (ssh->state == SSH_STATE_CLOSED)
4536 if (pktin && ssh->packet_dispatch[pktin->type]) {
4537 ssh->packet_dispatch[pktin->type](ssh, pktin);
4541 if (!ssh->protocol_initial_phase_done) {
4542 if (do_ssh1_login(ssh, in, inlen, pktin))
4543 ssh->protocol_initial_phase_done = TRUE;
4548 do_ssh1_connection(ssh, in, inlen, pktin);
4552 * Utility routine for decoding comma-separated strings in KEXINIT.
4554 static int in_commasep_string(char *needle, char *haystack, int haylen)
4557 if (!needle || !haystack) /* protect against null pointers */
4559 needlen = strlen(needle);
4562 * Is it at the start of the string?
4564 if (haylen >= needlen && /* haystack is long enough */
4565 !memcmp(needle, haystack, needlen) && /* initial match */
4566 (haylen == needlen || haystack[needlen] == ',')
4567 /* either , or EOS follows */
4571 * If not, search for the next comma and resume after that.
4572 * If no comma found, terminate.
4574 while (haylen > 0 && *haystack != ',')
4575 haylen--, haystack++;
4578 haylen--, haystack++; /* skip over comma itself */
4583 * SSH2 key creation method.
4585 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H,
4586 unsigned char *sessid, char chr,
4587 unsigned char *keyspace)
4590 /* First 20 bytes. */
4592 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
4594 SHA_Bytes(&s, H, 20);
4595 SHA_Bytes(&s, &chr, 1);
4596 SHA_Bytes(&s, sessid, 20);
4597 SHA_Final(&s, keyspace);
4598 /* Next 20 bytes. */
4600 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
4602 SHA_Bytes(&s, H, 20);
4603 SHA_Bytes(&s, keyspace, 20);
4604 SHA_Final(&s, keyspace + 20);
4608 * Handle the SSH2 transport layer.
4610 static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen,
4611 struct Packet *pktin)
4613 struct do_ssh2_transport_state {
4614 int nbits, pbits, warn;
4615 Bignum p, g, e, f, K;
4616 int kex_init_value, kex_reply_value;
4617 const struct ssh_mac **maclist;
4619 const struct ssh2_cipher *cscipher_tobe;
4620 const struct ssh2_cipher *sccipher_tobe;
4621 const struct ssh_mac *csmac_tobe;
4622 const struct ssh_mac *scmac_tobe;
4623 const struct ssh_compress *cscomp_tobe;
4624 const struct ssh_compress *sccomp_tobe;
4625 char *hostkeydata, *sigdata, *keystr, *fingerprint;
4626 int hostkeylen, siglen;
4627 void *hkey; /* actual host key */
4628 unsigned char exchange_hash[20];
4629 int n_preferred_kex;
4630 const struct ssh_kex *preferred_kex[KEX_MAX];
4631 int n_preferred_ciphers;
4632 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
4633 const struct ssh_compress *preferred_comp;
4635 struct Packet *pktout;
4637 crState(do_ssh2_transport_state);
4639 crBegin(ssh->do_ssh2_transport_crstate);
4641 s->cscipher_tobe = s->sccipher_tobe = NULL;
4642 s->csmac_tobe = s->scmac_tobe = NULL;
4643 s->cscomp_tobe = s->sccomp_tobe = NULL;
4650 * Set up the preferred key exchange. (NULL => warn below here)
4652 s->n_preferred_kex = 0;
4653 for (i = 0; i < KEX_MAX; i++) {
4654 switch (ssh->cfg.ssh_kexlist[i]) {
4656 s->preferred_kex[s->n_preferred_kex++] =
4657 &ssh_diffiehellman_gex;
4660 s->preferred_kex[s->n_preferred_kex++] =
4661 &ssh_diffiehellman_group14;
4664 s->preferred_kex[s->n_preferred_kex++] =
4665 &ssh_diffiehellman_group1;
4668 /* Flag for later. Don't bother if it's the last in
4670 if (i < KEX_MAX - 1) {
4671 s->preferred_kex[s->n_preferred_kex++] = NULL;
4681 * Set up the preferred ciphers. (NULL => warn below here)
4683 s->n_preferred_ciphers = 0;
4684 for (i = 0; i < CIPHER_MAX; i++) {
4685 switch (ssh->cfg.ssh_cipherlist[i]) {
4686 case CIPHER_BLOWFISH:
4687 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
4690 if (ssh->cfg.ssh2_des_cbc) {
4691 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
4695 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
4698 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
4701 /* Flag for later. Don't bother if it's the last in
4703 if (i < CIPHER_MAX - 1) {
4704 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
4712 * Set up preferred compression.
4714 if (ssh->cfg.compression)
4715 s->preferred_comp = &ssh_zlib;
4717 s->preferred_comp = &ssh_comp_none;
4720 * Be prepared to work around the buggy MAC problem.
4722 if (ssh->remote_bugs & BUG_SSH2_HMAC)
4723 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
4725 s->maclist = macs, s->nmacs = lenof(macs);
4729 int i, j, commalist_started;
4732 * Enable queueing of outgoing auth- or connection-layer
4733 * packets while we are in the middle of a key exchange.
4735 ssh->queueing = TRUE;
4738 * Flag that KEX is in progress.
4740 ssh->kex_in_progress = TRUE;
4743 * Construct and send our key exchange packet.
4745 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
4746 for (i = 0; i < 16; i++)
4747 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
4748 /* List key exchange algorithms. */
4749 ssh2_pkt_addstring_start(s->pktout);
4750 commalist_started = 0;
4751 for (i = 0; i < s->n_preferred_kex; i++) {
4752 const struct ssh_kex *k = s->preferred_kex[i];
4753 if (!k) continue; /* warning flag */
4754 if (commalist_started)
4755 ssh2_pkt_addstring_str(s->pktout, ",");
4756 ssh2_pkt_addstring_str(s->pktout, s->preferred_kex[i]->name);
4757 commalist_started = 1;
4759 /* List server host key algorithms. */
4760 ssh2_pkt_addstring_start(s->pktout);
4761 for (i = 0; i < lenof(hostkey_algs); i++) {
4762 ssh2_pkt_addstring_str(s->pktout, hostkey_algs[i]->name);
4763 if (i < lenof(hostkey_algs) - 1)
4764 ssh2_pkt_addstring_str(s->pktout, ",");
4766 /* List client->server encryption algorithms. */
4767 ssh2_pkt_addstring_start(s->pktout);
4768 commalist_started = 0;
4769 for (i = 0; i < s->n_preferred_ciphers; i++) {
4770 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
4771 if (!c) continue; /* warning flag */
4772 for (j = 0; j < c->nciphers; j++) {
4773 if (commalist_started)
4774 ssh2_pkt_addstring_str(s->pktout, ",");
4775 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
4776 commalist_started = 1;
4779 /* List server->client encryption algorithms. */
4780 ssh2_pkt_addstring_start(s->pktout);
4781 commalist_started = 0;
4782 for (i = 0; i < s->n_preferred_ciphers; i++) {
4783 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
4784 if (!c) continue; /* warning flag */
4785 for (j = 0; j < c->nciphers; j++) {
4786 if (commalist_started)
4787 ssh2_pkt_addstring_str(s->pktout, ",");
4788 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
4789 commalist_started = 1;
4792 /* List client->server MAC algorithms. */
4793 ssh2_pkt_addstring_start(s->pktout);
4794 for (i = 0; i < s->nmacs; i++) {
4795 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
4796 if (i < s->nmacs - 1)
4797 ssh2_pkt_addstring_str(s->pktout, ",");
4799 /* List server->client MAC algorithms. */
4800 ssh2_pkt_addstring_start(s->pktout);
4801 for (i = 0; i < s->nmacs; i++) {
4802 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
4803 if (i < s->nmacs - 1)
4804 ssh2_pkt_addstring_str(s->pktout, ",");
4806 /* List client->server compression algorithms. */
4807 ssh2_pkt_addstring_start(s->pktout);
4808 assert(lenof(compressions) > 1);
4809 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
4810 for (i = 0; i < lenof(compressions); i++) {
4811 const struct ssh_compress *c = compressions[i];
4812 if (c != s->preferred_comp) {
4813 ssh2_pkt_addstring_str(s->pktout, ",");
4814 ssh2_pkt_addstring_str(s->pktout, c->name);
4817 /* List server->client compression algorithms. */
4818 ssh2_pkt_addstring_start(s->pktout);
4819 assert(lenof(compressions) > 1);
4820 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
4821 for (i = 0; i < lenof(compressions); i++) {
4822 const struct ssh_compress *c = compressions[i];
4823 if (c != s->preferred_comp) {
4824 ssh2_pkt_addstring_str(s->pktout, ",");
4825 ssh2_pkt_addstring_str(s->pktout, c->name);
4828 /* List client->server languages. Empty list. */
4829 ssh2_pkt_addstring_start(s->pktout);
4830 /* List server->client languages. Empty list. */
4831 ssh2_pkt_addstring_start(s->pktout);
4832 /* First KEX packet does _not_ follow, because we're not that brave. */
4833 ssh2_pkt_addbool(s->pktout, FALSE);
4835 ssh2_pkt_adduint32(s->pktout, 0);
4838 ssh->exhash = ssh->exhashbase;
4839 sha_string(&ssh->exhash, s->pktout->data + 5, s->pktout->length - 5);
4841 ssh2_pkt_send_noqueue(ssh, s->pktout);
4845 if (pktin->length > 5)
4846 sha_string(&ssh->exhash, pktin->data + 5, pktin->length - 5);
4849 * Now examine the other side's KEXINIT to see what we're up
4856 if (pktin->type != SSH2_MSG_KEXINIT) {
4857 bombout(("expected key exchange packet from server"));
4861 ssh->hostkey = NULL;
4862 s->cscipher_tobe = NULL;
4863 s->sccipher_tobe = NULL;
4864 s->csmac_tobe = NULL;
4865 s->scmac_tobe = NULL;
4866 s->cscomp_tobe = NULL;
4867 s->sccomp_tobe = NULL;
4868 pktin->savedpos += 16; /* skip garbage cookie */
4869 ssh_pkt_getstring(pktin, &str, &len); /* key exchange algorithms */
4871 for (i = 0; i < s->n_preferred_kex; i++) {
4872 const struct ssh_kex *k = s->preferred_kex[i];
4875 } else if (in_commasep_string(k->name, str, len)) {
4880 askalg(ssh->frontend, "key-exchange algorithm",
4886 bombout(("Couldn't agree a key exchange algorithm (available: %s)",
4887 str ? str : "(null)"));
4890 ssh_pkt_getstring(pktin, &str, &len); /* host key algorithms */
4891 for (i = 0; i < lenof(hostkey_algs); i++) {
4892 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
4893 ssh->hostkey = hostkey_algs[i];
4897 ssh_pkt_getstring(pktin, &str, &len); /* client->server cipher */
4899 for (i = 0; i < s->n_preferred_ciphers; i++) {
4900 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
4904 for (j = 0; j < c->nciphers; j++) {
4905 if (in_commasep_string(c->list[j]->name, str, len)) {
4906 s->cscipher_tobe = c->list[j];
4911 if (s->cscipher_tobe) {
4913 askalg(ssh->frontend, "client-to-server cipher",
4914 s->cscipher_tobe->name);
4918 if (!s->cscipher_tobe) {
4919 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
4920 str ? str : "(null)"));
4924 ssh_pkt_getstring(pktin, &str, &len); /* server->client cipher */
4926 for (i = 0; i < s->n_preferred_ciphers; i++) {
4927 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
4931 for (j = 0; j < c->nciphers; j++) {
4932 if (in_commasep_string(c->list[j]->name, str, len)) {
4933 s->sccipher_tobe = c->list[j];
4938 if (s->sccipher_tobe) {
4940 askalg(ssh->frontend, "server-to-client cipher",
4941 s->sccipher_tobe->name);
4945 if (!s->sccipher_tobe) {
4946 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
4947 str ? str : "(null)"));
4951 ssh_pkt_getstring(pktin, &str, &len); /* client->server mac */
4952 for (i = 0; i < s->nmacs; i++) {
4953 if (in_commasep_string(s->maclist[i]->name, str, len)) {
4954 s->csmac_tobe = s->maclist[i];
4958 ssh_pkt_getstring(pktin, &str, &len); /* server->client mac */
4959 for (i = 0; i < s->nmacs; i++) {
4960 if (in_commasep_string(s->maclist[i]->name, str, len)) {
4961 s->scmac_tobe = s->maclist[i];
4965 ssh_pkt_getstring(pktin, &str, &len); /* client->server compression */
4966 for (i = 0; i < lenof(compressions) + 1; i++) {
4967 const struct ssh_compress *c =
4968 i == 0 ? s->preferred_comp : compressions[i - 1];
4969 if (in_commasep_string(c->name, str, len)) {
4974 ssh_pkt_getstring(pktin, &str, &len); /* server->client compression */
4975 for (i = 0; i < lenof(compressions) + 1; i++) {
4976 const struct ssh_compress *c =
4977 i == 0 ? s->preferred_comp : compressions[i - 1];
4978 if (in_commasep_string(c->name, str, len)) {
4986 * Work out the number of bits of key we will need from the key
4987 * exchange. We start with the maximum key length of either
4993 csbits = s->cscipher_tobe->keylen;
4994 scbits = s->sccipher_tobe->keylen;
4995 s->nbits = (csbits > scbits ? csbits : scbits);
4997 /* The keys only have 160-bit entropy, since they're based on
4998 * a SHA-1 hash. So cap the key size at 160 bits. */
5003 * If we're doing Diffie-Hellman group exchange, start by
5004 * requesting a group.
5006 if (!ssh->kex->pdata) {
5007 logevent("Doing Diffie-Hellman group exchange");
5008 ssh->pkt_ctx |= SSH2_PKTCTX_DHGEX;
5010 * Work out how big a DH group we will need to allow that
5013 s->pbits = 512 << ((s->nbits - 1) / 64);
5014 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
5015 ssh2_pkt_adduint32(s->pktout, s->pbits);
5016 ssh2_pkt_send_noqueue(ssh, s->pktout);
5019 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
5020 bombout(("expected key exchange group packet from server"));
5023 s->p = ssh2_pkt_getmp(pktin);
5024 s->g = ssh2_pkt_getmp(pktin);
5025 if (!s->p || !s->g) {
5026 bombout(("unable to read mp-ints from incoming group packet"));
5029 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
5030 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
5031 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
5033 ssh->pkt_ctx |= SSH2_PKTCTX_DHGROUP;
5034 ssh->kex_ctx = dh_setup_group(ssh->kex);
5035 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
5036 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
5037 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
5038 ssh->kex->groupname);
5041 logevent("Doing Diffie-Hellman key exchange");
5043 * Now generate and send e for Diffie-Hellman.
5045 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
5046 s->pktout = ssh2_pkt_init(s->kex_init_value);
5047 ssh2_pkt_addmp(s->pktout, s->e);
5048 ssh2_pkt_send_noqueue(ssh, s->pktout);
5051 if (pktin->type != s->kex_reply_value) {
5052 bombout(("expected key exchange reply packet from server"));
5055 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
5056 s->f = ssh2_pkt_getmp(pktin);
5058 bombout(("unable to parse key exchange reply packet"));
5061 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
5063 s->K = dh_find_K(ssh->kex_ctx, s->f);
5065 sha_string(&ssh->exhash, s->hostkeydata, s->hostkeylen);
5066 if (ssh->kex == &ssh_diffiehellman_gex) {
5067 sha_uint32(&ssh->exhash, s->pbits);
5068 sha_mpint(&ssh->exhash, s->p);
5069 sha_mpint(&ssh->exhash, s->g);
5071 sha_mpint(&ssh->exhash, s->e);
5072 sha_mpint(&ssh->exhash, s->f);
5073 sha_mpint(&ssh->exhash, s->K);
5074 SHA_Final(&ssh->exhash, s->exchange_hash);
5076 dh_cleanup(ssh->kex_ctx);
5077 ssh->kex_ctx = NULL;
5080 debug(("Exchange hash is:\n"));
5081 dmemdump(s->exchange_hash, 20);
5084 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
5086 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
5087 (char *)s->exchange_hash, 20)) {
5088 bombout(("Server's host key did not match the signature supplied"));
5093 * Authenticate remote host: verify host key. (We've already
5094 * checked the signature of the exchange hash.)
5096 s->keystr = ssh->hostkey->fmtkey(s->hkey);
5097 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
5098 verify_ssh_host_key(ssh->frontend,
5099 ssh->savedhost, ssh->savedport, ssh->hostkey->keytype,
5100 s->keystr, s->fingerprint);
5101 if (s->first_kex) { /* don't bother logging this in rekeys */
5102 logevent("Host key fingerprint is:");
5103 logevent(s->fingerprint);
5105 sfree(s->fingerprint);
5107 ssh->hostkey->freekey(s->hkey);
5110 * The exchange hash from the very first key exchange is also
5111 * the session id, used in session key construction and
5115 memcpy(ssh->v2_session_id, s->exchange_hash,
5116 sizeof(s->exchange_hash));
5119 * Send SSH2_MSG_NEWKEYS.
5121 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
5122 ssh2_pkt_send_noqueue(ssh, s->pktout);
5123 ssh->outgoing_data_size = 0; /* start counting from here */
5126 * We've sent client NEWKEYS, so create and initialise
5127 * client-to-server session keys.
5129 if (ssh->cs_cipher_ctx)
5130 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
5131 ssh->cscipher = s->cscipher_tobe;
5132 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
5134 if (ssh->cs_mac_ctx)
5135 ssh->csmac->free_context(ssh->cs_mac_ctx);
5136 ssh->csmac = s->csmac_tobe;
5137 ssh->cs_mac_ctx = ssh->csmac->make_context();
5139 if (ssh->cs_comp_ctx)
5140 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
5141 ssh->cscomp = s->cscomp_tobe;
5142 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
5145 * Set IVs on client-to-server keys. Here we use the exchange
5146 * hash from the _first_ key exchange.
5149 unsigned char keyspace[40];
5150 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'C',keyspace);
5151 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
5152 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'A',keyspace);
5153 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
5154 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'E',keyspace);
5155 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
5158 logeventf(ssh, "Initialised %.200s client->server encryption",
5159 ssh->cscipher->text_name);
5160 logeventf(ssh, "Initialised %.200s client->server MAC algorithm",
5161 ssh->csmac->text_name);
5162 if (ssh->cscomp->text_name)
5163 logeventf(ssh, "Initialised %s compression",
5164 ssh->cscomp->text_name);
5167 * Now our end of the key exchange is complete, we can send all
5168 * our queued higher-layer packets.
5170 ssh->queueing = FALSE;
5171 ssh2_pkt_queuesend(ssh);
5174 * Expect SSH2_MSG_NEWKEYS from server.
5177 if (pktin->type != SSH2_MSG_NEWKEYS) {
5178 bombout(("expected new-keys packet from server"));
5181 ssh->incoming_data_size = 0; /* start counting from here */
5184 * We've seen server NEWKEYS, so create and initialise
5185 * server-to-client session keys.
5187 if (ssh->sc_cipher_ctx)
5188 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
5189 ssh->sccipher = s->sccipher_tobe;
5190 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
5192 if (ssh->sc_mac_ctx)
5193 ssh->scmac->free_context(ssh->sc_mac_ctx);
5194 ssh->scmac = s->scmac_tobe;
5195 ssh->sc_mac_ctx = ssh->scmac->make_context();
5197 if (ssh->sc_comp_ctx)
5198 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
5199 ssh->sccomp = s->sccomp_tobe;
5200 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
5203 * Set IVs on server-to-client keys. Here we use the exchange
5204 * hash from the _first_ key exchange.
5207 unsigned char keyspace[40];
5208 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'D',keyspace);
5209 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
5210 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'B',keyspace);
5211 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
5212 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'F',keyspace);
5213 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
5215 logeventf(ssh, "Initialised %.200s server->client encryption",
5216 ssh->sccipher->text_name);
5217 logeventf(ssh, "Initialised %.200s server->client MAC algorithm",
5218 ssh->scmac->text_name);
5219 if (ssh->sccomp->text_name)
5220 logeventf(ssh, "Initialised %s decompression",
5221 ssh->sccomp->text_name);
5224 * Free key exchange data.
5228 if (ssh->kex == &ssh_diffiehellman_gex) {
5234 * Key exchange is over. Schedule a timer for our next rekey.
5236 ssh->kex_in_progress = FALSE;
5237 ssh->last_rekey = GETTICKCOUNT();
5238 if (ssh->cfg.ssh_rekey_time != 0)
5239 ssh->next_rekey = schedule_timer(ssh->cfg.ssh_rekey_time*60*TICKSPERSEC,
5243 * If this is the first key exchange phase, we must pass the
5244 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
5245 * wants to see it but because it will need time to initialise
5246 * itself before it sees an actual packet. In subsequent key
5247 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
5248 * it would only confuse the layer above.
5250 if (!s->first_kex) {
5256 * Now we're encrypting. Begin returning 1 to the protocol main
5257 * function so that other things can run on top of the
5258 * transport. If we ever see a KEXINIT, we must go back to the
5261 * We _also_ go back to the start if we see pktin==NULL and
5262 * inlen==-1, because this is a special signal meaning
5263 * `initiate client-driven rekey', and `in' contains a message
5264 * giving the reason for the rekey.
5266 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
5267 (!pktin && inlen == -1))) {
5271 logevent("Server initiated key re-exchange");
5273 logevent((char *)in);
5275 goto begin_key_exchange;
5281 * Add data to an SSH2 channel output buffer.
5283 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
5286 bufchain_add(&c->v.v2.outbuffer, buf, len);
5290 * Attempt to send data on an SSH2 channel.
5292 static int ssh2_try_send(struct ssh_channel *c)
5295 struct Packet *pktout;
5297 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
5300 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
5301 if ((unsigned)len > c->v.v2.remwindow)
5302 len = c->v.v2.remwindow;
5303 if ((unsigned)len > c->v.v2.remmaxpkt)
5304 len = c->v.v2.remmaxpkt;
5305 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
5306 ssh2_pkt_adduint32(pktout, c->remoteid);
5307 dont_log_data(ssh, pktout, PKTLOG_OMIT);
5308 ssh2_pkt_addstring_start(pktout);
5309 ssh2_pkt_addstring_data(pktout, data, len);
5310 end_log_omission(ssh, pktout);
5311 ssh2_pkt_send(ssh, pktout);
5312 bufchain_consume(&c->v.v2.outbuffer, len);
5313 c->v.v2.remwindow -= len;
5317 * After having sent as much data as we can, return the amount
5320 return bufchain_size(&c->v.v2.outbuffer);
5324 * Potentially enlarge the window on an SSH2 channel.
5326 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin)
5331 * Never send WINDOW_ADJUST for a channel that the remote side
5332 * already thinks it's closed; there's no point, since it won't
5333 * be sending any more data anyway.
5338 if (newwin > c->v.v2.locwindow) {
5339 struct Packet *pktout;
5341 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5342 ssh2_pkt_adduint32(pktout, c->remoteid);
5343 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
5344 ssh2_pkt_send(ssh, pktout);
5345 c->v.v2.locwindow = newwin;
5349 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
5351 unsigned i = ssh_pkt_getuint32(pktin);
5352 struct ssh_channel *c;
5353 c = find234(ssh->channels, &i, ssh_channelfind);
5354 if (c && !c->closes)
5355 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
5358 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
5361 unsigned int length;
5362 unsigned i = ssh_pkt_getuint32(pktin);
5363 struct ssh_channel *c;
5364 c = find234(ssh->channels, &i, ssh_channelfind);
5366 return; /* nonexistent channel */
5367 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
5368 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
5369 return; /* extended but not stderr */
5370 ssh_pkt_getstring(pktin, &data, &length);
5373 c->v.v2.locwindow -= length;
5375 case CHAN_MAINSESSION:
5377 from_backend(ssh->frontend, pktin->type ==
5378 SSH2_MSG_CHANNEL_EXTENDED_DATA,
5382 bufsize = x11_send(c->u.x11.s, data, length);
5385 bufsize = pfd_send(c->u.pfd.s, data, length);
5388 while (length > 0) {
5389 if (c->u.a.lensofar < 4) {
5390 unsigned int l = min(4 - c->u.a.lensofar, length);
5391 memcpy(c->u.a.msglen + c->u.a.lensofar,
5395 c->u.a.lensofar += l;
5397 if (c->u.a.lensofar == 4) {
5399 4 + GET_32BIT(c->u.a.msglen);
5400 c->u.a.message = snewn(c->u.a.totallen,
5402 memcpy(c->u.a.message, c->u.a.msglen, 4);
5404 if (c->u.a.lensofar >= 4 && length > 0) {
5406 min(c->u.a.totallen - c->u.a.lensofar,
5408 memcpy(c->u.a.message + c->u.a.lensofar,
5412 c->u.a.lensofar += l;
5414 if (c->u.a.lensofar == c->u.a.totallen) {
5417 if (agent_query(c->u.a.message,
5420 ssh_agentf_callback, c))
5421 ssh_agentf_callback(c, reply, replylen);
5422 sfree(c->u.a.message);
5423 c->u.a.lensofar = 0;
5430 * If we are not buffering too much data,
5431 * enlarge the window again at the remote side.
5433 if (bufsize < OUR_V2_WINSIZE)
5434 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
5438 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
5440 unsigned i = ssh_pkt_getuint32(pktin);
5441 struct ssh_channel *c;
5443 c = find234(ssh->channels, &i, ssh_channelfind);
5445 return; /* nonexistent channel */
5447 if (c->type == CHAN_X11) {
5449 * Remote EOF on an X11 channel means we should
5450 * wrap up and close the channel ourselves.
5452 x11_close(c->u.x11.s);
5454 } else if (c->type == CHAN_AGENT) {
5456 } else if (c->type == CHAN_SOCKDATA) {
5457 pfd_close(c->u.pfd.s);
5462 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
5464 unsigned i = ssh_pkt_getuint32(pktin);
5465 struct ssh_channel *c;
5466 struct Packet *pktout;
5468 c = find234(ssh->channels, &i, ssh_channelfind);
5469 if (!c || ((int)c->remoteid) == -1) {
5470 bombout(("Received CHANNEL_CLOSE for %s channel %d\n",
5471 c ? "half-open" : "nonexistent", i));
5474 /* Do pre-close processing on the channel. */
5476 case CHAN_MAINSESSION:
5477 ssh->mainchan = NULL;
5478 update_specials_menu(ssh->frontend);
5481 if (c->u.x11.s != NULL)
5482 x11_close(c->u.x11.s);
5489 if (c->u.pfd.s != NULL)
5490 pfd_close(c->u.pfd.s);
5494 if (c->closes == 0) {
5495 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
5496 ssh2_pkt_adduint32(pktout, c->remoteid);
5497 ssh2_pkt_send(ssh, pktout);
5499 del234(ssh->channels, c);
5500 bufchain_clear(&c->v.v2.outbuffer);
5504 * See if that was the last channel left open.
5505 * (This is only our termination condition if we're
5506 * not running in -N mode.)
5508 if (!ssh->cfg.ssh_no_shell && count234(ssh->channels) == 0) {
5509 logevent("All channels closed. Disconnecting");
5512 * We used to send SSH_MSG_DISCONNECT here,
5513 * because I'd believed that _every_ conforming
5514 * SSH2 connection had to end with a disconnect
5515 * being sent by at least one side; apparently
5516 * I was wrong and it's perfectly OK to
5517 * unceremoniously slam the connection shut
5518 * when you're done, and indeed OpenSSH feels
5519 * this is more polite than sending a
5520 * DISCONNECT. So now we don't.
5522 s->pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
5523 ssh2_pkt_adduint32(s->pktout, SSH2_DISCONNECT_BY_APPLICATION);
5524 ssh2_pkt_addstring(s->pktout, "All open channels closed");
5525 ssh2_pkt_addstring(s->pktout, "en"); /* language tag */
5526 ssh2_pkt_send_noqueue(ssh, s->pktout);
5528 ssh_closing((Plug)ssh, NULL, 0, 0);
5532 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
5534 unsigned i = ssh_pkt_getuint32(pktin);
5535 struct ssh_channel *c;
5536 struct Packet *pktout;
5538 c = find234(ssh->channels, &i, ssh_channelfind);
5540 return; /* nonexistent channel */
5541 if (c->type != CHAN_SOCKDATA_DORMANT)
5542 return; /* dunno why they're confirming this */
5543 c->remoteid = ssh_pkt_getuint32(pktin);
5544 c->type = CHAN_SOCKDATA;
5545 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
5546 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
5548 pfd_confirm(c->u.pfd.s);
5551 * We have a pending close on this channel,
5552 * which we decided on before the server acked
5553 * the channel open. So now we know the
5554 * remoteid, we can close it again.
5556 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
5557 ssh2_pkt_adduint32(pktout, c->remoteid);
5558 ssh2_pkt_send(ssh, pktout);
5562 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
5564 static const char *const reasons[] = {
5565 "<unknown reason code>",
5566 "Administratively prohibited",
5568 "Unknown channel type",
5569 "Resource shortage",
5571 unsigned i = ssh_pkt_getuint32(pktin);
5572 unsigned reason_code;
5573 char *reason_string;
5576 struct ssh_channel *c;
5577 c = find234(ssh->channels, &i, ssh_channelfind);
5579 return; /* nonexistent channel */
5580 if (c->type != CHAN_SOCKDATA_DORMANT)
5581 return; /* dunno why they're failing this */
5583 reason_code = ssh_pkt_getuint32(pktin);
5584 if (reason_code >= lenof(reasons))
5585 reason_code = 0; /* ensure reasons[reason_code] in range */
5586 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
5587 message = dupprintf("Forwarded connection refused by"
5588 " server: %s [%.*s]", reasons[reason_code],
5589 reason_length, reason_string);
5593 pfd_close(c->u.pfd.s);
5595 del234(ssh->channels, c);
5599 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
5603 int typelen, want_reply;
5604 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
5605 struct ssh_channel *c;
5606 struct Packet *pktout;
5608 localid = ssh_pkt_getuint32(pktin);
5609 ssh_pkt_getstring(pktin, &type, &typelen);
5610 want_reply = ssh2_pkt_getbool(pktin);
5613 * First, check that the channel exists. Otherwise,
5614 * we can instantly disconnect with a rude message.
5616 c = find234(ssh->channels, &localid, ssh_channelfind);
5619 sprintf(buf, "Received channel request for nonexistent"
5620 " channel %d", localid);
5622 pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
5623 ssh2_pkt_adduint32(pktout, SSH2_DISCONNECT_BY_APPLICATION);
5624 ssh2_pkt_addstring(pktout, buf);
5625 ssh2_pkt_addstring(pktout, "en"); /* language tag */
5626 ssh2_pkt_send_noqueue(ssh, pktout);
5627 connection_fatal(ssh->frontend, "%s", buf);
5628 ssh_closing((Plug)ssh, NULL, 0, 0);
5633 * Having got the channel number, we now look at
5634 * the request type string to see if it's something
5637 if (c == ssh->mainchan) {
5639 * We recognise "exit-status" and "exit-signal" on
5640 * the primary channel.
5642 if (typelen == 11 &&
5643 !memcmp(type, "exit-status", 11)) {
5645 ssh->exitcode = ssh_pkt_getuint32(pktin);
5646 logeventf(ssh, "Server sent command exit status %d",
5648 reply = SSH2_MSG_CHANNEL_SUCCESS;
5650 } else if (typelen == 11 &&
5651 !memcmp(type, "exit-signal", 11)) {
5653 int is_plausible = TRUE, is_int = FALSE;
5654 char *fmt_sig = "", *fmt_msg = "";
5656 int msglen = 0, core = FALSE;
5657 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
5658 * provide an `int' for the signal, despite its
5659 * having been a `string' in the drafts since at
5660 * least 2001. (Fixed in session.c 1.147.) Try to
5661 * infer which we can safely parse it as. */
5663 unsigned char *p = pktin->body +
5665 long len = pktin->length - pktin->savedpos;
5666 unsigned long num = GET_32BIT(p); /* what is it? */
5667 /* If it's 0, it hardly matters; assume string */
5671 int maybe_int = FALSE, maybe_str = FALSE;
5672 #define CHECK_HYPOTHESIS(offset, result) \
5675 if (q >= 0 && q+4 <= len) { \
5676 q = q + 4 + GET_32BIT(p+q); \
5677 if (q >= 0 && q+4 <= len && \
5678 (q = q + 4 + GET_32BIT(p+q)) && q == len) \
5682 CHECK_HYPOTHESIS(4+1, maybe_int);
5683 CHECK_HYPOTHESIS(4+num+1, maybe_str);
5684 #undef CHECK_HYPOTHESIS
5685 if (maybe_int && !maybe_str)
5687 else if (!maybe_int && maybe_str)
5690 /* Crikey. Either or neither. Panic. */
5691 is_plausible = FALSE;
5696 /* Old non-standard OpenSSH. */
5697 int signum = ssh_pkt_getuint32(pktin);
5698 fmt_sig = dupprintf(" %d", signum);
5700 /* As per the drafts. */
5703 ssh_pkt_getstring(pktin, &sig, &siglen);
5704 /* Signal name isn't supposed to be blank, but
5705 * let's cope gracefully if it is. */
5707 fmt_sig = dupprintf(" \"%.*s\"",
5711 core = ssh2_pkt_getbool(pktin);
5712 ssh_pkt_getstring(pktin, &msg, &msglen);
5714 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
5716 /* ignore lang tag */
5717 } /* else don't attempt to parse */
5718 logeventf(ssh, "Server exited on signal%s%s%s",
5719 fmt_sig, core ? " (core dumped)" : "",
5721 if (*fmt_sig) sfree(fmt_sig);
5722 if (*fmt_msg) sfree(fmt_msg);
5723 reply = SSH2_MSG_CHANNEL_SUCCESS;
5728 * This is a channel request we don't know
5729 * about, so we now either ignore the request
5730 * or respond with CHANNEL_FAILURE, depending
5733 reply = SSH2_MSG_CHANNEL_FAILURE;
5736 pktout = ssh2_pkt_init(reply);
5737 ssh2_pkt_adduint32(pktout, c->remoteid);
5738 ssh2_pkt_send(ssh, pktout);
5742 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
5745 int typelen, want_reply;
5746 struct Packet *pktout;
5748 ssh_pkt_getstring(pktin, &type, &typelen);
5749 want_reply = ssh2_pkt_getbool(pktin);
5752 * We currently don't support any global requests
5753 * at all, so we either ignore the request or
5754 * respond with REQUEST_FAILURE, depending on
5758 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
5759 ssh2_pkt_send(ssh, pktout);
5763 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
5771 struct ssh_channel *c;
5772 unsigned remid, winsize, pktsize;
5773 struct Packet *pktout;
5775 ssh_pkt_getstring(pktin, &type, &typelen);
5776 c = snew(struct ssh_channel);
5779 remid = ssh_pkt_getuint32(pktin);
5780 winsize = ssh_pkt_getuint32(pktin);
5781 pktsize = ssh_pkt_getuint32(pktin);
5783 if (typelen == 3 && !memcmp(type, "x11", 3)) {
5786 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
5787 addrstr = snewn(peeraddrlen+1, char);
5788 memcpy(addrstr, peeraddr, peeraddrlen);
5789 addrstr[peeraddrlen] = '\0';
5790 peerport = ssh_pkt_getuint32(pktin);
5792 logeventf(ssh, "Received X11 connect request from %s:%d",
5795 if (!ssh->X11_fwd_enabled)
5796 error = "X11 forwarding is not enabled";
5797 else if (x11_init(&c->u.x11.s, ssh->cfg.x11_display, c,
5798 ssh->x11auth, addrstr, peerport,
5799 &ssh->cfg) != NULL) {
5800 error = "Unable to open an X11 connection";
5802 logevent("Opening X11 forward connection succeeded");
5807 } else if (typelen == 15 &&
5808 !memcmp(type, "forwarded-tcpip", 15)) {
5809 struct ssh_rportfwd pf, *realpf;
5812 ssh_pkt_getstring(pktin, &dummy, &dummylen);/* skip address */
5813 pf.sport = ssh_pkt_getuint32(pktin);
5814 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
5815 peerport = ssh_pkt_getuint32(pktin);
5816 realpf = find234(ssh->rportfwds, &pf, NULL);
5817 logeventf(ssh, "Received remote port %d open request "
5818 "from %s:%d", pf.sport, peeraddr, peerport);
5819 if (realpf == NULL) {
5820 error = "Remote port is not recognised";
5822 const char *e = pfd_newconnect(&c->u.pfd.s,
5826 realpf->pfrec->addressfamily);
5827 logeventf(ssh, "Attempting to forward remote port to "
5828 "%s:%d", realpf->dhost, realpf->dport);
5830 logeventf(ssh, "Port open failed: %s", e);
5831 error = "Port open failed";
5833 logevent("Forwarded port opened successfully");
5834 c->type = CHAN_SOCKDATA;
5837 } else if (typelen == 22 &&
5838 !memcmp(type, "auth-agent@openssh.com", 3)) {
5839 if (!ssh->agentfwd_enabled)
5840 error = "Agent forwarding is not enabled";
5842 c->type = CHAN_AGENT; /* identify channel type */
5843 c->u.a.lensofar = 0;
5846 error = "Unsupported channel type requested";
5849 c->remoteid = remid;
5851 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
5852 ssh2_pkt_adduint32(pktout, c->remoteid);
5853 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
5854 ssh2_pkt_addstring(pktout, error);
5855 ssh2_pkt_addstring(pktout, "en"); /* language tag */
5856 ssh2_pkt_send(ssh, pktout);
5857 logeventf(ssh, "Rejected channel open: %s", error);
5860 c->localid = alloc_channel_id(ssh);
5862 c->v.v2.locwindow = OUR_V2_WINSIZE;
5863 c->v.v2.remwindow = winsize;
5864 c->v.v2.remmaxpkt = pktsize;
5865 bufchain_init(&c->v.v2.outbuffer);
5866 add234(ssh->channels, c);
5867 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
5868 ssh2_pkt_adduint32(pktout, c->remoteid);
5869 ssh2_pkt_adduint32(pktout, c->localid);
5870 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
5871 ssh2_pkt_adduint32(pktout, 0x4000UL); /* our max pkt size */
5872 ssh2_pkt_send(ssh, pktout);
5877 * Handle the SSH2 userauth and connection layers.
5879 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
5880 struct Packet *pktin)
5882 struct do_ssh2_authconn_state {
5884 AUTH_INVALID, AUTH_PUBLICKEY_AGENT, AUTH_PUBLICKEY_FILE,
5886 AUTH_KEYBOARD_INTERACTIVE
5890 AUTH_TYPE_PUBLICKEY,
5891 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
5892 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
5894 AUTH_TYPE_KEYBOARD_INTERACTIVE,
5895 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
5897 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
5898 int tried_pubkey_config, tried_agent, tried_keyb_inter;
5899 int kbd_inter_running;
5901 int num_prompts, curr_prompt, echo;
5906 void *publickey_blob;
5907 int publickey_bloblen;
5908 unsigned char request[5], *response, *p;
5912 char *pkblob, *alg, *commentp;
5913 int pklen, alglen, commentlen;
5914 int siglen, retlen, len;
5915 char *q, *agentreq, *ret;
5917 int num_env, env_left, env_ok;
5918 struct Packet *pktout;
5920 crState(do_ssh2_authconn_state);
5922 crBegin(ssh->do_ssh2_authconn_crstate);
5925 * Request userauth protocol, and await a response to it.
5927 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
5928 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
5929 ssh2_pkt_send(ssh, s->pktout);
5930 crWaitUntilV(pktin);
5931 if (pktin->type != SSH2_MSG_SERVICE_ACCEPT) {
5932 bombout(("Server refused user authentication protocol"));
5937 * We repeat this whole loop, including the username prompt,
5938 * until we manage a successful authentication. If the user
5939 * types the wrong _password_, they can be sent back to the
5940 * beginning to try another username, if this is configured on.
5941 * (If they specify a username in the config, they are never
5942 * asked, even if they do give a wrong password.)
5944 * I think this best serves the needs of
5946 * - the people who have no configuration, no keys, and just
5947 * want to try repeated (username,password) pairs until they
5948 * type both correctly
5950 * - people who have keys and configuration but occasionally
5951 * need to fall back to passwords
5953 * - people with a key held in Pageant, who might not have
5954 * logged in to a particular machine before; so they want to
5955 * type a username, and then _either_ their key will be
5956 * accepted, _or_ they will type a password. If they mistype
5957 * the username they will want to be able to get back and
5960 s->username[0] = '\0';
5961 s->got_username = FALSE;
5966 if (s->got_username && !ssh->cfg.change_username) {
5968 * We got a username last time round this loop, and
5969 * with change_username turned off we don't try to get
5972 } else if (!*ssh->cfg.username) {
5973 if (ssh_get_line && !ssh_getline_pw_only) {
5974 if (!ssh_get_line("login as: ",
5975 s->username, sizeof(s->username), FALSE)) {
5977 * get_line failed to get a username.
5980 logevent("No username provided. Abandoning session.");
5981 ssh_closing((Plug)ssh, NULL, 0, 0);
5985 int ret; /* need not be saved across crReturn */
5986 c_write_str(ssh, "login as: ");
5988 setup_userpass_input(ssh, s->username, sizeof(s->username), 1);
5990 crWaitUntilV(!pktin);
5991 ret = process_userpass_input(ssh, in, inlen);
5995 c_write_str(ssh, "\r\n");
5997 s->username[strcspn(s->username, "\n\r")] = '\0';
6000 strncpy(s->username, ssh->cfg.username, sizeof(s->username));
6001 s->username[sizeof(s->username)-1] = '\0';
6002 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
6003 stuff = dupprintf("Using username \"%s\".\r\n", s->username);
6004 c_write_str(ssh, stuff);
6008 s->got_username = TRUE;
6011 * Send an authentication request using method "none": (a)
6012 * just in case it succeeds, and (b) so that we know what
6013 * authentication methods we can usefully try next.
6015 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6017 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6018 ssh2_pkt_addstring(s->pktout, s->username);
6019 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
6020 ssh2_pkt_addstring(s->pktout, "none"); /* method */
6021 ssh2_pkt_send(ssh, s->pktout);
6022 s->type = AUTH_TYPE_NONE;
6024 s->we_are_in = FALSE;
6026 s->tried_pubkey_config = FALSE;
6027 s->tried_agent = FALSE;
6028 s->tried_keyb_inter = FALSE;
6029 s->kbd_inter_running = FALSE;
6030 /* Load the pub half of ssh->cfg.keyfile so we notice if it's in Pageant */
6031 if (!filename_is_null(ssh->cfg.keyfile)) {
6033 logeventf(ssh, "Reading private key file \"%.150s\"",
6034 filename_to_str(&ssh->cfg.keyfile));
6035 keytype = key_type(&ssh->cfg.keyfile);
6036 if (keytype == SSH_KEYTYPE_SSH2) {
6038 ssh2_userkey_loadpub(&ssh->cfg.keyfile, NULL,
6039 &s->publickey_bloblen, NULL);
6042 logeventf(ssh, "Unable to use this key file (%s)",
6043 key_type_to_str(keytype));
6044 msgbuf = dupprintf("Unable to use key file \"%.150s\""
6046 filename_to_str(&ssh->cfg.keyfile),
6047 key_type_to_str(keytype));
6048 c_write_str(ssh, msgbuf);
6050 s->publickey_blob = NULL;
6053 s->publickey_blob = NULL;
6057 * Wait for the result of the last authentication request.
6060 crWaitUntilV(pktin);
6061 while (pktin->type == SSH2_MSG_USERAUTH_BANNER) {
6065 * Don't show the banner if we're operating in
6066 * non-verbose non-interactive mode. (It's probably
6067 * a script, which means nobody will read the
6068 * banner _anyway_, and moreover the printing of
6069 * the banner will screw up processing on the
6070 * output of (say) plink.)
6072 if (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE)) {
6073 ssh_pkt_getstring(pktin, &banner, &size);
6075 c_write_untrusted(ssh, banner, size);
6077 crWaitUntilV(pktin);
6079 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
6080 logevent("Access granted");
6081 s->we_are_in = TRUE;
6085 if (s->kbd_inter_running &&
6086 pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
6088 * This is either a further set-of-prompts packet
6089 * in keyboard-interactive authentication, or it's
6090 * the same one and we came back here with `gotit'
6091 * set. In the former case, we must reset the
6092 * curr_prompt variable.
6096 } else if (pktin->type != SSH2_MSG_USERAUTH_FAILURE) {
6097 bombout(("Strange packet received during authentication: type %d",
6105 * OK, we're now sitting on a USERAUTH_FAILURE message, so
6106 * we can look at the string in it and know what we can
6107 * helpfully try next.
6109 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
6112 ssh_pkt_getstring(pktin, &methods, &methlen);
6113 s->kbd_inter_running = FALSE;
6114 if (!ssh2_pkt_getbool(pktin)) {
6116 * We have received an unequivocal Access
6117 * Denied. This can translate to a variety of
6120 * - if we'd just tried "none" authentication,
6121 * it's not worth printing anything at all
6123 * - if we'd just tried a public key _offer_,
6124 * the message should be "Server refused our
6125 * key" (or no message at all if the key
6126 * came from Pageant)
6128 * - if we'd just tried anything else, the
6129 * message really should be "Access denied".
6131 * Additionally, if we'd just tried password
6132 * authentication, we should break out of this
6133 * whole loop so as to go back to the username
6134 * prompt (iff we're configured to allow
6135 * username change attempts).
6137 if (s->type == AUTH_TYPE_NONE) {
6139 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
6140 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
6141 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
6142 c_write_str(ssh, "Server refused our key\r\n");
6143 logevent("Server refused public key");
6144 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
6145 /* server declined keyboard-interactive; ignore */
6147 c_write_str(ssh, "Access denied\r\n");
6148 logevent("Access denied");
6149 if (s->type == AUTH_TYPE_PASSWORD &&
6150 ssh->cfg.change_username) {
6151 /* XXX perhaps we should allow
6152 * keyboard-interactive to do this too? */
6153 s->we_are_in = FALSE;
6158 c_write_str(ssh, "Further authentication required\r\n");
6159 logevent("Further authentication required");
6163 in_commasep_string("publickey", methods, methlen);
6165 in_commasep_string("password", methods, methlen);
6166 s->can_keyb_inter = ssh->cfg.try_ki_auth &&
6167 in_commasep_string("keyboard-interactive", methods, methlen);
6171 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6175 * Most password/passphrase prompts will be
6176 * non-echoing, so we set this to 0 by default.
6177 * Exception is that some keyboard-interactive prompts
6178 * can be echoing, in which case we'll set this to 1.
6182 if (!s->method && s->can_pubkey &&
6183 agent_exists() && !s->tried_agent) {
6185 * Attempt public-key authentication using Pageant.
6190 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6191 ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
6193 s->tried_agent = TRUE;
6195 logevent("Pageant is running. Requesting keys.");
6197 /* Request the keys held by the agent. */
6198 PUT_32BIT(s->request, 1);
6199 s->request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
6200 if (!agent_query(s->request, 5, &r, &s->responselen,
6201 ssh_agent_callback, ssh)) {
6205 bombout(("Unexpected data from server while"
6206 " waiting for agent response"));
6209 } while (pktin || inlen > 0);
6210 r = ssh->agent_response;
6211 s->responselen = ssh->agent_response_len;
6213 s->response = (unsigned char *) r;
6214 if (s->response && s->responselen >= 5 &&
6215 s->response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
6216 s->p = s->response + 5;
6217 s->nkeys = GET_32BIT(s->p);
6221 sprintf(buf, "Pageant has %d SSH2 keys", s->nkeys);
6224 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
6229 sprintf(buf, "Trying Pageant key #%d", s->keyi);
6232 s->pklen = GET_32BIT(s->p);
6234 if (s->publickey_blob &&
6235 s->pklen == s->publickey_bloblen &&
6236 !memcmp(s->p, s->publickey_blob,
6237 s->publickey_bloblen)) {
6238 logevent("This key matches configured key file");
6239 s->tried_pubkey_config = 1;
6241 s->pkblob = (char *)s->p;
6243 s->alglen = GET_32BIT(s->pkblob);
6244 s->alg = s->pkblob + 4;
6245 s->commentlen = GET_32BIT(s->p);
6247 s->commentp = (char *)s->p;
6248 s->p += s->commentlen;
6249 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6250 ssh2_pkt_addstring(s->pktout, s->username);
6251 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
6252 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
6253 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
6254 ssh2_pkt_addstring_start(s->pktout);
6255 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
6256 ssh2_pkt_addstring_start(s->pktout);
6257 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
6258 ssh2_pkt_send(ssh, s->pktout);
6260 crWaitUntilV(pktin);
6261 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
6262 logevent("Key refused");
6266 if (flags & FLAG_VERBOSE) {
6267 c_write_str(ssh, "Authenticating with "
6269 c_write(ssh, s->commentp, s->commentlen);
6270 c_write_str(ssh, "\" from agent\r\n");
6274 * Server is willing to accept the key.
6275 * Construct a SIGN_REQUEST.
6277 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6278 ssh2_pkt_addstring(s->pktout, s->username);
6279 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
6280 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
6281 ssh2_pkt_addbool(s->pktout, TRUE);
6282 ssh2_pkt_addstring_start(s->pktout);
6283 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
6284 ssh2_pkt_addstring_start(s->pktout);
6285 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
6287 s->siglen = s->pktout->length - 5 + 4 + 20;
6288 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
6290 s->len = 1; /* message type */
6291 s->len += 4 + s->pklen; /* key blob */
6292 s->len += 4 + s->siglen; /* data to sign */
6293 s->len += 4; /* flags */
6294 s->agentreq = snewn(4 + s->len, char);
6295 PUT_32BIT(s->agentreq, s->len);
6296 s->q = s->agentreq + 4;
6297 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
6298 PUT_32BIT(s->q, s->pklen);
6300 memcpy(s->q, s->pkblob, s->pklen);
6302 PUT_32BIT(s->q, s->siglen);
6304 /* Now the data to be signed... */
6305 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
6306 PUT_32BIT(s->q, 20);
6309 memcpy(s->q, ssh->v2_session_id, 20);
6311 memcpy(s->q, s->pktout->data + 5,
6312 s->pktout->length - 5);
6313 s->q += s->pktout->length - 5;
6314 /* And finally the (zero) flags word. */
6316 if (!agent_query(s->agentreq, s->len + 4,
6318 ssh_agent_callback, ssh)) {
6322 bombout(("Unexpected data from server"
6323 " while waiting for agent"
6327 } while (pktin || inlen > 0);
6328 vret = ssh->agent_response;
6329 s->retlen = ssh->agent_response_len;
6334 if (s->ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
6335 logevent("Sending Pageant's response");
6336 ssh2_add_sigblob(ssh, s->pktout,
6337 s->pkblob, s->pklen,
6339 GET_32BIT(s->ret + 5));
6340 ssh2_pkt_send(ssh, s->pktout);
6345 ("Pageant failed to answer challenge");
6356 if (!s->method && s->can_pubkey && s->publickey_blob
6357 && !s->tried_pubkey_config) {
6358 unsigned char *pub_blob;
6359 char *algorithm, *comment;
6362 s->tried_pubkey_config = TRUE;
6364 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6365 ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
6368 * Try the public key supplied in the configuration.
6370 * First, offer the public blob to see if the server is
6371 * willing to accept it.
6374 (unsigned char *)ssh2_userkey_loadpub(&ssh->cfg.keyfile,
6379 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6380 ssh2_pkt_addstring(s->pktout, s->username);
6381 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
6382 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
6383 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
6384 ssh2_pkt_addstring(s->pktout, algorithm);
6385 ssh2_pkt_addstring_start(s->pktout);
6386 ssh2_pkt_addstring_data(s->pktout, (char *)pub_blob,
6388 ssh2_pkt_send(ssh, s->pktout);
6389 logevent("Offered public key");
6391 crWaitUntilV(pktin);
6392 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
6394 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
6395 continue; /* key refused; give up on it */
6398 logevent("Offer of public key accepted");
6400 * Actually attempt a serious authentication using
6403 if (ssh2_userkey_encrypted(&ssh->cfg.keyfile, &comment)) {
6404 sprintf(s->pwprompt,
6405 "Passphrase for key \"%.100s\": ",
6411 if (flags & FLAG_VERBOSE) {
6412 c_write_str(ssh, "Authenticating with public key \"");
6413 c_write_str(ssh, comment);
6414 c_write_str(ssh, "\"\r\n");
6416 s->method = AUTH_PUBLICKEY_FILE;
6420 if (!s->method && s->can_keyb_inter && !s->tried_keyb_inter) {
6421 s->method = AUTH_KEYBOARD_INTERACTIVE;
6422 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
6423 s->tried_keyb_inter = TRUE;
6425 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6426 ssh->pkt_ctx |= SSH2_PKTCTX_KBDINTER;
6428 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6429 ssh2_pkt_addstring(s->pktout, s->username);
6430 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
6431 ssh2_pkt_addstring(s->pktout, "keyboard-interactive"); /* method */
6432 ssh2_pkt_addstring(s->pktout, ""); /* lang */
6433 ssh2_pkt_addstring(s->pktout, "");
6434 ssh2_pkt_send(ssh, s->pktout);
6436 crWaitUntilV(pktin);
6437 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
6438 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE)
6440 logevent("Keyboard-interactive authentication refused");
6441 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
6445 s->kbd_inter_running = TRUE;
6449 if (s->kbd_inter_running) {
6450 s->method = AUTH_KEYBOARD_INTERACTIVE;
6451 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
6452 s->tried_keyb_inter = TRUE;
6454 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6455 ssh->pkt_ctx |= SSH2_PKTCTX_KBDINTER;
6457 if (s->curr_prompt == 0) {
6459 * We've got a fresh USERAUTH_INFO_REQUEST.
6460 * Display header data, and start going through
6463 char *name, *inst, *lang;
6464 int name_len, inst_len, lang_len;
6466 ssh_pkt_getstring(pktin, &name, &name_len);
6467 ssh_pkt_getstring(pktin, &inst, &inst_len);
6468 ssh_pkt_getstring(pktin, &lang, &lang_len);
6470 c_write_untrusted(ssh, name, name_len);
6471 c_write_str(ssh, "\r\n");
6474 c_write_untrusted(ssh, inst, inst_len);
6475 c_write_str(ssh, "\r\n");
6477 s->num_prompts = ssh_pkt_getuint32(pktin);
6481 * If there are prompts remaining in the packet,
6482 * display one and get a response.
6484 if (s->curr_prompt < s->num_prompts) {
6488 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
6489 if (prompt_len > 0) {
6490 static const char trunc[] = "<prompt truncated>: ";
6491 static const int prlen = sizeof(s->pwprompt) -
6493 if (prompt_len > prlen) {
6494 memcpy(s->pwprompt, prompt, prlen);
6495 strcpy(s->pwprompt + prlen, trunc);
6497 memcpy(s->pwprompt, prompt, prompt_len);
6498 s->pwprompt[prompt_len] = '\0';
6502 "<server failed to send prompt>: ");
6504 s->echo = ssh2_pkt_getbool(pktin);
6510 if (!s->method && s->can_passwd) {
6511 s->method = AUTH_PASSWORD;
6512 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6513 ssh->pkt_ctx |= SSH2_PKTCTX_PASSWORD;
6514 sprintf(s->pwprompt, "%.90s@%.90s's password: ", s->username,
6521 if (!ssh_get_line(s->pwprompt, s->password,
6522 sizeof(s->password), TRUE)) {
6524 * get_line failed to get a password (for
6525 * example because one was supplied on the
6526 * command line which has already failed to
6529 s->pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
6530 ssh2_pkt_adduint32(s->pktout,SSH2_DISCONNECT_BY_APPLICATION);
6531 ssh2_pkt_addstring(s->pktout, "No more passwords available"
6533 ssh2_pkt_addstring(s->pktout, "en"); /* language tag */
6534 ssh2_pkt_send_noqueue(ssh, s->pktout);
6535 logevent("Unable to authenticate");
6536 connection_fatal(ssh->frontend,
6537 "Unable to authenticate");
6538 ssh_closing((Plug)ssh, NULL, 0, 0);
6542 int ret; /* need not be saved across crReturn */
6543 c_write_untrusted(ssh, s->pwprompt, strlen(s->pwprompt));
6546 setup_userpass_input(ssh, s->password,
6547 sizeof(s->password), s->echo);
6549 crWaitUntilV(!pktin);
6550 ret = process_userpass_input(ssh, in, inlen);
6554 c_write_str(ssh, "\r\n");
6558 if (s->method == AUTH_PUBLICKEY_FILE) {
6560 * We have our passphrase. Now try the actual authentication.
6562 struct ssh2_userkey *key;
6563 const char *error = NULL;
6565 key = ssh2_load_userkey(&ssh->cfg.keyfile, s->password,
6567 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
6568 if (key == SSH2_WRONG_PASSPHRASE) {
6569 c_write_str(ssh, "Wrong passphrase\r\n");
6570 s->tried_pubkey_config = FALSE;
6572 c_write_str(ssh, "Unable to load private key (");
6573 c_write_str(ssh, error);
6574 c_write_str(ssh, ")\r\n");
6575 s->tried_pubkey_config = TRUE;
6577 /* Send a spurious AUTH_NONE to return to the top. */
6578 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6579 ssh2_pkt_addstring(s->pktout, s->username);
6580 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
6581 ssh2_pkt_addstring(s->pktout, "none"); /* method */
6582 ssh2_pkt_send(ssh, s->pktout);
6583 s->type = AUTH_TYPE_NONE;
6585 unsigned char *pkblob, *sigblob, *sigdata;
6586 int pkblob_len, sigblob_len, sigdata_len;
6590 * We have loaded the private key and the server
6591 * has announced that it's willing to accept it.
6592 * Hallelujah. Generate a signature and send it.
6594 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6595 ssh2_pkt_addstring(s->pktout, s->username);
6596 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
6597 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
6598 ssh2_pkt_addbool(s->pktout, TRUE);
6599 ssh2_pkt_addstring(s->pktout, key->alg->name);
6600 pkblob = key->alg->public_blob(key->data, &pkblob_len);
6601 ssh2_pkt_addstring_start(s->pktout);
6602 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob, pkblob_len);
6605 * The data to be signed is:
6609 * followed by everything so far placed in the
6612 sigdata_len = s->pktout->length - 5 + 4 + 20;
6613 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
6615 sigdata = snewn(sigdata_len, unsigned char);
6617 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
6618 PUT_32BIT(sigdata+p, 20);
6621 memcpy(sigdata+p, ssh->v2_session_id, 20); p += 20;
6622 memcpy(sigdata+p, s->pktout->data + 5,
6623 s->pktout->length - 5);
6624 p += s->pktout->length - 5;
6625 assert(p == sigdata_len);
6626 sigblob = key->alg->sign(key->data, (char *)sigdata,
6627 sigdata_len, &sigblob_len);
6628 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
6629 sigblob, sigblob_len);
6634 ssh2_pkt_send(ssh, s->pktout);
6635 s->type = AUTH_TYPE_PUBLICKEY;
6636 key->alg->freekey(key->data);
6638 } else if (s->method == AUTH_PASSWORD) {
6640 * We send the password packet lumped tightly together with
6641 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
6642 * string long enough to make the total length of the two
6643 * packets constant. This should ensure that a passive
6644 * listener doing traffic analyis can't work out the length
6647 * For this to work, we need an assumption about the
6648 * maximum length of the password packet. I think 256 is
6649 * pretty conservative. Anyone using a password longer than
6650 * that probably doesn't have much to worry about from
6651 * people who find out how long their password is!
6653 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6654 ssh2_pkt_addstring(s->pktout, s->username);
6655 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
6656 ssh2_pkt_addstring(s->pktout, "password");
6657 ssh2_pkt_addbool(s->pktout, FALSE);
6658 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
6659 ssh2_pkt_addstring(s->pktout, s->password);
6660 memset(s->password, 0, sizeof(s->password));
6661 end_log_omission(ssh, s->pktout);
6662 ssh2_pkt_defer(ssh, s->pktout);
6664 * We'll include a string that's an exact multiple of the
6665 * cipher block size. If the cipher is NULL for some
6666 * reason, we don't do this trick at all because we gain
6669 if (ssh->cscipher) {
6672 stringlen = (256 - ssh->deferred_len);
6673 stringlen += ssh->cscipher->blksize - 1;
6674 stringlen -= (stringlen % ssh->cscipher->blksize);
6677 * Temporarily disable actual compression,
6678 * so we can guarantee to get this string
6679 * exactly the length we want it. The
6680 * compression-disabling routine should
6681 * return an integer indicating how many
6682 * bytes we should adjust our string length
6686 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
6688 s->pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
6689 ssh2_pkt_addstring_start(s->pktout);
6690 for (i = 0; i < stringlen; i++) {
6691 char c = (char) random_byte();
6692 ssh2_pkt_addstring_data(s->pktout, &c, 1);
6694 ssh2_pkt_defer(ssh, s->pktout);
6696 ssh_pkt_defersend(ssh);
6697 logevent("Sent password");
6698 s->type = AUTH_TYPE_PASSWORD;
6699 } else if (s->method == AUTH_KEYBOARD_INTERACTIVE) {
6700 if (s->curr_prompt == 0) {
6701 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
6702 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
6704 if (s->need_pw) { /* only add pw if we just got one! */
6705 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
6706 ssh2_pkt_addstring(s->pktout, s->password);
6707 memset(s->password, 0, sizeof(s->password));
6708 end_log_omission(ssh, s->pktout);
6711 if (s->curr_prompt >= s->num_prompts) {
6712 ssh2_pkt_send(ssh, s->pktout);
6715 * If there are prompts remaining, we set
6716 * `gotit' so that we won't attempt to get
6717 * another packet. Then we go back round the
6718 * loop and will end up retrieving another
6719 * prompt out of the existing packet. Funky or
6724 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
6726 c_write_str(ssh, "No supported authentication methods"
6727 " left to try!\r\n");
6728 logevent("No supported authentications offered."
6730 s->pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
6731 ssh2_pkt_adduint32(s->pktout, SSH2_DISCONNECT_BY_APPLICATION);
6732 ssh2_pkt_addstring(s->pktout, "No supported authentication"
6733 " methods available");
6734 ssh2_pkt_addstring(s->pktout, "en"); /* language tag */
6735 ssh2_pkt_send_noqueue(ssh, s->pktout);
6736 ssh_closing((Plug)ssh, NULL, 0, 0);
6740 } while (!s->we_are_in);
6743 * Now we're authenticated for the connection protocol. The
6744 * connection protocol will automatically have started at this
6745 * point; there's no need to send SERVICE_REQUEST.
6748 ssh->channels = newtree234(ssh_channelcmp);
6751 * Set up handlers for some connection protocol messages, so we
6752 * don't have to handle them repeatedly in this coroutine.
6754 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
6755 ssh2_msg_channel_window_adjust;
6756 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
6757 ssh2_msg_global_request;
6760 * Create the main session channel.
6762 if (!ssh->cfg.ssh_no_shell) {
6763 ssh->mainchan = snew(struct ssh_channel);
6764 ssh->mainchan->ssh = ssh;
6765 ssh->mainchan->localid = alloc_channel_id(ssh);
6766 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
6767 ssh2_pkt_addstring(s->pktout, "session");
6768 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
6769 ssh->mainchan->v.v2.locwindow = OUR_V2_WINSIZE;
6770 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
6771 ssh2_pkt_adduint32(s->pktout, 0x4000UL); /* our max pkt size */
6772 ssh2_pkt_send(ssh, s->pktout);
6773 crWaitUntilV(pktin);
6774 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
6775 bombout(("Server refused to open a session"));
6777 /* FIXME: error data comes back in FAILURE packet */
6779 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
6780 bombout(("Server's channel confirmation cited wrong channel"));
6783 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
6784 ssh->mainchan->type = CHAN_MAINSESSION;
6785 ssh->mainchan->closes = 0;
6786 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
6787 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
6788 bufchain_init(&ssh->mainchan->v.v2.outbuffer);
6789 add234(ssh->channels, ssh->mainchan);
6790 update_specials_menu(ssh->frontend);
6791 logevent("Opened channel for session");
6793 ssh->mainchan = NULL;
6796 * Now we have a channel, make dispatch table entries for
6797 * general channel-based messages.
6799 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
6800 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
6801 ssh2_msg_channel_data;
6802 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
6803 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
6804 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
6805 ssh2_msg_channel_open_confirmation;
6806 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
6807 ssh2_msg_channel_open_failure;
6808 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
6809 ssh2_msg_channel_request;
6810 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
6811 ssh2_msg_channel_open;
6814 * Potentially enable X11 forwarding.
6816 if (ssh->mainchan && ssh->cfg.x11_forward) {
6817 char proto[20], data[64];
6818 logevent("Requesting X11 forwarding");
6819 ssh->x11auth = x11_invent_auth(proto, sizeof(proto),
6820 data, sizeof(data), ssh->cfg.x11_auth);
6821 x11_get_real_auth(ssh->x11auth, ssh->cfg.x11_display);
6822 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6823 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
6824 ssh2_pkt_addstring(s->pktout, "x11-req");
6825 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
6826 ssh2_pkt_addbool(s->pktout, 0); /* many connections */
6827 ssh2_pkt_addstring(s->pktout, proto);
6828 ssh2_pkt_addstring(s->pktout, data);
6829 ssh2_pkt_adduint32(s->pktout, x11_get_screen_number(ssh->cfg.x11_display));
6830 ssh2_pkt_send(ssh, s->pktout);
6832 crWaitUntilV(pktin);
6834 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
6835 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
6836 bombout(("Unexpected response to X11 forwarding request:"
6837 " packet type %d", pktin->type));
6840 logevent("X11 forwarding refused");
6842 logevent("X11 forwarding enabled");
6843 ssh->X11_fwd_enabled = TRUE;
6848 * Enable port forwardings.
6850 ssh_setup_portfwd(ssh, &ssh->cfg);
6853 * Potentially enable agent forwarding.
6855 if (ssh->mainchan && ssh->cfg.agentfwd && agent_exists()) {
6856 logevent("Requesting OpenSSH-style agent forwarding");
6857 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6858 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
6859 ssh2_pkt_addstring(s->pktout, "auth-agent-req@openssh.com");
6860 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
6861 ssh2_pkt_send(ssh, s->pktout);
6863 crWaitUntilV(pktin);
6865 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
6866 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
6867 bombout(("Unexpected response to agent forwarding request:"
6868 " packet type %d", pktin->type));
6871 logevent("Agent forwarding refused");
6873 logevent("Agent forwarding enabled");
6874 ssh->agentfwd_enabled = TRUE;
6879 * Now allocate a pty for the session.
6881 if (ssh->mainchan && !ssh->cfg.nopty) {
6882 /* Unpick the terminal-speed string. */
6883 /* XXX perhaps we should allow no speeds to be sent. */
6884 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
6885 sscanf(ssh->cfg.termspeed, "%d,%d", &ssh->ospeed, &ssh->ispeed);
6886 /* Build the pty request. */
6887 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6888 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
6889 ssh2_pkt_addstring(s->pktout, "pty-req");
6890 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
6891 ssh2_pkt_addstring(s->pktout, ssh->cfg.termtype);
6892 ssh2_pkt_adduint32(s->pktout, ssh->term_width);
6893 ssh2_pkt_adduint32(s->pktout, ssh->term_height);
6894 ssh2_pkt_adduint32(s->pktout, 0); /* pixel width */
6895 ssh2_pkt_adduint32(s->pktout, 0); /* pixel height */
6896 ssh2_pkt_addstring_start(s->pktout);
6897 ssh2_pkt_addbyte(s->pktout, 128); /* TTY_OP_ISPEED */
6898 ssh2_pkt_adduint32(s->pktout, ssh->ispeed);
6899 ssh2_pkt_addbyte(s->pktout, 129); /* TTY_OP_OSPEED */
6900 ssh2_pkt_adduint32(s->pktout, ssh->ospeed);
6901 ssh2_pkt_addstring_data(s->pktout, "\0", 1); /* TTY_OP_END */
6902 ssh2_pkt_send(ssh, s->pktout);
6903 ssh->state = SSH_STATE_INTERMED;
6905 crWaitUntilV(pktin);
6907 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
6908 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
6909 bombout(("Unexpected response to pty request:"
6910 " packet type %d", pktin->type));
6913 c_write_str(ssh, "Server refused to allocate pty\r\n");
6914 ssh->editing = ssh->echoing = 1;
6916 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
6917 ssh->ospeed, ssh->ispeed);
6920 ssh->editing = ssh->echoing = 1;
6924 * Send environment variables.
6926 * Simplest thing here is to send all the requests at once, and
6927 * then wait for a whole bunch of successes or failures.
6929 if (ssh->mainchan && *ssh->cfg.environmt) {
6930 char *e = ssh->cfg.environmt;
6931 char *var, *varend, *val;
6937 while (*e && *e != '\t') e++;
6939 if (*e == '\t') e++;
6944 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6945 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
6946 ssh2_pkt_addstring(s->pktout, "env");
6947 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
6948 ssh2_pkt_addstring_start(s->pktout);
6949 ssh2_pkt_addstring_data(s->pktout, var, varend-var);
6950 ssh2_pkt_addstring(s->pktout, val);
6951 ssh2_pkt_send(ssh, s->pktout);
6956 logeventf(ssh, "Sent %d environment variables", s->num_env);
6959 s->env_left = s->num_env;
6961 while (s->env_left > 0) {
6962 crWaitUntilV(pktin);
6964 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
6965 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
6966 bombout(("Unexpected response to environment request:"
6967 " packet type %d", pktin->type));
6977 if (s->env_ok == s->num_env) {
6978 logevent("All environment variables successfully set");
6979 } else if (s->env_ok == 0) {
6980 logevent("All environment variables refused");
6981 c_write_str(ssh, "Server refused to set environment variables\r\n");
6983 logeventf(ssh, "%d environment variables refused",
6984 s->num_env - s->env_ok);
6985 c_write_str(ssh, "Server refused to set all environment variables\r\n");
6990 * Start a shell or a remote command. We may have to attempt
6991 * this twice if the config data has provided a second choice
6994 if (ssh->mainchan) while (1) {
6998 if (ssh->fallback_cmd) {
6999 subsys = ssh->cfg.ssh_subsys2;
7000 cmd = ssh->cfg.remote_cmd_ptr2;
7002 subsys = ssh->cfg.ssh_subsys;
7003 cmd = ssh->cfg.remote_cmd_ptr;
7006 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7007 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
7009 ssh2_pkt_addstring(s->pktout, "subsystem");
7010 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
7011 ssh2_pkt_addstring(s->pktout, cmd);
7013 ssh2_pkt_addstring(s->pktout, "exec");
7014 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
7015 ssh2_pkt_addstring(s->pktout, cmd);
7017 ssh2_pkt_addstring(s->pktout, "shell");
7018 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
7020 ssh2_pkt_send(ssh, s->pktout);
7022 crWaitUntilV(pktin);
7024 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
7025 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
7026 bombout(("Unexpected response to shell/command request:"
7027 " packet type %d", pktin->type));
7031 * We failed to start the command. If this is the
7032 * fallback command, we really are finished; if it's
7033 * not, and if the fallback command exists, try falling
7034 * back to it before complaining.
7036 if (!ssh->fallback_cmd && ssh->cfg.remote_cmd_ptr2 != NULL) {
7037 logevent("Primary command failed; attempting fallback");
7038 ssh->fallback_cmd = TRUE;
7041 bombout(("Server refused to start a shell/command"));
7044 logevent("Started a shell/command");
7049 ssh->state = SSH_STATE_SESSION;
7050 if (ssh->size_needed)
7051 ssh_size(ssh, ssh->term_width, ssh->term_height);
7052 if (ssh->eof_needed)
7053 ssh_special(ssh, TS_EOF);
7059 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
7064 s->try_send = FALSE;
7068 * _All_ the connection-layer packets we expect to
7069 * receive are now handled by the dispatch table.
7070 * Anything that reaches here must be bogus.
7073 bombout(("Strange packet received: type %d", pktin->type));
7075 } else if (ssh->mainchan) {
7077 * We have spare data. Add it to the channel buffer.
7079 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
7084 struct ssh_channel *c;
7086 * Try to send data on all channels if we can.
7088 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
7091 continue; /* don't send on closing channels */
7092 bufsize = ssh2_try_send(c);
7095 case CHAN_MAINSESSION:
7096 /* stdin need not receive an unthrottle
7097 * notification since it will be polled */
7100 x11_unthrottle(c->u.x11.s);
7103 /* agent sockets are request/response and need no
7104 * buffer management */
7107 pfd_unthrottle(c->u.pfd.s);
7119 * Handlers for SSH2 messages that might arrive at any moment.
7121 void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
7123 /* log reason code in disconnect message */
7125 int nowlen, reason, msglen;
7127 reason = ssh_pkt_getuint32(pktin);
7128 ssh_pkt_getstring(pktin, &msg, &msglen);
7130 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
7131 buf = dupprintf("Received disconnect message (%s)",
7132 ssh2_disconnect_reasons[reason]);
7134 buf = dupprintf("Received disconnect message (unknown"
7135 " type %d)", reason);
7139 buf = dupprintf("Disconnection message text: %n%.*s",
7140 &nowlen, msglen, msg);
7142 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
7144 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
7145 ssh2_disconnect_reasons[reason] : "unknown",
7150 void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
7152 /* log the debug message */
7157 /* XXX maybe we should actually take notice of this */
7158 always_display = ssh2_pkt_getbool(pktin);
7159 ssh_pkt_getstring(pktin, &msg, &msglen);
7161 buf = dupprintf("Remote debug message: %.*s", msglen, msg);
7166 void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
7168 struct Packet *pktout;
7169 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
7170 ssh2_pkt_adduint32(pktout, pktin->sequence);
7172 * UNIMPLEMENTED messages MUST appear in the same order as the
7173 * messages they respond to. Hence, never queue them.
7175 ssh2_pkt_send_noqueue(ssh, pktout);
7179 * Handle the top-level SSH2 protocol.
7181 static void ssh2_protocol_setup(Ssh ssh)
7186 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
7188 for (i = 0; i < 256; i++)
7189 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
7192 * Any message we actually understand, we set to NULL so that
7193 * the coroutines will get it.
7195 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = NULL;
7196 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = NULL;
7197 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = NULL;
7198 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = NULL;
7199 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = NULL;
7200 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = NULL;
7201 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = NULL;
7202 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = NULL; duplicate case value */
7203 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = NULL; duplicate case value */
7204 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = NULL;
7205 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = NULL;
7206 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = NULL;
7207 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = NULL;
7208 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = NULL;
7209 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
7210 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = NULL;
7211 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = NULL; duplicate case value */
7212 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = NULL; duplicate case value */
7213 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = NULL;
7214 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = NULL;
7215 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = NULL;
7216 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = NULL;
7217 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = NULL;
7218 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = NULL;
7219 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = NULL;
7220 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = NULL;
7221 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = NULL;
7222 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = NULL;
7223 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = NULL;
7224 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = NULL;
7225 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = NULL;
7226 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = NULL;
7227 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = NULL;
7230 * These special message types we install handlers for.
7232 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
7233 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with ssh1 */
7234 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
7237 static void ssh2_timer(void *ctx, long now)
7241 if (!ssh->kex_in_progress && ssh->cfg.ssh_rekey_time != 0 &&
7242 now - ssh->next_rekey >= 0) {
7243 do_ssh2_transport(ssh, "Initiating key re-exchange (timeout)",
7248 static void ssh2_protocol(Ssh ssh, unsigned char *in, int inlen,
7249 struct Packet *pktin)
7251 if (ssh->state == SSH_STATE_CLOSED)
7255 ssh->incoming_data_size += pktin->encrypted_len;
7256 if (!ssh->kex_in_progress &&
7257 ssh->max_data_size != 0 &&
7258 ssh->incoming_data_size > ssh->max_data_size)
7259 do_ssh2_transport(ssh, "Initiating key re-exchange "
7260 "(too much data received)", -1, NULL);
7263 if (pktin && ssh->packet_dispatch[pktin->type]) {
7264 ssh->packet_dispatch[pktin->type](ssh, pktin);
7268 if (!ssh->protocol_initial_phase_done ||
7269 (pktin && pktin->type >= 20 && pktin->type < 50)) {
7270 if (do_ssh2_transport(ssh, in, inlen, pktin) &&
7271 !ssh->protocol_initial_phase_done) {
7272 ssh->protocol_initial_phase_done = TRUE;
7274 * Allow authconn to initialise itself.
7276 do_ssh2_authconn(ssh, NULL, 0, NULL);
7279 do_ssh2_authconn(ssh, in, inlen, pktin);
7284 * Called to set up the connection.
7286 * Returns an error message, or NULL on success.
7288 static const char *ssh_init(void *frontend_handle, void **backend_handle,
7290 char *host, int port, char **realhost, int nodelay,
7296 ssh = snew(struct ssh_tag);
7297 ssh->cfg = *cfg; /* STRUCTURE COPY */
7298 ssh->version = 0; /* when not ready yet */
7301 ssh->v1_cipher_ctx = NULL;
7302 ssh->crcda_ctx = NULL;
7303 ssh->cscipher = NULL;
7304 ssh->cs_cipher_ctx = NULL;
7305 ssh->sccipher = NULL;
7306 ssh->sc_cipher_ctx = NULL;
7308 ssh->cs_mac_ctx = NULL;
7310 ssh->sc_mac_ctx = NULL;
7312 ssh->cs_comp_ctx = NULL;
7314 ssh->sc_comp_ctx = NULL;
7316 ssh->kex_ctx = NULL;
7317 ssh->hostkey = NULL;
7319 ssh->state = SSH_STATE_PREPACKET;
7320 ssh->size_needed = FALSE;
7321 ssh->eof_needed = FALSE;
7324 ssh->deferred_send_data = NULL;
7325 ssh->deferred_len = 0;
7326 ssh->deferred_size = 0;
7327 ssh->fallback_cmd = 0;
7329 ssh->x11auth = NULL;
7330 ssh->v1_compressing = FALSE;
7331 ssh->v2_outgoing_sequence = 0;
7332 ssh->ssh1_rdpkt_crstate = 0;
7333 ssh->ssh2_rdpkt_crstate = 0;
7334 ssh->do_ssh_init_crstate = 0;
7335 ssh->ssh_gotdata_crstate = 0;
7336 ssh->do_ssh1_connection_crstate = 0;
7337 ssh->do_ssh1_login_crstate = 0;
7338 ssh->do_ssh2_transport_crstate = 0;
7339 ssh->do_ssh2_authconn_crstate = 0;
7340 ssh->do_ssh_init_state = NULL;
7341 ssh->do_ssh1_login_state = NULL;
7342 ssh->do_ssh2_transport_state = NULL;
7343 ssh->do_ssh2_authconn_state = NULL;
7344 ssh->mainchan = NULL;
7345 ssh->throttled_all = 0;
7346 ssh->v1_stdout_throttling = 0;
7348 ssh->queuelen = ssh->queuesize = 0;
7349 ssh->queueing = FALSE;
7350 ssh->qhead = ssh->qtail = NULL;
7352 *backend_handle = ssh;
7355 if (crypto_startup() == 0)
7356 return "Microsoft high encryption pack not installed!";
7359 ssh->frontend = frontend_handle;
7360 ssh->term_width = ssh->cfg.width;
7361 ssh->term_height = ssh->cfg.height;
7363 ssh->channels = NULL;
7364 ssh->rportfwds = NULL;
7365 ssh->portfwds = NULL;
7370 ssh->v1_throttle_count = 0;
7371 ssh->overall_bufsize = 0;
7372 ssh->fallback_cmd = 0;
7374 ssh->protocol = NULL;
7376 ssh->protocol_initial_phase_done = FALSE;
7380 ssh->incoming_data_size = ssh->outgoing_data_size =
7381 ssh->deferred_data_size = 0L;
7382 ssh->max_data_size = parse_blocksize(ssh->cfg.ssh_rekey_data);
7383 ssh->kex_in_progress = FALSE;
7385 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
7394 static void ssh_free(void *handle)
7396 Ssh ssh = (Ssh) handle;
7397 struct ssh_channel *c;
7398 struct ssh_rportfwd *pf;
7400 if (ssh->v1_cipher_ctx)
7401 ssh->cipher->free_context(ssh->v1_cipher_ctx);
7402 if (ssh->cs_cipher_ctx)
7403 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
7404 if (ssh->sc_cipher_ctx)
7405 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
7406 if (ssh->cs_mac_ctx)
7407 ssh->csmac->free_context(ssh->cs_mac_ctx);
7408 if (ssh->sc_mac_ctx)
7409 ssh->scmac->free_context(ssh->sc_mac_ctx);
7410 if (ssh->cs_comp_ctx) {
7412 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
7414 zlib_compress_cleanup(ssh->cs_comp_ctx);
7416 if (ssh->sc_comp_ctx) {
7418 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
7420 zlib_decompress_cleanup(ssh->sc_comp_ctx);
7423 dh_cleanup(ssh->kex_ctx);
7424 sfree(ssh->savedhost);
7426 while (ssh->queuelen-- > 0)
7427 ssh_free_packet(ssh->queue[ssh->queuelen]);
7430 while (ssh->qhead) {
7431 struct queued_handler *qh = ssh->qhead;
7432 ssh->qhead = qh->next;
7435 ssh->qhead = ssh->qtail = NULL;
7437 if (ssh->channels) {
7438 while ((c = delpos234(ssh->channels, 0)) != NULL) {
7441 if (c->u.x11.s != NULL)
7442 x11_close(c->u.x11.s);
7445 if (c->u.pfd.s != NULL)
7446 pfd_close(c->u.pfd.s);
7451 freetree234(ssh->channels);
7452 ssh->channels = NULL;
7455 if (ssh->rportfwds) {
7456 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
7458 freetree234(ssh->rportfwds);
7459 ssh->rportfwds = NULL;
7461 sfree(ssh->deferred_send_data);
7463 x11_free_auth(ssh->x11auth);
7464 sfree(ssh->do_ssh_init_state);
7465 sfree(ssh->do_ssh1_login_state);
7466 sfree(ssh->do_ssh2_transport_state);
7467 sfree(ssh->do_ssh2_authconn_state);
7468 if (ssh->crcda_ctx) {
7469 crcda_free_context(ssh->crcda_ctx);
7470 ssh->crcda_ctx = NULL;
7474 expire_timer_context(ssh);
7476 pinger_free(ssh->pinger);
7483 * Reconfigure the SSH backend.
7485 static void ssh_reconfig(void *handle, Config *cfg)
7487 Ssh ssh = (Ssh) handle;
7488 char *rekeying = NULL;
7489 unsigned long old_max_data_size;
7491 pinger_reconfig(ssh->pinger, &ssh->cfg, cfg);
7492 ssh_setup_portfwd(ssh, cfg);
7494 if (ssh->cfg.ssh_rekey_time != cfg->ssh_rekey_time &&
7495 cfg->ssh_rekey_time != 0) {
7496 long new_next = ssh->last_rekey + cfg->ssh_rekey_time*60*TICKSPERSEC;
7497 long now = GETTICKCOUNT();
7499 if (new_next - now < 0) {
7500 rekeying = "Initiating key re-exchange (timeout shortened)";
7502 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
7506 old_max_data_size = ssh->max_data_size;
7507 ssh->max_data_size = parse_blocksize(cfg->ssh_rekey_data);
7508 if (old_max_data_size != ssh->max_data_size &&
7509 ssh->max_data_size != 0) {
7510 if (ssh->outgoing_data_size > ssh->max_data_size ||
7511 ssh->incoming_data_size > ssh->max_data_size)
7512 rekeying = "Initiating key re-exchange (data limit lowered)";
7515 if (rekeying && !ssh->kex_in_progress) {
7516 do_ssh2_transport(ssh, rekeying, -1, NULL);
7519 ssh->cfg = *cfg; /* STRUCTURE COPY */
7523 * Called to send data down the Telnet connection.
7525 static int ssh_send(void *handle, char *buf, int len)
7527 Ssh ssh = (Ssh) handle;
7529 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
7532 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
7534 return ssh_sendbuffer(ssh);
7538 * Called to query the current amount of buffered stdin data.
7540 static int ssh_sendbuffer(void *handle)
7542 Ssh ssh = (Ssh) handle;
7545 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
7549 * If the SSH socket itself has backed up, add the total backup
7550 * size on that to any individual buffer on the stdin channel.
7553 if (ssh->throttled_all)
7554 override_value = ssh->overall_bufsize;
7556 if (ssh->version == 1) {
7557 return override_value;
7558 } else if (ssh->version == 2) {
7559 if (!ssh->mainchan || ssh->mainchan->closes > 0)
7560 return override_value;
7562 return (override_value +
7563 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
7570 * Called to set the size of the window from SSH's POV.
7572 static void ssh_size(void *handle, int width, int height)
7574 Ssh ssh = (Ssh) handle;
7575 struct Packet *pktout;
7577 ssh->term_width = width;
7578 ssh->term_height = height;
7580 switch (ssh->state) {
7581 case SSH_STATE_BEFORE_SIZE:
7582 case SSH_STATE_PREPACKET:
7583 case SSH_STATE_CLOSED:
7584 break; /* do nothing */
7585 case SSH_STATE_INTERMED:
7586 ssh->size_needed = TRUE; /* buffer for later */
7588 case SSH_STATE_SESSION:
7589 if (!ssh->cfg.nopty) {
7590 if (ssh->version == 1) {
7591 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
7592 PKT_INT, ssh->term_height,
7593 PKT_INT, ssh->term_width,
7594 PKT_INT, 0, PKT_INT, 0, PKT_END);
7595 } else if (ssh->mainchan) {
7596 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7597 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
7598 ssh2_pkt_addstring(pktout, "window-change");
7599 ssh2_pkt_addbool(pktout, 0);
7600 ssh2_pkt_adduint32(pktout, ssh->term_width);
7601 ssh2_pkt_adduint32(pktout, ssh->term_height);
7602 ssh2_pkt_adduint32(pktout, 0);
7603 ssh2_pkt_adduint32(pktout, 0);
7604 ssh2_pkt_send(ssh, pktout);
7612 * Return a list of the special codes that make sense in this
7615 static const struct telnet_special *ssh_get_specials(void *handle)
7617 static const struct telnet_special ssh1_ignore_special[] = {
7618 {"IGNORE message", TS_NOP}
7620 static const struct telnet_special ssh2_transport_specials[] = {
7621 {"IGNORE message", TS_NOP},
7622 {"Repeat key exchange", TS_REKEY},
7624 static const struct telnet_special ssh2_session_specials[] = {
7627 /* These are the signal names defined by draft-ietf-secsh-connect-23.
7628 * They include all the ISO C signals, but are a subset of the POSIX
7629 * required signals. */
7630 {"SIGINT (Interrupt)", TS_SIGINT},
7631 {"SIGTERM (Terminate)", TS_SIGTERM},
7632 {"SIGKILL (Kill)", TS_SIGKILL},
7633 {"SIGQUIT (Quit)", TS_SIGQUIT},
7634 {"SIGHUP (Hangup)", TS_SIGHUP},
7635 {"More signals", TS_SUBMENU},
7636 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
7637 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
7638 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
7639 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
7642 static const struct telnet_special specials_end[] = {
7645 /* XXX review this length for any changes: */
7646 static struct telnet_special ssh_specials[lenof(ssh2_transport_specials) +
7647 lenof(ssh2_session_specials) +
7648 lenof(specials_end)];
7649 Ssh ssh = (Ssh) handle;
7651 #define ADD_SPECIALS(name) \
7653 assert((i + lenof(name)) <= lenof(ssh_specials)); \
7654 memcpy(&ssh_specials[i], name, sizeof name); \
7658 if (ssh->version == 1) {
7659 /* Don't bother offering IGNORE if we've decided the remote
7660 * won't cope with it, since we wouldn't bother sending it if
7662 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
7663 ADD_SPECIALS(ssh1_ignore_special);
7664 } else if (ssh->version == 2) {
7665 ADD_SPECIALS(ssh2_transport_specials);
7667 ADD_SPECIALS(ssh2_session_specials);
7668 } /* else we're not ready yet */
7671 ADD_SPECIALS(specials_end);
7672 return ssh_specials;
7680 * Send Telnet special codes. TS_EOF is useful for `plink', so you
7681 * can send an EOF and collect resulting output (e.g. `plink
7684 static void ssh_special(void *handle, Telnet_Special code)
7686 Ssh ssh = (Ssh) handle;
7687 struct Packet *pktout;
7689 if (code == TS_EOF) {
7690 if (ssh->state != SSH_STATE_SESSION) {
7692 * Buffer the EOF in case we are pre-SESSION, so we can
7693 * send it as soon as we reach SESSION.
7696 ssh->eof_needed = TRUE;
7699 if (ssh->version == 1) {
7700 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
7701 } else if (ssh->mainchan) {
7702 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
7703 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
7704 ssh2_pkt_send(ssh, pktout);
7706 logevent("Sent EOF message");
7707 } else if (code == TS_PING || code == TS_NOP) {
7708 if (ssh->state == SSH_STATE_CLOSED
7709 || ssh->state == SSH_STATE_PREPACKET) return;
7710 if (ssh->version == 1) {
7711 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
7712 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
7714 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
7715 ssh2_pkt_addstring_start(pktout);
7716 ssh2_pkt_send_noqueue(ssh, pktout);
7718 } else if (code == TS_REKEY) {
7719 if (!ssh->kex_in_progress && ssh->version == 2) {
7720 do_ssh2_transport(ssh, "Initiating key re-exchange at"
7721 " user request", -1, NULL);
7723 } else if (code == TS_BRK) {
7724 if (ssh->state == SSH_STATE_CLOSED
7725 || ssh->state == SSH_STATE_PREPACKET) return;
7726 if (ssh->version == 1) {
7727 logevent("Unable to send BREAK signal in SSH1");
7728 } else if (ssh->mainchan) {
7729 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7730 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
7731 ssh2_pkt_addstring(pktout, "break");
7732 ssh2_pkt_addbool(pktout, 0);
7733 ssh2_pkt_adduint32(pktout, 0); /* default break length */
7734 ssh2_pkt_send(ssh, pktout);
7737 /* Is is a POSIX signal? */
7738 char *signame = NULL;
7739 if (code == TS_SIGABRT) signame = "ABRT";
7740 if (code == TS_SIGALRM) signame = "ALRM";
7741 if (code == TS_SIGFPE) signame = "FPE";
7742 if (code == TS_SIGHUP) signame = "HUP";
7743 if (code == TS_SIGILL) signame = "ILL";
7744 if (code == TS_SIGINT) signame = "INT";
7745 if (code == TS_SIGKILL) signame = "KILL";
7746 if (code == TS_SIGPIPE) signame = "PIPE";
7747 if (code == TS_SIGQUIT) signame = "QUIT";
7748 if (code == TS_SIGSEGV) signame = "SEGV";
7749 if (code == TS_SIGTERM) signame = "TERM";
7750 if (code == TS_SIGUSR1) signame = "USR1";
7751 if (code == TS_SIGUSR2) signame = "USR2";
7752 /* The SSH-2 protocol does in principle support arbitrary named
7753 * signals, including signame@domain, but we don't support those. */
7755 /* It's a signal. */
7756 if (ssh->version == 2 && ssh->mainchan) {
7757 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7758 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
7759 ssh2_pkt_addstring(pktout, "signal");
7760 ssh2_pkt_addbool(pktout, 0);
7761 ssh2_pkt_addstring(pktout, signame);
7762 ssh2_pkt_send(ssh, pktout);
7763 logeventf(ssh, "Sent signal SIG%s", signame);
7766 /* Never heard of it. Do nothing */
7771 void *new_sock_channel(void *handle, Socket s)
7773 Ssh ssh = (Ssh) handle;
7774 struct ssh_channel *c;
7775 c = snew(struct ssh_channel);
7779 c->remoteid = -1; /* to be set when open confirmed */
7780 c->localid = alloc_channel_id(ssh);
7782 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
7784 bufchain_init(&c->v.v2.outbuffer);
7785 add234(ssh->channels, c);
7791 * This is called when stdout/stderr (the entity to which
7792 * from_backend sends data) manages to clear some backlog.
7794 static void ssh_unthrottle(void *handle, int bufsize)
7796 Ssh ssh = (Ssh) handle;
7797 if (ssh->version == 1) {
7798 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
7799 ssh->v1_stdout_throttling = 0;
7800 ssh1_throttle(ssh, -1);
7803 if (ssh->mainchan && ssh->mainchan->closes == 0)
7804 ssh2_set_window(ssh->mainchan, OUR_V2_WINSIZE - bufsize);
7808 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
7810 struct ssh_channel *c = (struct ssh_channel *)channel;
7812 struct Packet *pktout;
7814 logeventf(ssh, "Opening forwarded connection to %s:%d", hostname, port);
7816 if (ssh->version == 1) {
7817 send_packet(ssh, SSH1_MSG_PORT_OPEN,
7818 PKT_INT, c->localid,
7821 /* PKT_STR, <org:orgport>, */
7824 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7825 ssh2_pkt_addstring(pktout, "direct-tcpip");
7826 ssh2_pkt_adduint32(pktout, c->localid);
7827 c->v.v2.locwindow = OUR_V2_WINSIZE;
7828 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
7829 ssh2_pkt_adduint32(pktout, 0x4000UL); /* our max pkt size */
7830 ssh2_pkt_addstring(pktout, hostname);
7831 ssh2_pkt_adduint32(pktout, port);
7833 * We make up values for the originator data; partly it's
7834 * too much hassle to keep track, and partly I'm not
7835 * convinced the server should be told details like that
7836 * about my local network configuration.
7838 ssh2_pkt_addstring(pktout, "client-side-connection");
7839 ssh2_pkt_adduint32(pktout, 0);
7840 ssh2_pkt_send(ssh, pktout);
7844 static Socket ssh_socket(void *handle)
7846 Ssh ssh = (Ssh) handle;
7850 static int ssh_sendok(void *handle)
7852 Ssh ssh = (Ssh) handle;
7853 return ssh->send_ok;
7856 static int ssh_ldisc(void *handle, int option)
7858 Ssh ssh = (Ssh) handle;
7859 if (option == LD_ECHO)
7860 return ssh->echoing;
7861 if (option == LD_EDIT)
7862 return ssh->editing;
7866 static void ssh_provide_ldisc(void *handle, void *ldisc)
7868 Ssh ssh = (Ssh) handle;
7872 static void ssh_provide_logctx(void *handle, void *logctx)
7874 Ssh ssh = (Ssh) handle;
7875 ssh->logctx = logctx;
7878 static int ssh_return_exitcode(void *handle)
7880 Ssh ssh = (Ssh) handle;
7884 return (ssh->exitcode >= 0 ? ssh->exitcode : 0);
7888 * cfg_info for SSH is the currently running version of the
7889 * protocol. (1 for 1; 2 for 2; 0 for not-decided-yet.)
7891 static int ssh_cfg_info(void *handle)
7893 Ssh ssh = (Ssh) handle;
7894 return ssh->version;
7898 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
7899 * that fails. This variable is the means by which scp.c can reach
7900 * into the SSH code and find out which one it got.
7902 extern int ssh_fallback_cmd(void *handle)
7904 Ssh ssh = (Ssh) handle;
7905 return ssh->fallback_cmd;
7908 Backend ssh_backend = {
7918 ssh_return_exitcode,