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_KEX_MASK 0x000F
110 #define SSH2_PKTCTX_PUBLICKEY 0x0010
111 #define SSH2_PKTCTX_PASSWORD 0x0020
112 #define SSH2_PKTCTX_KBDINTER 0x0040
113 #define SSH2_PKTCTX_AUTH_MASK 0x00F0
115 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
116 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
117 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
118 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
119 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
120 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
121 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
122 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
123 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
124 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
125 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
126 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
127 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
128 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
129 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
131 static const char *const ssh2_disconnect_reasons[] = {
133 "SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT",
134 "SSH_DISCONNECT_PROTOCOL_ERROR",
135 "SSH_DISCONNECT_KEY_EXCHANGE_FAILED",
136 "SSH_DISCONNECT_HOST_AUTHENTICATION_FAILED",
137 "SSH_DISCONNECT_MAC_ERROR",
138 "SSH_DISCONNECT_COMPRESSION_ERROR",
139 "SSH_DISCONNECT_SERVICE_NOT_AVAILABLE",
140 "SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED",
141 "SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE",
142 "SSH_DISCONNECT_CONNECTION_LOST",
143 "SSH_DISCONNECT_BY_APPLICATION",
144 "SSH_DISCONNECT_TOO_MANY_CONNECTIONS",
145 "SSH_DISCONNECT_AUTH_CANCELLED_BY_USER",
146 "SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE",
147 "SSH_DISCONNECT_ILLEGAL_USER_NAME",
150 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
151 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
152 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
153 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
155 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
158 * Various remote-bug flags.
160 #define BUG_CHOKES_ON_SSH1_IGNORE 1
161 #define BUG_SSH2_HMAC 2
162 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
163 #define BUG_CHOKES_ON_RSA 8
164 #define BUG_SSH2_RSA_PADDING 16
165 #define BUG_SSH2_DERIVEKEY 32
166 #define BUG_SSH2_REKEY 64
167 #define BUG_SSH2_PK_SESSIONID 128
169 #define translate(x) if (type == x) return #x
170 #define translatec(x,ctx) if (type == x && (pkt_ctx & ctx)) return #x
171 static char *ssh1_pkt_type(int type)
173 translate(SSH1_MSG_DISCONNECT);
174 translate(SSH1_SMSG_PUBLIC_KEY);
175 translate(SSH1_CMSG_SESSION_KEY);
176 translate(SSH1_CMSG_USER);
177 translate(SSH1_CMSG_AUTH_RSA);
178 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
179 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
180 translate(SSH1_CMSG_AUTH_PASSWORD);
181 translate(SSH1_CMSG_REQUEST_PTY);
182 translate(SSH1_CMSG_WINDOW_SIZE);
183 translate(SSH1_CMSG_EXEC_SHELL);
184 translate(SSH1_CMSG_EXEC_CMD);
185 translate(SSH1_SMSG_SUCCESS);
186 translate(SSH1_SMSG_FAILURE);
187 translate(SSH1_CMSG_STDIN_DATA);
188 translate(SSH1_SMSG_STDOUT_DATA);
189 translate(SSH1_SMSG_STDERR_DATA);
190 translate(SSH1_CMSG_EOF);
191 translate(SSH1_SMSG_EXIT_STATUS);
192 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
193 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
194 translate(SSH1_MSG_CHANNEL_DATA);
195 translate(SSH1_MSG_CHANNEL_CLOSE);
196 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
197 translate(SSH1_SMSG_X11_OPEN);
198 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
199 translate(SSH1_MSG_PORT_OPEN);
200 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
201 translate(SSH1_SMSG_AGENT_OPEN);
202 translate(SSH1_MSG_IGNORE);
203 translate(SSH1_CMSG_EXIT_CONFIRMATION);
204 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
205 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
206 translate(SSH1_MSG_DEBUG);
207 translate(SSH1_CMSG_REQUEST_COMPRESSION);
208 translate(SSH1_CMSG_AUTH_TIS);
209 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
210 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
211 translate(SSH1_CMSG_AUTH_CCARD);
212 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
213 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
216 static char *ssh2_pkt_type(int pkt_ctx, int type)
218 translate(SSH2_MSG_DISCONNECT);
219 translate(SSH2_MSG_IGNORE);
220 translate(SSH2_MSG_UNIMPLEMENTED);
221 translate(SSH2_MSG_DEBUG);
222 translate(SSH2_MSG_SERVICE_REQUEST);
223 translate(SSH2_MSG_SERVICE_ACCEPT);
224 translate(SSH2_MSG_KEXINIT);
225 translate(SSH2_MSG_NEWKEYS);
226 translatec(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP);
227 translatec(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP);
228 translatec(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
229 translatec(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
230 translatec(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
231 translatec(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
232 translate(SSH2_MSG_USERAUTH_REQUEST);
233 translate(SSH2_MSG_USERAUTH_FAILURE);
234 translate(SSH2_MSG_USERAUTH_SUCCESS);
235 translate(SSH2_MSG_USERAUTH_BANNER);
236 translatec(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
237 translatec(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
238 translatec(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
239 translatec(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
240 translate(SSH2_MSG_GLOBAL_REQUEST);
241 translate(SSH2_MSG_REQUEST_SUCCESS);
242 translate(SSH2_MSG_REQUEST_FAILURE);
243 translate(SSH2_MSG_CHANNEL_OPEN);
244 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
245 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
246 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
247 translate(SSH2_MSG_CHANNEL_DATA);
248 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
249 translate(SSH2_MSG_CHANNEL_EOF);
250 translate(SSH2_MSG_CHANNEL_CLOSE);
251 translate(SSH2_MSG_CHANNEL_REQUEST);
252 translate(SSH2_MSG_CHANNEL_SUCCESS);
253 translate(SSH2_MSG_CHANNEL_FAILURE);
259 /* Enumeration values for fields in SSH-1 packets */
261 PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
262 /* These values are for communicating relevant semantics of
263 * fields to the packet logging code. */
264 PKTT_OTHER, PKTT_PASSWORD, PKTT_DATA
268 * Coroutine mechanics for the sillier bits of the code. If these
269 * macros look impenetrable to you, you might find it helpful to
272 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
274 * which explains the theory behind these macros.
276 * In particular, if you are getting `case expression not constant'
277 * errors when building with MS Visual Studio, this is because MS's
278 * Edit and Continue debugging feature causes their compiler to
279 * violate ANSI C. To disable Edit and Continue debugging:
281 * - right-click ssh.c in the FileView
283 * - select the C/C++ tab and the General category
284 * - under `Debug info:', select anything _other_ than `Program
285 * Database for Edit and Continue'.
287 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
290 if (!ssh->t) ssh->t = snew(struct t); \
292 #define crFinish(z) } *crLine = 0; return (z); }
293 #define crFinishV } *crLine = 0; return; }
294 #define crReturn(z) \
296 *crLine =__LINE__; return (z); case __LINE__:;\
300 *crLine=__LINE__; return; case __LINE__:;\
302 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
303 #define crStopV do{ *crLine = 0; return; }while(0)
304 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
305 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
307 typedef struct ssh_tag *Ssh;
310 static struct Packet *ssh2_pkt_init(int pkt_type);
311 static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
312 static void ssh2_pkt_adduint32(struct Packet *, unsigned long value);
313 static void ssh2_pkt_addstring_start(struct Packet *);
314 static void ssh2_pkt_addstring_str(struct Packet *, char *data);
315 static void ssh2_pkt_addstring_data(struct Packet *, char *data, int len);
316 static void ssh2_pkt_addstring(struct Packet *, char *data);
317 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
318 static void ssh2_pkt_addmp(struct Packet *, Bignum b);
319 static int ssh2_pkt_construct(Ssh, struct Packet *);
320 static void ssh2_pkt_send(Ssh, struct Packet *);
321 static void ssh2_pkt_send_noqueue(Ssh, struct Packet *);
322 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
323 struct Packet *pktin);
324 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
325 struct Packet *pktin);
328 * Buffer management constants. There are several of these for
329 * various different purposes:
331 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
332 * on a local data stream before we throttle the whole SSH
333 * connection (in SSH-1 only). Throttling the whole connection is
334 * pretty drastic so we set this high in the hope it won't
337 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
338 * on the SSH connection itself before we defensively throttle
339 * _all_ local data streams. This is pretty drastic too (though
340 * thankfully unlikely in SSH-2 since the window mechanism should
341 * ensure that the server never has any need to throttle its end
342 * of the connection), so we set this high as well.
344 * - OUR_V2_WINSIZE is the maximum window size we present on SSH-2
348 #define SSH1_BUFFER_LIMIT 32768
349 #define SSH_MAX_BACKLOG 32768
350 #define OUR_V2_WINSIZE 16384
351 #define OUR_V2_MAXPKT 0x4000UL
353 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
355 static void *nullmac_make_context(void)
359 static void nullmac_free_context(void *handle)
362 static void nullmac_key(void *handle, unsigned char *key)
365 static void nullmac_generate(void *handle, unsigned char *blk, int len,
369 static int nullmac_verify(void *handle, unsigned char *blk, int len,
374 const static struct ssh_mac ssh_mac_none = {
375 nullmac_make_context, nullmac_free_context, nullmac_key,
376 nullmac_generate, nullmac_verify, "none", 0
378 const static struct ssh_mac *macs[] = {
379 &ssh_sha1, &ssh_md5, &ssh_mac_none
381 const static struct ssh_mac *buggymacs[] = {
382 &ssh_sha1_buggy, &ssh_md5, &ssh_mac_none
385 static void *ssh_comp_none_init(void)
389 static void ssh_comp_none_cleanup(void *handle)
392 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
393 unsigned char **outblock, int *outlen)
397 static int ssh_comp_none_disable(void *handle)
401 const static struct ssh_compress ssh_comp_none = {
403 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
404 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
405 ssh_comp_none_disable, NULL
407 extern const struct ssh_compress ssh_zlib;
408 const static struct ssh_compress *compressions[] = {
409 &ssh_zlib, &ssh_comp_none
412 enum { /* channel types */
417 CHAN_SOCKDATA_DORMANT /* one the remote hasn't confirmed */
421 * 2-3-4 tree storing channels.
424 Ssh ssh; /* pointer back to main context */
425 unsigned remoteid, localid;
427 /* True if we opened this channel but server hasn't confirmed. */
430 * In SSH-1, this value contains four bits:
432 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
433 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
434 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
435 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
437 * A channel is completely finished with when all four bits are set.
441 struct ssh1_data_channel {
444 struct ssh2_data_channel {
446 unsigned remwindow, remmaxpkt;
451 struct ssh_agent_channel {
452 unsigned char *message;
453 unsigned char msglen[4];
454 unsigned lensofar, totallen;
456 struct ssh_x11_channel {
459 struct ssh_pfd_channel {
466 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
467 * use this structure in different ways, reflecting SSH-2's
468 * altogether saner approach to port forwarding.
470 * In SSH-1, you arrange a remote forwarding by sending the server
471 * the remote port number, and the local destination host:port.
472 * When a connection comes in, the server sends you back that
473 * host:port pair, and you connect to it. This is a ready-made
474 * security hole if you're not on the ball: a malicious server
475 * could send you back _any_ host:port pair, so if you trustingly
476 * connect to the address it gives you then you've just opened the
477 * entire inside of your corporate network just by connecting
478 * through it to a dodgy SSH server. Hence, we must store a list of
479 * host:port pairs we _are_ trying to forward to, and reject a
480 * connection request from the server if it's not in the list.
482 * In SSH-2, each side of the connection minds its own business and
483 * doesn't send unnecessary information to the other. You arrange a
484 * remote forwarding by sending the server just the remote port
485 * number. When a connection comes in, the server tells you which
486 * of its ports was connected to; and _you_ have to remember what
487 * local host:port pair went with that port number.
489 * Hence, in SSH-1 this structure is indexed by destination
490 * host:port pair, whereas in SSH-2 it is indexed by source port.
492 struct ssh_portfwd; /* forward declaration */
494 struct ssh_rportfwd {
495 unsigned sport, dport;
498 struct ssh_portfwd *pfrec;
500 #define free_rportfwd(pf) ( \
501 ((pf) ? (sfree((pf)->sportdesc)) : (void)0 ), sfree(pf) )
504 * Separately to the rportfwd tree (which is for looking up port
505 * open requests from the server), a tree of _these_ structures is
506 * used to keep track of all the currently open port forwardings,
507 * so that we can reconfigure in mid-session if the user requests
511 enum { DESTROY, KEEP, CREATE } status;
513 unsigned sport, dport;
516 struct ssh_rportfwd *remote;
520 #define free_portfwd(pf) ( \
521 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
522 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
526 long forcepad; /* Force padding to at least this length */
528 unsigned long sequence;
533 long encrypted_len; /* for SSH-2 total-size counting */
536 * State associated with packet logging
540 struct logblank_t *blanks;
543 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
544 struct Packet *pktin);
545 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
546 struct Packet *pktin);
547 static void ssh1_protocol_setup(Ssh ssh);
548 static void ssh2_protocol_setup(Ssh ssh);
549 static void ssh_size(void *handle, int width, int height);
550 static void ssh_special(void *handle, Telnet_Special);
551 static int ssh2_try_send(struct ssh_channel *c);
552 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
553 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
554 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin);
555 static int ssh_sendbuffer(void *handle);
556 static int ssh_do_close(Ssh ssh, int notify_exit);
557 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
558 static int ssh2_pkt_getbool(struct Packet *pkt);
559 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
560 static void ssh2_timer(void *ctx, long now);
561 static int do_ssh2_transport(Ssh ssh, void *vin, int inlen,
562 struct Packet *pktin);
564 struct rdpkt1_state_tag {
565 long len, pad, biglen, to_read;
566 unsigned long realcrc, gotcrc;
570 struct Packet *pktin;
573 struct rdpkt2_state_tag {
574 long len, pad, payload, packetlen, maclen;
577 unsigned long incoming_sequence;
578 struct Packet *pktin;
581 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
582 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
584 struct queued_handler;
585 struct queued_handler {
587 chandler_fn_t handler;
589 struct queued_handler *next;
593 const struct plug_function_table *fn;
594 /* the above field _must_ be first in the structure */
596 SHA_State exhash, exhashbase;
603 unsigned char session_key[32];
605 int v1_remote_protoflags;
606 int v1_local_protoflags;
607 int agentfwd_enabled;
610 const struct ssh_cipher *cipher;
613 const struct ssh2_cipher *cscipher, *sccipher;
614 void *cs_cipher_ctx, *sc_cipher_ctx;
615 const struct ssh_mac *csmac, *scmac;
616 void *cs_mac_ctx, *sc_mac_ctx;
617 const struct ssh_compress *cscomp, *sccomp;
618 void *cs_comp_ctx, *sc_comp_ctx;
619 const struct ssh_kex *kex;
620 const struct ssh_signkey *hostkey;
621 unsigned char v2_session_id[20];
627 int echoing, editing;
631 int ospeed, ispeed; /* temporaries */
632 int term_width, term_height;
634 tree234 *channels; /* indexed by local id */
635 struct ssh_channel *mainchan; /* primary session channel */
639 tree234 *rportfwds, *portfwds;
643 SSH_STATE_BEFORE_SIZE,
649 int size_needed, eof_needed;
651 struct Packet **queue;
652 int queuelen, queuesize;
654 unsigned char *deferred_send_data;
655 int deferred_len, deferred_size;
658 * Gross hack: pscp will try to start SFTP but fall back to
659 * scp1 if that fails. This variable is the means by which
660 * scp.c can reach into the SSH code and find out which one it
666 * Used for username and password input.
668 char *userpass_input_buffer;
669 int userpass_input_buflen;
670 int userpass_input_bufpos;
671 int userpass_input_echo;
678 int v1_throttle_count;
681 int v1_stdout_throttling;
682 unsigned long v2_outgoing_sequence;
684 int ssh1_rdpkt_crstate;
685 int ssh2_rdpkt_crstate;
686 int do_ssh_init_crstate;
687 int ssh_gotdata_crstate;
688 int do_ssh1_login_crstate;
689 int do_ssh1_connection_crstate;
690 int do_ssh2_transport_crstate;
691 int do_ssh2_authconn_crstate;
693 void *do_ssh_init_state;
694 void *do_ssh1_login_state;
695 void *do_ssh2_transport_state;
696 void *do_ssh2_authconn_state;
698 struct rdpkt1_state_tag rdpkt1_state;
699 struct rdpkt2_state_tag rdpkt2_state;
701 /* SSH-1 and SSH-2 use this for different things, but both use it */
702 int protocol_initial_phase_done;
704 void (*protocol) (Ssh ssh, void *vin, int inlen,
706 struct Packet *(*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
709 * We maintain a full _copy_ of a Config structure here, not
710 * merely a pointer to it. That way, when we're passed a new
711 * one for reconfiguration, we can check the differences and
712 * potentially reconfigure port forwardings etc in mid-session.
717 * Used to transfer data back from async callbacks.
719 void *agent_response;
720 int agent_response_len;
724 * The SSH connection can be set as `frozen', meaning we are
725 * not currently accepting incoming data from the network. This
726 * is slightly more serious than setting the _socket_ as
727 * frozen, because we may already have had data passed to us
728 * from the network which we need to delay processing until
729 * after the freeze is lifted, so we also need a bufchain to
733 bufchain queued_incoming_data;
736 * Dispatch table for packet types that we may have to deal
739 handler_fn_t packet_dispatch[256];
742 * Queues of one-off handler functions for success/failure
743 * indications from a request.
745 struct queued_handler *qhead, *qtail;
748 * This module deals with sending keepalives.
753 * Track incoming and outgoing data sizes and time, for
756 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
757 unsigned long max_data_size;
759 long next_rekey, last_rekey;
760 char *deferred_rekey_reason; /* points to STATIC string; don't free */
763 #define logevent(s) logevent(ssh->frontend, s)
765 /* logevent, only printf-formatted. */
766 static void logeventf(Ssh ssh, const char *fmt, ...)
772 buf = dupvprintf(fmt, ap);
778 #define bombout(msg) \
780 char *text = dupprintf msg; \
781 ssh_do_close(ssh, FALSE); \
783 connection_fatal(ssh->frontend, "%s", text); \
787 /* Functions to leave bits out of the SSH packet log file. */
789 static void dont_log_password(Ssh ssh, struct Packet *pkt, int blanktype)
791 if (ssh->cfg.logomitpass)
792 pkt->logmode = blanktype;
795 static void dont_log_data(Ssh ssh, struct Packet *pkt, int blanktype)
797 if (ssh->cfg.logomitdata)
798 pkt->logmode = blanktype;
801 static void end_log_omission(Ssh ssh, struct Packet *pkt)
803 pkt->logmode = PKTLOG_EMIT;
806 static int ssh_channelcmp(void *av, void *bv)
808 struct ssh_channel *a = (struct ssh_channel *) av;
809 struct ssh_channel *b = (struct ssh_channel *) bv;
810 if (a->localid < b->localid)
812 if (a->localid > b->localid)
816 static int ssh_channelfind(void *av, void *bv)
818 unsigned *a = (unsigned *) av;
819 struct ssh_channel *b = (struct ssh_channel *) bv;
827 static int ssh_rportcmp_ssh1(void *av, void *bv)
829 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
830 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
832 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
833 return i < 0 ? -1 : +1;
834 if (a->dport > b->dport)
836 if (a->dport < b->dport)
841 static int ssh_rportcmp_ssh2(void *av, void *bv)
843 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
844 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
846 if (a->sport > b->sport)
848 if (a->sport < b->sport)
854 * Special form of strcmp which can cope with NULL inputs. NULL is
855 * defined to sort before even the empty string.
857 static int nullstrcmp(const char *a, const char *b)
859 if (a == NULL && b == NULL)
868 static int ssh_portcmp(void *av, void *bv)
870 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
871 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
873 if (a->type > b->type)
875 if (a->type < b->type)
877 if (a->addressfamily > b->addressfamily)
879 if (a->addressfamily < b->addressfamily)
881 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
882 return i < 0 ? -1 : +1;
883 if (a->sport > b->sport)
885 if (a->sport < b->sport)
887 if (a->type != 'D') {
888 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
889 return i < 0 ? -1 : +1;
890 if (a->dport > b->dport)
892 if (a->dport < b->dport)
898 static int alloc_channel_id(Ssh ssh)
900 const unsigned CHANNEL_NUMBER_OFFSET = 256;
901 unsigned low, high, mid;
903 struct ssh_channel *c;
906 * First-fit allocation of channel numbers: always pick the
907 * lowest unused one. To do this, binary-search using the
908 * counted B-tree to find the largest channel ID which is in a
909 * contiguous sequence from the beginning. (Precisely
910 * everything in that sequence must have ID equal to its tree
911 * index plus CHANNEL_NUMBER_OFFSET.)
913 tsize = count234(ssh->channels);
917 while (high - low > 1) {
918 mid = (high + low) / 2;
919 c = index234(ssh->channels, mid);
920 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
921 low = mid; /* this one is fine */
923 high = mid; /* this one is past it */
926 * Now low points to either -1, or the tree index of the
927 * largest ID in the initial sequence.
930 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
931 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
933 return low + 1 + CHANNEL_NUMBER_OFFSET;
936 static void c_write(Ssh ssh, const char *buf, int len)
938 if ((flags & FLAG_STDERR)) {
940 for (i = 0; i < len; i++)
942 fputc(buf[i], stderr);
945 from_backend(ssh->frontend, 1, buf, len);
948 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
951 for (i = 0; i < len; i++) {
953 c_write(ssh, "\r\n", 2);
954 else if ((buf[i] & 0x60) || (buf[i] == '\r'))
955 c_write(ssh, buf + i, 1);
959 static void c_write_str(Ssh ssh, const char *buf)
961 c_write(ssh, buf, strlen(buf));
964 static void ssh_free_packet(struct Packet *pkt)
969 static struct Packet *ssh_new_packet(void)
971 struct Packet *pkt = snew(struct Packet);
975 pkt->logmode = PKTLOG_EMIT;
983 * Collect incoming data in the incoming packet buffer.
984 * Decipher and verify the packet when it is completely read.
985 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
986 * Update the *data and *datalen variables.
987 * Return a Packet structure when a packet is completed.
989 static struct Packet *ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
991 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
993 crBegin(ssh->ssh1_rdpkt_crstate);
995 st->pktin = ssh_new_packet();
998 st->pktin->length = 0;
1000 for (st->i = st->len = 0; st->i < 4; st->i++) {
1001 while ((*datalen) == 0)
1003 st->len = (st->len << 8) + **data;
1004 (*data)++, (*datalen)--;
1007 st->pad = 8 - (st->len % 8);
1008 st->biglen = st->len + st->pad;
1009 st->pktin->length = st->len - 5;
1011 if (st->biglen < 0) {
1012 bombout(("Extremely large packet length from server suggests"
1013 " data stream corruption"));
1014 ssh_free_packet(st->pktin);
1018 st->pktin->maxlen = st->biglen;
1019 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1021 st->to_read = st->biglen;
1022 st->p = st->pktin->data;
1023 while (st->to_read > 0) {
1024 st->chunk = st->to_read;
1025 while ((*datalen) == 0)
1027 if (st->chunk > (*datalen))
1028 st->chunk = (*datalen);
1029 memcpy(st->p, *data, st->chunk);
1031 *datalen -= st->chunk;
1033 st->to_read -= st->chunk;
1036 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1037 st->biglen, NULL)) {
1038 bombout(("Network attack (CRC compensation) detected!"));
1039 ssh_free_packet(st->pktin);
1044 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1046 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1047 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1048 if (st->gotcrc != st->realcrc) {
1049 bombout(("Incorrect CRC received on packet"));
1050 ssh_free_packet(st->pktin);
1054 st->pktin->body = st->pktin->data + st->pad + 1;
1055 st->pktin->savedpos = 0;
1057 if (ssh->v1_compressing) {
1058 unsigned char *decompblk;
1060 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1061 st->pktin->body - 1, st->pktin->length + 1,
1062 &decompblk, &decomplen)) {
1063 bombout(("Zlib decompression encountered invalid data"));
1064 ssh_free_packet(st->pktin);
1068 if (st->pktin->maxlen < st->pad + decomplen) {
1069 st->pktin->maxlen = st->pad + decomplen;
1070 st->pktin->data = sresize(st->pktin->data,
1071 st->pktin->maxlen + APIEXTRA,
1073 st->pktin->body = st->pktin->data + st->pad + 1;
1076 memcpy(st->pktin->body - 1, decompblk, decomplen);
1078 st->pktin->length = decomplen - 1;
1081 st->pktin->type = st->pktin->body[-1];
1084 * Log incoming packet, possibly omitting sensitive fields.
1088 struct logblank_t blank;
1089 if (ssh->cfg.logomitdata) {
1090 int do_blank = FALSE, blank_prefix = 0;
1091 /* "Session data" packets - omit the data field */
1092 if ((st->pktin->type == SSH1_SMSG_STDOUT_DATA) ||
1093 (st->pktin->type == SSH1_SMSG_STDERR_DATA)) {
1094 do_blank = TRUE; blank_prefix = 0;
1095 } else if (st->pktin->type == SSH1_MSG_CHANNEL_DATA) {
1096 do_blank = TRUE; blank_prefix = 4;
1099 blank.offset = blank_prefix;
1100 blank.len = st->pktin->length;
1101 blank.type = PKTLOG_OMIT;
1105 log_packet(ssh->logctx,
1106 PKT_INCOMING, st->pktin->type,
1107 ssh1_pkt_type(st->pktin->type),
1108 st->pktin->body, st->pktin->length,
1112 crFinish(st->pktin);
1115 static struct Packet *ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1117 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1119 crBegin(ssh->ssh2_rdpkt_crstate);
1121 st->pktin = ssh_new_packet();
1123 st->pktin->type = 0;
1124 st->pktin->length = 0;
1126 st->cipherblk = ssh->sccipher->blksize;
1129 if (st->cipherblk < 8)
1132 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1135 * Acquire and decrypt the first block of the packet. This will
1136 * contain the length and padding details.
1138 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1139 while ((*datalen) == 0)
1141 st->pktin->data[st->i] = *(*data)++;
1146 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1147 st->pktin->data, st->cipherblk);
1150 * Now get the length and padding figures.
1152 st->len = GET_32BIT(st->pktin->data);
1153 st->pad = st->pktin->data[4];
1156 * _Completely_ silly lengths should be stomped on before they
1157 * do us any more damage.
1159 if (st->len < 0 || st->pad < 0 || st->len + st->pad < 0) {
1160 bombout(("Incoming packet was garbled on decryption"));
1161 ssh_free_packet(st->pktin);
1166 * This enables us to deduce the payload length.
1168 st->payload = st->len - st->pad - 1;
1170 st->pktin->length = st->payload + 5;
1173 * So now we can work out the total packet length.
1175 st->packetlen = st->len + 4;
1176 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1179 * Allocate memory for the rest of the packet.
1181 st->pktin->maxlen = st->packetlen + st->maclen;
1182 st->pktin->data = sresize(st->pktin->data,
1183 st->pktin->maxlen + APIEXTRA,
1187 * Read and decrypt the remainder of the packet.
1189 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1191 while ((*datalen) == 0)
1193 st->pktin->data[st->i] = *(*data)++;
1196 /* Decrypt everything _except_ the MAC. */
1198 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1199 st->pktin->data + st->cipherblk,
1200 st->packetlen - st->cipherblk);
1202 st->pktin->encrypted_len = st->packetlen;
1208 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data, st->len + 4,
1209 st->incoming_sequence)) {
1210 bombout(("Incorrect MAC received on packet"));
1211 ssh_free_packet(st->pktin);
1215 st->pktin->sequence = st->incoming_sequence++;
1218 * Decompress packet payload.
1221 unsigned char *newpayload;
1224 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1225 st->pktin->data + 5, st->pktin->length - 5,
1226 &newpayload, &newlen)) {
1227 if (st->pktin->maxlen < newlen + 5) {
1228 st->pktin->maxlen = newlen + 5;
1229 st->pktin->data = sresize(st->pktin->data,
1230 st->pktin->maxlen + APIEXTRA,
1233 st->pktin->length = 5 + newlen;
1234 memcpy(st->pktin->data + 5, newpayload, newlen);
1239 st->pktin->savedpos = 6;
1240 st->pktin->body = st->pktin->data;
1241 st->pktin->type = st->pktin->data[5];
1244 * Log incoming packet, possibly omitting sensitive fields.
1248 struct logblank_t blank;
1249 if (ssh->cfg.logomitdata) {
1250 int do_blank = FALSE, blank_prefix = 0;
1251 /* "Session data" packets - omit the data field */
1252 if (st->pktin->type == SSH2_MSG_CHANNEL_DATA) {
1253 do_blank = TRUE; blank_prefix = 4;
1254 } else if (st->pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
1255 do_blank = TRUE; blank_prefix = 8;
1258 blank.offset = blank_prefix;
1259 blank.len = (st->pktin->length-6) - blank_prefix;
1260 blank.type = PKTLOG_OMIT;
1264 log_packet(ssh->logctx, PKT_INCOMING, st->pktin->type,
1265 ssh2_pkt_type(ssh->pkt_ctx, st->pktin->type),
1266 st->pktin->data+6, st->pktin->length-6,
1270 crFinish(st->pktin);
1273 static void ssh1_pktout_size(struct Packet *pkt, int len)
1277 len += 5; /* type and CRC */
1278 pad = 8 - (len % 8);
1281 pkt->length = len - 5;
1282 if (pkt->maxlen < biglen) {
1283 pkt->maxlen = biglen;
1284 pkt->data = sresize(pkt->data, biglen + 4 + APIEXTRA, unsigned char);
1286 pkt->body = pkt->data + 4 + pad + 1;
1289 static struct Packet *s_wrpkt_start(int type, int len)
1291 struct Packet *pkt = ssh_new_packet();
1292 ssh1_pktout_size(pkt, len);
1294 /* Initialise log omission state */
1300 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt)
1306 * XXX various versions of SC (including 8.8.4) screw up the
1307 * register allocation in this function and use the same register
1308 * (D6) for len and as a temporary, with predictable results. The
1309 * following sledgehammer prevents this.
1315 pkt->body[-1] = pkt->type;
1318 log_packet(ssh->logctx, PKT_OUTGOING, pkt->type,
1319 ssh1_pkt_type(pkt->type),
1320 pkt->body, pkt->length,
1321 pkt->nblanks, pkt->blanks);
1322 sfree(pkt->blanks); pkt->blanks = NULL;
1325 if (ssh->v1_compressing) {
1326 unsigned char *compblk;
1328 zlib_compress_block(ssh->cs_comp_ctx,
1329 pkt->body - 1, pkt->length + 1,
1330 &compblk, &complen);
1331 ssh1_pktout_size(pkt, complen - 1);
1332 memcpy(pkt->body - 1, compblk, complen);
1336 len = pkt->length + 5; /* type and CRC */
1337 pad = 8 - (len % 8);
1340 for (i = 0; i < pad; i++)
1341 pkt->data[i + 4] = random_byte();
1342 crc = crc32_compute(pkt->data + 4, biglen - 4);
1343 PUT_32BIT(pkt->data + biglen, crc);
1344 PUT_32BIT(pkt->data, len);
1347 ssh->cipher->encrypt(ssh->v1_cipher_ctx, pkt->data + 4, biglen);
1352 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1355 len = s_wrpkt_prepare(ssh, pkt);
1356 backlog = sk_write(ssh->s, (char *)pkt->data, len);
1357 if (backlog > SSH_MAX_BACKLOG)
1358 ssh_throttle_all(ssh, 1, backlog);
1361 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1364 len = s_wrpkt_prepare(ssh, pkt);
1365 if (ssh->deferred_len + len > ssh->deferred_size) {
1366 ssh->deferred_size = ssh->deferred_len + len + 128;
1367 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1371 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->data, len);
1372 ssh->deferred_len += len;
1376 * Construct a packet with the specified contents.
1378 static struct Packet *construct_packet(Ssh ssh, int pkttype,
1379 va_list ap1, va_list ap2)
1381 unsigned char *p, *argp, argchar;
1382 unsigned long argint;
1383 int pktlen, argtype, arglen;
1388 while ((argtype = va_arg(ap1, int)) != PKT_END) {
1391 (void) va_arg(ap1, int);
1395 (void) va_arg(ap1, int);
1399 (void) va_arg(ap1, unsigned char *);
1400 arglen = va_arg(ap1, int);
1404 argp = va_arg(ap1, unsigned char *);
1405 arglen = strlen((char *)argp);
1406 pktlen += 4 + arglen;
1409 bn = va_arg(ap1, Bignum);
1410 pktlen += ssh1_bignum_length(bn);
1415 /* ignore this pass */
1422 pkt = s_wrpkt_start(pkttype, pktlen);
1425 while ((argtype = va_arg(ap2, int)) != PKT_END) {
1426 int offset = p - pkt->body, len = 0;
1428 /* Actual fields in the packet */
1430 argint = va_arg(ap2, int);
1431 PUT_32BIT(p, argint);
1435 argchar = (unsigned char) va_arg(ap2, int);
1440 argp = va_arg(ap2, unsigned char *);
1441 arglen = va_arg(ap2, int);
1442 memcpy(p, argp, arglen);
1446 argp = va_arg(ap2, unsigned char *);
1447 arglen = strlen((char *)argp);
1448 PUT_32BIT(p, arglen);
1449 memcpy(p + 4, argp, arglen);
1453 bn = va_arg(ap2, Bignum);
1454 len = ssh1_write_bignum(p, bn);
1456 /* Tokens for modifications to packet logging */
1458 dont_log_password(ssh, pkt, PKTLOG_BLANK);
1461 dont_log_data(ssh, pkt, PKTLOG_OMIT);
1464 end_log_omission(ssh, pkt);
1468 /* Deal with logfile omission, if required. */
1469 if (len && (pkt->logmode != PKTLOG_EMIT)) {
1471 pkt->blanks = sresize(pkt->blanks, pkt->nblanks,
1473 pkt->blanks[pkt->nblanks-1].offset = offset;
1474 pkt->blanks[pkt->nblanks-1].len = len;
1475 pkt->blanks[pkt->nblanks-1].type = pkt->logmode;
1482 static void send_packet(Ssh ssh, int pkttype, ...)
1486 va_start(ap1, pkttype);
1487 va_start(ap2, pkttype);
1488 pkt = construct_packet(ssh, pkttype, ap1, ap2);
1492 ssh_free_packet(pkt);
1495 static void defer_packet(Ssh ssh, int pkttype, ...)
1499 va_start(ap1, pkttype);
1500 va_start(ap2, pkttype);
1501 pkt = construct_packet(ssh, pkttype, ap1, ap2);
1504 s_wrpkt_defer(ssh, pkt);
1505 ssh_free_packet(pkt);
1508 static int ssh_versioncmp(char *a, char *b)
1511 unsigned long av, bv;
1513 av = strtoul(a, &ae, 10);
1514 bv = strtoul(b, &be, 10);
1516 return (av < bv ? -1 : +1);
1521 av = strtoul(ae, &ae, 10);
1522 bv = strtoul(be, &be, 10);
1524 return (av < bv ? -1 : +1);
1529 * Utility routines for putting an SSH-protocol `string' and
1530 * `uint32' into a SHA state.
1533 static void sha_string(SHA_State * s, void *str, int len)
1535 unsigned char lenblk[4];
1536 PUT_32BIT(lenblk, len);
1537 SHA_Bytes(s, lenblk, 4);
1538 SHA_Bytes(s, str, len);
1541 static void sha_uint32(SHA_State * s, unsigned i)
1543 unsigned char intblk[4];
1544 PUT_32BIT(intblk, i);
1545 SHA_Bytes(s, intblk, 4);
1549 * SSH-2 packet construction functions.
1551 static void ssh2_pkt_ensure(struct Packet *pkt, int length)
1553 if (pkt->maxlen < length) {
1554 pkt->maxlen = length + 256;
1555 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
1558 static void ssh2_pkt_adddata(struct Packet *pkt, void *data, int len)
1560 if (pkt->logmode != PKTLOG_EMIT) {
1562 pkt->blanks = sresize(pkt->blanks, pkt->nblanks, struct logblank_t);
1563 pkt->blanks[pkt->nblanks-1].offset = pkt->length - 6;
1564 pkt->blanks[pkt->nblanks-1].len = len;
1565 pkt->blanks[pkt->nblanks-1].type = pkt->logmode;
1568 ssh2_pkt_ensure(pkt, pkt->length);
1569 memcpy(pkt->data + pkt->length - len, data, len);
1571 static void ssh2_pkt_addbyte(struct Packet *pkt, unsigned char byte)
1573 ssh2_pkt_adddata(pkt, &byte, 1);
1575 static struct Packet *ssh2_pkt_init(int pkt_type)
1577 struct Packet *pkt = ssh_new_packet();
1580 ssh2_pkt_addbyte(pkt, (unsigned char) pkt_type);
1583 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
1585 ssh2_pkt_adddata(pkt, &value, 1);
1587 static void ssh2_pkt_adduint32(struct Packet *pkt, unsigned long value)
1590 PUT_32BIT(x, value);
1591 ssh2_pkt_adddata(pkt, x, 4);
1593 static void ssh2_pkt_addstring_start(struct Packet *pkt)
1595 ssh2_pkt_adduint32(pkt, 0);
1596 pkt->savedpos = pkt->length;
1598 static void ssh2_pkt_addstring_str(struct Packet *pkt, char *data)
1600 ssh2_pkt_adddata(pkt, data, strlen(data));
1601 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1603 static void ssh2_pkt_addstring_data(struct Packet *pkt, char *data, int len)
1605 ssh2_pkt_adddata(pkt, data, len);
1606 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1608 static void ssh2_pkt_addstring(struct Packet *pkt, char *data)
1610 ssh2_pkt_addstring_start(pkt);
1611 ssh2_pkt_addstring_str(pkt, data);
1613 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
1616 int i, n = (bignum_bitcount(b) + 7) / 8;
1617 p = snewn(n + 1, unsigned char);
1619 fatalbox("out of memory");
1621 for (i = 1; i <= n; i++)
1622 p[i] = bignum_byte(b, n - i);
1624 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1626 memmove(p, p + i, n + 1 - i);
1630 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
1634 p = ssh2_mpint_fmt(b, &len);
1635 ssh2_pkt_addstring_start(pkt);
1636 ssh2_pkt_addstring_data(pkt, (char *)p, len);
1641 * Construct an SSH-2 final-form packet: compress it, encrypt it,
1642 * put the MAC on it. Final packet, ready to be sent, is stored in
1643 * pkt->data. Total length is returned.
1645 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
1647 int cipherblk, maclen, padding, i;
1650 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1651 ssh2_pkt_type(ssh->pkt_ctx, pkt->data[5]),
1652 pkt->data + 6, pkt->length - 6,
1653 pkt->nblanks, pkt->blanks);
1654 sfree(pkt->blanks); pkt->blanks = NULL;
1658 * Compress packet payload.
1661 unsigned char *newpayload;
1664 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
1666 &newpayload, &newlen)) {
1668 ssh2_pkt_adddata(pkt, newpayload, newlen);
1674 * Add padding. At least four bytes, and must also bring total
1675 * length (minus MAC) up to a multiple of the block size.
1676 * If pkt->forcepad is set, make sure the packet is at least that size
1679 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
1680 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1682 if (pkt->length + padding < pkt->forcepad)
1683 padding = pkt->forcepad - pkt->length;
1685 (cipherblk - (pkt->length + padding) % cipherblk) % cipherblk;
1686 assert(padding <= 255);
1687 maclen = ssh->csmac ? ssh->csmac->len : 0;
1688 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
1689 pkt->data[4] = padding;
1690 for (i = 0; i < padding; i++)
1691 pkt->data[pkt->length + i] = random_byte();
1692 PUT_32BIT(pkt->data, pkt->length + padding - 4);
1694 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
1695 pkt->length + padding,
1696 ssh->v2_outgoing_sequence);
1697 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
1700 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
1701 pkt->data, pkt->length + padding);
1703 pkt->encrypted_len = pkt->length + padding;
1705 /* Ready-to-send packet starts at pkt->data. We return length. */
1706 return pkt->length + padding + maclen;
1710 * Routines called from the main SSH code to send packets. There
1711 * are quite a few of these, because we have two separate
1712 * mechanisms for delaying the sending of packets:
1714 * - In order to send an IGNORE message and a password message in
1715 * a single fixed-length blob, we require the ability to
1716 * concatenate the encrypted forms of those two packets _into_ a
1717 * single blob and then pass it to our <network.h> transport
1718 * layer in one go. Hence, there's a deferment mechanism which
1719 * works after packet encryption.
1721 * - In order to avoid sending any connection-layer messages
1722 * during repeat key exchange, we have to queue up any such
1723 * outgoing messages _before_ they are encrypted (and in
1724 * particular before they're allocated sequence numbers), and
1725 * then send them once we've finished.
1727 * I call these mechanisms `defer' and `queue' respectively, so as
1728 * to distinguish them reasonably easily.
1730 * The functions send_noqueue() and defer_noqueue() free the packet
1731 * structure they are passed. Every outgoing packet goes through
1732 * precisely one of these functions in its life; packets passed to
1733 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
1734 * these or get queued, and then when the queue is later emptied
1735 * the packets are all passed to defer_noqueue().
1739 * Send an SSH-2 packet immediately, without queuing or deferring.
1741 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
1745 len = ssh2_pkt_construct(ssh, pkt);
1746 backlog = sk_write(ssh->s, (char *)pkt->data, len);
1747 if (backlog > SSH_MAX_BACKLOG)
1748 ssh_throttle_all(ssh, 1, backlog);
1750 ssh->outgoing_data_size += pkt->encrypted_len;
1751 if (!ssh->kex_in_progress &&
1752 ssh->max_data_size != 0 &&
1753 ssh->outgoing_data_size > ssh->max_data_size)
1754 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
1756 ssh_free_packet(pkt);
1760 * Defer an SSH-2 packet.
1762 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt)
1764 int len = ssh2_pkt_construct(ssh, pkt);
1765 if (ssh->deferred_len + len > ssh->deferred_size) {
1766 ssh->deferred_size = ssh->deferred_len + len + 128;
1767 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1771 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->data, len);
1772 ssh->deferred_len += len;
1773 ssh->deferred_data_size += pkt->encrypted_len;
1774 ssh_free_packet(pkt);
1778 * Queue an SSH-2 packet.
1780 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
1782 assert(ssh->queueing);
1784 if (ssh->queuelen >= ssh->queuesize) {
1785 ssh->queuesize = ssh->queuelen + 32;
1786 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
1789 ssh->queue[ssh->queuelen++] = pkt;
1793 * Either queue or send a packet, depending on whether queueing is
1796 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
1799 ssh2_pkt_queue(ssh, pkt);
1801 ssh2_pkt_send_noqueue(ssh, pkt);
1806 * Either queue or defer a packet, depending on whether queueing is
1809 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
1812 ssh2_pkt_queue(ssh, pkt);
1814 ssh2_pkt_defer_noqueue(ssh, pkt);
1819 * Send the whole deferred data block constructed by
1820 * ssh2_pkt_defer() or SSH-1's defer_packet().
1822 * The expected use of the defer mechanism is that you call
1823 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
1824 * not currently queueing, this simply sets up deferred_send_data
1825 * and then sends it. If we _are_ currently queueing, the calls to
1826 * ssh2_pkt_defer() put the deferred packets on to the queue
1827 * instead, and therefore ssh_pkt_defersend() has no deferred data
1828 * to send. Hence, there's no need to make it conditional on
1831 static void ssh_pkt_defersend(Ssh ssh)
1834 backlog = sk_write(ssh->s, (char *)ssh->deferred_send_data,
1836 ssh->deferred_len = ssh->deferred_size = 0;
1837 sfree(ssh->deferred_send_data);
1838 ssh->deferred_send_data = NULL;
1839 if (backlog > SSH_MAX_BACKLOG)
1840 ssh_throttle_all(ssh, 1, backlog);
1842 ssh->outgoing_data_size += ssh->deferred_data_size;
1843 if (!ssh->kex_in_progress &&
1844 ssh->max_data_size != 0 &&
1845 ssh->outgoing_data_size > ssh->max_data_size)
1846 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
1847 ssh->deferred_data_size = 0;
1851 * Send all queued SSH-2 packets. We send them by means of
1852 * ssh2_pkt_defer_noqueue(), in case they included a pair of
1853 * packets that needed to be lumped together.
1855 static void ssh2_pkt_queuesend(Ssh ssh)
1859 assert(!ssh->queueing);
1861 for (i = 0; i < ssh->queuelen; i++)
1862 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i]);
1865 ssh_pkt_defersend(ssh);
1869 void bndebug(char *string, Bignum b)
1873 p = ssh2_mpint_fmt(b, &len);
1874 debug(("%s", string));
1875 for (i = 0; i < len; i++)
1876 debug((" %02x", p[i]));
1882 static void sha_mpint(SHA_State * s, Bignum b)
1886 p = ssh2_mpint_fmt(b, &len);
1887 sha_string(s, p, len);
1892 * Packet decode functions for both SSH-1 and SSH-2.
1894 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
1896 unsigned long value;
1897 if (pkt->length - pkt->savedpos < 4)
1898 return 0; /* arrgh, no way to decline (FIXME?) */
1899 value = GET_32BIT(pkt->body + pkt->savedpos);
1903 static int ssh2_pkt_getbool(struct Packet *pkt)
1905 unsigned long value;
1906 if (pkt->length - pkt->savedpos < 1)
1907 return 0; /* arrgh, no way to decline (FIXME?) */
1908 value = pkt->body[pkt->savedpos] != 0;
1912 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
1917 if (pkt->length - pkt->savedpos < 4)
1919 len = GET_32BIT(pkt->body + pkt->savedpos);
1924 if (pkt->length - pkt->savedpos < *length)
1926 *p = (char *)(pkt->body + pkt->savedpos);
1927 pkt->savedpos += *length;
1929 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
1931 if (pkt->length - pkt->savedpos < length)
1933 pkt->savedpos += length;
1934 return pkt->body + (pkt->savedpos - length);
1936 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
1937 unsigned char **keystr)
1941 j = makekey(pkt->body + pkt->savedpos,
1942 pkt->length - pkt->savedpos,
1949 assert(pkt->savedpos < pkt->length);
1953 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
1958 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
1959 pkt->length - pkt->savedpos, &b);
1967 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
1973 ssh_pkt_getstring(pkt, &p, &length);
1978 b = bignum_from_bytes((unsigned char *)p, length);
1983 * Helper function to add an SSH-2 signature blob to a packet.
1984 * Expects to be shown the public key blob as well as the signature
1985 * blob. Normally works just like ssh2_pkt_addstring, but will
1986 * fiddle with the signature packet if necessary for
1987 * BUG_SSH2_RSA_PADDING.
1989 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
1990 void *pkblob_v, int pkblob_len,
1991 void *sigblob_v, int sigblob_len)
1993 unsigned char *pkblob = (unsigned char *)pkblob_v;
1994 unsigned char *sigblob = (unsigned char *)sigblob_v;
1996 /* dmemdump(pkblob, pkblob_len); */
1997 /* dmemdump(sigblob, sigblob_len); */
2000 * See if this is in fact an ssh-rsa signature and a buggy
2001 * server; otherwise we can just do this the easy way.
2003 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) &&
2004 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2005 int pos, len, siglen;
2008 * Find the byte length of the modulus.
2011 pos = 4+7; /* skip over "ssh-rsa" */
2012 pos += 4 + GET_32BIT(pkblob+pos); /* skip over exponent */
2013 len = GET_32BIT(pkblob+pos); /* find length of modulus */
2014 pos += 4; /* find modulus itself */
2015 while (len > 0 && pkblob[pos] == 0)
2017 /* debug(("modulus length is %d\n", len)); */
2020 * Now find the signature integer.
2022 pos = 4+7; /* skip over "ssh-rsa" */
2023 siglen = GET_32BIT(sigblob+pos);
2024 /* debug(("signature length is %d\n", siglen)); */
2026 if (len != siglen) {
2027 unsigned char newlen[4];
2028 ssh2_pkt_addstring_start(pkt);
2029 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2030 /* dmemdump(sigblob, pos); */
2031 pos += 4; /* point to start of actual sig */
2032 PUT_32BIT(newlen, len);
2033 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2034 /* dmemdump(newlen, 4); */
2036 while (len-- > siglen) {
2037 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2038 /* dmemdump(newlen, 1); */
2040 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2041 /* dmemdump(sigblob+pos, siglen); */
2045 /* Otherwise fall through and do it the easy way. */
2048 ssh2_pkt_addstring_start(pkt);
2049 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2053 * Examine the remote side's version string and compare it against
2054 * a list of known buggy implementations.
2056 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2058 char *imp; /* pointer to implementation part */
2060 imp += strcspn(imp, "-");
2062 imp += strcspn(imp, "-");
2065 ssh->remote_bugs = 0;
2067 if (ssh->cfg.sshbug_ignore1 == FORCE_ON ||
2068 (ssh->cfg.sshbug_ignore1 == AUTO &&
2069 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2070 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2071 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2072 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2074 * These versions don't support SSH1_MSG_IGNORE, so we have
2075 * to use a different defence against password length
2078 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2079 logevent("We believe remote version has SSH-1 ignore bug");
2082 if (ssh->cfg.sshbug_plainpw1 == FORCE_ON ||
2083 (ssh->cfg.sshbug_plainpw1 == AUTO &&
2084 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2086 * These versions need a plain password sent; they can't
2087 * handle having a null and a random length of data after
2090 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2091 logevent("We believe remote version needs a plain SSH-1 password");
2094 if (ssh->cfg.sshbug_rsa1 == FORCE_ON ||
2095 (ssh->cfg.sshbug_rsa1 == AUTO &&
2096 (!strcmp(imp, "Cisco-1.25")))) {
2098 * These versions apparently have no clue whatever about
2099 * RSA authentication and will panic and die if they see
2100 * an AUTH_RSA message.
2102 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2103 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2106 if (ssh->cfg.sshbug_hmac2 == FORCE_ON ||
2107 (ssh->cfg.sshbug_hmac2 == AUTO &&
2108 !wc_match("* VShell", imp) &&
2109 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2110 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2111 wc_match("2.1 *", imp)))) {
2113 * These versions have the HMAC bug.
2115 ssh->remote_bugs |= BUG_SSH2_HMAC;
2116 logevent("We believe remote version has SSH-2 HMAC bug");
2119 if (ssh->cfg.sshbug_derivekey2 == FORCE_ON ||
2120 (ssh->cfg.sshbug_derivekey2 == AUTO &&
2121 !wc_match("* VShell", imp) &&
2122 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2124 * These versions have the key-derivation bug (failing to
2125 * include the literal shared secret in the hashes that
2126 * generate the keys).
2128 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2129 logevent("We believe remote version has SSH-2 key-derivation bug");
2132 if (ssh->cfg.sshbug_rsapad2 == FORCE_ON ||
2133 (ssh->cfg.sshbug_rsapad2 == AUTO &&
2134 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2135 wc_match("OpenSSH_3.[0-2]*", imp)))) {
2137 * These versions have the SSH-2 RSA padding bug.
2139 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2140 logevent("We believe remote version has SSH-2 RSA padding bug");
2143 if (ssh->cfg.sshbug_pksessid2 == FORCE_ON ||
2144 (ssh->cfg.sshbug_pksessid2 == AUTO &&
2145 wc_match("OpenSSH_2.[0-2]*", imp))) {
2147 * These versions have the SSH-2 session-ID bug in
2148 * public-key authentication.
2150 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2151 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2154 if (ssh->cfg.sshbug_rekey2 == FORCE_ON ||
2155 (ssh->cfg.sshbug_rekey2 == AUTO &&
2156 (wc_match("OpenSSH_2.[0-4]*", imp) ||
2157 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2158 wc_match("Sun_SSH_1.0", imp) ||
2159 wc_match("Sun_SSH_1.0.1", imp)))) {
2161 * These versions have the SSH-2 rekey bug.
2163 ssh->remote_bugs |= BUG_SSH2_REKEY;
2164 logevent("We believe remote version has SSH-2 rekey bug");
2169 * The `software version' part of an SSH version string is required
2170 * to contain no spaces or minus signs.
2172 static void ssh_fix_verstring(char *str)
2174 /* Eat "SSH-<protoversion>-". */
2175 assert(*str == 'S'); str++;
2176 assert(*str == 'S'); str++;
2177 assert(*str == 'H'); str++;
2178 assert(*str == '-'); str++;
2179 while (*str && *str != '-') str++;
2180 assert(*str == '-'); str++;
2182 /* Convert minus signs and spaces in the remaining string into
2185 if (*str == '-' || *str == ' ')
2191 static int do_ssh_init(Ssh ssh, unsigned char c)
2193 struct do_ssh_init_state {
2201 crState(do_ssh_init_state);
2203 crBegin(ssh->do_ssh_init_crstate);
2205 /* Search for the string "SSH-" in the input. */
2208 static const int transS[] = { 1, 2, 2, 1 };
2209 static const int transH[] = { 0, 0, 3, 0 };
2210 static const int transminus[] = { 0, 0, 0, -1 };
2212 s->i = transS[s->i];
2214 s->i = transH[s->i];
2216 s->i = transminus[s->i];
2221 crReturn(1); /* get another character */
2225 s->vstring = snewn(s->vstrsize, char);
2226 strcpy(s->vstring, "SSH-");
2230 crReturn(1); /* get another char */
2231 if (s->vslen >= s->vstrsize - 1) {
2233 s->vstring = sresize(s->vstring, s->vstrsize, char);
2235 s->vstring[s->vslen++] = c;
2238 s->version[s->i] = '\0';
2240 } else if (s->i < sizeof(s->version) - 1)
2241 s->version[s->i++] = c;
2242 } else if (c == '\012')
2246 ssh->agentfwd_enabled = FALSE;
2247 ssh->rdpkt2_state.incoming_sequence = 0;
2249 s->vstring[s->vslen] = 0;
2250 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
2251 logeventf(ssh, "Server version: %s", s->vstring);
2252 ssh_detect_bugs(ssh, s->vstring);
2255 * Decide which SSH protocol version to support.
2258 /* Anything strictly below "2.0" means protocol 1 is supported. */
2259 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
2260 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2261 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
2263 if (ssh->cfg.sshprot == 0 && !s->proto1) {
2264 bombout(("SSH protocol version 1 required by user but not provided by server"));
2267 if (ssh->cfg.sshprot == 3 && !s->proto2) {
2268 bombout(("SSH protocol version 2 required by user but not provided by server"));
2275 if (s->proto2 && (ssh->cfg.sshprot >= 2 || !s->proto1)) {
2277 * Construct a v2 version string.
2279 verstring = dupprintf("SSH-2.0-%s\015\012", sshver);
2283 * Construct a v1 version string.
2285 verstring = dupprintf("SSH-%s-%s\012",
2286 (ssh_versioncmp(s->version, "1.5") <= 0 ?
2287 s->version : "1.5"),
2292 ssh_fix_verstring(verstring);
2294 if (ssh->version == 2) {
2296 * Hash our version string and their version string.
2298 SHA_Init(&ssh->exhashbase);
2299 sha_string(&ssh->exhashbase, verstring,
2300 strcspn(verstring, "\015\012"));
2301 sha_string(&ssh->exhashbase, s->vstring,
2302 strcspn(s->vstring, "\015\012"));
2305 * Initialise SSH-2 protocol.
2307 ssh->protocol = ssh2_protocol;
2308 ssh2_protocol_setup(ssh);
2309 ssh->s_rdpkt = ssh2_rdpkt;
2312 * Initialise SSH-1 protocol.
2314 ssh->protocol = ssh1_protocol;
2315 ssh1_protocol_setup(ssh);
2316 ssh->s_rdpkt = ssh1_rdpkt;
2318 logeventf(ssh, "We claim version: %.*s",
2319 strcspn(verstring, "\015\012"), verstring);
2320 sk_write(ssh->s, verstring, strlen(verstring));
2324 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
2326 update_specials_menu(ssh->frontend);
2327 ssh->state = SSH_STATE_BEFORE_SIZE;
2328 ssh->pinger = pinger_new(&ssh->cfg, &ssh_backend, ssh);
2335 static void ssh_process_incoming_data(Ssh ssh,
2336 unsigned char **data, int *datalen)
2338 struct Packet *pktin = ssh->s_rdpkt(ssh, data, datalen);
2340 ssh->protocol(ssh, NULL, 0, pktin);
2341 ssh_free_packet(pktin);
2345 static void ssh_queue_incoming_data(Ssh ssh,
2346 unsigned char **data, int *datalen)
2348 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
2353 static void ssh_process_queued_incoming_data(Ssh ssh)
2356 unsigned char *data;
2359 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
2360 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
2364 while (!ssh->frozen && len > 0)
2365 ssh_process_incoming_data(ssh, &data, &len);
2368 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
2372 static void ssh_set_frozen(Ssh ssh, int frozen)
2375 sk_set_frozen(ssh->s, frozen);
2376 ssh->frozen = frozen;
2379 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
2381 crBegin(ssh->ssh_gotdata_crstate);
2384 * To begin with, feed the characters one by one to the
2385 * protocol initialisation / selection function do_ssh_init().
2386 * When that returns 0, we're done with the initial greeting
2387 * exchange and can move on to packet discipline.
2390 int ret; /* need not be kept across crReturn */
2392 crReturnV; /* more data please */
2393 ret = do_ssh_init(ssh, *data);
2401 * We emerge from that loop when the initial negotiation is
2402 * over and we have selected an s_rdpkt function. Now pass
2403 * everything to s_rdpkt, and then pass the resulting packets
2404 * to the proper protocol handler.
2410 * Process queued data if there is any.
2412 ssh_process_queued_incoming_data(ssh);
2415 while (datalen > 0) {
2417 ssh_queue_incoming_data(ssh, &data, &datalen);
2419 ssh_process_incoming_data(ssh, &data, &datalen);
2421 if (ssh->state == SSH_STATE_CLOSED)
2429 static int ssh_do_close(Ssh ssh, int notify_exit)
2432 struct ssh_channel *c;
2434 ssh->state = SSH_STATE_CLOSED;
2435 expire_timer_context(ssh);
2440 notify_remote_exit(ssh->frontend);
2445 * Now we must shut down any port- and X-forwarded channels going
2446 * through this connection.
2448 if (ssh->channels) {
2449 while (NULL != (c = index234(ssh->channels, 0))) {
2452 x11_close(c->u.x11.s);
2455 pfd_close(c->u.pfd.s);
2458 del234(ssh->channels, c); /* moving next one to index 0 */
2459 if (ssh->version == 2)
2460 bufchain_clear(&c->v.v2.outbuffer);
2465 * Go through port-forwardings, and close any associated
2466 * listening sockets.
2468 if (ssh->portfwds) {
2469 struct ssh_portfwd *pf;
2470 while (NULL != (pf = index234(ssh->portfwds, 0))) {
2471 /* Dispose of any listening socket. */
2473 pfd_terminate(pf->local);
2474 del234(ssh->portfwds, pf); /* moving next one to index 0 */
2482 static void ssh_log(Plug plug, int type, SockAddr addr, int port,
2483 const char *error_msg, int error_code)
2485 Ssh ssh = (Ssh) plug;
2486 char addrbuf[256], *msg;
2488 sk_getaddr(addr, addrbuf, lenof(addrbuf));
2491 msg = dupprintf("Connecting to %s port %d", addrbuf, port);
2493 msg = dupprintf("Failed to connect to %s: %s", addrbuf, error_msg);
2499 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
2502 Ssh ssh = (Ssh) plug;
2503 int need_notify = ssh_do_close(ssh, FALSE);
2505 if (!error_msg && !ssh->close_expected) {
2506 error_msg = "Server unexpectedly closed network connection";
2510 notify_remote_exit(ssh->frontend);
2513 /* A socket error has occurred. */
2514 logevent(error_msg);
2515 connection_fatal(ssh->frontend, "%s", error_msg);
2517 logevent("Server closed network connection");
2522 static int ssh_receive(Plug plug, int urgent, char *data, int len)
2524 Ssh ssh = (Ssh) plug;
2525 ssh_gotdata(ssh, (unsigned char *)data, len);
2526 if (ssh->state == SSH_STATE_CLOSED) {
2527 ssh_do_close(ssh, TRUE);
2533 static void ssh_sent(Plug plug, int bufsize)
2535 Ssh ssh = (Ssh) plug;
2537 * If the send backlog on the SSH socket itself clears, we
2538 * should unthrottle the whole world if it was throttled.
2540 if (bufsize < SSH_MAX_BACKLOG)
2541 ssh_throttle_all(ssh, 0, bufsize);
2545 * Connect to specified host and port.
2546 * Returns an error message, or NULL on success.
2547 * Also places the canonical host name into `realhost'. It must be
2548 * freed by the caller.
2550 static const char *connect_to_host(Ssh ssh, char *host, int port,
2551 char **realhost, int nodelay, int keepalive)
2553 static const struct plug_function_table fn_table = {
2564 ssh->savedhost = snewn(1 + strlen(host), char);
2565 if (!ssh->savedhost)
2566 fatalbox("Out of memory");
2567 strcpy(ssh->savedhost, host);
2570 port = 22; /* default ssh port */
2571 ssh->savedport = port;
2576 logeventf(ssh, "Looking up host \"%s\"%s", host,
2577 (ssh->cfg.addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
2578 (ssh->cfg.addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" : "")));
2579 addr = name_lookup(host, port, realhost, &ssh->cfg,
2580 ssh->cfg.addressfamily);
2581 if ((err = sk_addr_error(addr)) != NULL) {
2589 ssh->fn = &fn_table;
2590 ssh->s = new_connection(addr, *realhost, port,
2591 0, 1, nodelay, keepalive, (Plug) ssh, &ssh->cfg);
2592 if ((err = sk_socket_error(ssh->s)) != NULL) {
2594 notify_remote_exit(ssh->frontend);
2602 * Throttle or unthrottle the SSH connection.
2604 static void ssh1_throttle(Ssh ssh, int adjust)
2606 int old_count = ssh->v1_throttle_count;
2607 ssh->v1_throttle_count += adjust;
2608 assert(ssh->v1_throttle_count >= 0);
2609 if (ssh->v1_throttle_count && !old_count) {
2610 ssh_set_frozen(ssh, 1);
2611 } else if (!ssh->v1_throttle_count && old_count) {
2612 ssh_set_frozen(ssh, 0);
2617 * Throttle or unthrottle _all_ local data streams (for when sends
2618 * on the SSH connection itself back up).
2620 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
2623 struct ssh_channel *c;
2625 if (enable == ssh->throttled_all)
2627 ssh->throttled_all = enable;
2628 ssh->overall_bufsize = bufsize;
2631 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
2633 case CHAN_MAINSESSION:
2635 * This is treated separately, outside the switch.
2639 x11_override_throttle(c->u.x11.s, enable);
2642 /* Agent channels require no buffer management. */
2645 pfd_override_throttle(c->u.pfd.s, enable);
2652 * Username and password input, abstracted off into routines
2653 * reusable in several places - even between SSH-1 and SSH-2.
2656 /* Set up a username or password input loop on a given buffer. */
2657 static void setup_userpass_input(Ssh ssh, char *buffer, int buflen, int echo)
2659 ssh->userpass_input_buffer = buffer;
2660 ssh->userpass_input_buflen = buflen;
2661 ssh->userpass_input_bufpos = 0;
2662 ssh->userpass_input_echo = echo;
2666 * Process some terminal data in the course of username/password
2667 * input. Returns >0 for success (line of input returned in
2668 * buffer), <0 for failure (user hit ^C/^D, bomb out and exit), 0
2669 * for inconclusive (keep waiting for more input please).
2671 static int process_userpass_input(Ssh ssh, unsigned char *in, int inlen)
2676 switch (c = *in++) {
2679 ssh->userpass_input_buffer[ssh->userpass_input_bufpos] = 0;
2680 ssh->userpass_input_buffer[ssh->userpass_input_buflen-1] = 0;
2685 if (ssh->userpass_input_bufpos > 0) {
2686 if (ssh->userpass_input_echo)
2687 c_write_str(ssh, "\b \b");
2688 ssh->userpass_input_bufpos--;
2693 while (ssh->userpass_input_bufpos > 0) {
2694 if (ssh->userpass_input_echo)
2695 c_write_str(ssh, "\b \b");
2696 ssh->userpass_input_bufpos--;
2705 * This simplistic check for printability is disabled
2706 * when we're doing password input, because some people
2707 * have control characters in their passwords.o
2709 if ((!ssh->userpass_input_echo ||
2710 (c >= ' ' && c <= '~') ||
2711 ((unsigned char) c >= 160))
2712 && ssh->userpass_input_bufpos < ssh->userpass_input_buflen-1) {
2713 ssh->userpass_input_buffer[ssh->userpass_input_bufpos++] = c;
2714 if (ssh->userpass_input_echo)
2715 c_write(ssh, &c, 1);
2723 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
2725 Ssh ssh = (Ssh) sshv;
2727 ssh->agent_response = reply;
2728 ssh->agent_response_len = replylen;
2730 if (ssh->version == 1)
2731 do_ssh1_login(ssh, NULL, -1, NULL);
2733 do_ssh2_authconn(ssh, NULL, -1, NULL);
2736 static void ssh_dialog_callback(void *sshv, int ret)
2738 Ssh ssh = (Ssh) sshv;
2740 ssh->user_response = ret;
2742 if (ssh->version == 1)
2743 do_ssh1_login(ssh, NULL, -1, NULL);
2745 do_ssh2_transport(ssh, NULL, -1, NULL);
2748 * This may have unfrozen the SSH connection, so do a
2751 ssh_process_queued_incoming_data(ssh);
2754 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
2756 struct ssh_channel *c = (struct ssh_channel *)cv;
2758 void *sentreply = reply;
2761 /* Fake SSH_AGENT_FAILURE. */
2762 sentreply = "\0\0\0\1\5";
2765 if (ssh->version == 2) {
2766 ssh2_add_channel_data(c, sentreply, replylen);
2769 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
2770 PKT_INT, c->remoteid,
2773 PKT_DATA, sentreply, replylen,
2782 * Handle the key exchange and user authentication phases.
2784 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
2785 struct Packet *pktin)
2788 unsigned char cookie[8], *ptr;
2789 struct RSAKey servkey, hostkey;
2790 struct MD5Context md5c;
2791 struct do_ssh1_login_state {
2793 unsigned char *rsabuf, *keystr1, *keystr2;
2794 unsigned long supported_ciphers_mask, supported_auths_mask;
2795 int tried_publickey, tried_agent;
2796 int tis_auth_refused, ccard_auth_refused;
2797 unsigned char session_id[16];
2800 void *publickey_blob;
2801 int publickey_bloblen;
2807 unsigned char request[5], *response, *p;
2817 crState(do_ssh1_login_state);
2819 crBegin(ssh->do_ssh1_login_crstate);
2824 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
2825 bombout(("Public key packet not received"));
2829 logevent("Received public keys");
2831 ptr = ssh_pkt_getdata(pktin, 8);
2833 bombout(("SSH-1 public key packet stopped before random cookie"));
2836 memcpy(cookie, ptr, 8);
2838 if (!ssh1_pkt_getrsakey(pktin, &servkey, &s->keystr1) ||
2839 !ssh1_pkt_getrsakey(pktin, &hostkey, &s->keystr2)) {
2840 bombout(("Failed to read SSH-1 public keys from public key packet"));
2845 * Log the host key fingerprint.
2849 logevent("Host key fingerprint is:");
2850 strcpy(logmsg, " ");
2851 hostkey.comment = NULL;
2852 rsa_fingerprint(logmsg + strlen(logmsg),
2853 sizeof(logmsg) - strlen(logmsg), &hostkey);
2857 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
2858 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
2859 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
2861 ssh->v1_local_protoflags =
2862 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
2863 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
2866 MD5Update(&md5c, s->keystr2, hostkey.bytes);
2867 MD5Update(&md5c, s->keystr1, servkey.bytes);
2868 MD5Update(&md5c, cookie, 8);
2869 MD5Final(s->session_id, &md5c);
2871 for (i = 0; i < 32; i++)
2872 ssh->session_key[i] = random_byte();
2875 * Verify that the `bits' and `bytes' parameters match.
2877 if (hostkey.bits > hostkey.bytes * 8 ||
2878 servkey.bits > servkey.bytes * 8) {
2879 bombout(("SSH-1 public keys were badly formatted"));
2883 s->len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
2885 s->rsabuf = snewn(s->len, unsigned char);
2887 fatalbox("Out of memory");
2890 * Verify the host key.
2894 * First format the key into a string.
2896 int len = rsastr_len(&hostkey);
2897 char fingerprint[100];
2898 char *keystr = snewn(len, char);
2900 fatalbox("Out of memory");
2901 rsastr_fmt(keystr, &hostkey);
2902 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
2904 ssh_set_frozen(ssh, 1);
2905 s->dlgret = verify_ssh_host_key(ssh->frontend,
2906 ssh->savedhost, ssh->savedport,
2907 "rsa", keystr, fingerprint,
2908 ssh_dialog_callback, ssh);
2910 if (s->dlgret < 0) {
2914 bombout(("Unexpected data from server while waiting"
2915 " for user host key response"));
2918 } while (pktin || inlen > 0);
2919 s->dlgret = ssh->user_response;
2921 ssh_set_frozen(ssh, 0);
2923 if (s->dlgret == 0) {
2924 ssh->close_expected = TRUE;
2925 ssh_closing((Plug)ssh, NULL, 0, 0);
2930 for (i = 0; i < 32; i++) {
2931 s->rsabuf[i] = ssh->session_key[i];
2933 s->rsabuf[i] ^= s->session_id[i];
2936 if (hostkey.bytes > servkey.bytes) {
2937 ret = rsaencrypt(s->rsabuf, 32, &servkey);
2939 ret = rsaencrypt(s->rsabuf, servkey.bytes, &hostkey);
2941 ret = rsaencrypt(s->rsabuf, 32, &hostkey);
2943 ret = rsaencrypt(s->rsabuf, hostkey.bytes, &servkey);
2946 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
2950 logevent("Encrypted session key");
2953 int cipher_chosen = 0, warn = 0;
2954 char *cipher_string = NULL;
2956 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
2957 int next_cipher = ssh->cfg.ssh_cipherlist[i];
2958 if (next_cipher == CIPHER_WARN) {
2959 /* If/when we choose a cipher, warn about it */
2961 } else if (next_cipher == CIPHER_AES) {
2962 /* XXX Probably don't need to mention this. */
2963 logevent("AES not supported in SSH-1, skipping");
2965 switch (next_cipher) {
2966 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
2967 cipher_string = "3DES"; break;
2968 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
2969 cipher_string = "Blowfish"; break;
2970 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
2971 cipher_string = "single-DES"; break;
2973 if (s->supported_ciphers_mask & (1 << s->cipher_type))
2977 if (!cipher_chosen) {
2978 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
2979 bombout(("Server violates SSH-1 protocol by not "
2980 "supporting 3DES encryption"));
2982 /* shouldn't happen */
2983 bombout(("No supported ciphers found"));
2987 /* Warn about chosen cipher if necessary. */
2989 ssh_set_frozen(ssh, 1);
2990 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
2991 ssh_dialog_callback, ssh);
2992 if (s->dlgret < 0) {
2996 bombout(("Unexpected data from server while waiting"
2997 " for user response"));
3000 } while (pktin || inlen > 0);
3001 s->dlgret = ssh->user_response;
3003 ssh_set_frozen(ssh, 0);
3004 if (s->dlgret == 0) {
3005 ssh->close_expected = TRUE;
3006 ssh_closing((Plug)ssh, NULL, 0, 0);
3012 switch (s->cipher_type) {
3013 case SSH_CIPHER_3DES:
3014 logevent("Using 3DES encryption");
3016 case SSH_CIPHER_DES:
3017 logevent("Using single-DES encryption");
3019 case SSH_CIPHER_BLOWFISH:
3020 logevent("Using Blowfish encryption");
3024 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
3025 PKT_CHAR, s->cipher_type,
3026 PKT_DATA, cookie, 8,
3027 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
3028 PKT_DATA, s->rsabuf, s->len,
3029 PKT_INT, ssh->v1_local_protoflags, PKT_END);
3031 logevent("Trying to enable encryption...");
3035 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
3036 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
3038 ssh->v1_cipher_ctx = ssh->cipher->make_context();
3039 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
3040 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
3042 ssh->crcda_ctx = crcda_make_context();
3043 logevent("Installing CRC compensation attack detector");
3045 if (servkey.modulus) {
3046 sfree(servkey.modulus);
3047 servkey.modulus = NULL;
3049 if (servkey.exponent) {
3050 sfree(servkey.exponent);
3051 servkey.exponent = NULL;
3053 if (hostkey.modulus) {
3054 sfree(hostkey.modulus);
3055 hostkey.modulus = NULL;
3057 if (hostkey.exponent) {
3058 sfree(hostkey.exponent);
3059 hostkey.exponent = NULL;
3063 if (pktin->type != SSH1_SMSG_SUCCESS) {
3064 bombout(("Encryption not successfully enabled"));
3068 logevent("Successfully started encryption");
3072 if (!*ssh->cfg.username) {
3073 if (ssh_get_line && !ssh_getline_pw_only) {
3074 if (!ssh_get_line("login as: ",
3075 s->username, sizeof(s->username), FALSE)) {
3077 * get_line failed to get a username.
3080 logevent("No username provided. Abandoning session.");
3081 ssh->close_expected = TRUE;
3082 ssh_closing((Plug)ssh, NULL, 0, 0);
3086 int ret; /* need not be kept over crReturn */
3087 c_write_str(ssh, "login as: ");
3090 setup_userpass_input(ssh, s->username, sizeof(s->username), 1);
3092 crWaitUntil(!pktin);
3093 ret = process_userpass_input(ssh, in, inlen);
3097 c_write_str(ssh, "\r\n");
3100 strncpy(s->username, ssh->cfg.username, sizeof(s->username));
3101 s->username[sizeof(s->username)-1] = '\0';
3104 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, s->username, PKT_END);
3106 char userlog[22 + sizeof(s->username)];
3107 sprintf(userlog, "Sent username \"%s\"", s->username);
3109 if (flags & FLAG_INTERACTIVE &&
3110 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
3111 strcat(userlog, "\r\n");
3112 c_write_str(ssh, userlog);
3119 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA)) {
3120 /* We must not attempt PK auth. Pretend we've already tried it. */
3121 s->tried_publickey = s->tried_agent = 1;
3123 s->tried_publickey = s->tried_agent = 0;
3125 s->tis_auth_refused = s->ccard_auth_refused = 0;
3126 /* Load the public half of ssh->cfg.keyfile so we notice if it's in Pageant */
3127 if (!filename_is_null(ssh->cfg.keyfile)) {
3128 if (!rsakey_pubblob(&ssh->cfg.keyfile,
3129 &s->publickey_blob, &s->publickey_bloblen, NULL))
3130 s->publickey_blob = NULL;
3132 s->publickey_blob = NULL;
3134 while (pktin->type == SSH1_SMSG_FAILURE) {
3135 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
3137 if (agent_exists() && !s->tried_agent) {
3139 * Attempt RSA authentication using Pageant.
3145 logevent("Pageant is running. Requesting keys.");
3147 /* Request the keys held by the agent. */
3148 PUT_32BIT(s->request, 1);
3149 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
3150 if (!agent_query(s->request, 5, &r, &s->responselen,
3151 ssh_agent_callback, ssh)) {
3155 bombout(("Unexpected data from server while waiting"
3156 " for agent response"));
3159 } while (pktin || inlen > 0);
3160 r = ssh->agent_response;
3161 s->responselen = ssh->agent_response_len;
3163 s->response = (unsigned char *) r;
3164 if (s->response && s->responselen >= 5 &&
3165 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
3166 s->p = s->response + 5;
3167 s->nkeys = GET_32BIT(s->p);
3169 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
3170 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
3171 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
3172 if (s->publickey_blob &&
3173 !memcmp(s->p, s->publickey_blob,
3174 s->publickey_bloblen)) {
3175 logevent("This key matches configured key file");
3176 s->tried_publickey = 1;
3181 do { /* do while (0) to make breaking easy */
3182 n = ssh1_read_bignum
3183 (s->p, s->responselen-(s->p-s->response),
3188 n = ssh1_read_bignum
3189 (s->p, s->responselen-(s->p-s->response),
3194 if (s->responselen - (s->p-s->response) < 4)
3196 s->commentlen = GET_32BIT(s->p);
3198 if (s->responselen - (s->p-s->response) <
3201 s->commentp = (char *)s->p;
3202 s->p += s->commentlen;
3206 logevent("Pageant key list packet was truncated");
3210 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3211 PKT_BIGNUM, s->key.modulus, PKT_END);
3213 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3214 logevent("Key refused");
3217 logevent("Received RSA challenge");
3218 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3219 bombout(("Server's RSA challenge was badly formatted"));
3224 char *agentreq, *q, *ret;
3227 len = 1 + 4; /* message type, bit count */
3228 len += ssh1_bignum_length(s->key.exponent);
3229 len += ssh1_bignum_length(s->key.modulus);
3230 len += ssh1_bignum_length(s->challenge);
3231 len += 16; /* session id */
3232 len += 4; /* response format */
3233 agentreq = snewn(4 + len, char);
3234 PUT_32BIT(agentreq, len);
3236 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
3237 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
3239 q += ssh1_write_bignum(q, s->key.exponent);
3240 q += ssh1_write_bignum(q, s->key.modulus);
3241 q += ssh1_write_bignum(q, s->challenge);
3242 memcpy(q, s->session_id, 16);
3244 PUT_32BIT(q, 1); /* response format */
3245 if (!agent_query(agentreq, len + 4, &vret, &retlen,
3246 ssh_agent_callback, ssh)) {
3251 bombout(("Unexpected data from server"
3252 " while waiting for agent"
3256 } while (pktin || inlen > 0);
3257 vret = ssh->agent_response;
3258 retlen = ssh->agent_response_len;
3263 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
3264 logevent("Sending Pageant's response");
3265 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3266 PKT_DATA, ret + 5, 16,
3270 if (pktin->type == SSH1_SMSG_SUCCESS) {
3272 ("Pageant's response accepted");
3273 if (flags & FLAG_VERBOSE) {
3274 c_write_str(ssh, "Authenticated using"
3276 c_write(ssh, s->commentp,
3278 c_write_str(ssh, "\" from agent\r\n");
3283 ("Pageant's response not accepted");
3286 ("Pageant failed to answer challenge");
3290 logevent("No reply received from Pageant");
3293 freebn(s->key.exponent);
3294 freebn(s->key.modulus);
3295 freebn(s->challenge);
3304 if (!filename_is_null(ssh->cfg.keyfile) && !s->tried_publickey)
3305 s->pwpkt_type = SSH1_CMSG_AUTH_RSA;
3307 if (ssh->cfg.try_tis_auth &&
3308 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
3309 !s->tis_auth_refused) {
3310 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
3311 logevent("Requested TIS authentication");
3312 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
3314 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
3315 logevent("TIS authentication declined");
3316 if (flags & FLAG_INTERACTIVE)
3317 c_write_str(ssh, "TIS authentication refused.\r\n");
3318 s->tis_auth_refused = 1;
3324 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3326 bombout(("TIS challenge packet was badly formed"));
3329 c_write_str(ssh, "Using TIS authentication.\r\n");
3330 logevent("Received TIS challenge");
3331 if (challengelen > sizeof(s->prompt) - 1)
3332 challengelen = sizeof(s->prompt) - 1;/* prevent overrun */
3333 memcpy(s->prompt, challenge, challengelen);
3334 /* Prompt heuristic comes from OpenSSH */
3335 strncpy(s->prompt + challengelen,
3336 memchr(s->prompt, '\n', challengelen) ?
3337 "": "\r\nResponse: ",
3338 (sizeof s->prompt) - challengelen);
3339 s->prompt[(sizeof s->prompt) - 1] = '\0';
3342 if (ssh->cfg.try_tis_auth &&
3343 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
3344 !s->ccard_auth_refused) {
3345 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
3346 logevent("Requested CryptoCard authentication");
3347 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
3349 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
3350 logevent("CryptoCard authentication declined");
3351 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
3352 s->ccard_auth_refused = 1;
3358 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3360 bombout(("CryptoCard challenge packet was badly formed"));
3363 c_write_str(ssh, "Using CryptoCard authentication.\r\n");
3364 logevent("Received CryptoCard challenge");
3365 if (challengelen > sizeof(s->prompt) - 1)
3366 challengelen = sizeof(s->prompt) - 1;/* prevent overrun */
3367 memcpy(s->prompt, challenge, challengelen);
3368 strncpy(s->prompt + challengelen,
3369 memchr(s->prompt, '\n', challengelen) ?
3370 "" : "\r\nResponse: ",
3371 sizeof(s->prompt) - challengelen);
3372 s->prompt[sizeof(s->prompt) - 1] = '\0';
3375 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
3376 sprintf(s->prompt, "%.90s@%.90s's password: ",
3377 s->username, ssh->savedhost);
3379 if (s->pwpkt_type == SSH1_CMSG_AUTH_RSA) {
3380 char *comment = NULL;
3382 if (flags & FLAG_VERBOSE)
3383 c_write_str(ssh, "Trying public key authentication.\r\n");
3384 logeventf(ssh, "Trying public key \"%s\"",
3385 filename_to_str(&ssh->cfg.keyfile));
3386 type = key_type(&ssh->cfg.keyfile);
3387 if (type != SSH_KEYTYPE_SSH1) {
3388 char *msg = dupprintf("Key is of wrong type (%s)",
3389 key_type_to_str(type));
3391 c_write_str(ssh, msg);
3392 c_write_str(ssh, "\r\n");
3394 s->tried_publickey = 1;
3397 if (!rsakey_encrypted(&ssh->cfg.keyfile, &comment)) {
3398 if (flags & FLAG_VERBOSE)
3399 c_write_str(ssh, "No passphrase required.\r\n");
3402 sprintf(s->prompt, "Passphrase for key \"%.100s\": ", comment);
3407 * Show password prompt, having first obtained it via a TIS
3408 * or CryptoCard exchange if we're doing TIS or CryptoCard
3412 if (!ssh_get_line(s->prompt, s->password,
3413 sizeof(s->password), TRUE)) {
3415 * get_line failed to get a password (for example
3416 * because one was supplied on the command line
3417 * which has already failed to work). Terminate.
3419 send_packet(ssh, SSH1_MSG_DISCONNECT,
3420 PKT_STR, "No more passwords available to try",
3422 logevent("Unable to authenticate");
3423 connection_fatal(ssh->frontend, "Unable to authenticate");
3424 ssh->close_expected = TRUE;
3425 ssh_closing((Plug)ssh, NULL, 0, 0);
3429 /* Prompt may have come from server. We've munged it a bit, so
3430 * we know it to be zero-terminated at least once. */
3431 int ret; /* need not be saved over crReturn */
3432 c_write_untrusted(ssh, s->prompt, strlen(s->prompt));
3435 setup_userpass_input(ssh, s->password, sizeof(s->password), 0);
3437 crWaitUntil(!pktin);
3438 ret = process_userpass_input(ssh, in, inlen);
3442 c_write_str(ssh, "\r\n");
3446 if (s->pwpkt_type == SSH1_CMSG_AUTH_RSA) {
3448 * Try public key authentication with the specified
3451 s->tried_publickey = 1;
3454 const char *error = NULL;
3455 int ret = loadrsakey(&ssh->cfg.keyfile, &s->key, s->password,
3458 c_write_str(ssh, "Couldn't load private key from ");
3459 c_write_str(ssh, filename_to_str(&ssh->cfg.keyfile));
3460 c_write_str(ssh, " (");
3461 c_write_str(ssh, error);
3462 c_write_str(ssh, ").\r\n");
3463 continue; /* go and try password */
3466 c_write_str(ssh, "Wrong passphrase.\r\n");
3467 s->tried_publickey = 0;
3468 continue; /* try again */
3473 * Send a public key attempt.
3475 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3476 PKT_BIGNUM, s->key.modulus, PKT_END);
3479 if (pktin->type == SSH1_SMSG_FAILURE) {
3480 c_write_str(ssh, "Server refused our public key.\r\n");
3481 continue; /* go and try password */
3483 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3484 bombout(("Bizarre response to offer of public key"));
3490 unsigned char buffer[32];
3491 Bignum challenge, response;
3493 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3494 bombout(("Server's RSA challenge was badly formatted"));
3497 response = rsadecrypt(challenge, &s->key);
3498 freebn(s->key.private_exponent);/* burn the evidence */
3500 for (i = 0; i < 32; i++) {
3501 buffer[i] = bignum_byte(response, 31 - i);
3505 MD5Update(&md5c, buffer, 32);
3506 MD5Update(&md5c, s->session_id, 16);
3507 MD5Final(buffer, &md5c);
3509 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3510 PKT_DATA, buffer, 16, PKT_END);
3517 if (pktin->type == SSH1_SMSG_FAILURE) {
3518 if (flags & FLAG_VERBOSE)
3519 c_write_str(ssh, "Failed to authenticate with"
3520 " our public key.\r\n");
3521 continue; /* go and try password */
3522 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
3523 bombout(("Bizarre response to RSA authentication response"));
3527 break; /* we're through! */
3529 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
3531 * Defence against traffic analysis: we send a
3532 * whole bunch of packets containing strings of
3533 * different lengths. One of these strings is the
3534 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
3535 * The others are all random data in
3536 * SSH1_MSG_IGNORE packets. This way a passive
3537 * listener can't tell which is the password, and
3538 * hence can't deduce the password length.
3540 * Anybody with a password length greater than 16
3541 * bytes is going to have enough entropy in their
3542 * password that a listener won't find it _that_
3543 * much help to know how long it is. So what we'll
3546 * - if password length < 16, we send 15 packets
3547 * containing string lengths 1 through 15
3549 * - otherwise, we let N be the nearest multiple
3550 * of 8 below the password length, and send 8
3551 * packets containing string lengths N through
3552 * N+7. This won't obscure the order of
3553 * magnitude of the password length, but it will
3554 * introduce a bit of extra uncertainty.
3556 * A few servers (the old 1.2.18 through 1.2.22)
3557 * can't deal with SSH1_MSG_IGNORE. For these
3558 * servers, we need an alternative defence. We make
3559 * use of the fact that the password is interpreted
3560 * as a C string: so we can append a NUL, then some
3563 * One server (a Cisco one) can deal with neither
3564 * SSH1_MSG_IGNORE _nor_ a padded password string.
3565 * For this server we are left with no defences
3566 * against password length sniffing.
3568 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE)) {
3570 * The server can deal with SSH1_MSG_IGNORE, so
3571 * we can use the primary defence.
3573 int bottom, top, pwlen, i;
3576 pwlen = strlen(s->password);
3578 bottom = 0; /* zero length passwords are OK! :-) */
3581 bottom = pwlen & ~7;
3585 assert(pwlen >= bottom && pwlen <= top);
3587 randomstr = snewn(top + 1, char);
3589 for (i = bottom; i <= top; i++) {
3591 defer_packet(ssh, s->pwpkt_type,
3592 PKTT_PASSWORD, PKT_STR, s->password,
3593 PKTT_OTHER, PKT_END);
3595 for (j = 0; j < i; j++) {
3597 randomstr[j] = random_byte();
3598 } while (randomstr[j] == '\0');
3600 randomstr[i] = '\0';
3601 defer_packet(ssh, SSH1_MSG_IGNORE,
3602 PKT_STR, randomstr, PKT_END);
3605 logevent("Sending password with camouflage packets");
3606 ssh_pkt_defersend(ssh);
3609 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
3611 * The server can't deal with SSH1_MSG_IGNORE
3612 * but can deal with padded passwords, so we
3613 * can use the secondary defence.
3619 len = strlen(s->password);
3620 if (len < sizeof(string)) {
3622 strcpy(string, s->password);
3623 len++; /* cover the zero byte */
3624 while (len < sizeof(string)) {
3625 string[len++] = (char) random_byte();
3630 logevent("Sending length-padded password");
3631 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
3632 PKT_INT, len, PKT_DATA, ss, len,
3633 PKTT_OTHER, PKT_END);
3636 * The server has _both_
3637 * BUG_CHOKES_ON_SSH1_IGNORE and
3638 * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
3639 * therefore nothing we can do.
3642 len = strlen(s->password);
3643 logevent("Sending unpadded password");
3644 send_packet(ssh, s->pwpkt_type,
3645 PKTT_PASSWORD, PKT_INT, len,
3646 PKT_DATA, s->password, len,
3647 PKTT_OTHER, PKT_END);
3650 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
3651 PKT_STR, s->password, PKTT_OTHER, PKT_END);
3654 logevent("Sent password");
3655 memset(s->password, 0, strlen(s->password));
3657 if (pktin->type == SSH1_SMSG_FAILURE) {
3658 if (flags & FLAG_VERBOSE)
3659 c_write_str(ssh, "Access denied\r\n");
3660 logevent("Authentication refused");
3661 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
3662 bombout(("Strange packet received, type %d", pktin->type));
3667 logevent("Authentication successful");
3672 void sshfwd_close(struct ssh_channel *c)
3676 if (ssh->state == SSH_STATE_CLOSED)
3679 if (c && !c->closes) {
3681 * If halfopen is true, we have sent
3682 * CHANNEL_OPEN for this channel, but it hasn't even been
3683 * acknowledged by the server. So we must set a close flag
3684 * on it now, and then when the server acks the channel
3685 * open, we can close it then.
3688 if (ssh->version == 1) {
3689 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
3692 struct Packet *pktout;
3693 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
3694 ssh2_pkt_adduint32(pktout, c->remoteid);
3695 ssh2_pkt_send(ssh, pktout);
3698 c->closes = 1; /* sent MSG_CLOSE */
3699 if (c->type == CHAN_X11) {
3701 logevent("Forwarded X11 connection terminated");
3702 } else if (c->type == CHAN_SOCKDATA ||
3703 c->type == CHAN_SOCKDATA_DORMANT) {
3705 logevent("Forwarded port closed");
3710 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
3714 if (ssh->state == SSH_STATE_CLOSED)
3717 if (ssh->version == 1) {
3718 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3719 PKT_INT, c->remoteid,
3721 PKT_INT, len, PKT_DATA, buf, len,
3722 PKTT_OTHER, PKT_END);
3724 * In SSH-1 we can return 0 here - implying that forwarded
3725 * connections are never individually throttled - because
3726 * the only circumstance that can cause throttling will be
3727 * the whole SSH connection backing up, in which case
3728 * _everything_ will be throttled as a whole.
3732 ssh2_add_channel_data(c, buf, len);
3733 return ssh2_try_send(c);
3737 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
3741 if (ssh->state == SSH_STATE_CLOSED)
3744 if (ssh->version == 1) {
3745 if (c->v.v1.throttling && bufsize < SSH1_BUFFER_LIMIT) {
3746 c->v.v1.throttling = 0;
3747 ssh1_throttle(ssh, -1);
3750 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
3754 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
3756 struct queued_handler *qh = ssh->qhead;
3760 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
3763 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
3764 ssh->packet_dispatch[qh->msg1] = NULL;
3767 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
3768 ssh->packet_dispatch[qh->msg2] = NULL;
3772 ssh->qhead = qh->next;
3774 if (ssh->qhead->msg1 > 0) {
3775 assert(ssh->packet_dispatch[ssh->qhead->msg1] == NULL);
3776 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
3778 if (ssh->qhead->msg2 > 0) {
3779 assert(ssh->packet_dispatch[ssh->qhead->msg2] == NULL);
3780 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
3783 ssh->qhead = ssh->qtail = NULL;
3784 ssh->packet_dispatch[pktin->type] = NULL;
3787 qh->handler(ssh, pktin, qh->ctx);
3792 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
3793 chandler_fn_t handler, void *ctx)
3795 struct queued_handler *qh;
3797 qh = snew(struct queued_handler);
3800 qh->handler = handler;
3804 if (ssh->qtail == NULL) {
3808 assert(ssh->packet_dispatch[qh->msg1] == NULL);
3809 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
3812 assert(ssh->packet_dispatch[qh->msg2] == NULL);
3813 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
3816 ssh->qtail->next = qh;
3821 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
3823 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
3825 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
3826 SSH2_MSG_REQUEST_SUCCESS)) {
3827 logeventf(ssh, "Remote port forwarding from %s enabled",
3830 logeventf(ssh, "Remote port forwarding from %s refused",
3833 rpf = del234(ssh->rportfwds, pf);
3839 static void ssh_setup_portfwd(Ssh ssh, const Config *cfg)
3841 const char *portfwd_strptr = cfg->portfwd;
3842 struct ssh_portfwd *epf;
3845 if (!ssh->portfwds) {
3846 ssh->portfwds = newtree234(ssh_portcmp);
3849 * Go through the existing port forwardings and tag them
3850 * with status==DESTROY. Any that we want to keep will be
3851 * re-enabled (status==KEEP) as we go through the
3852 * configuration and find out which bits are the same as
3855 struct ssh_portfwd *epf;
3857 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
3858 epf->status = DESTROY;
3861 while (*portfwd_strptr) {
3862 char address_family, type;
3863 int sport,dport,sserv,dserv;
3864 char sports[256], dports[256], saddr[256], host[256];
3867 address_family = 'A';
3869 if (*portfwd_strptr == 'A' ||
3870 *portfwd_strptr == '4' ||
3871 *portfwd_strptr == '6')
3872 address_family = *portfwd_strptr++;
3873 if (*portfwd_strptr == 'L' ||
3874 *portfwd_strptr == 'R' ||
3875 *portfwd_strptr == 'D')
3876 type = *portfwd_strptr++;
3881 while (*portfwd_strptr && *portfwd_strptr != '\t') {
3882 if (*portfwd_strptr == ':') {
3884 * We've seen a colon in the middle of the
3885 * source port number. This means that
3886 * everything we've seen until now is the
3887 * source _address_, so we'll move it into
3888 * saddr and start sports from the beginning
3893 if (ssh->version == 1 && type == 'R') {
3894 logeventf(ssh, "SSH-1 cannot handle remote source address "
3895 "spec \"%s\"; ignoring", sports);
3897 strcpy(saddr, sports);
3900 if (n < lenof(sports)-1) sports[n++] = *portfwd_strptr++;
3904 if (*portfwd_strptr == '\t')
3907 while (*portfwd_strptr && *portfwd_strptr != ':') {
3908 if (n < lenof(host)-1) host[n++] = *portfwd_strptr++;
3911 if (*portfwd_strptr == ':')
3914 while (*portfwd_strptr) {
3915 if (n < lenof(dports)-1) dports[n++] = *portfwd_strptr++;
3919 dport = atoi(dports);
3923 dport = net_service_lookup(dports);
3925 logeventf(ssh, "Service lookup failed for destination"
3926 " port \"%s\"", dports);
3930 while (*portfwd_strptr) portfwd_strptr++;
3934 portfwd_strptr++; /* eat the NUL and move to next one */
3936 sport = atoi(sports);
3940 sport = net_service_lookup(sports);
3942 logeventf(ssh, "Service lookup failed for source"
3943 " port \"%s\"", sports);
3946 if (sport && dport) {
3947 /* Set up a description of the source port. */
3948 struct ssh_portfwd *pfrec, *epfrec;
3950 pfrec = snew(struct ssh_portfwd);
3952 pfrec->saddr = *saddr ? dupstr(saddr) : NULL;
3953 pfrec->sserv = sserv ? dupstr(sports) : NULL;
3954 pfrec->sport = sport;
3955 pfrec->daddr = *host ? dupstr(host) : NULL;
3956 pfrec->dserv = dserv ? dupstr(dports) : NULL;
3957 pfrec->dport = dport;
3958 pfrec->local = NULL;
3959 pfrec->remote = NULL;
3960 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
3961 address_family == '6' ? ADDRTYPE_IPV6 :
3964 epfrec = add234(ssh->portfwds, pfrec);
3965 if (epfrec != pfrec) {
3967 * We already have a port forwarding with precisely
3968 * these parameters. Hence, no need to do anything;
3969 * simply tag the existing one as KEEP.
3971 epfrec->status = KEEP;
3972 free_portfwd(pfrec);
3974 pfrec->status = CREATE;
3980 * Now go through and destroy any port forwardings which were
3983 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
3984 if (epf->status == DESTROY) {
3987 message = dupprintf("%s port forwarding from %s%s%d",
3988 epf->type == 'L' ? "local" :
3989 epf->type == 'R' ? "remote" : "dynamic",
3990 epf->saddr ? epf->saddr : "",
3991 epf->saddr ? ":" : "",
3994 if (epf->type != 'D') {
3995 char *msg2 = dupprintf("%s to %s:%d", message,
3996 epf->daddr, epf->dport);
4001 logeventf(ssh, "Cancelling %s", message);
4005 struct ssh_rportfwd *rpf = epf->remote;
4006 struct Packet *pktout;
4009 * Cancel the port forwarding at the server
4012 if (ssh->version == 1) {
4014 * We cannot cancel listening ports on the
4015 * server side in SSH-1! There's no message
4016 * to support it. Instead, we simply remove
4017 * the rportfwd record from the local end
4018 * so that any connections the server tries
4019 * to make on it are rejected.
4022 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4023 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
4024 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
4026 ssh2_pkt_addstring(pktout, epf->saddr);
4027 } else if (ssh->cfg.rport_acceptall) {
4028 /* XXX: ssh->cfg.rport_acceptall may not represent
4029 * what was used to open the original connection,
4030 * since it's reconfigurable. */
4031 ssh2_pkt_addstring(pktout, "0.0.0.0");
4033 ssh2_pkt_addstring(pktout, "127.0.0.1");
4035 ssh2_pkt_adduint32(pktout, epf->sport);
4036 ssh2_pkt_send(ssh, pktout);
4039 del234(ssh->rportfwds, rpf);
4041 } else if (epf->local) {
4042 pfd_terminate(epf->local);
4045 delpos234(ssh->portfwds, i);
4047 i--; /* so we don't skip one in the list */
4051 * And finally, set up any new port forwardings (status==CREATE).
4053 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4054 if (epf->status == CREATE) {
4055 char *sportdesc, *dportdesc;
4056 sportdesc = dupprintf("%s%s%s%s%d%s",
4057 epf->saddr ? epf->saddr : "",
4058 epf->saddr ? ":" : "",
4059 epf->sserv ? epf->sserv : "",
4060 epf->sserv ? "(" : "",
4062 epf->sserv ? ")" : "");
4063 if (epf->type == 'D') {
4066 dportdesc = dupprintf("%s:%s%s%d%s",
4068 epf->dserv ? epf->dserv : "",
4069 epf->dserv ? "(" : "",
4071 epf->dserv ? ")" : "");
4074 if (epf->type == 'L') {
4075 const char *err = pfd_addforward(epf->daddr, epf->dport,
4076 epf->saddr, epf->sport,
4079 epf->addressfamily);
4081 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
4082 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4083 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4084 sportdesc, dportdesc,
4085 err ? " failed: " : "", err ? err : "");
4086 } else if (epf->type == 'D') {
4087 const char *err = pfd_addforward(NULL, -1,
4088 epf->saddr, epf->sport,
4091 epf->addressfamily);
4093 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
4094 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4095 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4097 err ? " failed: " : "", err ? err : "");
4099 struct ssh_rportfwd *pf;
4102 * Ensure the remote port forwardings tree exists.
4104 if (!ssh->rportfwds) {
4105 if (ssh->version == 1)
4106 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
4108 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
4111 pf = snew(struct ssh_rportfwd);
4112 strncpy(pf->dhost, epf->daddr, lenof(pf->dhost)-1);
4113 pf->dhost[lenof(pf->dhost)-1] = '\0';
4114 pf->dport = epf->dport;
4115 pf->sport = epf->sport;
4116 if (add234(ssh->rportfwds, pf) != pf) {
4117 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
4118 epf->daddr, epf->dport);
4121 logeventf(ssh, "Requesting remote port %s"
4122 " forward to %s", sportdesc, dportdesc);
4124 pf->sportdesc = sportdesc;
4129 if (ssh->version == 1) {
4130 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
4131 PKT_INT, epf->sport,
4132 PKT_STR, epf->daddr,
4133 PKT_INT, epf->dport,
4135 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
4137 ssh_rportfwd_succfail, pf);
4139 struct Packet *pktout;
4140 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4141 ssh2_pkt_addstring(pktout, "tcpip-forward");
4142 ssh2_pkt_addbool(pktout, 1);/* want reply */
4144 ssh2_pkt_addstring(pktout, epf->saddr);
4145 } else if (cfg->rport_acceptall) {
4146 ssh2_pkt_addstring(pktout, "0.0.0.0");
4148 ssh2_pkt_addstring(pktout, "127.0.0.1");
4150 ssh2_pkt_adduint32(pktout, epf->sport);
4151 ssh2_pkt_send(ssh, pktout);
4153 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
4154 SSH2_MSG_REQUEST_FAILURE,
4155 ssh_rportfwd_succfail, pf);
4164 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
4167 int stringlen, bufsize;
4169 ssh_pkt_getstring(pktin, &string, &stringlen);
4170 if (string == NULL) {
4171 bombout(("Incoming terminal data packet was badly formed"));
4175 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
4177 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
4178 ssh->v1_stdout_throttling = 1;
4179 ssh1_throttle(ssh, +1);
4183 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
4185 /* Remote side is trying to open a channel to talk to our
4186 * X-Server. Give them back a local channel number. */
4187 struct ssh_channel *c;
4188 int remoteid = ssh_pkt_getuint32(pktin);
4190 logevent("Received X11 connect request");
4191 /* Refuse if X11 forwarding is disabled. */
4192 if (!ssh->X11_fwd_enabled) {
4193 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4194 PKT_INT, remoteid, PKT_END);
4195 logevent("Rejected X11 connect request");
4197 c = snew(struct ssh_channel);
4200 if (x11_init(&c->u.x11.s, ssh->cfg.x11_display, c,
4201 ssh->x11auth, NULL, -1, &ssh->cfg) != NULL) {
4202 logevent("Opening X11 forward connection failed");
4204 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4205 PKT_INT, remoteid, PKT_END);
4208 ("Opening X11 forward connection succeeded");
4209 c->remoteid = remoteid;
4210 c->halfopen = FALSE;
4211 c->localid = alloc_channel_id(ssh);
4213 c->v.v1.throttling = 0;
4214 c->type = CHAN_X11; /* identify channel type */
4215 add234(ssh->channels, c);
4216 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4217 PKT_INT, c->remoteid, PKT_INT,
4218 c->localid, PKT_END);
4219 logevent("Opened X11 forward channel");
4224 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
4226 /* Remote side is trying to open a channel to talk to our
4227 * agent. Give them back a local channel number. */
4228 struct ssh_channel *c;
4229 int remoteid = ssh_pkt_getuint32(pktin);
4231 /* Refuse if agent forwarding is disabled. */
4232 if (!ssh->agentfwd_enabled) {
4233 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4234 PKT_INT, remoteid, PKT_END);
4236 c = snew(struct ssh_channel);
4238 c->remoteid = remoteid;
4239 c->halfopen = FALSE;
4240 c->localid = alloc_channel_id(ssh);
4242 c->v.v1.throttling = 0;
4243 c->type = CHAN_AGENT; /* identify channel type */
4244 c->u.a.lensofar = 0;
4245 add234(ssh->channels, c);
4246 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4247 PKT_INT, c->remoteid, PKT_INT, c->localid,
4252 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
4254 /* Remote side is trying to open a channel to talk to a
4255 * forwarded port. Give them back a local channel number. */
4256 struct ssh_channel *c;
4257 struct ssh_rportfwd pf, *pfp;
4262 c = snew(struct ssh_channel);
4265 remoteid = ssh_pkt_getuint32(pktin);
4266 ssh_pkt_getstring(pktin, &host, &hostsize);
4267 port = ssh_pkt_getuint32(pktin);
4269 if (hostsize >= lenof(pf.dhost))
4270 hostsize = lenof(pf.dhost)-1;
4271 memcpy(pf.dhost, host, hostsize);
4272 pf.dhost[hostsize] = '\0';
4274 pfp = find234(ssh->rportfwds, &pf, NULL);
4277 logeventf(ssh, "Rejected remote port open request for %s:%d",
4279 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4280 PKT_INT, remoteid, PKT_END);
4282 logeventf(ssh, "Received remote port open request for %s:%d",
4284 e = pfd_newconnect(&c->u.pfd.s, pf.dhost, port,
4285 c, &ssh->cfg, pfp->pfrec->addressfamily);
4287 logeventf(ssh, "Port open failed: %s", e);
4289 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4290 PKT_INT, remoteid, PKT_END);
4292 c->remoteid = remoteid;
4293 c->halfopen = FALSE;
4294 c->localid = alloc_channel_id(ssh);
4296 c->v.v1.throttling = 0;
4297 c->type = CHAN_SOCKDATA; /* identify channel type */
4298 add234(ssh->channels, c);
4299 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4300 PKT_INT, c->remoteid, PKT_INT,
4301 c->localid, PKT_END);
4302 logevent("Forwarded port opened successfully");
4307 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
4309 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4310 unsigned int localid = ssh_pkt_getuint32(pktin);
4311 struct ssh_channel *c;
4313 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4314 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4315 c->remoteid = localid;
4316 c->halfopen = FALSE;
4317 c->type = CHAN_SOCKDATA;
4318 c->v.v1.throttling = 0;
4319 pfd_confirm(c->u.pfd.s);
4322 if (c && c->closes) {
4324 * We have a pending close on this channel,
4325 * which we decided on before the server acked
4326 * the channel open. So now we know the
4327 * remoteid, we can close it again.
4329 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE,
4330 PKT_INT, c->remoteid, PKT_END);
4334 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
4336 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4337 struct ssh_channel *c;
4339 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4340 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4341 logevent("Forwarded connection refused by server");
4342 pfd_close(c->u.pfd.s);
4343 del234(ssh->channels, c);
4348 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
4350 /* Remote side closes a channel. */
4351 unsigned i = ssh_pkt_getuint32(pktin);
4352 struct ssh_channel *c;
4353 c = find234(ssh->channels, &i, ssh_channelfind);
4354 if (c && !c->halfopen) {
4357 (pktin->type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
4359 if ((c->closes == 0) && (c->type == CHAN_X11)) {
4360 logevent("Forwarded X11 connection terminated");
4361 assert(c->u.x11.s != NULL);
4362 x11_close(c->u.x11.s);
4365 if ((c->closes == 0) && (c->type == CHAN_SOCKDATA)) {
4366 logevent("Forwarded port closed");
4367 assert(c->u.pfd.s != NULL);
4368 pfd_close(c->u.pfd.s);
4372 c->closes |= (closetype << 2); /* seen this message */
4373 if (!(c->closes & closetype)) {
4374 send_packet(ssh, pktin->type, PKT_INT, c->remoteid,
4376 c->closes |= closetype; /* sent it too */
4379 if (c->closes == 15) {
4380 del234(ssh->channels, c);
4384 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
4385 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
4386 "_CONFIRMATION", c ? "half-open" : "nonexistent",
4391 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
4393 /* Data sent down one of our channels. */
4394 int i = ssh_pkt_getuint32(pktin);
4397 struct ssh_channel *c;
4399 ssh_pkt_getstring(pktin, &p, &len);
4401 c = find234(ssh->channels, &i, ssh_channelfind);
4406 bufsize = x11_send(c->u.x11.s, p, len);
4409 bufsize = pfd_send(c->u.pfd.s, p, len);
4412 /* Data for an agent message. Buffer it. */
4414 if (c->u.a.lensofar < 4) {
4415 unsigned int l = min(4 - c->u.a.lensofar, len);
4416 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
4420 c->u.a.lensofar += l;
4422 if (c->u.a.lensofar == 4) {
4424 4 + GET_32BIT(c->u.a.msglen);
4425 c->u.a.message = snewn(c->u.a.totallen,
4427 memcpy(c->u.a.message, c->u.a.msglen, 4);
4429 if (c->u.a.lensofar >= 4 && len > 0) {
4431 min(c->u.a.totallen - c->u.a.lensofar,
4433 memcpy(c->u.a.message + c->u.a.lensofar, p,
4437 c->u.a.lensofar += l;
4439 if (c->u.a.lensofar == c->u.a.totallen) {
4442 if (agent_query(c->u.a.message,
4445 ssh_agentf_callback, c))
4446 ssh_agentf_callback(c, reply, replylen);
4447 sfree(c->u.a.message);
4448 c->u.a.lensofar = 0;
4451 bufsize = 0; /* agent channels never back up */
4454 if (!c->v.v1.throttling && bufsize > SSH1_BUFFER_LIMIT) {
4455 c->v.v1.throttling = 1;
4456 ssh1_throttle(ssh, +1);
4461 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
4463 ssh->exitcode = ssh_pkt_getuint32(pktin);
4464 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
4465 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
4467 * In case `helpful' firewalls or proxies tack
4468 * extra human-readable text on the end of the
4469 * session which we might mistake for another
4470 * encrypted packet, we close the session once
4471 * we've sent EXIT_CONFIRMATION.
4473 ssh->close_expected = TRUE;
4474 ssh_closing((Plug)ssh, NULL, 0, 0);
4477 static void do_ssh1_connection(Ssh ssh, unsigned char *in, int inlen,
4478 struct Packet *pktin)
4480 crBegin(ssh->do_ssh1_connection_crstate);
4482 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
4483 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
4484 ssh1_smsg_stdout_stderr_data;
4486 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
4487 ssh1_msg_channel_open_confirmation;
4488 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
4489 ssh1_msg_channel_open_failure;
4490 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
4491 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
4492 ssh1_msg_channel_close;
4493 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
4494 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
4496 if (ssh->cfg.agentfwd && agent_exists()) {
4497 logevent("Requesting agent forwarding");
4498 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
4502 if (pktin->type != SSH1_SMSG_SUCCESS
4503 && pktin->type != SSH1_SMSG_FAILURE) {
4504 bombout(("Protocol confusion"));
4506 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4507 logevent("Agent forwarding refused");
4509 logevent("Agent forwarding enabled");
4510 ssh->agentfwd_enabled = TRUE;
4511 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
4515 if (ssh->cfg.x11_forward) {
4516 char proto[20], data[64];
4517 logevent("Requesting X11 forwarding");
4518 ssh->x11auth = x11_invent_auth(proto, sizeof(proto),
4519 data, sizeof(data), ssh->cfg.x11_auth);
4520 x11_get_real_auth(ssh->x11auth, ssh->cfg.x11_display);
4521 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
4522 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
4523 PKT_STR, proto, PKT_STR, data,
4524 PKT_INT, x11_get_screen_number(ssh->cfg.x11_display),
4527 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
4528 PKT_STR, proto, PKT_STR, data, PKT_END);
4533 if (pktin->type != SSH1_SMSG_SUCCESS
4534 && pktin->type != SSH1_SMSG_FAILURE) {
4535 bombout(("Protocol confusion"));
4537 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4538 logevent("X11 forwarding refused");
4540 logevent("X11 forwarding enabled");
4541 ssh->X11_fwd_enabled = TRUE;
4542 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
4546 ssh_setup_portfwd(ssh, &ssh->cfg);
4547 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
4549 if (!ssh->cfg.nopty) {
4550 /* Unpick the terminal-speed string. */
4551 /* XXX perhaps we should allow no speeds to be sent. */
4552 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
4553 sscanf(ssh->cfg.termspeed, "%d,%d", &ssh->ospeed, &ssh->ispeed);
4554 /* Send the pty request. */
4555 send_packet(ssh, SSH1_CMSG_REQUEST_PTY,
4556 PKT_STR, ssh->cfg.termtype,
4557 PKT_INT, ssh->term_height,
4558 PKT_INT, ssh->term_width,
4559 PKT_INT, 0, PKT_INT, 0, /* width,height in pixels */
4560 PKT_CHAR, 192, PKT_INT, ssh->ispeed, /* TTY_OP_ISPEED */
4561 PKT_CHAR, 193, PKT_INT, ssh->ospeed, /* TTY_OP_OSPEED */
4562 PKT_CHAR, 0, PKT_END);
4563 ssh->state = SSH_STATE_INTERMED;
4567 if (pktin->type != SSH1_SMSG_SUCCESS
4568 && pktin->type != SSH1_SMSG_FAILURE) {
4569 bombout(("Protocol confusion"));
4571 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4572 c_write_str(ssh, "Server refused to allocate pty\r\n");
4573 ssh->editing = ssh->echoing = 1;
4575 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
4576 ssh->ospeed, ssh->ispeed);
4578 ssh->editing = ssh->echoing = 1;
4581 if (ssh->cfg.compression) {
4582 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
4586 if (pktin->type != SSH1_SMSG_SUCCESS
4587 && pktin->type != SSH1_SMSG_FAILURE) {
4588 bombout(("Protocol confusion"));
4590 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4591 c_write_str(ssh, "Server refused to compress\r\n");
4593 logevent("Started compression");
4594 ssh->v1_compressing = TRUE;
4595 ssh->cs_comp_ctx = zlib_compress_init();
4596 logevent("Initialised zlib (RFC1950) compression");
4597 ssh->sc_comp_ctx = zlib_decompress_init();
4598 logevent("Initialised zlib (RFC1950) decompression");
4602 * Start the shell or command.
4604 * Special case: if the first-choice command is an SSH-2
4605 * subsystem (hence not usable here) and the second choice
4606 * exists, we fall straight back to that.
4609 char *cmd = ssh->cfg.remote_cmd_ptr;
4611 if (!cmd) cmd = ssh->cfg.remote_cmd;
4613 if (ssh->cfg.ssh_subsys && ssh->cfg.remote_cmd_ptr2) {
4614 cmd = ssh->cfg.remote_cmd_ptr2;
4615 ssh->fallback_cmd = TRUE;
4618 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
4620 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
4621 logevent("Started session");
4624 ssh->state = SSH_STATE_SESSION;
4625 if (ssh->size_needed)
4626 ssh_size(ssh, ssh->term_width, ssh->term_height);
4627 if (ssh->eof_needed)
4628 ssh_special(ssh, TS_EOF);
4631 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
4633 ssh->channels = newtree234(ssh_channelcmp);
4637 * By this point, most incoming packets are already being
4638 * handled by the dispatch table, and we need only pay
4639 * attention to the unusual ones.
4644 if (pktin->type == SSH1_SMSG_SUCCESS) {
4645 /* may be from EXEC_SHELL on some servers */
4646 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4647 /* may be from EXEC_SHELL on some servers
4648 * if no pty is available or in other odd cases. Ignore */
4650 bombout(("Strange packet received: type %d", pktin->type));
4655 int len = min(inlen, 512);
4656 send_packet(ssh, SSH1_CMSG_STDIN_DATA, PKTT_DATA,
4657 PKT_INT, len, PKT_DATA, in, len,
4658 PKTT_OTHER, PKT_END);
4669 * Handle the top-level SSH-2 protocol.
4671 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
4676 ssh_pkt_getstring(pktin, &msg, &msglen);
4677 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
4680 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
4682 /* log reason code in disconnect message */
4686 ssh_pkt_getstring(pktin, &msg, &msglen);
4687 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
4690 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
4692 /* Do nothing, because we're ignoring it! Duhh. */
4695 static void ssh1_protocol_setup(Ssh ssh)
4700 * Most messages are handled by the coroutines.
4702 for (i = 0; i < 256; i++)
4703 ssh->packet_dispatch[i] = NULL;
4706 * These special message types we install handlers for.
4708 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
4709 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
4710 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
4713 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
4714 struct Packet *pktin)
4716 unsigned char *in=(unsigned char*)vin;
4717 if (ssh->state == SSH_STATE_CLOSED)
4720 if (pktin && ssh->packet_dispatch[pktin->type]) {
4721 ssh->packet_dispatch[pktin->type](ssh, pktin);
4725 if (!ssh->protocol_initial_phase_done) {
4726 if (do_ssh1_login(ssh, in, inlen, pktin))
4727 ssh->protocol_initial_phase_done = TRUE;
4732 do_ssh1_connection(ssh, in, inlen, pktin);
4736 * Utility routine for decoding comma-separated strings in KEXINIT.
4738 static int in_commasep_string(char *needle, char *haystack, int haylen)
4741 if (!needle || !haystack) /* protect against null pointers */
4743 needlen = strlen(needle);
4746 * Is it at the start of the string?
4748 if (haylen >= needlen && /* haystack is long enough */
4749 !memcmp(needle, haystack, needlen) && /* initial match */
4750 (haylen == needlen || haystack[needlen] == ',')
4751 /* either , or EOS follows */
4755 * If not, search for the next comma and resume after that.
4756 * If no comma found, terminate.
4758 while (haylen > 0 && *haystack != ',')
4759 haylen--, haystack++;
4762 haylen--, haystack++; /* skip over comma itself */
4767 * Similar routine for checking whether we have the first string in a list.
4769 static int first_in_commasep_string(char *needle, char *haystack, int haylen)
4772 if (!needle || !haystack) /* protect against null pointers */
4774 needlen = strlen(needle);
4776 * Is it at the start of the string?
4778 if (haylen >= needlen && /* haystack is long enough */
4779 !memcmp(needle, haystack, needlen) && /* initial match */
4780 (haylen == needlen || haystack[needlen] == ',')
4781 /* either , or EOS follows */
4789 * SSH-2 key creation method.
4791 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H,
4792 unsigned char *sessid, char chr,
4793 unsigned char *keyspace)
4796 /* First 20 bytes. */
4798 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
4800 SHA_Bytes(&s, H, 20);
4801 SHA_Bytes(&s, &chr, 1);
4802 SHA_Bytes(&s, sessid, 20);
4803 SHA_Final(&s, keyspace);
4804 /* Next 20 bytes. */
4806 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
4808 SHA_Bytes(&s, H, 20);
4809 SHA_Bytes(&s, keyspace, 20);
4810 SHA_Final(&s, keyspace + 20);
4814 * Handle the SSH-2 transport layer.
4816 static int do_ssh2_transport(Ssh ssh, void *vin, int inlen,
4817 struct Packet *pktin)
4819 unsigned char *in = (unsigned char *)vin;
4820 struct do_ssh2_transport_state {
4821 int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
4822 Bignum p, g, e, f, K;
4823 int kex_init_value, kex_reply_value;
4824 const struct ssh_mac **maclist;
4826 const struct ssh2_cipher *cscipher_tobe;
4827 const struct ssh2_cipher *sccipher_tobe;
4828 const struct ssh_mac *csmac_tobe;
4829 const struct ssh_mac *scmac_tobe;
4830 const struct ssh_compress *cscomp_tobe;
4831 const struct ssh_compress *sccomp_tobe;
4832 char *hostkeydata, *sigdata, *keystr, *fingerprint;
4833 int hostkeylen, siglen;
4834 void *hkey; /* actual host key */
4835 unsigned char exchange_hash[20];
4836 int n_preferred_kex;
4837 const struct ssh_kex *preferred_kex[KEX_MAX];
4838 int n_preferred_ciphers;
4839 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
4840 const struct ssh_compress *preferred_comp;
4841 int got_session_id, activated_authconn;
4842 struct Packet *pktout;
4847 crState(do_ssh2_transport_state);
4849 crBegin(ssh->do_ssh2_transport_crstate);
4851 s->cscipher_tobe = s->sccipher_tobe = NULL;
4852 s->csmac_tobe = s->scmac_tobe = NULL;
4853 s->cscomp_tobe = s->sccomp_tobe = NULL;
4855 s->got_session_id = s->activated_authconn = FALSE;
4858 * Be prepared to work around the buggy MAC problem.
4860 if (ssh->remote_bugs & BUG_SSH2_HMAC)
4861 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
4863 s->maclist = macs, s->nmacs = lenof(macs);
4866 ssh->pkt_ctx &= ~SSH2_PKTCTX_KEX_MASK;
4868 int i, j, commalist_started;
4871 * Set up the preferred key exchange. (NULL => warn below here)
4873 s->n_preferred_kex = 0;
4874 for (i = 0; i < KEX_MAX; i++) {
4875 switch (ssh->cfg.ssh_kexlist[i]) {
4877 s->preferred_kex[s->n_preferred_kex++] =
4878 &ssh_diffiehellman_gex;
4881 s->preferred_kex[s->n_preferred_kex++] =
4882 &ssh_diffiehellman_group14;
4885 s->preferred_kex[s->n_preferred_kex++] =
4886 &ssh_diffiehellman_group1;
4889 /* Flag for later. Don't bother if it's the last in
4891 if (i < KEX_MAX - 1) {
4892 s->preferred_kex[s->n_preferred_kex++] = NULL;
4899 * Set up the preferred ciphers. (NULL => warn below here)
4901 s->n_preferred_ciphers = 0;
4902 for (i = 0; i < CIPHER_MAX; i++) {
4903 switch (ssh->cfg.ssh_cipherlist[i]) {
4904 case CIPHER_BLOWFISH:
4905 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
4908 if (ssh->cfg.ssh2_des_cbc) {
4909 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
4913 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
4916 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
4918 case CIPHER_ARCFOUR:
4919 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
4922 /* Flag for later. Don't bother if it's the last in
4924 if (i < CIPHER_MAX - 1) {
4925 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
4932 * Set up preferred compression.
4934 if (ssh->cfg.compression)
4935 s->preferred_comp = &ssh_zlib;
4937 s->preferred_comp = &ssh_comp_none;
4940 * Enable queueing of outgoing auth- or connection-layer
4941 * packets while we are in the middle of a key exchange.
4943 ssh->queueing = TRUE;
4946 * Flag that KEX is in progress.
4948 ssh->kex_in_progress = TRUE;
4951 * Construct and send our key exchange packet.
4953 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
4954 for (i = 0; i < 16; i++)
4955 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
4956 /* List key exchange algorithms. */
4957 ssh2_pkt_addstring_start(s->pktout);
4958 commalist_started = 0;
4959 for (i = 0; i < s->n_preferred_kex; i++) {
4960 const struct ssh_kex *k = s->preferred_kex[i];
4961 if (!k) continue; /* warning flag */
4962 if (commalist_started)
4963 ssh2_pkt_addstring_str(s->pktout, ",");
4964 ssh2_pkt_addstring_str(s->pktout, s->preferred_kex[i]->name);
4965 commalist_started = 1;
4967 /* List server host key algorithms. */
4968 ssh2_pkt_addstring_start(s->pktout);
4969 for (i = 0; i < lenof(hostkey_algs); i++) {
4970 ssh2_pkt_addstring_str(s->pktout, hostkey_algs[i]->name);
4971 if (i < lenof(hostkey_algs) - 1)
4972 ssh2_pkt_addstring_str(s->pktout, ",");
4974 /* List client->server encryption algorithms. */
4975 ssh2_pkt_addstring_start(s->pktout);
4976 commalist_started = 0;
4977 for (i = 0; i < s->n_preferred_ciphers; i++) {
4978 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
4979 if (!c) continue; /* warning flag */
4980 for (j = 0; j < c->nciphers; j++) {
4981 if (commalist_started)
4982 ssh2_pkt_addstring_str(s->pktout, ",");
4983 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
4984 commalist_started = 1;
4987 /* List server->client encryption algorithms. */
4988 ssh2_pkt_addstring_start(s->pktout);
4989 commalist_started = 0;
4990 for (i = 0; i < s->n_preferred_ciphers; i++) {
4991 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
4992 if (!c) continue; /* warning flag */
4993 for (j = 0; j < c->nciphers; j++) {
4994 if (commalist_started)
4995 ssh2_pkt_addstring_str(s->pktout, ",");
4996 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
4997 commalist_started = 1;
5000 /* List client->server MAC algorithms. */
5001 ssh2_pkt_addstring_start(s->pktout);
5002 for (i = 0; i < s->nmacs; i++) {
5003 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5004 if (i < s->nmacs - 1)
5005 ssh2_pkt_addstring_str(s->pktout, ",");
5007 /* List server->client MAC algorithms. */
5008 ssh2_pkt_addstring_start(s->pktout);
5009 for (i = 0; i < s->nmacs; i++) {
5010 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5011 if (i < s->nmacs - 1)
5012 ssh2_pkt_addstring_str(s->pktout, ",");
5014 /* List client->server compression algorithms. */
5015 ssh2_pkt_addstring_start(s->pktout);
5016 assert(lenof(compressions) > 1);
5017 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
5018 for (i = 0; i < lenof(compressions); i++) {
5019 const struct ssh_compress *c = compressions[i];
5020 if (c != s->preferred_comp) {
5021 ssh2_pkt_addstring_str(s->pktout, ",");
5022 ssh2_pkt_addstring_str(s->pktout, c->name);
5025 /* List server->client compression algorithms. */
5026 ssh2_pkt_addstring_start(s->pktout);
5027 assert(lenof(compressions) > 1);
5028 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
5029 for (i = 0; i < lenof(compressions); i++) {
5030 const struct ssh_compress *c = compressions[i];
5031 if (c != s->preferred_comp) {
5032 ssh2_pkt_addstring_str(s->pktout, ",");
5033 ssh2_pkt_addstring_str(s->pktout, c->name);
5036 /* List client->server languages. Empty list. */
5037 ssh2_pkt_addstring_start(s->pktout);
5038 /* List server->client languages. Empty list. */
5039 ssh2_pkt_addstring_start(s->pktout);
5040 /* First KEX packet does _not_ follow, because we're not that brave. */
5041 ssh2_pkt_addbool(s->pktout, FALSE);
5043 ssh2_pkt_adduint32(s->pktout, 0);
5046 ssh->exhash = ssh->exhashbase;
5047 sha_string(&ssh->exhash, s->pktout->data + 5, s->pktout->length - 5);
5049 ssh2_pkt_send_noqueue(ssh, s->pktout);
5053 if (pktin->length > 5)
5054 sha_string(&ssh->exhash, pktin->data + 5, pktin->length - 5);
5057 * Now examine the other side's KEXINIT to see what we're up
5061 char *str, *preferred;
5064 if (pktin->type != SSH2_MSG_KEXINIT) {
5065 bombout(("expected key exchange packet from server"));
5069 ssh->hostkey = NULL;
5070 s->cscipher_tobe = NULL;
5071 s->sccipher_tobe = NULL;
5072 s->csmac_tobe = NULL;
5073 s->scmac_tobe = NULL;
5074 s->cscomp_tobe = NULL;
5075 s->sccomp_tobe = NULL;
5076 s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
5078 pktin->savedpos += 16; /* skip garbage cookie */
5079 ssh_pkt_getstring(pktin, &str, &len); /* key exchange algorithms */
5082 for (i = 0; i < s->n_preferred_kex; i++) {
5083 const struct ssh_kex *k = s->preferred_kex[i];
5087 if (!preferred) preferred = k->name;
5088 if (in_commasep_string(k->name, str, len))
5095 bombout(("Couldn't agree a key exchange algorithm (available: %s)",
5096 str ? str : "(null)"));
5100 * Note that the server's guess is considered wrong if it doesn't match
5101 * the first algorithm in our list, even if it's still the algorithm
5104 s->guessok = first_in_commasep_string(preferred, str, len);
5105 ssh_pkt_getstring(pktin, &str, &len); /* host key algorithms */
5106 for (i = 0; i < lenof(hostkey_algs); i++) {
5107 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
5108 ssh->hostkey = hostkey_algs[i];
5112 s->guessok = s->guessok &&
5113 first_in_commasep_string(hostkey_algs[0]->name, str, len);
5114 ssh_pkt_getstring(pktin, &str, &len); /* client->server cipher */
5115 for (i = 0; i < s->n_preferred_ciphers; i++) {
5116 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5118 s->warn_cscipher = TRUE;
5120 for (j = 0; j < c->nciphers; j++) {
5121 if (in_commasep_string(c->list[j]->name, str, len)) {
5122 s->cscipher_tobe = c->list[j];
5127 if (s->cscipher_tobe)
5130 if (!s->cscipher_tobe) {
5131 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
5132 str ? str : "(null)"));
5136 ssh_pkt_getstring(pktin, &str, &len); /* server->client cipher */
5137 for (i = 0; i < s->n_preferred_ciphers; i++) {
5138 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5140 s->warn_sccipher = TRUE;
5142 for (j = 0; j < c->nciphers; j++) {
5143 if (in_commasep_string(c->list[j]->name, str, len)) {
5144 s->sccipher_tobe = c->list[j];
5149 if (s->sccipher_tobe)
5152 if (!s->sccipher_tobe) {
5153 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
5154 str ? str : "(null)"));
5158 ssh_pkt_getstring(pktin, &str, &len); /* client->server mac */
5159 for (i = 0; i < s->nmacs; i++) {
5160 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5161 s->csmac_tobe = s->maclist[i];
5165 ssh_pkt_getstring(pktin, &str, &len); /* server->client mac */
5166 for (i = 0; i < s->nmacs; i++) {
5167 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5168 s->scmac_tobe = s->maclist[i];
5172 ssh_pkt_getstring(pktin, &str, &len); /* client->server compression */
5173 for (i = 0; i < lenof(compressions) + 1; i++) {
5174 const struct ssh_compress *c =
5175 i == 0 ? s->preferred_comp : compressions[i - 1];
5176 if (in_commasep_string(c->name, str, len)) {
5181 ssh_pkt_getstring(pktin, &str, &len); /* server->client compression */
5182 for (i = 0; i < lenof(compressions) + 1; i++) {
5183 const struct ssh_compress *c =
5184 i == 0 ? s->preferred_comp : compressions[i - 1];
5185 if (in_commasep_string(c->name, str, len)) {
5190 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
5191 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
5192 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
5195 ssh_set_frozen(ssh, 1);
5196 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
5198 ssh_dialog_callback, ssh);
5199 if (s->dlgret < 0) {
5203 bombout(("Unexpected data from server while"
5204 " waiting for user response"));
5207 } while (pktin || inlen > 0);
5208 s->dlgret = ssh->user_response;
5210 ssh_set_frozen(ssh, 0);
5211 if (s->dlgret == 0) {
5212 ssh->close_expected = TRUE;
5213 ssh_closing((Plug)ssh, NULL, 0, 0);
5218 if (s->warn_cscipher) {
5219 ssh_set_frozen(ssh, 1);
5220 s->dlgret = askalg(ssh->frontend,
5221 "client-to-server cipher",
5222 s->cscipher_tobe->name,
5223 ssh_dialog_callback, ssh);
5224 if (s->dlgret < 0) {
5228 bombout(("Unexpected data from server while"
5229 " waiting for user response"));
5232 } while (pktin || inlen > 0);
5233 s->dlgret = ssh->user_response;
5235 ssh_set_frozen(ssh, 0);
5236 if (s->dlgret == 0) {
5237 ssh->close_expected = TRUE;
5238 ssh_closing((Plug)ssh, NULL, 0, 0);
5243 if (s->warn_sccipher) {
5244 ssh_set_frozen(ssh, 1);
5245 s->dlgret = askalg(ssh->frontend,
5246 "server-to-client cipher",
5247 s->sccipher_tobe->name,
5248 ssh_dialog_callback, ssh);
5249 if (s->dlgret < 0) {
5253 bombout(("Unexpected data from server while"
5254 " waiting for user response"));
5257 } while (pktin || inlen > 0);
5258 s->dlgret = ssh->user_response;
5260 ssh_set_frozen(ssh, 0);
5261 if (s->dlgret == 0) {
5262 ssh->close_expected = TRUE;
5263 ssh_closing((Plug)ssh, NULL, 0, 0);
5268 if (s->ignorepkt) /* first_kex_packet_follows */
5269 crWaitUntil(pktin); /* Ignore packet */
5273 * Work out the number of bits of key we will need from the key
5274 * exchange. We start with the maximum key length of either
5280 csbits = s->cscipher_tobe->keylen;
5281 scbits = s->sccipher_tobe->keylen;
5282 s->nbits = (csbits > scbits ? csbits : scbits);
5284 /* The keys only have 160-bit entropy, since they're based on
5285 * a SHA-1 hash. So cap the key size at 160 bits. */
5290 * If we're doing Diffie-Hellman group exchange, start by
5291 * requesting a group.
5293 if (!ssh->kex->pdata) {
5294 logevent("Doing Diffie-Hellman group exchange");
5295 ssh->pkt_ctx |= SSH2_PKTCTX_DHGEX;
5297 * Work out how big a DH group we will need to allow that
5300 s->pbits = 512 << ((s->nbits - 1) / 64);
5301 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
5302 ssh2_pkt_adduint32(s->pktout, s->pbits);
5303 ssh2_pkt_send_noqueue(ssh, s->pktout);
5306 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
5307 bombout(("expected key exchange group packet from server"));
5310 s->p = ssh2_pkt_getmp(pktin);
5311 s->g = ssh2_pkt_getmp(pktin);
5312 if (!s->p || !s->g) {
5313 bombout(("unable to read mp-ints from incoming group packet"));
5316 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
5317 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
5318 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
5320 ssh->pkt_ctx |= SSH2_PKTCTX_DHGROUP;
5321 ssh->kex_ctx = dh_setup_group(ssh->kex);
5322 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
5323 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
5324 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
5325 ssh->kex->groupname);
5328 logevent("Doing Diffie-Hellman key exchange");
5330 * Now generate and send e for Diffie-Hellman.
5332 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
5333 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
5334 s->pktout = ssh2_pkt_init(s->kex_init_value);
5335 ssh2_pkt_addmp(s->pktout, s->e);
5336 ssh2_pkt_send_noqueue(ssh, s->pktout);
5338 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
5340 if (pktin->type != s->kex_reply_value) {
5341 bombout(("expected key exchange reply packet from server"));
5344 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
5345 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
5346 s->f = ssh2_pkt_getmp(pktin);
5348 bombout(("unable to parse key exchange reply packet"));
5351 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
5353 s->K = dh_find_K(ssh->kex_ctx, s->f);
5355 /* We assume everything from now on will be quick, and it might
5356 * involve user interaction. */
5357 set_busy_status(ssh->frontend, BUSY_NOT);
5359 sha_string(&ssh->exhash, s->hostkeydata, s->hostkeylen);
5360 if (ssh->kex == &ssh_diffiehellman_gex) {
5361 sha_uint32(&ssh->exhash, s->pbits);
5362 sha_mpint(&ssh->exhash, s->p);
5363 sha_mpint(&ssh->exhash, s->g);
5365 sha_mpint(&ssh->exhash, s->e);
5366 sha_mpint(&ssh->exhash, s->f);
5367 sha_mpint(&ssh->exhash, s->K);
5368 SHA_Final(&ssh->exhash, s->exchange_hash);
5370 dh_cleanup(ssh->kex_ctx);
5371 ssh->kex_ctx = NULL;
5374 debug(("Exchange hash is:\n"));
5375 dmemdump(s->exchange_hash, 20);
5378 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
5380 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
5381 (char *)s->exchange_hash, 20)) {
5382 bombout(("Server's host key did not match the signature supplied"));
5387 * Authenticate remote host: verify host key. (We've already
5388 * checked the signature of the exchange hash.)
5390 s->keystr = ssh->hostkey->fmtkey(s->hkey);
5391 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
5392 ssh_set_frozen(ssh, 1);
5393 s->dlgret = verify_ssh_host_key(ssh->frontend,
5394 ssh->savedhost, ssh->savedport,
5395 ssh->hostkey->keytype, s->keystr,
5397 ssh_dialog_callback, ssh);
5398 if (s->dlgret < 0) {
5402 bombout(("Unexpected data from server while waiting"
5403 " for user host key response"));
5406 } while (pktin || inlen > 0);
5407 s->dlgret = ssh->user_response;
5409 ssh_set_frozen(ssh, 0);
5410 if (s->dlgret == 0) {
5411 ssh->close_expected = TRUE;
5412 ssh_closing((Plug)ssh, NULL, 0, 0);
5415 if (!s->got_session_id) { /* don't bother logging this in rekeys */
5416 logevent("Host key fingerprint is:");
5417 logevent(s->fingerprint);
5419 sfree(s->fingerprint);
5421 ssh->hostkey->freekey(s->hkey);
5424 * The exchange hash from the very first key exchange is also
5425 * the session id, used in session key construction and
5428 if (!s->got_session_id) {
5429 memcpy(ssh->v2_session_id, s->exchange_hash,
5430 sizeof(s->exchange_hash));
5431 s->got_session_id = TRUE;
5435 * Send SSH2_MSG_NEWKEYS.
5437 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
5438 ssh2_pkt_send_noqueue(ssh, s->pktout);
5439 ssh->outgoing_data_size = 0; /* start counting from here */
5442 * We've sent client NEWKEYS, so create and initialise
5443 * client-to-server session keys.
5445 if (ssh->cs_cipher_ctx)
5446 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
5447 ssh->cscipher = s->cscipher_tobe;
5448 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
5450 if (ssh->cs_mac_ctx)
5451 ssh->csmac->free_context(ssh->cs_mac_ctx);
5452 ssh->csmac = s->csmac_tobe;
5453 ssh->cs_mac_ctx = ssh->csmac->make_context();
5455 if (ssh->cs_comp_ctx)
5456 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
5457 ssh->cscomp = s->cscomp_tobe;
5458 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
5461 * Set IVs on client-to-server keys. Here we use the exchange
5462 * hash from the _first_ key exchange.
5465 unsigned char keyspace[40];
5466 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'C',keyspace);
5467 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
5468 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'A',keyspace);
5469 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
5470 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'E',keyspace);
5471 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
5474 logeventf(ssh, "Initialised %.200s client->server encryption",
5475 ssh->cscipher->text_name);
5476 logeventf(ssh, "Initialised %.200s client->server MAC algorithm",
5477 ssh->csmac->text_name);
5478 if (ssh->cscomp->text_name)
5479 logeventf(ssh, "Initialised %s compression",
5480 ssh->cscomp->text_name);
5483 * Now our end of the key exchange is complete, we can send all
5484 * our queued higher-layer packets.
5486 ssh->queueing = FALSE;
5487 ssh2_pkt_queuesend(ssh);
5490 * Expect SSH2_MSG_NEWKEYS from server.
5493 if (pktin->type != SSH2_MSG_NEWKEYS) {
5494 bombout(("expected new-keys packet from server"));
5497 ssh->incoming_data_size = 0; /* start counting from here */
5500 * We've seen server NEWKEYS, so create and initialise
5501 * server-to-client session keys.
5503 if (ssh->sc_cipher_ctx)
5504 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
5505 ssh->sccipher = s->sccipher_tobe;
5506 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
5508 if (ssh->sc_mac_ctx)
5509 ssh->scmac->free_context(ssh->sc_mac_ctx);
5510 ssh->scmac = s->scmac_tobe;
5511 ssh->sc_mac_ctx = ssh->scmac->make_context();
5513 if (ssh->sc_comp_ctx)
5514 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
5515 ssh->sccomp = s->sccomp_tobe;
5516 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
5519 * Set IVs on server-to-client keys. Here we use the exchange
5520 * hash from the _first_ key exchange.
5523 unsigned char keyspace[40];
5524 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'D',keyspace);
5525 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
5526 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'B',keyspace);
5527 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
5528 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'F',keyspace);
5529 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
5531 logeventf(ssh, "Initialised %.200s server->client encryption",
5532 ssh->sccipher->text_name);
5533 logeventf(ssh, "Initialised %.200s server->client MAC algorithm",
5534 ssh->scmac->text_name);
5535 if (ssh->sccomp->text_name)
5536 logeventf(ssh, "Initialised %s decompression",
5537 ssh->sccomp->text_name);
5540 * Free key exchange data.
5544 if (ssh->kex == &ssh_diffiehellman_gex) {
5550 * Key exchange is over. Loop straight back round if we have a
5551 * deferred rekey reason.
5553 if (ssh->deferred_rekey_reason) {
5554 logevent(ssh->deferred_rekey_reason);
5556 ssh->deferred_rekey_reason = NULL;
5557 goto begin_key_exchange;
5561 * Otherwise, schedule a timer for our next rekey.
5563 ssh->kex_in_progress = FALSE;
5564 ssh->last_rekey = GETTICKCOUNT();
5565 if (ssh->cfg.ssh_rekey_time != 0)
5566 ssh->next_rekey = schedule_timer(ssh->cfg.ssh_rekey_time*60*TICKSPERSEC,
5570 * If this is the first key exchange phase, we must pass the
5571 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
5572 * wants to see it but because it will need time to initialise
5573 * itself before it sees an actual packet. In subsequent key
5574 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
5575 * it would only confuse the layer above.
5577 if (s->activated_authconn) {
5580 s->activated_authconn = TRUE;
5583 * Now we're encrypting. Begin returning 1 to the protocol main
5584 * function so that other things can run on top of the
5585 * transport. If we ever see a KEXINIT, we must go back to the
5588 * We _also_ go back to the start if we see pktin==NULL and
5589 * inlen==-1, because this is a special signal meaning
5590 * `initiate client-driven rekey', and `in' contains a message
5591 * giving the reason for the rekey.
5593 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
5594 (!pktin && inlen == -1))) {
5599 logevent("Server initiated key re-exchange");
5602 * Special case: if the server bug is set that doesn't
5603 * allow rekeying, we give a different log message and
5604 * continue waiting. (If such a server _initiates_ a rekey,
5605 * we process it anyway!)
5607 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
5608 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
5610 /* Reset the counters, so that at least this message doesn't
5611 * hit the event log _too_ often. */
5612 ssh->outgoing_data_size = 0;
5613 ssh->incoming_data_size = 0;
5614 if (ssh->cfg.ssh_rekey_time != 0) {
5616 schedule_timer(ssh->cfg.ssh_rekey_time*60*TICKSPERSEC,
5619 goto wait_for_rekey; /* this is utterly horrid */
5621 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
5624 goto begin_key_exchange;
5630 * Add data to an SSH-2 channel output buffer.
5632 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
5635 bufchain_add(&c->v.v2.outbuffer, buf, len);
5639 * Attempt to send data on an SSH-2 channel.
5641 static int ssh2_try_send(struct ssh_channel *c)
5644 struct Packet *pktout;
5646 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
5649 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
5650 if ((unsigned)len > c->v.v2.remwindow)
5651 len = c->v.v2.remwindow;
5652 if ((unsigned)len > c->v.v2.remmaxpkt)
5653 len = c->v.v2.remmaxpkt;
5654 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
5655 ssh2_pkt_adduint32(pktout, c->remoteid);
5656 dont_log_data(ssh, pktout, PKTLOG_OMIT);
5657 ssh2_pkt_addstring_start(pktout);
5658 ssh2_pkt_addstring_data(pktout, data, len);
5659 end_log_omission(ssh, pktout);
5660 ssh2_pkt_send(ssh, pktout);
5661 bufchain_consume(&c->v.v2.outbuffer, len);
5662 c->v.v2.remwindow -= len;
5666 * After having sent as much data as we can, return the amount
5669 return bufchain_size(&c->v.v2.outbuffer);
5672 static void ssh2_try_send_and_unthrottle(struct ssh_channel *c)
5676 return; /* don't send on closing channels */
5677 bufsize = ssh2_try_send(c);
5680 case CHAN_MAINSESSION:
5681 /* stdin need not receive an unthrottle
5682 * notification since it will be polled */
5685 x11_unthrottle(c->u.x11.s);
5688 /* agent sockets are request/response and need no
5689 * buffer management */
5692 pfd_unthrottle(c->u.pfd.s);
5699 * Potentially enlarge the window on an SSH-2 channel.
5701 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin)
5706 * Never send WINDOW_ADJUST for a channel that the remote side
5707 * already thinks it's closed; there's no point, since it won't
5708 * be sending any more data anyway.
5714 * Only send a WINDOW_ADJUST if there's significantly more window
5715 * available than the other end thinks there is. This saves us
5716 * sending a WINDOW_ADJUST for every character in a shell session.
5718 * "Significant" is arbitrarily defined as half the window size.
5720 if (newwin > c->v.v2.locwindow * 2) {
5721 struct Packet *pktout;
5723 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5724 ssh2_pkt_adduint32(pktout, c->remoteid);
5725 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
5726 ssh2_pkt_send(ssh, pktout);
5727 c->v.v2.locwindow = newwin;
5731 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
5733 unsigned i = ssh_pkt_getuint32(pktin);
5734 struct ssh_channel *c;
5735 c = find234(ssh->channels, &i, ssh_channelfind);
5736 if (c && !c->closes) {
5737 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
5738 ssh2_try_send_and_unthrottle(c);
5742 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
5746 unsigned i = ssh_pkt_getuint32(pktin);
5747 struct ssh_channel *c;
5748 c = find234(ssh->channels, &i, ssh_channelfind);
5750 return; /* nonexistent channel */
5751 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
5752 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
5753 return; /* extended but not stderr */
5754 ssh_pkt_getstring(pktin, &data, &length);
5757 c->v.v2.locwindow -= length;
5759 case CHAN_MAINSESSION:
5761 from_backend(ssh->frontend, pktin->type ==
5762 SSH2_MSG_CHANNEL_EXTENDED_DATA,
5766 bufsize = x11_send(c->u.x11.s, data, length);
5769 bufsize = pfd_send(c->u.pfd.s, data, length);
5772 while (length > 0) {
5773 if (c->u.a.lensofar < 4) {
5774 unsigned int l = min(4 - c->u.a.lensofar, length);
5775 memcpy(c->u.a.msglen + c->u.a.lensofar,
5779 c->u.a.lensofar += l;
5781 if (c->u.a.lensofar == 4) {
5783 4 + GET_32BIT(c->u.a.msglen);
5784 c->u.a.message = snewn(c->u.a.totallen,
5786 memcpy(c->u.a.message, c->u.a.msglen, 4);
5788 if (c->u.a.lensofar >= 4 && length > 0) {
5790 min(c->u.a.totallen - c->u.a.lensofar,
5792 memcpy(c->u.a.message + c->u.a.lensofar,
5796 c->u.a.lensofar += l;
5798 if (c->u.a.lensofar == c->u.a.totallen) {
5801 if (agent_query(c->u.a.message,
5804 ssh_agentf_callback, c))
5805 ssh_agentf_callback(c, reply, replylen);
5806 sfree(c->u.a.message);
5807 c->u.a.lensofar = 0;
5814 * If we are not buffering too much data,
5815 * enlarge the window again at the remote side.
5817 if (bufsize < OUR_V2_WINSIZE)
5818 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
5822 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
5824 unsigned i = ssh_pkt_getuint32(pktin);
5825 struct ssh_channel *c;
5827 c = find234(ssh->channels, &i, ssh_channelfind);
5829 return; /* nonexistent channel */
5831 if (c->type == CHAN_X11) {
5833 * Remote EOF on an X11 channel means we should
5834 * wrap up and close the channel ourselves.
5836 x11_close(c->u.x11.s);
5838 } else if (c->type == CHAN_AGENT) {
5840 } else if (c->type == CHAN_SOCKDATA) {
5841 pfd_close(c->u.pfd.s);
5846 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
5848 unsigned i = ssh_pkt_getuint32(pktin);
5849 struct ssh_channel *c;
5850 struct Packet *pktout;
5852 c = find234(ssh->channels, &i, ssh_channelfind);
5853 if (!c || c->halfopen) {
5854 bombout(("Received CHANNEL_CLOSE for %s channel %d\n",
5855 c ? "half-open" : "nonexistent", i));
5858 /* Do pre-close processing on the channel. */
5860 case CHAN_MAINSESSION:
5861 ssh->mainchan = NULL;
5862 update_specials_menu(ssh->frontend);
5865 if (c->u.x11.s != NULL)
5866 x11_close(c->u.x11.s);
5873 if (c->u.pfd.s != NULL)
5874 pfd_close(c->u.pfd.s);
5878 if (c->closes == 0) {
5879 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
5880 ssh2_pkt_adduint32(pktout, c->remoteid);
5881 ssh2_pkt_send(ssh, pktout);
5883 del234(ssh->channels, c);
5884 bufchain_clear(&c->v.v2.outbuffer);
5888 * See if that was the last channel left open.
5889 * (This is only our termination condition if we're
5890 * not running in -N mode.)
5892 if (!ssh->cfg.ssh_no_shell && count234(ssh->channels) == 0) {
5893 logevent("All channels closed. Disconnecting");
5896 * We used to send SSH_MSG_DISCONNECT here,
5897 * because I'd believed that _every_ conforming
5898 * SSH-2 connection had to end with a disconnect
5899 * being sent by at least one side; apparently
5900 * I was wrong and it's perfectly OK to
5901 * unceremoniously slam the connection shut
5902 * when you're done, and indeed OpenSSH feels
5903 * this is more polite than sending a
5904 * DISCONNECT. So now we don't.
5906 s->pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
5907 ssh2_pkt_adduint32(s->pktout, SSH2_DISCONNECT_BY_APPLICATION);
5908 ssh2_pkt_addstring(s->pktout, "All open channels closed");
5909 ssh2_pkt_addstring(s->pktout, "en"); /* language tag */
5910 ssh2_pkt_send_noqueue(ssh, s->pktout);
5912 ssh->close_expected = TRUE;
5913 ssh_closing((Plug)ssh, NULL, 0, 0);
5917 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
5919 unsigned i = ssh_pkt_getuint32(pktin);
5920 struct ssh_channel *c;
5921 struct Packet *pktout;
5923 c = find234(ssh->channels, &i, ssh_channelfind);
5925 return; /* nonexistent channel */
5926 if (c->type != CHAN_SOCKDATA_DORMANT)
5927 return; /* dunno why they're confirming this */
5928 c->remoteid = ssh_pkt_getuint32(pktin);
5929 c->halfopen = FALSE;
5930 c->type = CHAN_SOCKDATA;
5931 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
5932 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
5934 pfd_confirm(c->u.pfd.s);
5937 * We have a pending close on this channel,
5938 * which we decided on before the server acked
5939 * the channel open. So now we know the
5940 * remoteid, we can close it again.
5942 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
5943 ssh2_pkt_adduint32(pktout, c->remoteid);
5944 ssh2_pkt_send(ssh, pktout);
5948 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
5950 static const char *const reasons[] = {
5951 "<unknown reason code>",
5952 "Administratively prohibited",
5954 "Unknown channel type",
5955 "Resource shortage",
5957 unsigned i = ssh_pkt_getuint32(pktin);
5958 unsigned reason_code;
5959 char *reason_string;
5961 struct ssh_channel *c;
5962 c = find234(ssh->channels, &i, ssh_channelfind);
5964 return; /* nonexistent channel */
5965 if (c->type != CHAN_SOCKDATA_DORMANT)
5966 return; /* dunno why they're failing this */
5968 reason_code = ssh_pkt_getuint32(pktin);
5969 if (reason_code >= lenof(reasons))
5970 reason_code = 0; /* ensure reasons[reason_code] in range */
5971 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
5972 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
5973 reasons[reason_code], reason_length, reason_string);
5975 pfd_close(c->u.pfd.s);
5977 del234(ssh->channels, c);
5981 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
5985 int typelen, want_reply;
5986 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
5987 struct ssh_channel *c;
5988 struct Packet *pktout;
5990 localid = ssh_pkt_getuint32(pktin);
5991 ssh_pkt_getstring(pktin, &type, &typelen);
5992 want_reply = ssh2_pkt_getbool(pktin);
5995 * First, check that the channel exists. Otherwise,
5996 * we can instantly disconnect with a rude message.
5998 c = find234(ssh->channels, &localid, ssh_channelfind);
6001 sprintf(buf, "Received channel request for nonexistent"
6002 " channel %d", localid);
6004 pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
6005 ssh2_pkt_adduint32(pktout, SSH2_DISCONNECT_BY_APPLICATION);
6006 ssh2_pkt_addstring(pktout, buf);
6007 ssh2_pkt_addstring(pktout, "en"); /* language tag */
6008 ssh2_pkt_send_noqueue(ssh, pktout);
6009 connection_fatal(ssh->frontend, "%s", buf);
6010 ssh->close_expected = TRUE;
6011 ssh_closing((Plug)ssh, NULL, 0, 0);
6016 * Having got the channel number, we now look at
6017 * the request type string to see if it's something
6020 if (c == ssh->mainchan) {
6022 * We recognise "exit-status" and "exit-signal" on
6023 * the primary channel.
6025 if (typelen == 11 &&
6026 !memcmp(type, "exit-status", 11)) {
6028 ssh->exitcode = ssh_pkt_getuint32(pktin);
6029 logeventf(ssh, "Server sent command exit status %d",
6031 reply = SSH2_MSG_CHANNEL_SUCCESS;
6033 } else if (typelen == 11 &&
6034 !memcmp(type, "exit-signal", 11)) {
6036 int is_plausible = TRUE, is_int = FALSE;
6037 char *fmt_sig = "", *fmt_msg = "";
6039 int msglen = 0, core = FALSE;
6040 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
6041 * provide an `int' for the signal, despite its
6042 * having been a `string' in the drafts since at
6043 * least 2001. (Fixed in session.c 1.147.) Try to
6044 * infer which we can safely parse it as. */
6046 unsigned char *p = pktin->body +
6048 long len = pktin->length - pktin->savedpos;
6049 unsigned long num = GET_32BIT(p); /* what is it? */
6050 /* If it's 0, it hardly matters; assume string */
6054 int maybe_int = FALSE, maybe_str = FALSE;
6055 #define CHECK_HYPOTHESIS(offset, result) \
6058 if (q >= 0 && q+4 <= len) { \
6059 q = q + 4 + GET_32BIT(p+q); \
6060 if (q >= 0 && q+4 <= len && \
6061 ((q = q + 4 + GET_32BIT(p+q))!= 0) && q == len) \
6065 CHECK_HYPOTHESIS(4+1, maybe_int);
6066 CHECK_HYPOTHESIS(4+num+1, maybe_str);
6067 #undef CHECK_HYPOTHESIS
6068 if (maybe_int && !maybe_str)
6070 else if (!maybe_int && maybe_str)
6073 /* Crikey. Either or neither. Panic. */
6074 is_plausible = FALSE;
6079 /* Old non-standard OpenSSH. */
6080 int signum = ssh_pkt_getuint32(pktin);
6081 fmt_sig = dupprintf(" %d", signum);
6083 /* As per the drafts. */
6086 ssh_pkt_getstring(pktin, &sig, &siglen);
6087 /* Signal name isn't supposed to be blank, but
6088 * let's cope gracefully if it is. */
6090 fmt_sig = dupprintf(" \"%.*s\"",
6094 core = ssh2_pkt_getbool(pktin);
6095 ssh_pkt_getstring(pktin, &msg, &msglen);
6097 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
6099 /* ignore lang tag */
6100 } /* else don't attempt to parse */
6101 logeventf(ssh, "Server exited on signal%s%s%s",
6102 fmt_sig, core ? " (core dumped)" : "",
6104 if (*fmt_sig) sfree(fmt_sig);
6105 if (*fmt_msg) sfree(fmt_msg);
6106 reply = SSH2_MSG_CHANNEL_SUCCESS;
6111 * This is a channel request we don't know
6112 * about, so we now either ignore the request
6113 * or respond with CHANNEL_FAILURE, depending
6116 reply = SSH2_MSG_CHANNEL_FAILURE;
6119 pktout = ssh2_pkt_init(reply);
6120 ssh2_pkt_adduint32(pktout, c->remoteid);
6121 ssh2_pkt_send(ssh, pktout);
6125 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
6128 int typelen, want_reply;
6129 struct Packet *pktout;
6131 ssh_pkt_getstring(pktin, &type, &typelen);
6132 want_reply = ssh2_pkt_getbool(pktin);
6135 * We currently don't support any global requests
6136 * at all, so we either ignore the request or
6137 * respond with REQUEST_FAILURE, depending on
6141 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
6142 ssh2_pkt_send(ssh, pktout);
6146 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
6154 struct ssh_channel *c;
6155 unsigned remid, winsize, pktsize;
6156 struct Packet *pktout;
6158 ssh_pkt_getstring(pktin, &type, &typelen);
6159 c = snew(struct ssh_channel);
6162 remid = ssh_pkt_getuint32(pktin);
6163 winsize = ssh_pkt_getuint32(pktin);
6164 pktsize = ssh_pkt_getuint32(pktin);
6166 if (typelen == 3 && !memcmp(type, "x11", 3)) {
6169 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
6170 addrstr = snewn(peeraddrlen+1, char);
6171 memcpy(addrstr, peeraddr, peeraddrlen);
6172 addrstr[peeraddrlen] = '\0';
6173 peerport = ssh_pkt_getuint32(pktin);
6175 logeventf(ssh, "Received X11 connect request from %s:%d",
6178 if (!ssh->X11_fwd_enabled)
6179 error = "X11 forwarding is not enabled";
6180 else if (x11_init(&c->u.x11.s, ssh->cfg.x11_display, c,
6181 ssh->x11auth, addrstr, peerport,
6182 &ssh->cfg) != NULL) {
6183 error = "Unable to open an X11 connection";
6185 logevent("Opening X11 forward connection succeeded");
6190 } else if (typelen == 15 &&
6191 !memcmp(type, "forwarded-tcpip", 15)) {
6192 struct ssh_rportfwd pf, *realpf;
6195 ssh_pkt_getstring(pktin, &dummy, &dummylen);/* skip address */
6196 pf.sport = ssh_pkt_getuint32(pktin);
6197 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
6198 peerport = ssh_pkt_getuint32(pktin);
6199 realpf = find234(ssh->rportfwds, &pf, NULL);
6200 logeventf(ssh, "Received remote port %d open request "
6201 "from %s:%d", pf.sport, peeraddr, peerport);
6202 if (realpf == NULL) {
6203 error = "Remote port is not recognised";
6205 const char *e = pfd_newconnect(&c->u.pfd.s,
6209 realpf->pfrec->addressfamily);
6210 logeventf(ssh, "Attempting to forward remote port to "
6211 "%s:%d", realpf->dhost, realpf->dport);
6213 logeventf(ssh, "Port open failed: %s", e);
6214 error = "Port open failed";
6216 logevent("Forwarded port opened successfully");
6217 c->type = CHAN_SOCKDATA;
6220 } else if (typelen == 22 &&
6221 !memcmp(type, "auth-agent@openssh.com", 3)) {
6222 if (!ssh->agentfwd_enabled)
6223 error = "Agent forwarding is not enabled";
6225 c->type = CHAN_AGENT; /* identify channel type */
6226 c->u.a.lensofar = 0;
6229 error = "Unsupported channel type requested";
6232 c->remoteid = remid;
6233 c->halfopen = FALSE;
6235 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
6236 ssh2_pkt_adduint32(pktout, c->remoteid);
6237 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
6238 ssh2_pkt_addstring(pktout, error);
6239 ssh2_pkt_addstring(pktout, "en"); /* language tag */
6240 ssh2_pkt_send(ssh, pktout);
6241 logeventf(ssh, "Rejected channel open: %s", error);
6244 c->localid = alloc_channel_id(ssh);
6246 c->v.v2.locwindow = OUR_V2_WINSIZE;
6247 c->v.v2.remwindow = winsize;
6248 c->v.v2.remmaxpkt = pktsize;
6249 bufchain_init(&c->v.v2.outbuffer);
6250 add234(ssh->channels, c);
6251 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
6252 ssh2_pkt_adduint32(pktout, c->remoteid);
6253 ssh2_pkt_adduint32(pktout, c->localid);
6254 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
6255 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
6256 ssh2_pkt_send(ssh, pktout);
6261 * Handle the SSH-2 userauth and connection layers.
6263 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
6264 struct Packet *pktin)
6266 struct do_ssh2_authconn_state {
6268 AUTH_INVALID, AUTH_PUBLICKEY_AGENT, AUTH_PUBLICKEY_FILE,
6270 AUTH_KEYBOARD_INTERACTIVE
6274 AUTH_TYPE_PUBLICKEY,
6275 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
6276 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
6278 AUTH_TYPE_KEYBOARD_INTERACTIVE,
6279 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
6281 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
6282 int tried_pubkey_config, tried_agent;
6283 int kbd_inter_running, kbd_inter_refused;
6285 int num_prompts, curr_prompt, echo;
6290 void *publickey_blob;
6291 int publickey_bloblen;
6292 unsigned char request[5], *response, *p;
6296 char *pkblob, *alg, *commentp;
6297 int pklen, alglen, commentlen;
6298 int siglen, retlen, len;
6299 char *q, *agentreq, *ret;
6301 int num_env, env_left, env_ok;
6302 struct Packet *pktout;
6304 crState(do_ssh2_authconn_state);
6306 crBegin(ssh->do_ssh2_authconn_crstate);
6309 * Request userauth protocol, and await a response to it.
6311 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
6312 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
6313 ssh2_pkt_send(ssh, s->pktout);
6314 crWaitUntilV(pktin);
6315 if (pktin->type != SSH2_MSG_SERVICE_ACCEPT) {
6316 bombout(("Server refused user authentication protocol"));
6321 * We repeat this whole loop, including the username prompt,
6322 * until we manage a successful authentication. If the user
6323 * types the wrong _password_, they can be sent back to the
6324 * beginning to try another username, if this is configured on.
6325 * (If they specify a username in the config, they are never
6326 * asked, even if they do give a wrong password.)
6328 * I think this best serves the needs of
6330 * - the people who have no configuration, no keys, and just
6331 * want to try repeated (username,password) pairs until they
6332 * type both correctly
6334 * - people who have keys and configuration but occasionally
6335 * need to fall back to passwords
6337 * - people with a key held in Pageant, who might not have
6338 * logged in to a particular machine before; so they want to
6339 * type a username, and then _either_ their key will be
6340 * accepted, _or_ they will type a password. If they mistype
6341 * the username they will want to be able to get back and
6344 s->username[0] = '\0';
6345 s->got_username = FALSE;
6350 if (s->got_username && !ssh->cfg.change_username) {
6352 * We got a username last time round this loop, and
6353 * with change_username turned off we don't try to get
6356 } else if (!*ssh->cfg.username) {
6357 if (ssh_get_line && !ssh_getline_pw_only) {
6358 if (!ssh_get_line("login as: ",
6359 s->username, sizeof(s->username), FALSE)) {
6361 * get_line failed to get a username.
6364 logevent("No username provided. Abandoning session.");
6365 ssh->close_expected = TRUE;
6366 ssh_closing((Plug)ssh, NULL, 0, 0);
6370 int ret; /* need not be saved across crReturn */
6371 c_write_str(ssh, "login as: ");
6373 setup_userpass_input(ssh, s->username, sizeof(s->username), 1);
6375 crWaitUntilV(!pktin);
6376 ret = process_userpass_input(ssh, in, inlen);
6380 c_write_str(ssh, "\r\n");
6382 s->username[strcspn(s->username, "\n\r")] = '\0';
6385 strncpy(s->username, ssh->cfg.username, sizeof(s->username));
6386 s->username[sizeof(s->username)-1] = '\0';
6387 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
6388 stuff = dupprintf("Using username \"%s\".\r\n", s->username);
6389 c_write_str(ssh, stuff);
6393 s->got_username = TRUE;
6396 * Send an authentication request using method "none": (a)
6397 * just in case it succeeds, and (b) so that we know what
6398 * authentication methods we can usefully try next.
6400 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6402 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6403 ssh2_pkt_addstring(s->pktout, s->username);
6404 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
6405 ssh2_pkt_addstring(s->pktout, "none"); /* method */
6406 ssh2_pkt_send(ssh, s->pktout);
6407 s->type = AUTH_TYPE_NONE;
6409 s->we_are_in = FALSE;
6411 s->tried_pubkey_config = FALSE;
6412 s->tried_agent = FALSE;
6413 s->kbd_inter_running = FALSE;
6414 s->kbd_inter_refused = FALSE;
6415 /* Load the pub half of ssh->cfg.keyfile so we notice if it's in Pageant */
6416 if (!filename_is_null(ssh->cfg.keyfile)) {
6418 logeventf(ssh, "Reading private key file \"%.150s\"",
6419 filename_to_str(&ssh->cfg.keyfile));
6420 keytype = key_type(&ssh->cfg.keyfile);
6421 if (keytype == SSH_KEYTYPE_SSH2) {
6423 ssh2_userkey_loadpub(&ssh->cfg.keyfile, NULL,
6424 &s->publickey_bloblen, NULL);
6427 logeventf(ssh, "Unable to use this key file (%s)",
6428 key_type_to_str(keytype));
6429 msgbuf = dupprintf("Unable to use key file \"%.150s\""
6431 filename_to_str(&ssh->cfg.keyfile),
6432 key_type_to_str(keytype));
6433 c_write_str(ssh, msgbuf);
6435 s->publickey_blob = NULL;
6438 s->publickey_blob = NULL;
6442 * Wait for the result of the last authentication request.
6445 crWaitUntilV(pktin);
6446 while (pktin->type == SSH2_MSG_USERAUTH_BANNER) {
6450 * Don't show the banner if we're operating in
6451 * non-verbose non-interactive mode. (It's probably
6452 * a script, which means nobody will read the
6453 * banner _anyway_, and moreover the printing of
6454 * the banner will screw up processing on the
6455 * output of (say) plink.)
6457 if (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE)) {
6458 ssh_pkt_getstring(pktin, &banner, &size);
6460 c_write_untrusted(ssh, banner, size);
6462 crWaitUntilV(pktin);
6464 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
6465 logevent("Access granted");
6466 s->we_are_in = TRUE;
6470 if (s->kbd_inter_running &&
6471 pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
6473 * This is either a further set-of-prompts packet
6474 * in keyboard-interactive authentication, or it's
6475 * the same one and we came back here with `gotit'
6476 * set. In the former case, we must reset the
6477 * curr_prompt variable.
6481 } else if (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
6482 /* FIXME: perhaps we should support this? */
6483 bombout(("PASSWD_CHANGEREQ not yet supported"));
6485 } else if (pktin->type != SSH2_MSG_USERAUTH_FAILURE) {
6486 bombout(("Strange packet received during authentication: type %d",
6494 * OK, we're now sitting on a USERAUTH_FAILURE message, so
6495 * we can look at the string in it and know what we can
6496 * helpfully try next.
6498 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
6501 ssh_pkt_getstring(pktin, &methods, &methlen);
6502 s->kbd_inter_running = FALSE;
6503 if (!ssh2_pkt_getbool(pktin)) {
6505 * We have received an unequivocal Access
6506 * Denied. This can translate to a variety of
6509 * - if we'd just tried "none" authentication,
6510 * it's not worth printing anything at all
6512 * - if we'd just tried a public key _offer_,
6513 * the message should be "Server refused our
6514 * key" (or no message at all if the key
6515 * came from Pageant)
6517 * - if we'd just tried anything else, the
6518 * message really should be "Access denied".
6520 * Additionally, if we'd just tried password
6521 * authentication, we should break out of this
6522 * whole loop so as to go back to the username
6523 * prompt (iff we're configured to allow
6524 * username change attempts).
6526 if (s->type == AUTH_TYPE_NONE) {
6528 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
6529 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
6530 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
6531 c_write_str(ssh, "Server refused our key\r\n");
6532 logevent("Server refused public key");
6533 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
6534 /* server declined keyboard-interactive; ignore */
6536 c_write_str(ssh, "Access denied\r\n");
6537 logevent("Access denied");
6538 if (s->type == AUTH_TYPE_PASSWORD &&
6539 ssh->cfg.change_username) {
6540 /* XXX perhaps we should allow
6541 * keyboard-interactive to do this too? */
6542 s->we_are_in = FALSE;
6547 c_write_str(ssh, "Further authentication required\r\n");
6548 logevent("Further authentication required");
6552 in_commasep_string("publickey", methods, methlen);
6554 in_commasep_string("password", methods, methlen);
6555 s->can_keyb_inter = ssh->cfg.try_ki_auth &&
6556 in_commasep_string("keyboard-interactive", methods, methlen);
6560 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6564 * Most password/passphrase prompts will be
6565 * non-echoing, so we set this to 0 by default.
6566 * Exception is that some keyboard-interactive prompts
6567 * can be echoing, in which case we'll set this to 1.
6571 if (!s->method && s->can_pubkey &&
6572 agent_exists() && !s->tried_agent) {
6574 * Attempt public-key authentication using Pageant.
6579 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6580 ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
6582 s->tried_agent = TRUE;
6584 logevent("Pageant is running. Requesting keys.");
6586 /* Request the keys held by the agent. */
6587 PUT_32BIT(s->request, 1);
6588 s->request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
6589 if (!agent_query(s->request, 5, &r, &s->responselen,
6590 ssh_agent_callback, ssh)) {
6594 bombout(("Unexpected data from server while"
6595 " waiting for agent response"));
6598 } while (pktin || inlen > 0);
6599 r = ssh->agent_response;
6600 s->responselen = ssh->agent_response_len;
6602 s->response = (unsigned char *) r;
6603 if (s->response && s->responselen >= 5 &&
6604 s->response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
6605 s->p = s->response + 5;
6606 s->nkeys = GET_32BIT(s->p);
6608 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
6609 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
6612 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
6613 s->pklen = GET_32BIT(s->p);
6615 if (s->publickey_blob &&
6616 s->pklen == s->publickey_bloblen &&
6617 !memcmp(s->p, s->publickey_blob,
6618 s->publickey_bloblen)) {
6619 logevent("This key matches configured key file");
6620 s->tried_pubkey_config = 1;
6622 s->pkblob = (char *)s->p;
6624 s->alglen = GET_32BIT(s->pkblob);
6625 s->alg = s->pkblob + 4;
6626 s->commentlen = GET_32BIT(s->p);
6628 s->commentp = (char *)s->p;
6629 s->p += s->commentlen;
6630 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6631 ssh2_pkt_addstring(s->pktout, s->username);
6632 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
6633 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
6634 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
6635 ssh2_pkt_addstring_start(s->pktout);
6636 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
6637 ssh2_pkt_addstring_start(s->pktout);
6638 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
6639 ssh2_pkt_send(ssh, s->pktout);
6641 crWaitUntilV(pktin);
6642 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
6643 logevent("Key refused");
6647 if (flags & FLAG_VERBOSE) {
6648 c_write_str(ssh, "Authenticating with "
6650 c_write(ssh, s->commentp, s->commentlen);
6651 c_write_str(ssh, "\" from agent\r\n");
6655 * Server is willing to accept the key.
6656 * Construct a SIGN_REQUEST.
6658 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6659 ssh2_pkt_addstring(s->pktout, s->username);
6660 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
6661 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
6662 ssh2_pkt_addbool(s->pktout, TRUE);
6663 ssh2_pkt_addstring_start(s->pktout);
6664 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
6665 ssh2_pkt_addstring_start(s->pktout);
6666 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
6668 s->siglen = s->pktout->length - 5 + 4 + 20;
6669 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
6671 s->len = 1; /* message type */
6672 s->len += 4 + s->pklen; /* key blob */
6673 s->len += 4 + s->siglen; /* data to sign */
6674 s->len += 4; /* flags */
6675 s->agentreq = snewn(4 + s->len, char);
6676 PUT_32BIT(s->agentreq, s->len);
6677 s->q = s->agentreq + 4;
6678 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
6679 PUT_32BIT(s->q, s->pklen);
6681 memcpy(s->q, s->pkblob, s->pklen);
6683 PUT_32BIT(s->q, s->siglen);
6685 /* Now the data to be signed... */
6686 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
6687 PUT_32BIT(s->q, 20);
6690 memcpy(s->q, ssh->v2_session_id, 20);
6692 memcpy(s->q, s->pktout->data + 5,
6693 s->pktout->length - 5);
6694 s->q += s->pktout->length - 5;
6695 /* And finally the (zero) flags word. */
6697 if (!agent_query(s->agentreq, s->len + 4,
6699 ssh_agent_callback, ssh)) {
6703 bombout(("Unexpected data from server"
6704 " while waiting for agent"
6708 } while (pktin || inlen > 0);
6709 vret = ssh->agent_response;
6710 s->retlen = ssh->agent_response_len;
6715 if (s->ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
6716 logevent("Sending Pageant's response");
6717 ssh2_add_sigblob(ssh, s->pktout,
6718 s->pkblob, s->pklen,
6720 GET_32BIT(s->ret + 5));
6721 ssh2_pkt_send(ssh, s->pktout);
6726 ("Pageant failed to answer challenge");
6737 if (!s->method && s->can_pubkey && s->publickey_blob
6738 && !s->tried_pubkey_config) {
6739 unsigned char *pub_blob;
6740 char *algorithm, *comment;
6743 s->tried_pubkey_config = TRUE;
6745 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6746 ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
6749 * Try the public key supplied in the configuration.
6751 * First, offer the public blob to see if the server is
6752 * willing to accept it.
6755 (unsigned char *)ssh2_userkey_loadpub(&ssh->cfg.keyfile,
6760 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6761 ssh2_pkt_addstring(s->pktout, s->username);
6762 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
6763 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
6764 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
6765 ssh2_pkt_addstring(s->pktout, algorithm);
6766 ssh2_pkt_addstring_start(s->pktout);
6767 ssh2_pkt_addstring_data(s->pktout, (char *)pub_blob,
6769 ssh2_pkt_send(ssh, s->pktout);
6770 logevent("Offered public key");
6772 crWaitUntilV(pktin);
6773 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
6775 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
6776 continue; /* key refused; give up on it */
6779 logevent("Offer of public key accepted");
6781 * Actually attempt a serious authentication using
6784 if (ssh2_userkey_encrypted(&ssh->cfg.keyfile, &comment)) {
6785 sprintf(s->pwprompt,
6786 "Passphrase for key \"%.100s\": ",
6792 if (flags & FLAG_VERBOSE) {
6793 c_write_str(ssh, "Authenticating with public key \"");
6794 c_write_str(ssh, comment);
6795 c_write_str(ssh, "\"\r\n");
6797 s->method = AUTH_PUBLICKEY_FILE;
6801 if (!s->method && s->can_keyb_inter && !s->kbd_inter_refused &&
6802 !s->kbd_inter_running) {
6803 s->method = AUTH_KEYBOARD_INTERACTIVE;
6804 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
6806 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6807 ssh->pkt_ctx |= SSH2_PKTCTX_KBDINTER;
6809 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6810 ssh2_pkt_addstring(s->pktout, s->username);
6811 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
6812 ssh2_pkt_addstring(s->pktout, "keyboard-interactive"); /* method */
6813 ssh2_pkt_addstring(s->pktout, ""); /* lang */
6814 ssh2_pkt_addstring(s->pktout, "");
6815 ssh2_pkt_send(ssh, s->pktout);
6817 crWaitUntilV(pktin);
6818 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
6819 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE)
6821 logevent("Keyboard-interactive authentication refused");
6822 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
6823 s->kbd_inter_refused = TRUE; /* don't try it again */
6827 c_write_str(ssh, "Using keyboard-interactive authentication.\r\n");
6828 s->kbd_inter_running = TRUE;
6832 if (s->kbd_inter_running) {
6833 s->method = AUTH_KEYBOARD_INTERACTIVE;
6834 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
6836 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6837 ssh->pkt_ctx |= SSH2_PKTCTX_KBDINTER;
6839 if (s->curr_prompt == 0) {
6841 * We've got a fresh USERAUTH_INFO_REQUEST.
6842 * Display header data, and start going through
6845 char *name, *inst, *lang;
6846 int name_len, inst_len, lang_len;
6848 ssh_pkt_getstring(pktin, &name, &name_len);
6849 ssh_pkt_getstring(pktin, &inst, &inst_len);
6850 ssh_pkt_getstring(pktin, &lang, &lang_len);
6852 c_write_untrusted(ssh, name, name_len);
6853 c_write_str(ssh, "\r\n");
6856 c_write_untrusted(ssh, inst, inst_len);
6857 c_write_str(ssh, "\r\n");
6859 s->num_prompts = ssh_pkt_getuint32(pktin);
6863 * If there are prompts remaining in the packet,
6864 * display one and get a response.
6866 if (s->curr_prompt < s->num_prompts) {
6870 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
6871 if (prompt_len > 0) {
6872 static const char trunc[] = "<prompt truncated>: ";
6873 static const int prlen = sizeof(s->pwprompt) -
6875 if (prompt_len > prlen) {
6876 memcpy(s->pwprompt, prompt, prlen);
6877 strcpy(s->pwprompt + prlen, trunc);
6879 memcpy(s->pwprompt, prompt, prompt_len);
6880 s->pwprompt[prompt_len] = '\0';
6884 "<server failed to send prompt>: ");
6886 s->echo = ssh2_pkt_getbool(pktin);
6892 if (!s->method && s->can_passwd) {
6893 s->method = AUTH_PASSWORD;
6894 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6895 ssh->pkt_ctx |= SSH2_PKTCTX_PASSWORD;
6896 sprintf(s->pwprompt, "%.90s@%.90s's password: ", s->username,
6903 if (!ssh_get_line(s->pwprompt, s->password,
6904 sizeof(s->password), TRUE)) {
6906 * get_line failed to get a password (for
6907 * example because one was supplied on the
6908 * command line which has already failed to
6911 s->pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
6912 ssh2_pkt_adduint32(s->pktout,SSH2_DISCONNECT_BY_APPLICATION);
6913 ssh2_pkt_addstring(s->pktout, "No more passwords available"
6915 ssh2_pkt_addstring(s->pktout, "en"); /* language tag */
6916 ssh2_pkt_send_noqueue(ssh, s->pktout);
6917 logevent("Unable to authenticate");
6918 connection_fatal(ssh->frontend,
6919 "Unable to authenticate");
6920 ssh->close_expected = TRUE;
6921 ssh_closing((Plug)ssh, NULL, 0, 0);
6925 int ret; /* need not be saved across crReturn */
6926 c_write_untrusted(ssh, s->pwprompt, strlen(s->pwprompt));
6929 setup_userpass_input(ssh, s->password,
6930 sizeof(s->password), s->echo);
6932 crWaitUntilV(!pktin);
6933 ret = process_userpass_input(ssh, in, inlen);
6937 c_write_str(ssh, "\r\n");
6941 if (s->method == AUTH_PUBLICKEY_FILE) {
6943 * We have our passphrase. Now try the actual authentication.
6945 struct ssh2_userkey *key;
6946 const char *error = NULL;
6948 key = ssh2_load_userkey(&ssh->cfg.keyfile, s->password,
6950 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
6951 if (key == SSH2_WRONG_PASSPHRASE) {
6952 c_write_str(ssh, "Wrong passphrase\r\n");
6953 s->tried_pubkey_config = FALSE;
6955 c_write_str(ssh, "Unable to load private key (");
6956 c_write_str(ssh, error);
6957 c_write_str(ssh, ")\r\n");
6958 s->tried_pubkey_config = TRUE;
6960 /* Send a spurious AUTH_NONE to return to the top. */
6961 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6962 ssh2_pkt_addstring(s->pktout, s->username);
6963 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
6964 ssh2_pkt_addstring(s->pktout, "none"); /* method */
6965 ssh2_pkt_send(ssh, s->pktout);
6966 s->type = AUTH_TYPE_NONE;
6968 unsigned char *pkblob, *sigblob, *sigdata;
6969 int pkblob_len, sigblob_len, sigdata_len;
6973 * We have loaded the private key and the server
6974 * has announced that it's willing to accept it.
6975 * Hallelujah. Generate a signature and send it.
6977 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6978 ssh2_pkt_addstring(s->pktout, s->username);
6979 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
6980 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
6981 ssh2_pkt_addbool(s->pktout, TRUE);
6982 ssh2_pkt_addstring(s->pktout, key->alg->name);
6983 pkblob = key->alg->public_blob(key->data, &pkblob_len);
6984 ssh2_pkt_addstring_start(s->pktout);
6985 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob, pkblob_len);
6988 * The data to be signed is:
6992 * followed by everything so far placed in the
6995 sigdata_len = s->pktout->length - 5 + 4 + 20;
6996 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
6998 sigdata = snewn(sigdata_len, unsigned char);
7000 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
7001 PUT_32BIT(sigdata+p, 20);
7004 memcpy(sigdata+p, ssh->v2_session_id, 20); p += 20;
7005 memcpy(sigdata+p, s->pktout->data + 5,
7006 s->pktout->length - 5);
7007 p += s->pktout->length - 5;
7008 assert(p == sigdata_len);
7009 sigblob = key->alg->sign(key->data, (char *)sigdata,
7010 sigdata_len, &sigblob_len);
7011 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
7012 sigblob, sigblob_len);
7017 ssh2_pkt_send(ssh, s->pktout);
7018 s->type = AUTH_TYPE_PUBLICKEY;
7019 key->alg->freekey(key->data);
7021 } else if (s->method == AUTH_PASSWORD) {
7023 * We pad out the password packet to 256 bytes to make
7024 * it harder for an attacker to find the length of the
7027 * Anyone using a password longer than 256 bytes
7028 * probably doesn't have much to worry about from
7029 * people who find out how long their password is!
7031 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7032 s->pktout->forcepad = 256;
7033 ssh2_pkt_addstring(s->pktout, s->username);
7034 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
7035 ssh2_pkt_addstring(s->pktout, "password");
7036 ssh2_pkt_addbool(s->pktout, FALSE);
7037 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
7038 ssh2_pkt_addstring(s->pktout, s->password);
7039 memset(s->password, 0, sizeof(s->password));
7040 end_log_omission(ssh, s->pktout);
7041 ssh2_pkt_send(ssh, s->pktout);
7042 logevent("Sent password");
7043 s->type = AUTH_TYPE_PASSWORD;
7044 } else if (s->method == AUTH_KEYBOARD_INTERACTIVE) {
7045 if (s->curr_prompt == 0) {
7046 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
7047 s->pktout->forcepad = 256;
7048 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
7050 if (s->need_pw) { /* only add pw if we just got one! */
7051 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
7052 ssh2_pkt_addstring(s->pktout, s->password);
7053 memset(s->password, 0, sizeof(s->password));
7054 end_log_omission(ssh, s->pktout);
7057 if (s->curr_prompt >= s->num_prompts) {
7058 ssh2_pkt_send(ssh, s->pktout);
7061 * If there are prompts remaining, we set
7062 * `gotit' so that we won't attempt to get
7063 * another packet. Then we go back round the
7064 * loop and will end up retrieving another
7065 * prompt out of the existing packet. Funky or
7070 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
7072 c_write_str(ssh, "No supported authentication methods"
7073 " left to try!\r\n");
7074 logevent("No supported authentications offered."
7076 s->pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
7077 ssh2_pkt_adduint32(s->pktout, SSH2_DISCONNECT_BY_APPLICATION);
7078 ssh2_pkt_addstring(s->pktout, "No supported authentication"
7079 " methods available");
7080 ssh2_pkt_addstring(s->pktout, "en"); /* language tag */
7081 ssh2_pkt_send_noqueue(ssh, s->pktout);
7082 ssh->close_expected = TRUE;
7083 ssh_closing((Plug)ssh, NULL, 0, 0);
7087 } while (!s->we_are_in);
7090 * Now we're authenticated for the connection protocol. The
7091 * connection protocol will automatically have started at this
7092 * point; there's no need to send SERVICE_REQUEST.
7095 ssh->channels = newtree234(ssh_channelcmp);
7098 * Set up handlers for some connection protocol messages, so we
7099 * don't have to handle them repeatedly in this coroutine.
7101 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
7102 ssh2_msg_channel_window_adjust;
7103 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
7104 ssh2_msg_global_request;
7107 * Create the main session channel.
7109 if (!ssh->cfg.ssh_no_shell) {
7110 ssh->mainchan = snew(struct ssh_channel);
7111 ssh->mainchan->ssh = ssh;
7112 ssh->mainchan->localid = alloc_channel_id(ssh);
7113 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7114 ssh2_pkt_addstring(s->pktout, "session");
7115 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
7116 ssh->mainchan->v.v2.locwindow = OUR_V2_WINSIZE;
7117 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
7118 ssh2_pkt_adduint32(s->pktout, OUR_V2_MAXPKT); /* our max pkt size */
7119 ssh2_pkt_send(ssh, s->pktout);
7120 crWaitUntilV(pktin);
7121 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
7122 bombout(("Server refused to open a session"));
7124 /* FIXME: error data comes back in FAILURE packet */
7126 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
7127 bombout(("Server's channel confirmation cited wrong channel"));
7130 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
7131 ssh->mainchan->halfopen = FALSE;
7132 ssh->mainchan->type = CHAN_MAINSESSION;
7133 ssh->mainchan->closes = 0;
7134 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
7135 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
7136 bufchain_init(&ssh->mainchan->v.v2.outbuffer);
7137 add234(ssh->channels, ssh->mainchan);
7138 update_specials_menu(ssh->frontend);
7139 logevent("Opened channel for session");
7141 ssh->mainchan = NULL;
7144 * Now we have a channel, make dispatch table entries for
7145 * general channel-based messages.
7147 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
7148 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
7149 ssh2_msg_channel_data;
7150 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
7151 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
7152 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
7153 ssh2_msg_channel_open_confirmation;
7154 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
7155 ssh2_msg_channel_open_failure;
7156 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
7157 ssh2_msg_channel_request;
7158 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
7159 ssh2_msg_channel_open;
7162 * Potentially enable X11 forwarding.
7164 if (ssh->mainchan && ssh->cfg.x11_forward) {
7165 char proto[20], data[64];
7166 logevent("Requesting X11 forwarding");
7167 ssh->x11auth = x11_invent_auth(proto, sizeof(proto),
7168 data, sizeof(data), ssh->cfg.x11_auth);
7169 x11_get_real_auth(ssh->x11auth, ssh->cfg.x11_display);
7170 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7171 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
7172 ssh2_pkt_addstring(s->pktout, "x11-req");
7173 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
7174 ssh2_pkt_addbool(s->pktout, 0); /* many connections */
7175 ssh2_pkt_addstring(s->pktout, proto);
7176 ssh2_pkt_addstring(s->pktout, data);
7177 ssh2_pkt_adduint32(s->pktout, x11_get_screen_number(ssh->cfg.x11_display));
7178 ssh2_pkt_send(ssh, s->pktout);
7180 crWaitUntilV(pktin);
7182 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
7183 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
7184 bombout(("Unexpected response to X11 forwarding request:"
7185 " packet type %d", pktin->type));
7188 logevent("X11 forwarding refused");
7190 logevent("X11 forwarding enabled");
7191 ssh->X11_fwd_enabled = TRUE;
7196 * Enable port forwardings.
7198 ssh_setup_portfwd(ssh, &ssh->cfg);
7201 * Potentially enable agent forwarding.
7203 if (ssh->mainchan && ssh->cfg.agentfwd && agent_exists()) {
7204 logevent("Requesting OpenSSH-style agent forwarding");
7205 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7206 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
7207 ssh2_pkt_addstring(s->pktout, "auth-agent-req@openssh.com");
7208 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
7209 ssh2_pkt_send(ssh, s->pktout);
7211 crWaitUntilV(pktin);
7213 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
7214 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
7215 bombout(("Unexpected response to agent forwarding request:"
7216 " packet type %d", pktin->type));
7219 logevent("Agent forwarding refused");
7221 logevent("Agent forwarding enabled");
7222 ssh->agentfwd_enabled = TRUE;
7227 * Now allocate a pty for the session.
7229 if (ssh->mainchan && !ssh->cfg.nopty) {
7230 /* Unpick the terminal-speed string. */
7231 /* XXX perhaps we should allow no speeds to be sent. */
7232 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
7233 sscanf(ssh->cfg.termspeed, "%d,%d", &ssh->ospeed, &ssh->ispeed);
7234 /* Build the pty request. */
7235 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7236 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
7237 ssh2_pkt_addstring(s->pktout, "pty-req");
7238 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
7239 ssh2_pkt_addstring(s->pktout, ssh->cfg.termtype);
7240 ssh2_pkt_adduint32(s->pktout, ssh->term_width);
7241 ssh2_pkt_adduint32(s->pktout, ssh->term_height);
7242 ssh2_pkt_adduint32(s->pktout, 0); /* pixel width */
7243 ssh2_pkt_adduint32(s->pktout, 0); /* pixel height */
7244 ssh2_pkt_addstring_start(s->pktout);
7245 ssh2_pkt_addbyte(s->pktout, 128); /* TTY_OP_ISPEED */
7246 ssh2_pkt_adduint32(s->pktout, ssh->ispeed);
7247 ssh2_pkt_addbyte(s->pktout, 129); /* TTY_OP_OSPEED */
7248 ssh2_pkt_adduint32(s->pktout, ssh->ospeed);
7249 ssh2_pkt_addstring_data(s->pktout, "\0", 1); /* TTY_OP_END */
7250 ssh2_pkt_send(ssh, s->pktout);
7251 ssh->state = SSH_STATE_INTERMED;
7253 crWaitUntilV(pktin);
7255 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
7256 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
7257 bombout(("Unexpected response to pty request:"
7258 " packet type %d", pktin->type));
7261 c_write_str(ssh, "Server refused to allocate pty\r\n");
7262 ssh->editing = ssh->echoing = 1;
7264 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
7265 ssh->ospeed, ssh->ispeed);
7268 ssh->editing = ssh->echoing = 1;
7272 * Send environment variables.
7274 * Simplest thing here is to send all the requests at once, and
7275 * then wait for a whole bunch of successes or failures.
7277 if (ssh->mainchan && *ssh->cfg.environmt) {
7278 char *e = ssh->cfg.environmt;
7279 char *var, *varend, *val;
7285 while (*e && *e != '\t') e++;
7287 if (*e == '\t') e++;
7292 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7293 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
7294 ssh2_pkt_addstring(s->pktout, "env");
7295 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
7296 ssh2_pkt_addstring_start(s->pktout);
7297 ssh2_pkt_addstring_data(s->pktout, var, varend-var);
7298 ssh2_pkt_addstring(s->pktout, val);
7299 ssh2_pkt_send(ssh, s->pktout);
7304 logeventf(ssh, "Sent %d environment variables", s->num_env);
7307 s->env_left = s->num_env;
7309 while (s->env_left > 0) {
7310 crWaitUntilV(pktin);
7312 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
7313 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
7314 bombout(("Unexpected response to environment request:"
7315 " packet type %d", pktin->type));
7325 if (s->env_ok == s->num_env) {
7326 logevent("All environment variables successfully set");
7327 } else if (s->env_ok == 0) {
7328 logevent("All environment variables refused");
7329 c_write_str(ssh, "Server refused to set environment variables\r\n");
7331 logeventf(ssh, "%d environment variables refused",
7332 s->num_env - s->env_ok);
7333 c_write_str(ssh, "Server refused to set all environment variables\r\n");
7338 * Start a shell or a remote command. We may have to attempt
7339 * this twice if the config data has provided a second choice
7342 if (ssh->mainchan) while (1) {
7346 if (ssh->fallback_cmd) {
7347 subsys = ssh->cfg.ssh_subsys2;
7348 cmd = ssh->cfg.remote_cmd_ptr2;
7350 subsys = ssh->cfg.ssh_subsys;
7351 cmd = ssh->cfg.remote_cmd_ptr;
7352 if (!cmd) cmd = ssh->cfg.remote_cmd;
7355 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7356 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
7358 ssh2_pkt_addstring(s->pktout, "subsystem");
7359 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
7360 ssh2_pkt_addstring(s->pktout, cmd);
7362 ssh2_pkt_addstring(s->pktout, "exec");
7363 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
7364 ssh2_pkt_addstring(s->pktout, cmd);
7366 ssh2_pkt_addstring(s->pktout, "shell");
7367 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
7369 ssh2_pkt_send(ssh, s->pktout);
7371 crWaitUntilV(pktin);
7373 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
7374 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
7375 bombout(("Unexpected response to shell/command request:"
7376 " packet type %d", pktin->type));
7380 * We failed to start the command. If this is the
7381 * fallback command, we really are finished; if it's
7382 * not, and if the fallback command exists, try falling
7383 * back to it before complaining.
7385 if (!ssh->fallback_cmd && ssh->cfg.remote_cmd_ptr2 != NULL) {
7386 logevent("Primary command failed; attempting fallback");
7387 ssh->fallback_cmd = TRUE;
7390 bombout(("Server refused to start a shell/command"));
7393 logevent("Started a shell/command");
7398 ssh->state = SSH_STATE_SESSION;
7399 if (ssh->size_needed)
7400 ssh_size(ssh, ssh->term_width, ssh->term_height);
7401 if (ssh->eof_needed)
7402 ssh_special(ssh, TS_EOF);
7408 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
7413 s->try_send = FALSE;
7417 * _All_ the connection-layer packets we expect to
7418 * receive are now handled by the dispatch table.
7419 * Anything that reaches here must be bogus.
7422 bombout(("Strange packet received: type %d", pktin->type));
7424 } else if (ssh->mainchan) {
7426 * We have spare data. Add it to the channel buffer.
7428 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
7433 struct ssh_channel *c;
7435 * Try to send data on all channels if we can.
7437 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
7438 ssh2_try_send_and_unthrottle(c);
7446 * Handlers for SSH-2 messages that might arrive at any moment.
7448 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
7450 /* log reason code in disconnect message */
7452 int nowlen, reason, msglen;
7454 reason = ssh_pkt_getuint32(pktin);
7455 ssh_pkt_getstring(pktin, &msg, &msglen);
7457 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
7458 buf = dupprintf("Received disconnect message (%s)",
7459 ssh2_disconnect_reasons[reason]);
7461 buf = dupprintf("Received disconnect message (unknown"
7462 " type %d)", reason);
7466 buf = dupprintf("Disconnection message text: %n%.*s",
7467 &nowlen, msglen, msg);
7469 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
7471 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
7472 ssh2_disconnect_reasons[reason] : "unknown",
7477 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
7479 /* log the debug message */
7484 /* XXX maybe we should actually take notice of this */
7485 always_display = ssh2_pkt_getbool(pktin);
7486 ssh_pkt_getstring(pktin, &msg, &msglen);
7488 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
7491 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
7493 struct Packet *pktout;
7494 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
7495 ssh2_pkt_adduint32(pktout, pktin->sequence);
7497 * UNIMPLEMENTED messages MUST appear in the same order as the
7498 * messages they respond to. Hence, never queue them.
7500 ssh2_pkt_send_noqueue(ssh, pktout);
7504 * Handle the top-level SSH-2 protocol.
7506 static void ssh2_protocol_setup(Ssh ssh)
7511 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
7513 for (i = 0; i < 256; i++)
7514 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
7517 * Any message we actually understand, we set to NULL so that
7518 * the coroutines will get it.
7520 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = NULL;
7521 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = NULL;
7522 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = NULL;
7523 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = NULL;
7524 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = NULL;
7525 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = NULL;
7526 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = NULL;
7527 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = NULL; duplicate case value */
7528 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = NULL; duplicate case value */
7529 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = NULL;
7530 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = NULL;
7531 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = NULL;
7532 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = NULL;
7533 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = NULL;
7534 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
7535 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = NULL;
7536 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = NULL; duplicate case value */
7537 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = NULL; duplicate case value */
7538 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = NULL;
7539 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = NULL;
7540 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = NULL;
7541 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = NULL;
7542 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = NULL;
7543 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = NULL;
7544 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = NULL;
7545 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = NULL;
7546 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = NULL;
7547 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = NULL;
7548 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = NULL;
7549 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = NULL;
7550 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = NULL;
7551 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = NULL;
7552 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = NULL;
7555 * These special message types we install handlers for.
7557 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
7558 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
7559 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
7562 static void ssh2_timer(void *ctx, long now)
7566 if (ssh->state == SSH_STATE_CLOSED)
7569 if (!ssh->kex_in_progress && ssh->cfg.ssh_rekey_time != 0 &&
7570 now - ssh->next_rekey >= 0) {
7571 do_ssh2_transport(ssh, "timeout", -1, NULL);
7575 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
7576 struct Packet *pktin)
7578 unsigned char *in = (unsigned char *)vin;
7579 if (ssh->state == SSH_STATE_CLOSED)
7583 ssh->incoming_data_size += pktin->encrypted_len;
7584 if (!ssh->kex_in_progress &&
7585 ssh->max_data_size != 0 &&
7586 ssh->incoming_data_size > ssh->max_data_size)
7587 do_ssh2_transport(ssh, "too much data received", -1, NULL);
7590 if (pktin && ssh->packet_dispatch[pktin->type]) {
7591 ssh->packet_dispatch[pktin->type](ssh, pktin);
7595 if (!ssh->protocol_initial_phase_done ||
7596 (pktin && pktin->type >= 20 && pktin->type < 50)) {
7597 if (do_ssh2_transport(ssh, in, inlen, pktin) &&
7598 !ssh->protocol_initial_phase_done) {
7599 ssh->protocol_initial_phase_done = TRUE;
7601 * Allow authconn to initialise itself.
7603 do_ssh2_authconn(ssh, NULL, 0, NULL);
7606 do_ssh2_authconn(ssh, in, inlen, pktin);
7611 * Called to set up the connection.
7613 * Returns an error message, or NULL on success.
7615 static const char *ssh_init(void *frontend_handle, void **backend_handle,
7617 char *host, int port, char **realhost, int nodelay,
7623 ssh = snew(struct ssh_tag);
7624 ssh->cfg = *cfg; /* STRUCTURE COPY */
7625 ssh->version = 0; /* when not ready yet */
7628 ssh->v1_cipher_ctx = NULL;
7629 ssh->crcda_ctx = NULL;
7630 ssh->cscipher = NULL;
7631 ssh->cs_cipher_ctx = NULL;
7632 ssh->sccipher = NULL;
7633 ssh->sc_cipher_ctx = NULL;
7635 ssh->cs_mac_ctx = NULL;
7637 ssh->sc_mac_ctx = NULL;
7639 ssh->cs_comp_ctx = NULL;
7641 ssh->sc_comp_ctx = NULL;
7643 ssh->kex_ctx = NULL;
7644 ssh->hostkey = NULL;
7646 ssh->close_expected = FALSE;
7647 ssh->state = SSH_STATE_PREPACKET;
7648 ssh->size_needed = FALSE;
7649 ssh->eof_needed = FALSE;
7652 ssh->deferred_send_data = NULL;
7653 ssh->deferred_len = 0;
7654 ssh->deferred_size = 0;
7655 ssh->fallback_cmd = 0;
7657 ssh->x11auth = NULL;
7658 ssh->v1_compressing = FALSE;
7659 ssh->v2_outgoing_sequence = 0;
7660 ssh->ssh1_rdpkt_crstate = 0;
7661 ssh->ssh2_rdpkt_crstate = 0;
7662 ssh->do_ssh_init_crstate = 0;
7663 ssh->ssh_gotdata_crstate = 0;
7664 ssh->do_ssh1_connection_crstate = 0;
7665 ssh->do_ssh1_login_crstate = 0;
7666 ssh->do_ssh2_transport_crstate = 0;
7667 ssh->do_ssh2_authconn_crstate = 0;
7668 ssh->do_ssh_init_state = NULL;
7669 ssh->do_ssh1_login_state = NULL;
7670 ssh->do_ssh2_transport_state = NULL;
7671 ssh->do_ssh2_authconn_state = NULL;
7672 ssh->mainchan = NULL;
7673 ssh->throttled_all = 0;
7674 ssh->v1_stdout_throttling = 0;
7676 ssh->queuelen = ssh->queuesize = 0;
7677 ssh->queueing = FALSE;
7678 ssh->qhead = ssh->qtail = NULL;
7679 ssh->deferred_rekey_reason = NULL;
7680 bufchain_init(&ssh->queued_incoming_data);
7681 ssh->frozen = FALSE;
7683 *backend_handle = ssh;
7686 if (crypto_startup() == 0)
7687 return "Microsoft high encryption pack not installed!";
7690 ssh->frontend = frontend_handle;
7691 ssh->term_width = ssh->cfg.width;
7692 ssh->term_height = ssh->cfg.height;
7694 ssh->channels = NULL;
7695 ssh->rportfwds = NULL;
7696 ssh->portfwds = NULL;
7701 ssh->v1_throttle_count = 0;
7702 ssh->overall_bufsize = 0;
7703 ssh->fallback_cmd = 0;
7705 ssh->protocol = NULL;
7707 ssh->protocol_initial_phase_done = FALSE;
7711 ssh->incoming_data_size = ssh->outgoing_data_size =
7712 ssh->deferred_data_size = 0L;
7713 ssh->max_data_size = parse_blocksize(ssh->cfg.ssh_rekey_data);
7714 ssh->kex_in_progress = FALSE;
7716 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
7725 static void ssh_free(void *handle)
7727 Ssh ssh = (Ssh) handle;
7728 struct ssh_channel *c;
7729 struct ssh_rportfwd *pf;
7731 if (ssh->v1_cipher_ctx)
7732 ssh->cipher->free_context(ssh->v1_cipher_ctx);
7733 if (ssh->cs_cipher_ctx)
7734 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
7735 if (ssh->sc_cipher_ctx)
7736 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
7737 if (ssh->cs_mac_ctx)
7738 ssh->csmac->free_context(ssh->cs_mac_ctx);
7739 if (ssh->sc_mac_ctx)
7740 ssh->scmac->free_context(ssh->sc_mac_ctx);
7741 if (ssh->cs_comp_ctx) {
7743 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
7745 zlib_compress_cleanup(ssh->cs_comp_ctx);
7747 if (ssh->sc_comp_ctx) {
7749 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
7751 zlib_decompress_cleanup(ssh->sc_comp_ctx);
7754 dh_cleanup(ssh->kex_ctx);
7755 sfree(ssh->savedhost);
7757 while (ssh->queuelen-- > 0)
7758 ssh_free_packet(ssh->queue[ssh->queuelen]);
7761 while (ssh->qhead) {
7762 struct queued_handler *qh = ssh->qhead;
7763 ssh->qhead = qh->next;
7766 ssh->qhead = ssh->qtail = NULL;
7768 if (ssh->channels) {
7769 while ((c = delpos234(ssh->channels, 0)) != NULL) {
7772 if (c->u.x11.s != NULL)
7773 x11_close(c->u.x11.s);
7776 if (c->u.pfd.s != NULL)
7777 pfd_close(c->u.pfd.s);
7782 freetree234(ssh->channels);
7783 ssh->channels = NULL;
7786 if (ssh->rportfwds) {
7787 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
7789 freetree234(ssh->rportfwds);
7790 ssh->rportfwds = NULL;
7792 sfree(ssh->deferred_send_data);
7794 x11_free_auth(ssh->x11auth);
7795 sfree(ssh->do_ssh_init_state);
7796 sfree(ssh->do_ssh1_login_state);
7797 sfree(ssh->do_ssh2_transport_state);
7798 sfree(ssh->do_ssh2_authconn_state);
7799 if (ssh->crcda_ctx) {
7800 crcda_free_context(ssh->crcda_ctx);
7801 ssh->crcda_ctx = NULL;
7804 ssh_do_close(ssh, TRUE);
7805 expire_timer_context(ssh);
7807 pinger_free(ssh->pinger);
7808 bufchain_clear(&ssh->queued_incoming_data);
7815 * Reconfigure the SSH backend.
7817 static void ssh_reconfig(void *handle, Config *cfg)
7819 Ssh ssh = (Ssh) handle;
7820 char *rekeying = NULL, rekey_mandatory = FALSE;
7821 unsigned long old_max_data_size;
7823 pinger_reconfig(ssh->pinger, &ssh->cfg, cfg);
7824 ssh_setup_portfwd(ssh, cfg);
7826 if (ssh->cfg.ssh_rekey_time != cfg->ssh_rekey_time &&
7827 cfg->ssh_rekey_time != 0) {
7828 long new_next = ssh->last_rekey + cfg->ssh_rekey_time*60*TICKSPERSEC;
7829 long now = GETTICKCOUNT();
7831 if (new_next - now < 0) {
7832 rekeying = "timeout shortened";
7834 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
7838 old_max_data_size = ssh->max_data_size;
7839 ssh->max_data_size = parse_blocksize(cfg->ssh_rekey_data);
7840 if (old_max_data_size != ssh->max_data_size &&
7841 ssh->max_data_size != 0) {
7842 if (ssh->outgoing_data_size > ssh->max_data_size ||
7843 ssh->incoming_data_size > ssh->max_data_size)
7844 rekeying = "data limit lowered";
7847 if (ssh->cfg.compression != cfg->compression) {
7848 rekeying = "compression setting changed";
7849 rekey_mandatory = TRUE;
7852 if (ssh->cfg.ssh2_des_cbc != cfg->ssh2_des_cbc ||
7853 memcmp(ssh->cfg.ssh_cipherlist, cfg->ssh_cipherlist,
7854 sizeof(ssh->cfg.ssh_cipherlist))) {
7855 rekeying = "cipher settings changed";
7856 rekey_mandatory = TRUE;
7859 ssh->cfg = *cfg; /* STRUCTURE COPY */
7862 if (!ssh->kex_in_progress) {
7863 do_ssh2_transport(ssh, rekeying, -1, NULL);
7864 } else if (rekey_mandatory) {
7865 ssh->deferred_rekey_reason = rekeying;
7871 * Called to send data down the Telnet connection.
7873 static int ssh_send(void *handle, char *buf, int len)
7875 Ssh ssh = (Ssh) handle;
7877 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
7880 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
7882 return ssh_sendbuffer(ssh);
7886 * Called to query the current amount of buffered stdin data.
7888 static int ssh_sendbuffer(void *handle)
7890 Ssh ssh = (Ssh) handle;
7893 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
7897 * If the SSH socket itself has backed up, add the total backup
7898 * size on that to any individual buffer on the stdin channel.
7901 if (ssh->throttled_all)
7902 override_value = ssh->overall_bufsize;
7904 if (ssh->version == 1) {
7905 return override_value;
7906 } else if (ssh->version == 2) {
7907 if (!ssh->mainchan || ssh->mainchan->closes > 0)
7908 return override_value;
7910 return (override_value +
7911 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
7918 * Called to set the size of the window from SSH's POV.
7920 static void ssh_size(void *handle, int width, int height)
7922 Ssh ssh = (Ssh) handle;
7923 struct Packet *pktout;
7925 ssh->term_width = width;
7926 ssh->term_height = height;
7928 switch (ssh->state) {
7929 case SSH_STATE_BEFORE_SIZE:
7930 case SSH_STATE_PREPACKET:
7931 case SSH_STATE_CLOSED:
7932 break; /* do nothing */
7933 case SSH_STATE_INTERMED:
7934 ssh->size_needed = TRUE; /* buffer for later */
7936 case SSH_STATE_SESSION:
7937 if (!ssh->cfg.nopty) {
7938 if (ssh->version == 1) {
7939 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
7940 PKT_INT, ssh->term_height,
7941 PKT_INT, ssh->term_width,
7942 PKT_INT, 0, PKT_INT, 0, PKT_END);
7943 } else if (ssh->mainchan) {
7944 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7945 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
7946 ssh2_pkt_addstring(pktout, "window-change");
7947 ssh2_pkt_addbool(pktout, 0);
7948 ssh2_pkt_adduint32(pktout, ssh->term_width);
7949 ssh2_pkt_adduint32(pktout, ssh->term_height);
7950 ssh2_pkt_adduint32(pktout, 0);
7951 ssh2_pkt_adduint32(pktout, 0);
7952 ssh2_pkt_send(ssh, pktout);
7960 * Return a list of the special codes that make sense in this
7963 static const struct telnet_special *ssh_get_specials(void *handle)
7965 static const struct telnet_special ssh1_ignore_special[] = {
7966 {"IGNORE message", TS_NOP}
7968 static const struct telnet_special ssh2_transport_specials[] = {
7969 {"IGNORE message", TS_NOP},
7970 {"Repeat key exchange", TS_REKEY},
7972 static const struct telnet_special ssh2_session_specials[] = {
7975 /* These are the signal names defined by draft-ietf-secsh-connect-23.
7976 * They include all the ISO C signals, but are a subset of the POSIX
7977 * required signals. */
7978 {"SIGINT (Interrupt)", TS_SIGINT},
7979 {"SIGTERM (Terminate)", TS_SIGTERM},
7980 {"SIGKILL (Kill)", TS_SIGKILL},
7981 {"SIGQUIT (Quit)", TS_SIGQUIT},
7982 {"SIGHUP (Hangup)", TS_SIGHUP},
7983 {"More signals", TS_SUBMENU},
7984 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
7985 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
7986 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
7987 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
7990 static const struct telnet_special specials_end[] = {
7993 /* XXX review this length for any changes: */
7994 static struct telnet_special ssh_specials[lenof(ssh2_transport_specials) +
7995 lenof(ssh2_session_specials) +
7996 lenof(specials_end)];
7997 Ssh ssh = (Ssh) handle;
7999 #define ADD_SPECIALS(name) \
8001 assert((i + lenof(name)) <= lenof(ssh_specials)); \
8002 memcpy(&ssh_specials[i], name, sizeof name); \
8006 if (ssh->version == 1) {
8007 /* Don't bother offering IGNORE if we've decided the remote
8008 * won't cope with it, since we wouldn't bother sending it if
8010 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
8011 ADD_SPECIALS(ssh1_ignore_special);
8012 } else if (ssh->version == 2) {
8013 ADD_SPECIALS(ssh2_transport_specials);
8015 ADD_SPECIALS(ssh2_session_specials);
8016 } /* else we're not ready yet */
8019 ADD_SPECIALS(specials_end);
8020 return ssh_specials;
8028 * Send Telnet special codes. TS_EOF is useful for `plink', so you
8029 * can send an EOF and collect resulting output (e.g. `plink
8032 static void ssh_special(void *handle, Telnet_Special code)
8034 Ssh ssh = (Ssh) handle;
8035 struct Packet *pktout;
8037 if (code == TS_EOF) {
8038 if (ssh->state != SSH_STATE_SESSION) {
8040 * Buffer the EOF in case we are pre-SESSION, so we can
8041 * send it as soon as we reach SESSION.
8044 ssh->eof_needed = TRUE;
8047 if (ssh->version == 1) {
8048 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
8049 } else if (ssh->mainchan) {
8050 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
8051 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
8052 ssh2_pkt_send(ssh, pktout);
8053 ssh->send_ok = 0; /* now stop trying to read from stdin */
8055 logevent("Sent EOF message");
8056 } else if (code == TS_PING || code == TS_NOP) {
8057 if (ssh->state == SSH_STATE_CLOSED
8058 || ssh->state == SSH_STATE_PREPACKET) return;
8059 if (ssh->version == 1) {
8060 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
8061 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
8063 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
8064 ssh2_pkt_addstring_start(pktout);
8065 ssh2_pkt_send_noqueue(ssh, pktout);
8067 } else if (code == TS_REKEY) {
8068 if (!ssh->kex_in_progress && ssh->version == 2) {
8069 do_ssh2_transport(ssh, "at user request", -1, NULL);
8071 } else if (code == TS_BRK) {
8072 if (ssh->state == SSH_STATE_CLOSED
8073 || ssh->state == SSH_STATE_PREPACKET) return;
8074 if (ssh->version == 1) {
8075 logevent("Unable to send BREAK signal in SSH-1");
8076 } else if (ssh->mainchan) {
8077 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8078 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
8079 ssh2_pkt_addstring(pktout, "break");
8080 ssh2_pkt_addbool(pktout, 0);
8081 ssh2_pkt_adduint32(pktout, 0); /* default break length */
8082 ssh2_pkt_send(ssh, pktout);
8085 /* Is is a POSIX signal? */
8086 char *signame = NULL;
8087 if (code == TS_SIGABRT) signame = "ABRT";
8088 if (code == TS_SIGALRM) signame = "ALRM";
8089 if (code == TS_SIGFPE) signame = "FPE";
8090 if (code == TS_SIGHUP) signame = "HUP";
8091 if (code == TS_SIGILL) signame = "ILL";
8092 if (code == TS_SIGINT) signame = "INT";
8093 if (code == TS_SIGKILL) signame = "KILL";
8094 if (code == TS_SIGPIPE) signame = "PIPE";
8095 if (code == TS_SIGQUIT) signame = "QUIT";
8096 if (code == TS_SIGSEGV) signame = "SEGV";
8097 if (code == TS_SIGTERM) signame = "TERM";
8098 if (code == TS_SIGUSR1) signame = "USR1";
8099 if (code == TS_SIGUSR2) signame = "USR2";
8100 /* The SSH-2 protocol does in principle support arbitrary named
8101 * signals, including signame@domain, but we don't support those. */
8103 /* It's a signal. */
8104 if (ssh->version == 2 && ssh->mainchan) {
8105 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8106 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
8107 ssh2_pkt_addstring(pktout, "signal");
8108 ssh2_pkt_addbool(pktout, 0);
8109 ssh2_pkt_addstring(pktout, signame);
8110 ssh2_pkt_send(ssh, pktout);
8111 logeventf(ssh, "Sent signal SIG%s", signame);
8114 /* Never heard of it. Do nothing */
8119 void *new_sock_channel(void *handle, Socket s)
8121 Ssh ssh = (Ssh) handle;
8122 struct ssh_channel *c;
8123 c = snew(struct ssh_channel);
8128 c->localid = alloc_channel_id(ssh);
8130 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
8132 bufchain_init(&c->v.v2.outbuffer);
8133 add234(ssh->channels, c);
8139 * This is called when stdout/stderr (the entity to which
8140 * from_backend sends data) manages to clear some backlog.
8142 static void ssh_unthrottle(void *handle, int bufsize)
8144 Ssh ssh = (Ssh) handle;
8145 if (ssh->version == 1) {
8146 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
8147 ssh->v1_stdout_throttling = 0;
8148 ssh1_throttle(ssh, -1);
8151 if (ssh->mainchan && ssh->mainchan->closes == 0)
8152 ssh2_set_window(ssh->mainchan, OUR_V2_WINSIZE - bufsize);
8156 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
8158 struct ssh_channel *c = (struct ssh_channel *)channel;
8160 struct Packet *pktout;
8162 logeventf(ssh, "Opening forwarded connection to %s:%d", hostname, port);
8164 if (ssh->version == 1) {
8165 send_packet(ssh, SSH1_MSG_PORT_OPEN,
8166 PKT_INT, c->localid,
8169 /* PKT_STR, <org:orgport>, */
8172 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
8173 ssh2_pkt_addstring(pktout, "direct-tcpip");
8174 ssh2_pkt_adduint32(pktout, c->localid);
8175 c->v.v2.locwindow = OUR_V2_WINSIZE;
8176 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
8177 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
8178 ssh2_pkt_addstring(pktout, hostname);
8179 ssh2_pkt_adduint32(pktout, port);
8181 * We make up values for the originator data; partly it's
8182 * too much hassle to keep track, and partly I'm not
8183 * convinced the server should be told details like that
8184 * about my local network configuration.
8186 ssh2_pkt_addstring(pktout, "client-side-connection");
8187 ssh2_pkt_adduint32(pktout, 0);
8188 ssh2_pkt_send(ssh, pktout);
8192 static Socket ssh_socket(void *handle)
8194 Ssh ssh = (Ssh) handle;
8198 static int ssh_sendok(void *handle)
8200 Ssh ssh = (Ssh) handle;
8201 return ssh->send_ok;
8204 static int ssh_ldisc(void *handle, int option)
8206 Ssh ssh = (Ssh) handle;
8207 if (option == LD_ECHO)
8208 return ssh->echoing;
8209 if (option == LD_EDIT)
8210 return ssh->editing;
8214 static void ssh_provide_ldisc(void *handle, void *ldisc)
8216 Ssh ssh = (Ssh) handle;
8220 static void ssh_provide_logctx(void *handle, void *logctx)
8222 Ssh ssh = (Ssh) handle;
8223 ssh->logctx = logctx;
8226 static int ssh_return_exitcode(void *handle)
8228 Ssh ssh = (Ssh) handle;
8232 return (ssh->exitcode >= 0 ? ssh->exitcode : 0);
8236 * cfg_info for SSH is the currently running version of the
8237 * protocol. (1 for 1; 2 for 2; 0 for not-decided-yet.)
8239 static int ssh_cfg_info(void *handle)
8241 Ssh ssh = (Ssh) handle;
8242 return ssh->version;
8246 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
8247 * that fails. This variable is the means by which scp.c can reach
8248 * into the SSH code and find out which one it got.
8250 extern int ssh_fallback_cmd(void *handle)
8252 Ssh ssh = (Ssh) handle;
8253 return ssh->fallback_cmd;
8256 Backend ssh_backend = {
8266 ssh_return_exitcode,