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_DHGROUP1 0x0001
108 #define SSH2_PKTCTX_DHGEX 0x0002
109 #define SSH2_PKTCTX_PUBLICKEY 0x0010
110 #define SSH2_PKTCTX_PASSWORD 0x0020
111 #define SSH2_PKTCTX_KBDINTER 0x0040
112 #define SSH2_PKTCTX_AUTH_MASK 0x00F0
114 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
115 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
116 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
117 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
118 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
119 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
120 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
121 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
122 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
123 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
124 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
125 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
126 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
127 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
128 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
130 static const char *const ssh2_disconnect_reasons[] = {
132 "SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT",
133 "SSH_DISCONNECT_PROTOCOL_ERROR",
134 "SSH_DISCONNECT_KEY_EXCHANGE_FAILED",
135 "SSH_DISCONNECT_HOST_AUTHENTICATION_FAILED",
136 "SSH_DISCONNECT_MAC_ERROR",
137 "SSH_DISCONNECT_COMPRESSION_ERROR",
138 "SSH_DISCONNECT_SERVICE_NOT_AVAILABLE",
139 "SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED",
140 "SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE",
141 "SSH_DISCONNECT_CONNECTION_LOST",
142 "SSH_DISCONNECT_BY_APPLICATION",
143 "SSH_DISCONNECT_TOO_MANY_CONNECTIONS",
144 "SSH_DISCONNECT_AUTH_CANCELLED_BY_USER",
145 "SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE",
146 "SSH_DISCONNECT_ILLEGAL_USER_NAME",
149 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
150 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
151 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
152 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
154 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
157 * Various remote-bug flags.
159 #define BUG_CHOKES_ON_SSH1_IGNORE 1
160 #define BUG_SSH2_HMAC 2
161 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
162 #define BUG_CHOKES_ON_RSA 8
163 #define BUG_SSH2_RSA_PADDING 16
164 #define BUG_SSH2_DERIVEKEY 32
165 #define BUG_SSH2_DH_GEX 64
166 #define BUG_SSH2_PK_SESSIONID 128
168 #define translate(x) if (type == x) return #x
169 #define translatec(x,ctx) if (type == x && (pkt_ctx & ctx)) return #x
170 static char *ssh1_pkt_type(int type)
172 translate(SSH1_MSG_DISCONNECT);
173 translate(SSH1_SMSG_PUBLIC_KEY);
174 translate(SSH1_CMSG_SESSION_KEY);
175 translate(SSH1_CMSG_USER);
176 translate(SSH1_CMSG_AUTH_RSA);
177 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
178 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
179 translate(SSH1_CMSG_AUTH_PASSWORD);
180 translate(SSH1_CMSG_REQUEST_PTY);
181 translate(SSH1_CMSG_WINDOW_SIZE);
182 translate(SSH1_CMSG_EXEC_SHELL);
183 translate(SSH1_CMSG_EXEC_CMD);
184 translate(SSH1_SMSG_SUCCESS);
185 translate(SSH1_SMSG_FAILURE);
186 translate(SSH1_CMSG_STDIN_DATA);
187 translate(SSH1_SMSG_STDOUT_DATA);
188 translate(SSH1_SMSG_STDERR_DATA);
189 translate(SSH1_CMSG_EOF);
190 translate(SSH1_SMSG_EXIT_STATUS);
191 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
192 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
193 translate(SSH1_MSG_CHANNEL_DATA);
194 translate(SSH1_MSG_CHANNEL_CLOSE);
195 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
196 translate(SSH1_SMSG_X11_OPEN);
197 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
198 translate(SSH1_MSG_PORT_OPEN);
199 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
200 translate(SSH1_SMSG_AGENT_OPEN);
201 translate(SSH1_MSG_IGNORE);
202 translate(SSH1_CMSG_EXIT_CONFIRMATION);
203 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
204 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
205 translate(SSH1_MSG_DEBUG);
206 translate(SSH1_CMSG_REQUEST_COMPRESSION);
207 translate(SSH1_CMSG_AUTH_TIS);
208 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
209 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
210 translate(SSH1_CMSG_AUTH_CCARD);
211 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
212 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
215 static char *ssh2_pkt_type(int pkt_ctx, int type)
217 translate(SSH2_MSG_DISCONNECT);
218 translate(SSH2_MSG_IGNORE);
219 translate(SSH2_MSG_UNIMPLEMENTED);
220 translate(SSH2_MSG_DEBUG);
221 translate(SSH2_MSG_SERVICE_REQUEST);
222 translate(SSH2_MSG_SERVICE_ACCEPT);
223 translate(SSH2_MSG_KEXINIT);
224 translate(SSH2_MSG_NEWKEYS);
225 translatec(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP1);
226 translatec(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP1);
227 translatec(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
228 translatec(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
229 translatec(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
230 translatec(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
231 translate(SSH2_MSG_USERAUTH_REQUEST);
232 translate(SSH2_MSG_USERAUTH_FAILURE);
233 translate(SSH2_MSG_USERAUTH_SUCCESS);
234 translate(SSH2_MSG_USERAUTH_BANNER);
235 translatec(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
236 translatec(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
237 translatec(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
238 translatec(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
239 translate(SSH2_MSG_GLOBAL_REQUEST);
240 translate(SSH2_MSG_REQUEST_SUCCESS);
241 translate(SSH2_MSG_REQUEST_FAILURE);
242 translate(SSH2_MSG_CHANNEL_OPEN);
243 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
244 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
245 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
246 translate(SSH2_MSG_CHANNEL_DATA);
247 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
248 translate(SSH2_MSG_CHANNEL_EOF);
249 translate(SSH2_MSG_CHANNEL_CLOSE);
250 translate(SSH2_MSG_CHANNEL_REQUEST);
251 translate(SSH2_MSG_CHANNEL_SUCCESS);
252 translate(SSH2_MSG_CHANNEL_FAILURE);
258 #define GET_32BIT(cp) \
259 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
260 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
261 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
262 ((unsigned long)(unsigned char)(cp)[3]))
264 #define PUT_32BIT(cp, value) { \
265 (cp)[0] = (unsigned char)((value) >> 24); \
266 (cp)[1] = (unsigned char)((value) >> 16); \
267 (cp)[2] = (unsigned char)((value) >> 8); \
268 (cp)[3] = (unsigned char)(value); }
270 /* Enumeration values for fields in SSH-1 packets */
272 PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
273 /* These values are for communicating relevant semantics of
274 * fields to the packet logging code. */
275 PKTT_OTHER, PKTT_PASSWORD, PKTT_DATA
279 * Coroutine mechanics for the sillier bits of the code. If these
280 * macros look impenetrable to you, you might find it helpful to
283 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
285 * which explains the theory behind these macros.
287 * In particular, if you are getting `case expression not constant'
288 * errors when building with MS Visual Studio, this is because MS's
289 * Edit and Continue debugging feature causes their compiler to
290 * violate ANSI C. To disable Edit and Continue debugging:
292 * - right-click ssh.c in the FileView
294 * - select the C/C++ tab and the General category
295 * - under `Debug info:', select anything _other_ than `Program
296 * Database for Edit and Continue'.
298 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
301 if (!ssh->t) ssh->t = snew(struct t); \
303 #define crFinish(z) } *crLine = 0; return (z); }
304 #define crFinishV } *crLine = 0; return; }
305 #define crReturn(z) \
307 *crLine =__LINE__; return (z); case __LINE__:;\
311 *crLine=__LINE__; return; case __LINE__:;\
313 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
314 #define crStopV do{ *crLine = 0; return; }while(0)
315 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
316 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
318 typedef struct ssh_tag *Ssh;
321 static struct Packet *ssh2_pkt_init(int pkt_type);
322 static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
323 static void ssh2_pkt_adduint32(struct Packet *, unsigned long value);
324 static void ssh2_pkt_addstring_start(struct Packet *);
325 static void ssh2_pkt_addstring_str(struct Packet *, char *data);
326 static void ssh2_pkt_addstring_data(struct Packet *, char *data, int len);
327 static void ssh2_pkt_addstring(struct Packet *, char *data);
328 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
329 static void ssh2_pkt_addmp(struct Packet *, Bignum b);
330 static int ssh2_pkt_construct(Ssh, struct Packet *);
331 static void ssh2_pkt_send(Ssh, struct Packet *);
332 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
333 struct Packet *pktin);
334 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
335 struct Packet *pktin);
338 * Buffer management constants. There are several of these for
339 * various different purposes:
341 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
342 * on a local data stream before we throttle the whole SSH
343 * connection (in SSH1 only). Throttling the whole connection is
344 * pretty drastic so we set this high in the hope it won't
347 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
348 * on the SSH connection itself before we defensively throttle
349 * _all_ local data streams. This is pretty drastic too (though
350 * thankfully unlikely in SSH2 since the window mechanism should
351 * ensure that the server never has any need to throttle its end
352 * of the connection), so we set this high as well.
354 * - OUR_V2_WINSIZE is the maximum window size we present on SSH2
358 #define SSH1_BUFFER_LIMIT 32768
359 #define SSH_MAX_BACKLOG 32768
360 #define OUR_V2_WINSIZE 16384
362 const static struct ssh_kex *kex_algs[] = {
363 &ssh_diffiehellman_gex,
367 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
369 static void *nullmac_make_context(void)
373 static void nullmac_free_context(void *handle)
376 static void nullmac_key(void *handle, unsigned char *key)
379 static void nullmac_generate(void *handle, unsigned char *blk, int len,
383 static int nullmac_verify(void *handle, unsigned char *blk, int len,
388 const static struct ssh_mac ssh_mac_none = {
389 nullmac_make_context, nullmac_free_context, nullmac_key,
390 nullmac_generate, nullmac_verify, "none", 0
392 const static struct ssh_mac *macs[] = {
393 &ssh_sha1, &ssh_md5, &ssh_mac_none
395 const static struct ssh_mac *buggymacs[] = {
396 &ssh_sha1_buggy, &ssh_md5, &ssh_mac_none
399 static void *ssh_comp_none_init(void)
403 static void ssh_comp_none_cleanup(void *handle)
406 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
407 unsigned char **outblock, int *outlen)
411 static int ssh_comp_none_disable(void *handle)
415 const static struct ssh_compress ssh_comp_none = {
417 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
418 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
419 ssh_comp_none_disable, NULL
421 extern const struct ssh_compress ssh_zlib;
422 const static struct ssh_compress *compressions[] = {
423 &ssh_zlib, &ssh_comp_none
426 enum { /* channel types */
431 CHAN_SOCKDATA_DORMANT /* one the remote hasn't confirmed */
435 * 2-3-4 tree storing channels.
438 Ssh ssh; /* pointer back to main context */
439 unsigned remoteid, localid;
442 * In SSH1, this value contains four bits:
444 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
445 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
446 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
447 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
449 * A channel is completely finished with when all four bits are set.
453 struct ssh1_data_channel {
456 struct ssh2_data_channel {
458 unsigned remwindow, remmaxpkt;
463 struct ssh_agent_channel {
464 unsigned char *message;
465 unsigned char msglen[4];
466 unsigned lensofar, totallen;
468 struct ssh_x11_channel {
471 struct ssh_pfd_channel {
478 * 2-3-4 tree storing remote->local port forwardings. SSH 1 and SSH
479 * 2 use this structure in different ways, reflecting SSH 2's
480 * altogether saner approach to port forwarding.
482 * In SSH 1, you arrange a remote forwarding by sending the server
483 * the remote port number, and the local destination host:port.
484 * When a connection comes in, the server sends you back that
485 * host:port pair, and you connect to it. This is a ready-made
486 * security hole if you're not on the ball: a malicious server
487 * could send you back _any_ host:port pair, so if you trustingly
488 * connect to the address it gives you then you've just opened the
489 * entire inside of your corporate network just by connecting
490 * through it to a dodgy SSH server. Hence, we must store a list of
491 * host:port pairs we _are_ trying to forward to, and reject a
492 * connection request from the server if it's not in the list.
494 * In SSH 2, each side of the connection minds its own business and
495 * doesn't send unnecessary information to the other. You arrange a
496 * remote forwarding by sending the server just the remote port
497 * number. When a connection comes in, the server tells you which
498 * of its ports was connected to; and _you_ have to remember what
499 * local host:port pair went with that port number.
501 * Hence: in SSH 1 this structure stores host:port pairs we intend
502 * to allow connections to, and is indexed by those host:port
503 * pairs. In SSH 2 it stores a mapping from source port to
504 * destination host:port pair, and is indexed by source port.
506 struct ssh_rportfwd {
507 unsigned sport, dport;
520 * State associated with packet logging
524 struct logblank_t *blanks;
527 static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen,
528 struct Packet *pktin);
529 static void ssh2_protocol(Ssh ssh, unsigned char *in, int inlen,
530 struct Packet *pktin);
531 static void ssh_size(void *handle, int width, int height);
532 static void ssh_special(void *handle, Telnet_Special);
533 static int ssh2_try_send(struct ssh_channel *c);
534 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
535 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
536 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin);
537 static int ssh_sendbuffer(void *handle);
538 static void ssh_do_close(Ssh ssh);
539 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
540 static int ssh2_pkt_getbool(struct Packet *pkt);
541 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
543 struct rdpkt1_state_tag {
544 long len, pad, biglen, to_read;
545 unsigned long realcrc, gotcrc;
549 struct Packet *pktin;
552 struct rdpkt2_state_tag {
553 long len, pad, payload, packetlen, maclen;
556 unsigned long incoming_sequence;
557 struct Packet *pktin;
561 const struct plug_function_table *fn;
562 /* the above field _must_ be first in the structure */
564 SHA_State exhash, exhashbase;
571 unsigned char session_key[32];
573 int v1_remote_protoflags;
574 int v1_local_protoflags;
575 int agentfwd_enabled;
578 const struct ssh_cipher *cipher;
581 const struct ssh2_cipher *cscipher, *sccipher;
582 void *cs_cipher_ctx, *sc_cipher_ctx;
583 const struct ssh_mac *csmac, *scmac;
584 void *cs_mac_ctx, *sc_mac_ctx;
585 const struct ssh_compress *cscomp, *sccomp;
586 void *cs_comp_ctx, *sc_comp_ctx;
587 const struct ssh_kex *kex;
588 const struct ssh_signkey *hostkey;
589 unsigned char v2_session_id[20];
595 int echoing, editing;
599 int ospeed, ispeed; /* temporaries */
600 int term_width, term_height;
602 tree234 *channels; /* indexed by local id */
603 struct ssh_channel *mainchan; /* primary session channel */
610 SSH_STATE_BEFORE_SIZE,
616 int size_needed, eof_needed;
618 unsigned char *deferred_send_data;
619 int deferred_len, deferred_size;
622 * Gross hack: pscp will try to start SFTP but fall back to
623 * scp1 if that fails. This variable is the means by which
624 * scp.c can reach into the SSH code and find out which one it
630 * Used for username and password input.
632 char *userpass_input_buffer;
633 int userpass_input_buflen;
634 int userpass_input_bufpos;
635 int userpass_input_echo;
637 char *portfwd_strptr;
643 int v1_throttle_count;
646 int v1_stdout_throttling;
647 int v2_outgoing_sequence;
649 int ssh1_rdpkt_crstate;
650 int ssh2_rdpkt_crstate;
651 int do_ssh_init_crstate;
652 int ssh_gotdata_crstate;
653 int ssh1_protocol_crstate;
654 int do_ssh1_login_crstate;
655 int do_ssh2_transport_crstate;
656 int do_ssh2_authconn_crstate;
658 void *do_ssh_init_state;
659 void *do_ssh1_login_state;
660 void *do_ssh2_transport_state;
661 void *do_ssh2_authconn_state;
663 struct rdpkt1_state_tag rdpkt1_state;
664 struct rdpkt2_state_tag rdpkt2_state;
666 void (*protocol) (Ssh ssh, unsigned char *in, int inlen,
668 struct Packet *(*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
671 * We maintain a full _copy_ of a Config structure here, not
672 * merely a pointer to it. That way, when we're passed a new
673 * one for reconfiguration, we can check the differences and
674 * potentially reconfigure port forwardings etc in mid-session.
679 * Used to transfer data back from async agent callbacks.
681 void *agent_response;
682 int agent_response_len;
685 #define logevent(s) logevent(ssh->frontend, s)
687 /* logevent, only printf-formatted. */
688 static void logeventf(Ssh ssh, const char *fmt, ...)
694 buf = dupvprintf(fmt, ap);
700 #define bombout(msg) \
702 char *text = dupprintf msg; \
705 connection_fatal(ssh->frontend, "%s", text); \
709 /* Functions to leave bits out of the SSH packet log file. */
711 static void dont_log_password(Ssh ssh, struct Packet *pkt, int blanktype)
713 if (ssh->cfg.logomitpass)
714 pkt->logmode = blanktype;
717 static void dont_log_data(Ssh ssh, struct Packet *pkt, int blanktype)
719 if (ssh->cfg.logomitdata)
720 pkt->logmode = blanktype;
723 static void end_log_omission(Ssh ssh, struct Packet *pkt)
725 pkt->logmode = PKTLOG_EMIT;
728 static int ssh_channelcmp(void *av, void *bv)
730 struct ssh_channel *a = (struct ssh_channel *) av;
731 struct ssh_channel *b = (struct ssh_channel *) bv;
732 if (a->localid < b->localid)
734 if (a->localid > b->localid)
738 static int ssh_channelfind(void *av, void *bv)
740 unsigned *a = (unsigned *) av;
741 struct ssh_channel *b = (struct ssh_channel *) bv;
749 static int ssh_rportcmp_ssh1(void *av, void *bv)
751 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
752 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
754 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
755 return i < 0 ? -1 : +1;
756 if (a->dport > b->dport)
758 if (a->dport < b->dport)
763 static int ssh_rportcmp_ssh2(void *av, void *bv)
765 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
766 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
768 if (a->sport > b->sport)
770 if (a->sport < b->sport)
775 static int alloc_channel_id(Ssh ssh)
777 const unsigned CHANNEL_NUMBER_OFFSET = 256;
778 unsigned low, high, mid;
780 struct ssh_channel *c;
783 * First-fit allocation of channel numbers: always pick the
784 * lowest unused one. To do this, binary-search using the
785 * counted B-tree to find the largest channel ID which is in a
786 * contiguous sequence from the beginning. (Precisely
787 * everything in that sequence must have ID equal to its tree
788 * index plus CHANNEL_NUMBER_OFFSET.)
790 tsize = count234(ssh->channels);
794 while (high - low > 1) {
795 mid = (high + low) / 2;
796 c = index234(ssh->channels, mid);
797 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
798 low = mid; /* this one is fine */
800 high = mid; /* this one is past it */
803 * Now low points to either -1, or the tree index of the
804 * largest ID in the initial sequence.
807 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
808 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
810 return low + 1 + CHANNEL_NUMBER_OFFSET;
813 static void c_write(Ssh ssh, const char *buf, int len)
815 if ((flags & FLAG_STDERR)) {
817 for (i = 0; i < len; i++)
819 fputc(buf[i], stderr);
822 from_backend(ssh->frontend, 1, buf, len);
825 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
828 for (i = 0; i < len; i++) {
830 c_write(ssh, "\r\n", 2);
831 else if ((buf[i] & 0x60) || (buf[i] == '\r'))
832 c_write(ssh, buf + i, 1);
836 static void c_write_str(Ssh ssh, const char *buf)
838 c_write(ssh, buf, strlen(buf));
841 static void ssh_free_packet(struct Packet *pkt)
846 static struct Packet *ssh_new_packet(void)
848 struct Packet *pkt = snew(struct Packet);
852 pkt->logmode = PKTLOG_EMIT;
860 * Collect incoming data in the incoming packet buffer.
861 * Decipher and verify the packet when it is completely read.
862 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
863 * Update the *data and *datalen variables.
864 * Return a Packet structure when a packet is completed.
866 static struct Packet *ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
868 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
870 crBegin(ssh->ssh1_rdpkt_crstate);
874 st->pktin = ssh_new_packet();
877 st->pktin->length = 0;
879 for (st->i = st->len = 0; st->i < 4; st->i++) {
880 while ((*datalen) == 0)
882 st->len = (st->len << 8) + **data;
883 (*data)++, (*datalen)--;
886 st->pad = 8 - (st->len % 8);
887 st->biglen = st->len + st->pad;
888 st->pktin->length = st->len - 5;
890 if (st->biglen < 0) {
891 bombout(("Extremely large packet length from server suggests"
892 " data stream corruption"));
893 ssh_free_packet(st->pktin);
897 st->pktin->maxlen = st->biglen;
898 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
900 st->to_read = st->biglen;
901 st->p = st->pktin->data;
902 while (st->to_read > 0) {
903 st->chunk = st->to_read;
904 while ((*datalen) == 0)
906 if (st->chunk > (*datalen))
907 st->chunk = (*datalen);
908 memcpy(st->p, *data, st->chunk);
910 *datalen -= st->chunk;
912 st->to_read -= st->chunk;
915 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
917 bombout(("Network attack (CRC compensation) detected!"));
918 ssh_free_packet(st->pktin);
923 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
925 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
926 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
927 if (st->gotcrc != st->realcrc) {
928 bombout(("Incorrect CRC received on packet"));
929 ssh_free_packet(st->pktin);
933 st->pktin->body = st->pktin->data + st->pad + 1;
934 st->pktin->savedpos = 0;
936 if (ssh->v1_compressing) {
937 unsigned char *decompblk;
939 if (!zlib_decompress_block(ssh->sc_comp_ctx,
940 st->pktin->body - 1, st->pktin->length + 1,
941 &decompblk, &decomplen)) {
942 bombout(("Zlib decompression encountered invalid data"));
943 ssh_free_packet(st->pktin);
947 if (st->pktin->maxlen < st->pad + decomplen) {
948 st->pktin->maxlen = st->pad + decomplen;
949 st->pktin->data = sresize(st->pktin->data,
950 st->pktin->maxlen + APIEXTRA,
952 st->pktin->body = st->pktin->data + st->pad + 1;
955 memcpy(st->pktin->body - 1, decompblk, decomplen);
957 st->pktin->length = decomplen - 1;
960 st->pktin->type = st->pktin->body[-1];
963 * Log incoming packet, possibly omitting sensitive fields.
967 struct logblank_t blank;
968 if (ssh->cfg.logomitdata) {
969 int do_blank = FALSE, blank_prefix = 0;
970 /* "Session data" packets - omit the data field */
971 if ((st->pktin->type == SSH1_SMSG_STDOUT_DATA) ||
972 (st->pktin->type == SSH1_SMSG_STDERR_DATA)) {
973 do_blank = TRUE; blank_prefix = 0;
974 } else if (st->pktin->type == SSH1_MSG_CHANNEL_DATA) {
975 do_blank = TRUE; blank_prefix = 4;
978 blank.offset = blank_prefix;
979 blank.len = st->pktin->length;
980 blank.type = PKTLOG_OMIT;
984 log_packet(ssh->logctx,
985 PKT_INCOMING, st->pktin->type,
986 ssh1_pkt_type(st->pktin->type),
987 st->pktin->body, st->pktin->length,
991 if (st->pktin->type == SSH1_SMSG_STDOUT_DATA ||
992 st->pktin->type == SSH1_SMSG_STDERR_DATA ||
993 st->pktin->type == SSH1_MSG_DEBUG ||
994 st->pktin->type == SSH1_SMSG_AUTH_TIS_CHALLENGE ||
995 st->pktin->type == SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
996 long stringlen = GET_32BIT(st->pktin->body);
997 if (stringlen + 4 != st->pktin->length) {
998 bombout(("Received data packet with bogus string length"));
999 ssh_free_packet(st->pktin);
1004 if (st->pktin->type == SSH1_MSG_DEBUG) {
1008 ssh_pkt_getstring(st->pktin, &msg, &msglen);
1009 buf = dupprintf("Remote debug message: %.*s", msglen, msg);
1013 ssh_free_packet(st->pktin);
1015 } else if (st->pktin->type == SSH1_MSG_IGNORE) {
1017 ssh_free_packet(st->pktin);
1021 if (st->pktin->type == SSH1_MSG_DISCONNECT) {
1022 /* log reason code in disconnect message */
1026 ssh_pkt_getstring(st->pktin, &msg, &msglen);
1028 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
1029 ssh_free_packet(st->pktin);
1033 crFinish(st->pktin);
1036 static struct Packet *ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1038 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1040 crBegin(ssh->ssh2_rdpkt_crstate);
1044 st->pktin = ssh_new_packet();
1046 st->pktin->type = 0;
1047 st->pktin->length = 0;
1049 st->cipherblk = ssh->sccipher->blksize;
1052 if (st->cipherblk < 8)
1055 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1058 * Acquire and decrypt the first block of the packet. This will
1059 * contain the length and padding details.
1061 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1062 while ((*datalen) == 0)
1064 st->pktin->data[st->i] = *(*data)++;
1069 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1070 st->pktin->data, st->cipherblk);
1073 * Now get the length and padding figures.
1075 st->len = GET_32BIT(st->pktin->data);
1076 st->pad = st->pktin->data[4];
1079 * _Completely_ silly lengths should be stomped on before they
1080 * do us any more damage.
1082 if (st->len < 0 || st->pad < 0 || st->len + st->pad < 0) {
1083 bombout(("Incoming packet was garbled on decryption"));
1084 ssh_free_packet(st->pktin);
1089 * This enables us to deduce the payload length.
1091 st->payload = st->len - st->pad - 1;
1093 st->pktin->length = st->payload + 5;
1096 * So now we can work out the total packet length.
1098 st->packetlen = st->len + 4;
1099 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1102 * Allocate memory for the rest of the packet.
1104 st->pktin->maxlen = st->packetlen + st->maclen;
1105 st->pktin->data = sresize(st->pktin->data,
1106 st->pktin->maxlen + APIEXTRA,
1110 * Read and decrypt the remainder of the packet.
1112 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1114 while ((*datalen) == 0)
1116 st->pktin->data[st->i] = *(*data)++;
1119 /* Decrypt everything _except_ the MAC. */
1121 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1122 st->pktin->data + st->cipherblk,
1123 st->packetlen - st->cipherblk);
1129 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data, st->len + 4,
1130 st->incoming_sequence)) {
1131 bombout(("Incorrect MAC received on packet"));
1132 ssh_free_packet(st->pktin);
1135 st->incoming_sequence++; /* whether or not we MACed */
1138 * Decompress packet payload.
1141 unsigned char *newpayload;
1144 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1145 st->pktin->data + 5, st->pktin->length - 5,
1146 &newpayload, &newlen)) {
1147 if (st->pktin->maxlen < newlen + 5) {
1148 st->pktin->maxlen = newlen + 5;
1149 st->pktin->data = sresize(st->pktin->data,
1150 st->pktin->maxlen + APIEXTRA,
1153 st->pktin->length = 5 + newlen;
1154 memcpy(st->pktin->data + 5, newpayload, newlen);
1159 st->pktin->savedpos = 6;
1160 st->pktin->body = st->pktin->data;
1161 st->pktin->type = st->pktin->data[5];
1164 * Log incoming packet, possibly omitting sensitive fields.
1168 struct logblank_t blank;
1169 if (ssh->cfg.logomitdata) {
1170 int do_blank = FALSE, blank_prefix = 0;
1171 /* "Session data" packets - omit the data field */
1172 if (st->pktin->type == SSH2_MSG_CHANNEL_DATA) {
1173 do_blank = TRUE; blank_prefix = 4;
1174 } else if (st->pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
1175 do_blank = TRUE; blank_prefix = 8;
1178 blank.offset = blank_prefix;
1179 blank.len = (st->pktin->length-6) - blank_prefix;
1180 blank.type = PKTLOG_OMIT;
1184 log_packet(ssh->logctx, PKT_INCOMING, st->pktin->type,
1185 ssh2_pkt_type(ssh->pkt_ctx, st->pktin->type),
1186 st->pktin->data+6, st->pktin->length-6,
1190 switch (st->pktin->type) {
1192 * These packets we must handle instantly.
1194 case SSH2_MSG_DISCONNECT:
1196 /* log reason code in disconnect message */
1198 int nowlen, reason, msglen;
1200 reason = ssh_pkt_getuint32(st->pktin);
1201 ssh_pkt_getstring(st->pktin, &msg, &msglen);
1203 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
1204 buf = dupprintf("Received disconnect message (%s)",
1205 ssh2_disconnect_reasons[reason]);
1207 buf = dupprintf("Received disconnect message (unknown"
1208 " type %d)", reason);
1212 buf = dupprintf("Disconnection message text: %n%.*s",
1213 &nowlen, msglen, msg);
1215 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
1217 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
1218 ssh2_disconnect_reasons[reason] : "unknown",
1221 ssh_free_packet(st->pktin);
1225 case SSH2_MSG_IGNORE:
1226 ssh_free_packet(st->pktin);
1228 case SSH2_MSG_DEBUG:
1230 /* log the debug message */
1235 /* XXX maybe we should actually take notice of this */
1236 always_display = ssh2_pkt_getbool(st->pktin);
1237 ssh_pkt_getstring(st->pktin, &msg, &msglen);
1239 buf = dupprintf("Remote debug message: %.*s", msglen, msg);
1243 ssh_free_packet(st->pktin);
1247 * These packets we need do nothing about here.
1249 case SSH2_MSG_UNIMPLEMENTED:
1250 case SSH2_MSG_SERVICE_REQUEST:
1251 case SSH2_MSG_SERVICE_ACCEPT:
1252 case SSH2_MSG_KEXINIT:
1253 case SSH2_MSG_NEWKEYS:
1254 case SSH2_MSG_KEXDH_INIT:
1255 case SSH2_MSG_KEXDH_REPLY:
1256 /* case SSH2_MSG_KEX_DH_GEX_REQUEST: duplicate case value */
1257 /* case SSH2_MSG_KEX_DH_GEX_GROUP: duplicate case value */
1258 case SSH2_MSG_KEX_DH_GEX_INIT:
1259 case SSH2_MSG_KEX_DH_GEX_REPLY:
1260 case SSH2_MSG_USERAUTH_REQUEST:
1261 case SSH2_MSG_USERAUTH_FAILURE:
1262 case SSH2_MSG_USERAUTH_SUCCESS:
1263 case SSH2_MSG_USERAUTH_BANNER:
1264 case SSH2_MSG_USERAUTH_PK_OK:
1265 /* case SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ: duplicate case value */
1266 /* case SSH2_MSG_USERAUTH_INFO_REQUEST: duplicate case value */
1267 case SSH2_MSG_USERAUTH_INFO_RESPONSE:
1268 case SSH2_MSG_GLOBAL_REQUEST:
1269 case SSH2_MSG_REQUEST_SUCCESS:
1270 case SSH2_MSG_REQUEST_FAILURE:
1271 case SSH2_MSG_CHANNEL_OPEN:
1272 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
1273 case SSH2_MSG_CHANNEL_OPEN_FAILURE:
1274 case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
1275 case SSH2_MSG_CHANNEL_DATA:
1276 case SSH2_MSG_CHANNEL_EXTENDED_DATA:
1277 case SSH2_MSG_CHANNEL_EOF:
1278 case SSH2_MSG_CHANNEL_CLOSE:
1279 case SSH2_MSG_CHANNEL_REQUEST:
1280 case SSH2_MSG_CHANNEL_SUCCESS:
1281 case SSH2_MSG_CHANNEL_FAILURE:
1285 * For anything else we send SSH2_MSG_UNIMPLEMENTED.
1289 struct Packet *pktout;
1290 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
1291 ssh2_pkt_adduint32(pktout, st->incoming_sequence - 1);
1292 ssh2_pkt_send(ssh, pktout);
1297 crFinish(st->pktin);
1300 static void ssh1_pktout_size(struct Packet *pkt, int len)
1304 len += 5; /* type and CRC */
1305 pad = 8 - (len % 8);
1308 pkt->length = len - 5;
1309 if (pkt->maxlen < biglen) {
1310 pkt->maxlen = biglen;
1311 pkt->data = sresize(pkt->data, biglen + 4 + APIEXTRA, unsigned char);
1313 pkt->body = pkt->data + 4 + pad + 1;
1316 static struct Packet *s_wrpkt_start(int type, int len)
1318 struct Packet *pkt = ssh_new_packet();
1319 ssh1_pktout_size(pkt, len);
1321 /* Initialise log omission state */
1327 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt)
1333 * XXX various versions of SC (including 8.8.4) screw up the
1334 * register allocation in this function and use the same register
1335 * (D6) for len and as a temporary, with predictable results. The
1336 * following sledgehammer prevents this.
1342 pkt->body[-1] = pkt->type;
1345 log_packet(ssh->logctx, PKT_OUTGOING, pkt->type,
1346 ssh1_pkt_type(pkt->type),
1347 pkt->body, pkt->length,
1348 pkt->nblanks, pkt->blanks);
1349 sfree(pkt->blanks); pkt->blanks = NULL;
1352 if (ssh->v1_compressing) {
1353 unsigned char *compblk;
1355 zlib_compress_block(ssh->cs_comp_ctx,
1356 pkt->body - 1, pkt->length + 1,
1357 &compblk, &complen);
1358 ssh1_pktout_size(pkt, complen - 1);
1359 memcpy(pkt->body - 1, compblk, complen);
1363 len = pkt->length + 5; /* type and CRC */
1364 pad = 8 - (len % 8);
1367 for (i = 0; i < pad; i++)
1368 pkt->data[i + 4] = random_byte();
1369 crc = crc32_compute(pkt->data + 4, biglen - 4);
1370 PUT_32BIT(pkt->data + biglen, crc);
1371 PUT_32BIT(pkt->data, len);
1374 ssh->cipher->encrypt(ssh->v1_cipher_ctx, pkt->data + 4, biglen);
1379 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1382 len = s_wrpkt_prepare(ssh, pkt);
1383 backlog = sk_write(ssh->s, (char *)pkt->data, len);
1384 if (backlog > SSH_MAX_BACKLOG)
1385 ssh_throttle_all(ssh, 1, backlog);
1388 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1391 len = s_wrpkt_prepare(ssh, pkt);
1392 if (ssh->deferred_len + len > ssh->deferred_size) {
1393 ssh->deferred_size = ssh->deferred_len + len + 128;
1394 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1398 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->data, len);
1399 ssh->deferred_len += len;
1403 * Construct a packet with the specified contents.
1405 static struct Packet *construct_packet(Ssh ssh, int pkttype,
1406 va_list ap1, va_list ap2)
1408 unsigned char *p, *argp, argchar;
1409 unsigned long argint;
1410 int pktlen, argtype, arglen;
1415 while ((argtype = va_arg(ap1, int)) != PKT_END) {
1418 (void) va_arg(ap1, int);
1422 (void) va_arg(ap1, int);
1426 (void) va_arg(ap1, unsigned char *);
1427 arglen = va_arg(ap1, int);
1431 argp = va_arg(ap1, unsigned char *);
1432 arglen = strlen((char *)argp);
1433 pktlen += 4 + arglen;
1436 bn = va_arg(ap1, Bignum);
1437 pktlen += ssh1_bignum_length(bn);
1442 /* ignore this pass */
1449 pkt = s_wrpkt_start(pkttype, pktlen);
1452 while ((argtype = va_arg(ap2, int)) != PKT_END) {
1453 int offset = p - pkt->body, len = 0;
1455 /* Actual fields in the packet */
1457 argint = va_arg(ap2, int);
1458 PUT_32BIT(p, argint);
1462 argchar = (unsigned char) va_arg(ap2, int);
1467 argp = va_arg(ap2, unsigned char *);
1468 arglen = va_arg(ap2, int);
1469 memcpy(p, argp, arglen);
1473 argp = va_arg(ap2, unsigned char *);
1474 arglen = strlen((char *)argp);
1475 PUT_32BIT(p, arglen);
1476 memcpy(p + 4, argp, arglen);
1480 bn = va_arg(ap2, Bignum);
1481 len = ssh1_write_bignum(p, bn);
1483 /* Tokens for modifications to packet logging */
1485 dont_log_password(ssh, pkt, PKTLOG_BLANK);
1488 dont_log_data(ssh, pkt, PKTLOG_OMIT);
1491 end_log_omission(ssh, pkt);
1495 /* Deal with logfile omission, if required. */
1496 if (len && (pkt->logmode != PKTLOG_EMIT)) {
1498 pkt->blanks = sresize(pkt->blanks, pkt->nblanks,
1500 pkt->blanks[pkt->nblanks-1].offset = offset;
1501 pkt->blanks[pkt->nblanks-1].len = len;
1502 pkt->blanks[pkt->nblanks-1].type = pkt->logmode;
1509 static void send_packet(Ssh ssh, int pkttype, ...)
1513 va_start(ap1, pkttype);
1514 va_start(ap2, pkttype);
1515 pkt = construct_packet(ssh, pkttype, ap1, ap2);
1519 ssh_free_packet(pkt);
1522 static void defer_packet(Ssh ssh, int pkttype, ...)
1526 va_start(ap1, pkttype);
1527 va_start(ap2, pkttype);
1528 pkt = construct_packet(ssh, pkttype, ap1, ap2);
1531 s_wrpkt_defer(ssh, pkt);
1532 ssh_free_packet(pkt);
1535 static int ssh_versioncmp(char *a, char *b)
1538 unsigned long av, bv;
1540 av = strtoul(a, &ae, 10);
1541 bv = strtoul(b, &be, 10);
1543 return (av < bv ? -1 : +1);
1548 av = strtoul(ae, &ae, 10);
1549 bv = strtoul(be, &be, 10);
1551 return (av < bv ? -1 : +1);
1556 * Utility routines for putting an SSH-protocol `string' and
1557 * `uint32' into a SHA state.
1560 static void sha_string(SHA_State * s, void *str, int len)
1562 unsigned char lenblk[4];
1563 PUT_32BIT(lenblk, len);
1564 SHA_Bytes(s, lenblk, 4);
1565 SHA_Bytes(s, str, len);
1568 static void sha_uint32(SHA_State * s, unsigned i)
1570 unsigned char intblk[4];
1571 PUT_32BIT(intblk, i);
1572 SHA_Bytes(s, intblk, 4);
1576 * SSH2 packet construction functions.
1578 static void ssh2_pkt_ensure(struct Packet *pkt, int length)
1580 if (pkt->maxlen < length) {
1581 pkt->maxlen = length + 256;
1582 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
1585 static void ssh2_pkt_adddata(struct Packet *pkt, void *data, int len)
1587 if (pkt->logmode != PKTLOG_EMIT) {
1589 pkt->blanks = sresize(pkt->blanks, pkt->nblanks, struct logblank_t);
1590 pkt->blanks[pkt->nblanks-1].offset = pkt->length - 6;
1591 pkt->blanks[pkt->nblanks-1].len = len;
1592 pkt->blanks[pkt->nblanks-1].type = pkt->logmode;
1595 ssh2_pkt_ensure(pkt, pkt->length);
1596 memcpy(pkt->data + pkt->length - len, data, len);
1598 static void ssh2_pkt_addbyte(struct Packet *pkt, unsigned char byte)
1600 ssh2_pkt_adddata(pkt, &byte, 1);
1602 static struct Packet *ssh2_pkt_init(int pkt_type)
1604 struct Packet *pkt = ssh_new_packet();
1606 ssh2_pkt_addbyte(pkt, (unsigned char) pkt_type);
1609 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
1611 ssh2_pkt_adddata(pkt, &value, 1);
1613 static void ssh2_pkt_adduint32(struct Packet *pkt, unsigned long value)
1616 PUT_32BIT(x, value);
1617 ssh2_pkt_adddata(pkt, x, 4);
1619 static void ssh2_pkt_addstring_start(struct Packet *pkt)
1621 ssh2_pkt_adduint32(pkt, 0);
1622 pkt->savedpos = pkt->length;
1624 static void ssh2_pkt_addstring_str(struct Packet *pkt, char *data)
1626 ssh2_pkt_adddata(pkt, data, strlen(data));
1627 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1629 static void ssh2_pkt_addstring_data(struct Packet *pkt, char *data, int len)
1631 ssh2_pkt_adddata(pkt, data, len);
1632 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1634 static void ssh2_pkt_addstring(struct Packet *pkt, char *data)
1636 ssh2_pkt_addstring_start(pkt);
1637 ssh2_pkt_addstring_str(pkt, data);
1639 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
1642 int i, n = (bignum_bitcount(b) + 7) / 8;
1643 p = snewn(n + 1, unsigned char);
1645 fatalbox("out of memory");
1647 for (i = 1; i <= n; i++)
1648 p[i] = bignum_byte(b, n - i);
1650 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1652 memmove(p, p + i, n + 1 - i);
1656 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
1660 p = ssh2_mpint_fmt(b, &len);
1661 ssh2_pkt_addstring_start(pkt);
1662 ssh2_pkt_addstring_data(pkt, (char *)p, len);
1667 * Construct an SSH2 final-form packet: compress it, encrypt it,
1668 * put the MAC on it. Final packet, ready to be sent, is stored in
1669 * pkt->data. Total length is returned.
1671 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
1673 int cipherblk, maclen, padding, i;
1676 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1677 ssh2_pkt_type(ssh->pkt_ctx, pkt->data[5]),
1678 pkt->data + 6, pkt->length - 6,
1679 pkt->nblanks, pkt->blanks);
1680 sfree(pkt->blanks); pkt->blanks = NULL;
1684 * Compress packet payload.
1687 unsigned char *newpayload;
1690 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
1692 &newpayload, &newlen)) {
1694 ssh2_pkt_adddata(pkt, newpayload, newlen);
1700 * Add padding. At least four bytes, and must also bring total
1701 * length (minus MAC) up to a multiple of the block size.
1703 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
1704 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1707 (cipherblk - (pkt->length + padding) % cipherblk) % cipherblk;
1708 maclen = ssh->csmac ? ssh->csmac->len : 0;
1709 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
1710 pkt->data[4] = padding;
1711 for (i = 0; i < padding; i++)
1712 pkt->data[pkt->length + i] = random_byte();
1713 PUT_32BIT(pkt->data, pkt->length + padding - 4);
1715 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
1716 pkt->length + padding,
1717 ssh->v2_outgoing_sequence);
1718 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
1721 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
1722 pkt->data, pkt->length + padding);
1724 /* Ready-to-send packet starts at pkt->data. We return length. */
1725 return pkt->length + padding + maclen;
1729 * Construct and send an SSH2 packet immediately.
1731 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
1735 len = ssh2_pkt_construct(ssh, pkt);
1736 backlog = sk_write(ssh->s, (char *)pkt->data, len);
1737 if (backlog > SSH_MAX_BACKLOG)
1738 ssh_throttle_all(ssh, 1, backlog);
1739 ssh_free_packet(pkt);
1743 * Construct an SSH2 packet and add it to a deferred data block.
1744 * Useful for sending multiple packets in a single sk_write() call,
1745 * to prevent a traffic-analysing listener from being able to work
1746 * out the length of any particular packet (such as the password
1749 * Note that because SSH2 sequence-numbers its packets, this can
1750 * NOT be used as an m4-style `defer' allowing packets to be
1751 * constructed in one order and sent in another.
1753 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
1755 int len = ssh2_pkt_construct(ssh, pkt);
1756 if (ssh->deferred_len + len > ssh->deferred_size) {
1757 ssh->deferred_size = ssh->deferred_len + len + 128;
1758 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1762 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->data, len);
1763 ssh->deferred_len += len;
1764 ssh_free_packet(pkt);
1768 * Send the whole deferred data block constructed by
1769 * ssh2_pkt_defer() or SSH1's defer_packet().
1771 static void ssh_pkt_defersend(Ssh ssh)
1774 backlog = sk_write(ssh->s, (char *)ssh->deferred_send_data,
1776 ssh->deferred_len = ssh->deferred_size = 0;
1777 sfree(ssh->deferred_send_data);
1778 ssh->deferred_send_data = NULL;
1779 if (backlog > SSH_MAX_BACKLOG)
1780 ssh_throttle_all(ssh, 1, backlog);
1784 void bndebug(char *string, Bignum b)
1788 p = ssh2_mpint_fmt(b, &len);
1789 debug(("%s", string));
1790 for (i = 0; i < len; i++)
1791 debug((" %02x", p[i]));
1797 static void sha_mpint(SHA_State * s, Bignum b)
1801 p = ssh2_mpint_fmt(b, &len);
1802 sha_string(s, p, len);
1807 * Packet decode functions for both SSH1 and SSH2.
1809 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
1811 unsigned long value;
1812 if (pkt->length - pkt->savedpos < 4)
1813 return 0; /* arrgh, no way to decline (FIXME?) */
1814 value = GET_32BIT(pkt->body + pkt->savedpos);
1818 static int ssh2_pkt_getbool(struct Packet *pkt)
1820 unsigned long value;
1821 if (pkt->length - pkt->savedpos < 1)
1822 return 0; /* arrgh, no way to decline (FIXME?) */
1823 value = pkt->body[pkt->savedpos] != 0;
1827 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
1832 if (pkt->length - pkt->savedpos < 4)
1834 len = GET_32BIT(pkt->body + pkt->savedpos);
1839 if (pkt->length - pkt->savedpos < *length)
1841 *p = (char *)(pkt->body + pkt->savedpos);
1842 pkt->savedpos += *length;
1844 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
1846 if (pkt->length - pkt->savedpos < length)
1848 pkt->savedpos += length;
1849 return pkt->body + (pkt->savedpos - length);
1851 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
1852 unsigned char **keystr)
1856 j = makekey(pkt->body + pkt->savedpos,
1857 pkt->length - pkt->savedpos,
1864 assert(pkt->savedpos < pkt->length);
1868 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
1873 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
1874 pkt->length - pkt->savedpos, &b);
1882 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
1888 ssh_pkt_getstring(pkt, &p, &length);
1893 b = bignum_from_bytes((unsigned char *)p, length);
1898 * Helper function to add an SSH2 signature blob to a packet.
1899 * Expects to be shown the public key blob as well as the signature
1900 * blob. Normally works just like ssh2_pkt_addstring, but will
1901 * fiddle with the signature packet if necessary for
1902 * BUG_SSH2_RSA_PADDING.
1904 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
1905 void *pkblob_v, int pkblob_len,
1906 void *sigblob_v, int sigblob_len)
1908 unsigned char *pkblob = (unsigned char *)pkblob_v;
1909 unsigned char *sigblob = (unsigned char *)sigblob_v;
1911 /* dmemdump(pkblob, pkblob_len); */
1912 /* dmemdump(sigblob, sigblob_len); */
1915 * See if this is in fact an ssh-rsa signature and a buggy
1916 * server; otherwise we can just do this the easy way.
1918 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) &&
1919 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
1920 int pos, len, siglen;
1923 * Find the byte length of the modulus.
1926 pos = 4+7; /* skip over "ssh-rsa" */
1927 pos += 4 + GET_32BIT(pkblob+pos); /* skip over exponent */
1928 len = GET_32BIT(pkblob+pos); /* find length of modulus */
1929 pos += 4; /* find modulus itself */
1930 while (len > 0 && pkblob[pos] == 0)
1932 /* debug(("modulus length is %d\n", len)); */
1935 * Now find the signature integer.
1937 pos = 4+7; /* skip over "ssh-rsa" */
1938 siglen = GET_32BIT(sigblob+pos);
1939 /* debug(("signature length is %d\n", siglen)); */
1941 if (len != siglen) {
1942 unsigned char newlen[4];
1943 ssh2_pkt_addstring_start(pkt);
1944 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
1945 /* dmemdump(sigblob, pos); */
1946 pos += 4; /* point to start of actual sig */
1947 PUT_32BIT(newlen, len);
1948 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
1949 /* dmemdump(newlen, 4); */
1951 while (len-- > siglen) {
1952 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
1953 /* dmemdump(newlen, 1); */
1955 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
1956 /* dmemdump(sigblob+pos, siglen); */
1960 /* Otherwise fall through and do it the easy way. */
1963 ssh2_pkt_addstring_start(pkt);
1964 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
1968 * Examine the remote side's version string and compare it against
1969 * a list of known buggy implementations.
1971 static void ssh_detect_bugs(Ssh ssh, char *vstring)
1973 char *imp; /* pointer to implementation part */
1975 imp += strcspn(imp, "-");
1977 imp += strcspn(imp, "-");
1980 ssh->remote_bugs = 0;
1982 if (ssh->cfg.sshbug_ignore1 == FORCE_ON ||
1983 (ssh->cfg.sshbug_ignore1 == AUTO &&
1984 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
1985 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
1986 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
1987 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
1989 * These versions don't support SSH1_MSG_IGNORE, so we have
1990 * to use a different defence against password length
1993 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
1994 logevent("We believe remote version has SSH1 ignore bug");
1997 if (ssh->cfg.sshbug_plainpw1 == FORCE_ON ||
1998 (ssh->cfg.sshbug_plainpw1 == AUTO &&
1999 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2001 * These versions need a plain password sent; they can't
2002 * handle having a null and a random length of data after
2005 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2006 logevent("We believe remote version needs a plain SSH1 password");
2009 if (ssh->cfg.sshbug_rsa1 == FORCE_ON ||
2010 (ssh->cfg.sshbug_rsa1 == AUTO &&
2011 (!strcmp(imp, "Cisco-1.25")))) {
2013 * These versions apparently have no clue whatever about
2014 * RSA authentication and will panic and die if they see
2015 * an AUTH_RSA message.
2017 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2018 logevent("We believe remote version can't handle RSA authentication");
2021 if (ssh->cfg.sshbug_hmac2 == FORCE_ON ||
2022 (ssh->cfg.sshbug_hmac2 == AUTO &&
2023 !wc_match("* VShell", imp) &&
2024 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2025 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2026 wc_match("2.1 *", imp)))) {
2028 * These versions have the HMAC bug.
2030 ssh->remote_bugs |= BUG_SSH2_HMAC;
2031 logevent("We believe remote version has SSH2 HMAC bug");
2034 if (ssh->cfg.sshbug_derivekey2 == FORCE_ON ||
2035 (ssh->cfg.sshbug_derivekey2 == AUTO &&
2036 !wc_match("* VShell", imp) &&
2037 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2039 * These versions have the key-derivation bug (failing to
2040 * include the literal shared secret in the hashes that
2041 * generate the keys).
2043 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2044 logevent("We believe remote version has SSH2 key-derivation bug");
2047 if (ssh->cfg.sshbug_rsapad2 == FORCE_ON ||
2048 (ssh->cfg.sshbug_rsapad2 == AUTO &&
2049 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2050 wc_match("OpenSSH_3.[0-2]*", imp)))) {
2052 * These versions have the SSH2 RSA padding bug.
2054 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2055 logevent("We believe remote version has SSH2 RSA padding bug");
2058 if (ssh->cfg.sshbug_pksessid2 == FORCE_ON ||
2059 (ssh->cfg.sshbug_pksessid2 == AUTO &&
2060 wc_match("OpenSSH_2.[0-2]*", imp))) {
2062 * These versions have the SSH2 session-ID bug in
2063 * public-key authentication.
2065 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2066 logevent("We believe remote version has SSH2 public-key-session-ID bug");
2069 if (ssh->cfg.sshbug_dhgex2 == FORCE_ON) {
2071 * User specified the SSH2 DH GEX bug.
2073 ssh->remote_bugs |= BUG_SSH2_DH_GEX;
2074 logevent("We believe remote version has SSH2 DH group exchange bug");
2078 static int do_ssh_init(Ssh ssh, unsigned char c)
2080 struct do_ssh_init_state {
2088 crState(do_ssh_init_state);
2090 crBegin(ssh->do_ssh_init_crstate);
2092 /* Search for the string "SSH-" in the input. */
2095 static const int transS[] = { 1, 2, 2, 1 };
2096 static const int transH[] = { 0, 0, 3, 0 };
2097 static const int transminus[] = { 0, 0, 0, -1 };
2099 s->i = transS[s->i];
2101 s->i = transH[s->i];
2103 s->i = transminus[s->i];
2108 crReturn(1); /* get another character */
2112 s->vstring = snewn(s->vstrsize, char);
2113 strcpy(s->vstring, "SSH-");
2117 crReturn(1); /* get another char */
2118 if (s->vslen >= s->vstrsize - 1) {
2120 s->vstring = sresize(s->vstring, s->vstrsize, char);
2122 s->vstring[s->vslen++] = c;
2125 s->version[s->i] = '\0';
2127 } else if (s->i < sizeof(s->version) - 1)
2128 s->version[s->i++] = c;
2129 } else if (c == '\012')
2133 ssh->agentfwd_enabled = FALSE;
2134 ssh->rdpkt2_state.incoming_sequence = 0;
2136 s->vstring[s->vslen] = 0;
2137 s->vstring[strcspn(s->vstring, "\r\n")] = '\0';/* remove EOL chars */
2140 vlog = snewn(20 + s->vslen, char);
2141 sprintf(vlog, "Server version: %s", s->vstring);
2145 ssh_detect_bugs(ssh, s->vstring);
2148 * Decide which SSH protocol version to support.
2151 /* Anything strictly below "2.0" means protocol 1 is supported. */
2152 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
2153 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2154 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
2156 if (ssh->cfg.sshprot == 0 && !s->proto1) {
2157 bombout(("SSH protocol version 1 required by user but not provided by server"));
2160 if (ssh->cfg.sshprot == 3 && !s->proto2) {
2161 bombout(("SSH protocol version 2 required by user but not provided by server"));
2165 if (s->proto2 && (ssh->cfg.sshprot >= 2 || !s->proto1)) {
2169 char verstring[80], vlog[100];
2170 sprintf(verstring, "SSH-2.0-%s", sshver);
2171 SHA_Init(&ssh->exhashbase);
2173 * Hash our version string and their version string.
2175 sha_string(&ssh->exhashbase, verstring, strlen(verstring));
2176 sha_string(&ssh->exhashbase, s->vstring, strcspn(s->vstring, "\r\n"));
2177 sprintf(vlog, "We claim version: %s", verstring);
2179 strcat(verstring, "\012");
2180 logevent("Using SSH protocol version 2");
2181 sk_write(ssh->s, verstring, strlen(verstring));
2182 ssh->protocol = ssh2_protocol;
2184 ssh->s_rdpkt = ssh2_rdpkt;
2189 char verstring[80], vlog[100];
2190 sprintf(verstring, "SSH-%s-%s",
2191 (ssh_versioncmp(s->version, "1.5") <= 0 ? s->version : "1.5"),
2193 sprintf(vlog, "We claim version: %s", verstring);
2195 strcat(verstring, "\012");
2197 logevent("Using SSH protocol version 1");
2198 sk_write(ssh->s, verstring, strlen(verstring));
2199 ssh->protocol = ssh1_protocol;
2201 ssh->s_rdpkt = ssh1_rdpkt;
2203 update_specials_menu(ssh->frontend);
2204 ssh->state = SSH_STATE_BEFORE_SIZE;
2211 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
2213 crBegin(ssh->ssh_gotdata_crstate);
2216 * To begin with, feed the characters one by one to the
2217 * protocol initialisation / selection function do_ssh_init().
2218 * When that returns 0, we're done with the initial greeting
2219 * exchange and can move on to packet discipline.
2222 int ret; /* need not be kept across crReturn */
2224 crReturnV; /* more data please */
2225 ret = do_ssh_init(ssh, *data);
2233 * We emerge from that loop when the initial negotiation is
2234 * over and we have selected an s_rdpkt function. Now pass
2235 * everything to s_rdpkt, and then pass the resulting packets
2236 * to the proper protocol handler.
2241 while (datalen > 0) {
2242 struct Packet *pktin = ssh->s_rdpkt(ssh, &data, &datalen);
2244 ssh->protocol(ssh, NULL, 0, pktin);
2245 ssh_free_packet(pktin);
2247 if (ssh->state == SSH_STATE_CLOSED)
2255 static void ssh_do_close(Ssh ssh)
2258 struct ssh_channel *c;
2260 ssh->state = SSH_STATE_CLOSED;
2266 * Now we must shut down any port and X forwardings going
2267 * through this connection.
2269 if (ssh->channels) {
2270 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
2273 x11_close(c->u.x11.s);
2276 pfd_close(c->u.pfd.s);
2279 del234(ssh->channels, c);
2280 if (ssh->version == 2)
2281 bufchain_clear(&c->v.v2.outbuffer);
2287 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
2290 Ssh ssh = (Ssh) plug;
2293 /* A socket error has occurred. */
2294 logevent(error_msg);
2295 connection_fatal(ssh->frontend, "%s", error_msg);
2297 /* Otherwise, the remote side closed the connection normally. */
2302 static int ssh_receive(Plug plug, int urgent, char *data, int len)
2304 Ssh ssh = (Ssh) plug;
2305 ssh_gotdata(ssh, (unsigned char *)data, len);
2306 if (ssh->state == SSH_STATE_CLOSED) {
2313 static void ssh_sent(Plug plug, int bufsize)
2315 Ssh ssh = (Ssh) plug;
2317 * If the send backlog on the SSH socket itself clears, we
2318 * should unthrottle the whole world if it was throttled.
2320 if (bufsize < SSH_MAX_BACKLOG)
2321 ssh_throttle_all(ssh, 0, bufsize);
2325 * Connect to specified host and port.
2326 * Returns an error message, or NULL on success.
2327 * Also places the canonical host name into `realhost'. It must be
2328 * freed by the caller.
2330 static const char *connect_to_host(Ssh ssh, char *host, int port,
2331 char **realhost, int nodelay, int keepalive)
2333 static const struct plug_function_table fn_table = {
2343 ssh->savedhost = snewn(1 + strlen(host), char);
2344 if (!ssh->savedhost)
2345 fatalbox("Out of memory");
2346 strcpy(ssh->savedhost, host);
2349 port = 22; /* default ssh port */
2350 ssh->savedport = port;
2355 logeventf(ssh, "Looking up host \"%s\"", host);
2356 addr = name_lookup(host, port, realhost, &ssh->cfg);
2357 if ((err = sk_addr_error(addr)) != NULL) {
2367 sk_getaddr(addr, addrbuf, 100);
2368 logeventf(ssh, "Connecting to %s port %d", addrbuf, port);
2370 ssh->fn = &fn_table;
2371 ssh->s = new_connection(addr, *realhost, port,
2372 0, 1, nodelay, keepalive, (Plug) ssh, &ssh->cfg);
2373 if ((err = sk_socket_error(ssh->s)) != NULL) {
2382 * Throttle or unthrottle the SSH connection.
2384 static void ssh1_throttle(Ssh ssh, int adjust)
2386 int old_count = ssh->v1_throttle_count;
2387 ssh->v1_throttle_count += adjust;
2388 assert(ssh->v1_throttle_count >= 0);
2389 if (ssh->v1_throttle_count && !old_count) {
2390 sk_set_frozen(ssh->s, 1);
2391 } else if (!ssh->v1_throttle_count && old_count) {
2392 sk_set_frozen(ssh->s, 0);
2397 * Throttle or unthrottle _all_ local data streams (for when sends
2398 * on the SSH connection itself back up).
2400 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
2403 struct ssh_channel *c;
2405 if (enable == ssh->throttled_all)
2407 ssh->throttled_all = enable;
2408 ssh->overall_bufsize = bufsize;
2411 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
2413 case CHAN_MAINSESSION:
2415 * This is treated separately, outside the switch.
2419 x11_override_throttle(c->u.x11.s, enable);
2422 /* Agent channels require no buffer management. */
2425 pfd_override_throttle(c->u.pfd.s, enable);
2432 * Username and password input, abstracted off into routines
2433 * reusable in several places - even between SSH1 and SSH2.
2436 /* Set up a username or password input loop on a given buffer. */
2437 static void setup_userpass_input(Ssh ssh, char *buffer, int buflen, int echo)
2439 ssh->userpass_input_buffer = buffer;
2440 ssh->userpass_input_buflen = buflen;
2441 ssh->userpass_input_bufpos = 0;
2442 ssh->userpass_input_echo = echo;
2446 * Process some terminal data in the course of username/password
2447 * input. Returns >0 for success (line of input returned in
2448 * buffer), <0 for failure (user hit ^C/^D, bomb out and exit), 0
2449 * for inconclusive (keep waiting for more input please).
2451 static int process_userpass_input(Ssh ssh, unsigned char *in, int inlen)
2456 switch (c = *in++) {
2459 ssh->userpass_input_buffer[ssh->userpass_input_bufpos] = 0;
2460 ssh->userpass_input_buffer[ssh->userpass_input_buflen-1] = 0;
2465 if (ssh->userpass_input_bufpos > 0) {
2466 if (ssh->userpass_input_echo)
2467 c_write_str(ssh, "\b \b");
2468 ssh->userpass_input_bufpos--;
2473 while (ssh->userpass_input_bufpos > 0) {
2474 if (ssh->userpass_input_echo)
2475 c_write_str(ssh, "\b \b");
2476 ssh->userpass_input_bufpos--;
2485 * This simplistic check for printability is disabled
2486 * when we're doing password input, because some people
2487 * have control characters in their passwords.o
2489 if ((!ssh->userpass_input_echo ||
2490 (c >= ' ' && c <= '~') ||
2491 ((unsigned char) c >= 160))
2492 && ssh->userpass_input_bufpos < ssh->userpass_input_buflen-1) {
2493 ssh->userpass_input_buffer[ssh->userpass_input_bufpos++] = c;
2494 if (ssh->userpass_input_echo)
2495 c_write(ssh, &c, 1);
2503 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
2505 Ssh ssh = (Ssh) sshv;
2507 ssh->agent_response = reply;
2508 ssh->agent_response_len = replylen;
2510 if (ssh->version == 1)
2511 do_ssh1_login(ssh, NULL, -1, NULL);
2513 do_ssh2_authconn(ssh, NULL, -1, NULL);
2516 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
2518 struct ssh_channel *c = (struct ssh_channel *)cv;
2520 void *sentreply = reply;
2523 /* Fake SSH_AGENT_FAILURE. */
2524 sentreply = "\0\0\0\1\5";
2527 if (ssh->version == 2) {
2528 ssh2_add_channel_data(c, sentreply, replylen);
2531 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
2532 PKT_INT, c->remoteid,
2535 PKT_DATA, sentreply, replylen,
2544 * Handle the key exchange and user authentication phases.
2546 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
2547 struct Packet *pktin)
2550 unsigned char cookie[8], *ptr;
2551 struct RSAKey servkey, hostkey;
2552 struct MD5Context md5c;
2553 struct do_ssh1_login_state {
2555 unsigned char *rsabuf, *keystr1, *keystr2;
2556 unsigned long supported_ciphers_mask, supported_auths_mask;
2557 int tried_publickey, tried_agent;
2558 int tis_auth_refused, ccard_auth_refused;
2559 unsigned char session_id[16];
2562 void *publickey_blob;
2563 int publickey_bloblen;
2569 unsigned char request[5], *response, *p;
2578 crState(do_ssh1_login_state);
2580 crBegin(ssh->do_ssh1_login_crstate);
2585 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
2586 bombout(("Public key packet not received"));
2590 logevent("Received public keys");
2592 ptr = ssh_pkt_getdata(pktin, 8);
2594 bombout(("SSH1 public key packet stopped before random cookie"));
2597 memcpy(cookie, ptr, 8);
2599 if (!ssh1_pkt_getrsakey(pktin, &servkey, &s->keystr1) ||
2600 !ssh1_pkt_getrsakey(pktin, &hostkey, &s->keystr2)) {
2601 bombout(("Failed to read SSH1 public keys from public key packet"));
2606 * Log the host key fingerprint.
2610 logevent("Host key fingerprint is:");
2611 strcpy(logmsg, " ");
2612 hostkey.comment = NULL;
2613 rsa_fingerprint(logmsg + strlen(logmsg),
2614 sizeof(logmsg) - strlen(logmsg), &hostkey);
2618 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
2619 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
2620 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
2622 ssh->v1_local_protoflags =
2623 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
2624 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
2627 MD5Update(&md5c, s->keystr2, hostkey.bytes);
2628 MD5Update(&md5c, s->keystr1, servkey.bytes);
2629 MD5Update(&md5c, cookie, 8);
2630 MD5Final(s->session_id, &md5c);
2632 for (i = 0; i < 32; i++)
2633 ssh->session_key[i] = random_byte();
2636 * Verify that the `bits' and `bytes' parameters match.
2638 if (hostkey.bits > hostkey.bytes * 8 ||
2639 servkey.bits > servkey.bytes * 8) {
2640 bombout(("SSH1 public keys were badly formatted"));
2644 s->len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
2646 s->rsabuf = snewn(s->len, unsigned char);
2648 fatalbox("Out of memory");
2651 * Verify the host key.
2655 * First format the key into a string.
2657 int len = rsastr_len(&hostkey);
2658 char fingerprint[100];
2659 char *keystr = snewn(len, char);
2661 fatalbox("Out of memory");
2662 rsastr_fmt(keystr, &hostkey);
2663 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
2664 verify_ssh_host_key(ssh->frontend,
2665 ssh->savedhost, ssh->savedport, "rsa", keystr,
2670 for (i = 0; i < 32; i++) {
2671 s->rsabuf[i] = ssh->session_key[i];
2673 s->rsabuf[i] ^= s->session_id[i];
2676 if (hostkey.bytes > servkey.bytes) {
2677 ret = rsaencrypt(s->rsabuf, 32, &servkey);
2679 ret = rsaencrypt(s->rsabuf, servkey.bytes, &hostkey);
2681 ret = rsaencrypt(s->rsabuf, 32, &hostkey);
2683 ret = rsaencrypt(s->rsabuf, hostkey.bytes, &servkey);
2686 bombout(("SSH1 public key encryptions failed due to bad formatting"));
2690 logevent("Encrypted session key");
2693 int cipher_chosen = 0, warn = 0;
2694 char *cipher_string = NULL;
2696 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
2697 int next_cipher = ssh->cfg.ssh_cipherlist[i];
2698 if (next_cipher == CIPHER_WARN) {
2699 /* If/when we choose a cipher, warn about it */
2701 } else if (next_cipher == CIPHER_AES) {
2702 /* XXX Probably don't need to mention this. */
2703 logevent("AES not supported in SSH1, skipping");
2705 switch (next_cipher) {
2706 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
2707 cipher_string = "3DES"; break;
2708 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
2709 cipher_string = "Blowfish"; break;
2710 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
2711 cipher_string = "single-DES"; break;
2713 if (s->supported_ciphers_mask & (1 << s->cipher_type))
2717 if (!cipher_chosen) {
2718 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
2719 bombout(("Server violates SSH 1 protocol by not "
2720 "supporting 3DES encryption"));
2722 /* shouldn't happen */
2723 bombout(("No supported ciphers found"));
2727 /* Warn about chosen cipher if necessary. */
2729 askcipher(ssh->frontend, cipher_string, 0);
2732 switch (s->cipher_type) {
2733 case SSH_CIPHER_3DES:
2734 logevent("Using 3DES encryption");
2736 case SSH_CIPHER_DES:
2737 logevent("Using single-DES encryption");
2739 case SSH_CIPHER_BLOWFISH:
2740 logevent("Using Blowfish encryption");
2744 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
2745 PKT_CHAR, s->cipher_type,
2746 PKT_DATA, cookie, 8,
2747 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
2748 PKT_DATA, s->rsabuf, s->len,
2749 PKT_INT, ssh->v1_local_protoflags, PKT_END);
2751 logevent("Trying to enable encryption...");
2755 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
2756 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
2758 ssh->v1_cipher_ctx = ssh->cipher->make_context();
2759 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
2760 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
2762 ssh->crcda_ctx = crcda_make_context();
2763 logevent("Installing CRC compensation attack detector");
2765 if (servkey.modulus) {
2766 sfree(servkey.modulus);
2767 servkey.modulus = NULL;
2769 if (servkey.exponent) {
2770 sfree(servkey.exponent);
2771 servkey.exponent = NULL;
2773 if (hostkey.modulus) {
2774 sfree(hostkey.modulus);
2775 hostkey.modulus = NULL;
2777 if (hostkey.exponent) {
2778 sfree(hostkey.exponent);
2779 hostkey.exponent = NULL;
2783 if (pktin->type != SSH1_SMSG_SUCCESS) {
2784 bombout(("Encryption not successfully enabled"));
2788 logevent("Successfully started encryption");
2792 if (!*ssh->cfg.username) {
2793 if (ssh_get_line && !ssh_getline_pw_only) {
2794 if (!ssh_get_line("login as: ",
2795 s->username, sizeof(s->username), FALSE)) {
2797 * get_line failed to get a username.
2800 logevent("No username provided. Abandoning session.");
2801 ssh_closing((Plug)ssh, NULL, 0, 0);
2805 int ret; /* need not be kept over crReturn */
2806 c_write_str(ssh, "login as: ");
2809 setup_userpass_input(ssh, s->username, sizeof(s->username), 1);
2811 crWaitUntil(!pktin);
2812 ret = process_userpass_input(ssh, in, inlen);
2816 c_write_str(ssh, "\r\n");
2819 strncpy(s->username, ssh->cfg.username, sizeof(s->username));
2820 s->username[sizeof(s->username)-1] = '\0';
2823 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, s->username, PKT_END);
2825 char userlog[22 + sizeof(s->username)];
2826 sprintf(userlog, "Sent username \"%s\"", s->username);
2828 if (flags & FLAG_INTERACTIVE &&
2829 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
2830 strcat(userlog, "\r\n");
2831 c_write_str(ssh, userlog);
2838 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA)) {
2839 /* We must not attempt PK auth. Pretend we've already tried it. */
2840 s->tried_publickey = s->tried_agent = 1;
2842 s->tried_publickey = s->tried_agent = 0;
2844 s->tis_auth_refused = s->ccard_auth_refused = 0;
2845 /* Load the public half of ssh->cfg.keyfile so we notice if it's in Pageant */
2846 if (!filename_is_null(ssh->cfg.keyfile)) {
2847 if (!rsakey_pubblob(&ssh->cfg.keyfile,
2848 &s->publickey_blob, &s->publickey_bloblen, NULL))
2849 s->publickey_blob = NULL;
2851 s->publickey_blob = NULL;
2853 while (pktin->type == SSH1_SMSG_FAILURE) {
2854 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
2856 if (agent_exists() && !s->tried_agent) {
2858 * Attempt RSA authentication using Pageant.
2864 logevent("Pageant is running. Requesting keys.");
2866 /* Request the keys held by the agent. */
2867 PUT_32BIT(s->request, 1);
2868 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
2869 if (!agent_query(s->request, 5, &r, &s->responselen,
2870 ssh_agent_callback, ssh)) {
2874 bombout(("Unexpected data from server while waiting"
2875 " for agent response"));
2878 } while (pktin || inlen > 0);
2879 r = ssh->agent_response;
2880 s->responselen = ssh->agent_response_len;
2882 s->response = (unsigned char *) r;
2883 if (s->response && s->responselen >= 5 &&
2884 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
2885 s->p = s->response + 5;
2886 s->nkeys = GET_32BIT(s->p);
2890 sprintf(buf, "Pageant has %d SSH1 keys", s->nkeys);
2893 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
2896 sprintf(buf, "Trying Pageant key #%d", s->keyi);
2899 if (s->publickey_blob &&
2900 !memcmp(s->p, s->publickey_blob,
2901 s->publickey_bloblen)) {
2902 logevent("This key matches configured key file");
2903 s->tried_publickey = 1;
2908 do { /* do while (0) to make breaking easy */
2909 n = ssh1_read_bignum
2910 (s->p, s->responselen-(s->p-s->response),
2915 n = ssh1_read_bignum
2916 (s->p, s->responselen-(s->p-s->response),
2921 if (s->responselen - (s->p-s->response) < 4)
2923 s->commentlen = GET_32BIT(s->p);
2925 if (s->responselen - (s->p-s->response) <
2928 s->commentp = (char *)s->p;
2929 s->p += s->commentlen;
2933 logevent("Pageant key list packet was truncated");
2937 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
2938 PKT_BIGNUM, s->key.modulus, PKT_END);
2940 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
2941 logevent("Key refused");
2944 logevent("Received RSA challenge");
2945 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
2946 bombout(("Server's RSA challenge was badly formatted"));
2951 char *agentreq, *q, *ret;
2954 len = 1 + 4; /* message type, bit count */
2955 len += ssh1_bignum_length(s->key.exponent);
2956 len += ssh1_bignum_length(s->key.modulus);
2957 len += ssh1_bignum_length(s->challenge);
2958 len += 16; /* session id */
2959 len += 4; /* response format */
2960 agentreq = snewn(4 + len, char);
2961 PUT_32BIT(agentreq, len);
2963 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
2964 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
2966 q += ssh1_write_bignum(q, s->key.exponent);
2967 q += ssh1_write_bignum(q, s->key.modulus);
2968 q += ssh1_write_bignum(q, s->challenge);
2969 memcpy(q, s->session_id, 16);
2971 PUT_32BIT(q, 1); /* response format */
2972 if (!agent_query(agentreq, len + 4, &vret, &retlen,
2973 ssh_agent_callback, ssh)) {
2978 bombout(("Unexpected data from server"
2979 " while waiting for agent"
2983 } while (pktin || inlen > 0);
2984 vret = ssh->agent_response;
2985 retlen = ssh->agent_response_len;
2990 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
2991 logevent("Sending Pageant's response");
2992 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
2993 PKT_DATA, ret + 5, 16,
2997 if (pktin->type == SSH1_SMSG_SUCCESS) {
2999 ("Pageant's response accepted");
3000 if (flags & FLAG_VERBOSE) {
3001 c_write_str(ssh, "Authenticated using"
3003 c_write(ssh, s->commentp,
3005 c_write_str(ssh, "\" from agent\r\n");
3010 ("Pageant's response not accepted");
3013 ("Pageant failed to answer challenge");
3017 logevent("No reply received from Pageant");
3020 freebn(s->key.exponent);
3021 freebn(s->key.modulus);
3022 freebn(s->challenge);
3031 if (!filename_is_null(ssh->cfg.keyfile) && !s->tried_publickey)
3032 s->pwpkt_type = SSH1_CMSG_AUTH_RSA;
3034 if (ssh->cfg.try_tis_auth &&
3035 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
3036 !s->tis_auth_refused) {
3037 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
3038 logevent("Requested TIS authentication");
3039 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
3041 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
3042 logevent("TIS authentication declined");
3043 if (flags & FLAG_INTERACTIVE)
3044 c_write_str(ssh, "TIS authentication refused.\r\n");
3045 s->tis_auth_refused = 1;
3051 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3053 bombout(("TIS challenge packet was badly formed"));
3056 logevent("Received TIS challenge");
3057 if (challengelen > sizeof(s->prompt) - 1)
3058 challengelen = sizeof(s->prompt) - 1;/* prevent overrun */
3059 memcpy(s->prompt, challenge, challengelen);
3060 /* Prompt heuristic comes from OpenSSH */
3061 strncpy(s->prompt + challengelen,
3062 memchr(s->prompt, '\n', challengelen) ?
3063 "": "\r\nResponse: ",
3064 (sizeof s->prompt) - challengelen);
3065 s->prompt[(sizeof s->prompt) - 1] = '\0';
3068 if (ssh->cfg.try_tis_auth &&
3069 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
3070 !s->ccard_auth_refused) {
3071 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
3072 logevent("Requested CryptoCard authentication");
3073 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
3075 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
3076 logevent("CryptoCard authentication declined");
3077 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
3078 s->ccard_auth_refused = 1;
3084 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3086 bombout(("CryptoCard challenge packet was badly formed"));
3089 logevent("Received CryptoCard challenge");
3090 if (challengelen > sizeof(s->prompt) - 1)
3091 challengelen = sizeof(s->prompt) - 1;/* prevent overrun */
3092 memcpy(s->prompt, challenge, challengelen);
3093 strncpy(s->prompt + challengelen,
3094 memchr(s->prompt, '\n', challengelen) ?
3095 "" : "\r\nResponse: ",
3096 sizeof(s->prompt) - challengelen);
3097 s->prompt[sizeof(s->prompt) - 1] = '\0';
3100 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
3101 sprintf(s->prompt, "%.90s@%.90s's password: ",
3102 s->username, ssh->savedhost);
3104 if (s->pwpkt_type == SSH1_CMSG_AUTH_RSA) {
3105 char *comment = NULL;
3108 if (flags & FLAG_VERBOSE)
3109 c_write_str(ssh, "Trying public key authentication.\r\n");
3110 logeventf(ssh, "Trying public key \"%s\"",
3111 filename_to_str(&ssh->cfg.keyfile));
3112 type = key_type(&ssh->cfg.keyfile);
3113 if (type != SSH_KEYTYPE_SSH1) {
3114 sprintf(msgbuf, "Key is of wrong type (%s)",
3115 key_type_to_str(type));
3117 c_write_str(ssh, msgbuf);
3118 c_write_str(ssh, "\r\n");
3119 s->tried_publickey = 1;
3122 if (!rsakey_encrypted(&ssh->cfg.keyfile, &comment)) {
3123 if (flags & FLAG_VERBOSE)
3124 c_write_str(ssh, "No passphrase required.\r\n");
3127 sprintf(s->prompt, "Passphrase for key \"%.100s\": ", comment);
3132 * Show password prompt, having first obtained it via a TIS
3133 * or CryptoCard exchange if we're doing TIS or CryptoCard
3137 if (!ssh_get_line(s->prompt, s->password,
3138 sizeof(s->password), TRUE)) {
3140 * get_line failed to get a password (for example
3141 * because one was supplied on the command line
3142 * which has already failed to work). Terminate.
3144 send_packet(ssh, SSH1_MSG_DISCONNECT,
3145 PKT_STR, "No more passwords available to try",
3147 logevent("Unable to authenticate");
3148 connection_fatal(ssh->frontend, "Unable to authenticate");
3149 ssh_closing((Plug)ssh, NULL, 0, 0);
3153 /* Prompt may have come from server. We've munged it a bit, so
3154 * we know it to be zero-terminated at least once. */
3155 int ret; /* need not be saved over crReturn */
3156 c_write_untrusted(ssh, s->prompt, strlen(s->prompt));
3159 setup_userpass_input(ssh, s->password, sizeof(s->password), 0);
3161 crWaitUntil(!pktin);
3162 ret = process_userpass_input(ssh, in, inlen);
3166 c_write_str(ssh, "\r\n");
3170 if (s->pwpkt_type == SSH1_CMSG_AUTH_RSA) {
3172 * Try public key authentication with the specified
3175 s->tried_publickey = 1;
3178 const char *error = NULL;
3179 int ret = loadrsakey(&ssh->cfg.keyfile, &s->key, s->password,
3182 c_write_str(ssh, "Couldn't load private key from ");
3183 c_write_str(ssh, filename_to_str(&ssh->cfg.keyfile));
3184 c_write_str(ssh, " (");
3185 c_write_str(ssh, error);
3186 c_write_str(ssh, ").\r\n");
3187 continue; /* go and try password */
3190 c_write_str(ssh, "Wrong passphrase.\r\n");
3191 s->tried_publickey = 0;
3192 continue; /* try again */
3197 * Send a public key attempt.
3199 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3200 PKT_BIGNUM, s->key.modulus, PKT_END);
3203 if (pktin->type == SSH1_SMSG_FAILURE) {
3204 c_write_str(ssh, "Server refused our public key.\r\n");
3205 continue; /* go and try password */
3207 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3208 bombout(("Bizarre response to offer of public key"));
3214 unsigned char buffer[32];
3215 Bignum challenge, response;
3217 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3218 bombout(("Server's RSA challenge was badly formatted"));
3221 response = rsadecrypt(challenge, &s->key);
3222 freebn(s->key.private_exponent);/* burn the evidence */
3224 for (i = 0; i < 32; i++) {
3225 buffer[i] = bignum_byte(response, 31 - i);
3229 MD5Update(&md5c, buffer, 32);
3230 MD5Update(&md5c, s->session_id, 16);
3231 MD5Final(buffer, &md5c);
3233 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3234 PKT_DATA, buffer, 16, PKT_END);
3241 if (pktin->type == SSH1_SMSG_FAILURE) {
3242 if (flags & FLAG_VERBOSE)
3243 c_write_str(ssh, "Failed to authenticate with"
3244 " our public key.\r\n");
3245 continue; /* go and try password */
3246 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
3247 bombout(("Bizarre response to RSA authentication response"));
3251 break; /* we're through! */
3253 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
3255 * Defence against traffic analysis: we send a
3256 * whole bunch of packets containing strings of
3257 * different lengths. One of these strings is the
3258 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
3259 * The others are all random data in
3260 * SSH1_MSG_IGNORE packets. This way a passive
3261 * listener can't tell which is the password, and
3262 * hence can't deduce the password length.
3264 * Anybody with a password length greater than 16
3265 * bytes is going to have enough entropy in their
3266 * password that a listener won't find it _that_
3267 * much help to know how long it is. So what we'll
3270 * - if password length < 16, we send 15 packets
3271 * containing string lengths 1 through 15
3273 * - otherwise, we let N be the nearest multiple
3274 * of 8 below the password length, and send 8
3275 * packets containing string lengths N through
3276 * N+7. This won't obscure the order of
3277 * magnitude of the password length, but it will
3278 * introduce a bit of extra uncertainty.
3280 * A few servers (the old 1.2.18 through 1.2.22)
3281 * can't deal with SSH1_MSG_IGNORE. For these
3282 * servers, we need an alternative defence. We make
3283 * use of the fact that the password is interpreted
3284 * as a C string: so we can append a NUL, then some
3287 * One server (a Cisco one) can deal with neither
3288 * SSH1_MSG_IGNORE _nor_ a padded password string.
3289 * For this server we are left with no defences
3290 * against password length sniffing.
3292 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE)) {
3294 * The server can deal with SSH1_MSG_IGNORE, so
3295 * we can use the primary defence.
3297 int bottom, top, pwlen, i;
3300 pwlen = strlen(s->password);
3302 bottom = 0; /* zero length passwords are OK! :-) */
3305 bottom = pwlen & ~7;
3309 assert(pwlen >= bottom && pwlen <= top);
3311 randomstr = snewn(top + 1, char);
3313 for (i = bottom; i <= top; i++) {
3315 defer_packet(ssh, s->pwpkt_type,
3316 PKTT_PASSWORD, PKT_STR, s->password,
3317 PKTT_OTHER, PKT_END);
3319 for (j = 0; j < i; j++) {
3321 randomstr[j] = random_byte();
3322 } while (randomstr[j] == '\0');
3324 randomstr[i] = '\0';
3325 defer_packet(ssh, SSH1_MSG_IGNORE,
3326 PKT_STR, randomstr, PKT_END);
3329 logevent("Sending password with camouflage packets");
3330 ssh_pkt_defersend(ssh);
3333 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
3335 * The server can't deal with SSH1_MSG_IGNORE
3336 * but can deal with padded passwords, so we
3337 * can use the secondary defence.
3343 len = strlen(s->password);
3344 if (len < sizeof(string)) {
3346 strcpy(string, s->password);
3347 len++; /* cover the zero byte */
3348 while (len < sizeof(string)) {
3349 string[len++] = (char) random_byte();
3354 logevent("Sending length-padded password");
3355 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
3356 PKT_INT, len, PKT_DATA, ss, len,
3357 PKTT_OTHER, PKT_END);
3360 * The server has _both_
3361 * BUG_CHOKES_ON_SSH1_IGNORE and
3362 * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
3363 * therefore nothing we can do.
3366 len = strlen(s->password);
3367 logevent("Sending unpadded password");
3368 send_packet(ssh, s->pwpkt_type,
3369 PKTT_PASSWORD, PKT_INT, len,
3370 PKT_DATA, s->password, len,
3371 PKTT_OTHER, PKT_END);
3374 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
3375 PKT_STR, s->password, PKTT_OTHER, PKT_END);
3378 logevent("Sent password");
3379 memset(s->password, 0, strlen(s->password));
3381 if (pktin->type == SSH1_SMSG_FAILURE) {
3382 if (flags & FLAG_VERBOSE)
3383 c_write_str(ssh, "Access denied\r\n");
3384 logevent("Authentication refused");
3385 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
3386 bombout(("Strange packet received, type %d", pktin->type));
3391 logevent("Authentication successful");
3396 void sshfwd_close(struct ssh_channel *c)
3400 if (ssh->state != SSH_STATE_SESSION) {
3401 assert(ssh->state == SSH_STATE_CLOSED);
3405 if (c && !c->closes) {
3407 * If the channel's remoteid is -1, we have sent
3408 * CHANNEL_OPEN for this channel, but it hasn't even been
3409 * acknowledged by the server. So we must set a close flag
3410 * on it now, and then when the server acks the channel
3411 * open, we can close it then.
3413 if (((int)c->remoteid) != -1) {
3414 if (ssh->version == 1) {
3415 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
3418 struct Packet *pktout;
3419 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
3420 ssh2_pkt_adduint32(pktout, c->remoteid);
3421 ssh2_pkt_send(ssh, pktout);
3424 c->closes = 1; /* sent MSG_CLOSE */
3425 if (c->type == CHAN_X11) {
3427 logevent("Forwarded X11 connection terminated");
3428 } else if (c->type == CHAN_SOCKDATA ||
3429 c->type == CHAN_SOCKDATA_DORMANT) {
3431 logevent("Forwarded port closed");
3436 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
3440 if (ssh->state != SSH_STATE_SESSION) {
3441 assert(ssh->state == SSH_STATE_CLOSED);
3445 if (ssh->version == 1) {
3446 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3447 PKT_INT, c->remoteid,
3449 PKT_INT, len, PKT_DATA, buf, len,
3450 PKTT_OTHER, PKT_END);
3452 * In SSH1 we can return 0 here - implying that forwarded
3453 * connections are never individually throttled - because
3454 * the only circumstance that can cause throttling will be
3455 * the whole SSH connection backing up, in which case
3456 * _everything_ will be throttled as a whole.
3460 ssh2_add_channel_data(c, buf, len);
3461 return ssh2_try_send(c);
3465 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
3469 if (ssh->state != SSH_STATE_SESSION) {
3470 assert(ssh->state == SSH_STATE_CLOSED);
3474 if (ssh->version == 1) {
3475 if (c->v.v1.throttling && bufsize < SSH1_BUFFER_LIMIT) {
3476 c->v.v1.throttling = 0;
3477 ssh1_throttle(ssh, -1);
3480 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
3484 static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen,
3485 struct Packet *pktin)
3487 crBegin(ssh->ssh1_protocol_crstate);
3491 while (!do_ssh1_login(ssh, in, inlen, pktin)) {
3494 if (ssh->state == SSH_STATE_CLOSED)
3497 if (ssh->cfg.agentfwd && agent_exists()) {
3498 logevent("Requesting agent forwarding");
3499 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
3503 if (pktin->type != SSH1_SMSG_SUCCESS
3504 && pktin->type != SSH1_SMSG_FAILURE) {
3505 bombout(("Protocol confusion"));
3507 } else if (pktin->type == SSH1_SMSG_FAILURE) {
3508 logevent("Agent forwarding refused");
3510 logevent("Agent forwarding enabled");
3511 ssh->agentfwd_enabled = TRUE;
3515 if (ssh->cfg.x11_forward) {
3516 char proto[20], data[64];
3517 logevent("Requesting X11 forwarding");
3518 ssh->x11auth = x11_invent_auth(proto, sizeof(proto),
3519 data, sizeof(data), ssh->cfg.x11_auth);
3520 x11_get_real_auth(ssh->x11auth, ssh->cfg.x11_display);
3521 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
3522 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
3523 PKT_STR, proto, PKT_STR, data,
3524 PKT_INT, x11_get_screen_number(ssh->cfg.x11_display),
3527 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
3528 PKT_STR, proto, PKT_STR, data, PKT_END);
3533 if (pktin->type != SSH1_SMSG_SUCCESS
3534 && pktin->type != SSH1_SMSG_FAILURE) {
3535 bombout(("Protocol confusion"));
3537 } else if (pktin->type == SSH1_SMSG_FAILURE) {
3538 logevent("X11 forwarding refused");
3540 logevent("X11 forwarding enabled");
3541 ssh->X11_fwd_enabled = TRUE;
3548 int sport,dport,sserv,dserv;
3549 char sports[256], dports[256], saddr[256], host[256];
3551 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
3552 /* Add port forwardings. */
3553 ssh->portfwd_strptr = ssh->cfg.portfwd;
3554 while (*ssh->portfwd_strptr) {
3555 type = *ssh->portfwd_strptr++;
3558 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != '\t') {
3559 if (*ssh->portfwd_strptr == ':') {
3561 * We've seen a colon in the middle of the
3562 * source port number. This means that
3563 * everything we've seen until now is the
3564 * source _address_, so we'll move it into
3565 * saddr and start sports from the beginning
3568 ssh->portfwd_strptr++;
3570 strcpy(saddr, sports);
3573 if (n < 255) sports[n++] = *ssh->portfwd_strptr++;
3577 if (*ssh->portfwd_strptr == '\t')
3578 ssh->portfwd_strptr++;
3580 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != ':') {
3581 if (n < 255) host[n++] = *ssh->portfwd_strptr++;
3584 if (*ssh->portfwd_strptr == ':')
3585 ssh->portfwd_strptr++;
3587 while (*ssh->portfwd_strptr) {
3588 if (n < 255) dports[n++] = *ssh->portfwd_strptr++;
3591 ssh->portfwd_strptr++;
3592 dport = atoi(dports);
3596 dport = net_service_lookup(dports);
3598 logeventf(ssh, "Service lookup failed for"
3599 " destination port \"%s\"", dports);
3603 while (*ssh->portfwd_strptr) ssh->portfwd_strptr++;
3605 ssh->portfwd_strptr++; /* eat the NUL and move to next one */
3607 sport = atoi(sports);
3611 sport = net_service_lookup(sports);
3613 logeventf(ssh, "Service lookup failed for source"
3614 " port \"%s\"", sports);
3617 if (sport && dport) {
3618 /* Set up a description of the source port. */
3619 static char *sportdesc;
3620 sportdesc = dupprintf("%.*s%.*s%.*s%.*s%d%.*s",
3621 (int)(*saddr?strlen(saddr):0), *saddr?saddr:NULL,
3622 (int)(*saddr?1:0), ":",
3623 (int)(sserv ? strlen(sports) : 0), sports,
3624 sserv, "(", sport, sserv, ")");
3626 /* Verbose description of the destination port */
3627 char *dportdesc = dupprintf("%s:%.*s%.*s%d%.*s",
3629 (int)(dserv ? strlen(dports) : 0), dports,
3630 dserv, "(", dport, dserv, ")");
3631 const char *err = pfd_addforward(host, dport,
3632 *saddr ? saddr : NULL,
3633 sport, ssh, &ssh->cfg);
3635 logeventf(ssh, "Local port %s forward to %s"
3636 " failed: %s", sportdesc, dportdesc, err);
3638 logeventf(ssh, "Local port %s forwarding to %s",
3639 sportdesc, dportdesc);
3642 } else if (type == 'D') {
3643 const char *err = pfd_addforward(NULL, -1,
3644 *saddr ? saddr : NULL,
3645 sport, ssh, &ssh->cfg);
3647 logeventf(ssh, "Local port %s SOCKS dynamic forward"
3648 " setup failed: %s", sportdesc, err);
3650 logeventf(ssh, "Local port %s doing SOCKS"
3651 " dynamic forwarding", sportdesc);
3654 struct ssh_rportfwd *pf;
3655 pf = snew(struct ssh_rportfwd);
3656 strcpy(pf->dhost, host);
3660 "SSH1 cannot handle source address spec \"%s:%d\"; ignoring",
3663 if (add234(ssh->rportfwds, pf) != pf) {
3665 "Duplicate remote port forwarding to %s:%d",
3669 logeventf(ssh, "Requesting remote port %.*s%.*s%d%.*s"
3670 " forward to %s:%.*s%.*s%d%.*s",
3671 (int)(sserv ? strlen(sports) : 0), sports,
3672 sserv, "(", sport, sserv, ")",
3674 (int)(dserv ? strlen(dports) : 0), dports,
3675 dserv, "(", dport, dserv, ")");
3676 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
3684 if (pktin->type != SSH1_SMSG_SUCCESS
3685 && pktin->type != SSH1_SMSG_FAILURE) {
3686 bombout(("Protocol confusion"));
3688 } else if (pktin->type == SSH1_SMSG_FAILURE) {
3689 c_write_str(ssh, "Server refused port"
3692 logevent("Remote port forwarding enabled");
3700 if (!ssh->cfg.nopty) {
3701 /* Unpick the terminal-speed string. */
3702 /* XXX perhaps we should allow no speeds to be sent. */
3703 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
3704 sscanf(ssh->cfg.termspeed, "%d,%d", &ssh->ospeed, &ssh->ispeed);
3705 /* Send the pty request. */
3706 send_packet(ssh, SSH1_CMSG_REQUEST_PTY,
3707 PKT_STR, ssh->cfg.termtype,
3708 PKT_INT, ssh->term_height,
3709 PKT_INT, ssh->term_width,
3710 PKT_INT, 0, PKT_INT, 0, /* width,height in pixels */
3711 PKT_CHAR, 192, PKT_INT, ssh->ispeed, /* TTY_OP_ISPEED */
3712 PKT_CHAR, 193, PKT_INT, ssh->ospeed, /* TTY_OP_OSPEED */
3713 PKT_CHAR, 0, PKT_END);
3714 ssh->state = SSH_STATE_INTERMED;
3718 if (pktin->type != SSH1_SMSG_SUCCESS
3719 && pktin->type != SSH1_SMSG_FAILURE) {
3720 bombout(("Protocol confusion"));
3722 } else if (pktin->type == SSH1_SMSG_FAILURE) {
3723 c_write_str(ssh, "Server refused to allocate pty\r\n");
3724 ssh->editing = ssh->echoing = 1;
3726 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
3727 ssh->ospeed, ssh->ispeed);
3729 ssh->editing = ssh->echoing = 1;
3732 if (ssh->cfg.compression) {
3733 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
3737 if (pktin->type != SSH1_SMSG_SUCCESS
3738 && pktin->type != SSH1_SMSG_FAILURE) {
3739 bombout(("Protocol confusion"));
3741 } else if (pktin->type == SSH1_SMSG_FAILURE) {
3742 c_write_str(ssh, "Server refused to compress\r\n");
3744 logevent("Started compression");
3745 ssh->v1_compressing = TRUE;
3746 ssh->cs_comp_ctx = zlib_compress_init();
3747 logevent("Initialised zlib (RFC1950) compression");
3748 ssh->sc_comp_ctx = zlib_decompress_init();
3749 logevent("Initialised zlib (RFC1950) decompression");
3753 * Start the shell or command.
3755 * Special case: if the first-choice command is an SSH2
3756 * subsystem (hence not usable here) and the second choice
3757 * exists, we fall straight back to that.
3760 char *cmd = ssh->cfg.remote_cmd_ptr;
3762 if (ssh->cfg.ssh_subsys && ssh->cfg.remote_cmd_ptr2) {
3763 cmd = ssh->cfg.remote_cmd_ptr2;
3764 ssh->fallback_cmd = TRUE;
3767 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
3769 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
3770 logevent("Started session");
3773 ssh->state = SSH_STATE_SESSION;
3774 if (ssh->size_needed)
3775 ssh_size(ssh, ssh->term_width, ssh->term_height);
3776 if (ssh->eof_needed)
3777 ssh_special(ssh, TS_EOF);
3780 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
3782 ssh->channels = newtree234(ssh_channelcmp);
3786 if (pktin->type == SSH1_SMSG_STDOUT_DATA ||
3787 pktin->type == SSH1_SMSG_STDERR_DATA) {
3789 int stringlen, bufsize;
3791 ssh_pkt_getstring(pktin, &string, &stringlen);
3792 if (string == NULL) {
3793 bombout(("Incoming terminal data packet was badly formed"));
3798 from_backend(ssh->frontend,
3799 pktin->type == SSH1_SMSG_STDERR_DATA,
3801 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
3802 ssh->v1_stdout_throttling = 1;
3803 ssh1_throttle(ssh, +1);
3805 } else if (pktin->type == SSH1_MSG_DISCONNECT) {
3806 ssh_closing((Plug)ssh, NULL, 0, 0);
3807 logevent("Received disconnect request");
3809 } else if (pktin->type == SSH1_SMSG_X11_OPEN) {
3810 /* Remote side is trying to open a channel to talk to our
3811 * X-Server. Give them back a local channel number. */
3812 struct ssh_channel *c;
3813 int remoteid = ssh_pkt_getuint32(pktin);
3815 logevent("Received X11 connect request");
3816 /* Refuse if X11 forwarding is disabled. */
3817 if (!ssh->X11_fwd_enabled) {
3818 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3819 PKT_INT, remoteid, PKT_END);
3820 logevent("Rejected X11 connect request");
3822 c = snew(struct ssh_channel);
3825 if (x11_init(&c->u.x11.s, ssh->cfg.x11_display, c,
3826 ssh->x11auth, NULL, -1, &ssh->cfg) != NULL) {
3827 logevent("Opening X11 forward connection failed");
3829 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3830 PKT_INT, remoteid, PKT_END);
3833 ("Opening X11 forward connection succeeded");
3834 c->remoteid = remoteid;
3835 c->localid = alloc_channel_id(ssh);
3837 c->v.v1.throttling = 0;
3838 c->type = CHAN_X11; /* identify channel type */
3839 add234(ssh->channels, c);
3840 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3841 PKT_INT, c->remoteid, PKT_INT,
3842 c->localid, PKT_END);
3843 logevent("Opened X11 forward channel");
3846 } else if (pktin->type == SSH1_SMSG_AGENT_OPEN) {
3847 /* Remote side is trying to open a channel to talk to our
3848 * agent. Give them back a local channel number. */
3849 struct ssh_channel *c;
3850 int remoteid = ssh_pkt_getuint32(pktin);
3852 /* Refuse if agent forwarding is disabled. */
3853 if (!ssh->agentfwd_enabled) {
3854 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3855 PKT_INT, remoteid, PKT_END);
3857 c = snew(struct ssh_channel);
3859 c->remoteid = remoteid;
3860 c->localid = alloc_channel_id(ssh);
3862 c->v.v1.throttling = 0;
3863 c->type = CHAN_AGENT; /* identify channel type */
3864 c->u.a.lensofar = 0;
3865 add234(ssh->channels, c);
3866 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3867 PKT_INT, c->remoteid, PKT_INT, c->localid,
3870 } else if (pktin->type == SSH1_MSG_PORT_OPEN) {
3871 /* Remote side is trying to open a channel to talk to a
3872 * forwarded port. Give them back a local channel number. */
3873 struct ssh_channel *c;
3874 struct ssh_rportfwd pf;
3877 char *host, buf[1024];
3879 c = snew(struct ssh_channel);
3882 remoteid = ssh_pkt_getuint32(pktin);
3883 ssh_pkt_getstring(pktin, &host, &hostsize);
3884 port = ssh_pkt_getuint32(pktin);
3886 if (hostsize >= lenof(pf.dhost))
3887 hostsize = lenof(pf.dhost)-1;
3888 memcpy(pf.dhost, host, hostsize);
3889 pf.dhost[hostsize] = '\0';
3892 if (find234(ssh->rportfwds, &pf, NULL) == NULL) {
3893 sprintf(buf, "Rejected remote port open request for %s:%d",
3896 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3897 PKT_INT, remoteid, PKT_END);
3899 sprintf(buf, "Received remote port open request for %s:%d",
3902 e = pfd_newconnect(&c->u.pfd.s, pf.dhost, port,
3906 sprintf(buf, "Port open failed: %s", e);
3909 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3910 PKT_INT, remoteid, PKT_END);
3912 c->remoteid = remoteid;
3913 c->localid = alloc_channel_id(ssh);
3915 c->v.v1.throttling = 0;
3916 c->type = CHAN_SOCKDATA; /* identify channel type */
3917 add234(ssh->channels, c);
3918 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3919 PKT_INT, c->remoteid, PKT_INT,
3920 c->localid, PKT_END);
3921 logevent("Forwarded port opened successfully");
3925 } else if (pktin->type == SSH1_MSG_CHANNEL_OPEN_CONFIRMATION) {
3926 unsigned int remoteid = ssh_pkt_getuint32(pktin);
3927 unsigned int localid = ssh_pkt_getuint32(pktin);
3928 struct ssh_channel *c;
3930 c = find234(ssh->channels, &remoteid, ssh_channelfind);
3931 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
3932 c->remoteid = localid;
3933 c->type = CHAN_SOCKDATA;
3934 c->v.v1.throttling = 0;
3935 pfd_confirm(c->u.pfd.s);
3938 if (c && c->closes) {
3940 * We have a pending close on this channel,
3941 * which we decided on before the server acked
3942 * the channel open. So now we know the
3943 * remoteid, we can close it again.
3945 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE,
3946 PKT_INT, c->remoteid, PKT_END);
3949 } else if (pktin->type == SSH1_MSG_CHANNEL_OPEN_FAILURE) {
3950 unsigned int remoteid = ssh_pkt_getuint32(pktin);
3951 struct ssh_channel *c;
3953 c = find234(ssh->channels, &remoteid, ssh_channelfind);
3954 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
3955 logevent("Forwarded connection refused by server");
3956 pfd_close(c->u.pfd.s);
3957 del234(ssh->channels, c);
3961 } else if (pktin->type == SSH1_MSG_CHANNEL_CLOSE ||
3962 pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
3963 /* Remote side closes a channel. */
3964 unsigned i = ssh_pkt_getuint32(pktin);
3965 struct ssh_channel *c;
3966 c = find234(ssh->channels, &i, ssh_channelfind);
3967 if (c && ((int)c->remoteid) != -1) {
3970 (pktin->type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
3972 if ((c->closes == 0) && (c->type == CHAN_X11)) {
3973 logevent("Forwarded X11 connection terminated");
3974 assert(c->u.x11.s != NULL);
3975 x11_close(c->u.x11.s);
3978 if ((c->closes == 0) && (c->type == CHAN_SOCKDATA)) {
3979 logevent("Forwarded port closed");
3980 assert(c->u.pfd.s != NULL);
3981 pfd_close(c->u.pfd.s);
3985 c->closes |= (closetype << 2); /* seen this message */
3986 if (!(c->closes & closetype)) {
3987 send_packet(ssh, pktin->type, PKT_INT, c->remoteid,
3989 c->closes |= closetype; /* sent it too */
3992 if (c->closes == 15) {
3993 del234(ssh->channels, c);
3997 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
3998 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
3999 "_CONFIRMATION", c ? "half-open" : "nonexistent",
4003 } else if (pktin->type == SSH1_MSG_CHANNEL_DATA) {
4004 /* Data sent down one of our channels. */
4005 int i = ssh_pkt_getuint32(pktin);
4008 struct ssh_channel *c;
4010 ssh_pkt_getstring(pktin, &p, &len);
4012 c = find234(ssh->channels, &i, ssh_channelfind);
4017 bufsize = x11_send(c->u.x11.s, p, len);
4020 bufsize = pfd_send(c->u.pfd.s, p, len);
4023 /* Data for an agent message. Buffer it. */
4025 if (c->u.a.lensofar < 4) {
4026 int l = min(4 - c->u.a.lensofar, len);
4027 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
4031 c->u.a.lensofar += l;
4033 if (c->u.a.lensofar == 4) {
4035 4 + GET_32BIT(c->u.a.msglen);
4036 c->u.a.message = snewn(c->u.a.totallen,
4038 memcpy(c->u.a.message, c->u.a.msglen, 4);
4040 if (c->u.a.lensofar >= 4 && len > 0) {
4042 min(c->u.a.totallen - c->u.a.lensofar,
4044 memcpy(c->u.a.message + c->u.a.lensofar, p,
4048 c->u.a.lensofar += l;
4050 if (c->u.a.lensofar == c->u.a.totallen) {
4053 if (agent_query(c->u.a.message,
4056 ssh_agentf_callback, c))
4057 ssh_agentf_callback(c, reply, replylen);
4058 sfree(c->u.a.message);
4059 c->u.a.lensofar = 0;
4062 bufsize = 0; /* agent channels never back up */
4065 if (!c->v.v1.throttling && bufsize > SSH1_BUFFER_LIMIT) {
4066 c->v.v1.throttling = 1;
4067 ssh1_throttle(ssh, +1);
4070 } else if (pktin->type == SSH1_SMSG_SUCCESS) {
4071 /* may be from EXEC_SHELL on some servers */
4072 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4073 /* may be from EXEC_SHELL on some servers
4074 * if no pty is available or in other odd cases. Ignore */
4075 } else if (pktin->type == SSH1_SMSG_EXIT_STATUS) {
4077 ssh->exitcode = ssh_pkt_getuint32(pktin);
4078 sprintf(buf, "Server sent command exit status %d",
4081 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
4083 * In case `helpful' firewalls or proxies tack
4084 * extra human-readable text on the end of the
4085 * session which we might mistake for another
4086 * encrypted packet, we close the session once
4087 * we've sent EXIT_CONFIRMATION.
4089 ssh_closing((Plug)ssh, NULL, 0, 0);
4092 bombout(("Strange packet received: type %d", pktin->type));
4097 int len = min(inlen, 512);
4098 send_packet(ssh, SSH1_CMSG_STDIN_DATA, PKTT_DATA,
4099 PKT_INT, len, PKT_DATA, in, len,
4100 PKTT_OTHER, PKT_END);
4111 * Utility routine for decoding comma-separated strings in KEXINIT.
4113 static int in_commasep_string(char *needle, char *haystack, int haylen)
4116 if (!needle || !haystack) /* protect against null pointers */
4118 needlen = strlen(needle);
4121 * Is it at the start of the string?
4123 if (haylen >= needlen && /* haystack is long enough */
4124 !memcmp(needle, haystack, needlen) && /* initial match */
4125 (haylen == needlen || haystack[needlen] == ',')
4126 /* either , or EOS follows */
4130 * If not, search for the next comma and resume after that.
4131 * If no comma found, terminate.
4133 while (haylen > 0 && *haystack != ',')
4134 haylen--, haystack++;
4137 haylen--, haystack++; /* skip over comma itself */
4142 * SSH2 key creation method.
4144 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H,
4145 unsigned char *sessid, char chr,
4146 unsigned char *keyspace)
4149 /* First 20 bytes. */
4151 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
4153 SHA_Bytes(&s, H, 20);
4154 SHA_Bytes(&s, &chr, 1);
4155 SHA_Bytes(&s, sessid, 20);
4156 SHA_Final(&s, keyspace);
4157 /* Next 20 bytes. */
4159 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
4161 SHA_Bytes(&s, H, 20);
4162 SHA_Bytes(&s, keyspace, 20);
4163 SHA_Final(&s, keyspace + 20);
4167 * Handle the SSH2 transport layer.
4169 static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen,
4170 struct Packet *pktin)
4172 struct do_ssh2_transport_state {
4173 int nbits, pbits, warn;
4174 Bignum p, g, e, f, K;
4175 int kex_init_value, kex_reply_value;
4176 const struct ssh_mac **maclist;
4178 const struct ssh2_cipher *cscipher_tobe;
4179 const struct ssh2_cipher *sccipher_tobe;
4180 const struct ssh_mac *csmac_tobe;
4181 const struct ssh_mac *scmac_tobe;
4182 const struct ssh_compress *cscomp_tobe;
4183 const struct ssh_compress *sccomp_tobe;
4184 char *hostkeydata, *sigdata, *keystr, *fingerprint;
4185 int hostkeylen, siglen;
4186 void *hkey; /* actual host key */
4187 unsigned char exchange_hash[20];
4188 int n_preferred_ciphers;
4189 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
4190 const struct ssh_compress *preferred_comp;
4192 struct Packet *pktout;
4194 crState(do_ssh2_transport_state);
4196 crBegin(ssh->do_ssh2_transport_crstate);
4198 s->cscipher_tobe = s->sccipher_tobe = NULL;
4199 s->csmac_tobe = s->scmac_tobe = NULL;
4200 s->cscomp_tobe = s->sccomp_tobe = NULL;
4208 * Set up the preferred ciphers. (NULL => warn below here)
4210 s->n_preferred_ciphers = 0;
4211 for (i = 0; i < CIPHER_MAX; i++) {
4212 switch (ssh->cfg.ssh_cipherlist[i]) {
4213 case CIPHER_BLOWFISH:
4214 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
4217 if (ssh->cfg.ssh2_des_cbc) {
4218 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
4222 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
4225 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
4228 /* Flag for later. Don't bother if it's the last in
4230 if (i < CIPHER_MAX - 1) {
4231 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
4239 * Set up preferred compression.
4241 if (ssh->cfg.compression)
4242 s->preferred_comp = &ssh_zlib;
4244 s->preferred_comp = &ssh_comp_none;
4247 * Be prepared to work around the buggy MAC problem.
4249 if (ssh->remote_bugs & BUG_SSH2_HMAC)
4250 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
4252 s->maclist = macs, s->nmacs = lenof(macs);
4256 int i, j, cipherstr_started;
4259 * Construct and send our key exchange packet.
4261 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
4262 for (i = 0; i < 16; i++)
4263 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
4264 /* List key exchange algorithms. */
4265 ssh2_pkt_addstring_start(s->pktout);
4266 for (i = 0; i < lenof(kex_algs); i++) {
4267 if (kex_algs[i] == &ssh_diffiehellman_gex &&
4268 (ssh->remote_bugs & BUG_SSH2_DH_GEX))
4270 ssh2_pkt_addstring_str(s->pktout, kex_algs[i]->name);
4271 if (i < lenof(kex_algs) - 1)
4272 ssh2_pkt_addstring_str(s->pktout, ",");
4274 /* List server host key algorithms. */
4275 ssh2_pkt_addstring_start(s->pktout);
4276 for (i = 0; i < lenof(hostkey_algs); i++) {
4277 ssh2_pkt_addstring_str(s->pktout, hostkey_algs[i]->name);
4278 if (i < lenof(hostkey_algs) - 1)
4279 ssh2_pkt_addstring_str(s->pktout, ",");
4281 /* List client->server encryption algorithms. */
4282 ssh2_pkt_addstring_start(s->pktout);
4283 cipherstr_started = 0;
4284 for (i = 0; i < s->n_preferred_ciphers; i++) {
4285 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
4286 if (!c) continue; /* warning flag */
4287 for (j = 0; j < c->nciphers; j++) {
4288 if (cipherstr_started)
4289 ssh2_pkt_addstring_str(s->pktout, ",");
4290 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
4291 cipherstr_started = 1;
4294 /* List server->client encryption algorithms. */
4295 ssh2_pkt_addstring_start(s->pktout);
4296 cipherstr_started = 0;
4297 for (i = 0; i < s->n_preferred_ciphers; i++) {
4298 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
4299 if (!c) continue; /* warning flag */
4300 for (j = 0; j < c->nciphers; j++) {
4301 if (cipherstr_started)
4302 ssh2_pkt_addstring_str(s->pktout, ",");
4303 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
4304 cipherstr_started = 1;
4307 /* List client->server MAC algorithms. */
4308 ssh2_pkt_addstring_start(s->pktout);
4309 for (i = 0; i < s->nmacs; i++) {
4310 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
4311 if (i < s->nmacs - 1)
4312 ssh2_pkt_addstring_str(s->pktout, ",");
4314 /* List server->client MAC algorithms. */
4315 ssh2_pkt_addstring_start(s->pktout);
4316 for (i = 0; i < s->nmacs; i++) {
4317 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
4318 if (i < s->nmacs - 1)
4319 ssh2_pkt_addstring_str(s->pktout, ",");
4321 /* List client->server compression algorithms. */
4322 ssh2_pkt_addstring_start(s->pktout);
4323 assert(lenof(compressions) > 1);
4324 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
4325 for (i = 0; i < lenof(compressions); i++) {
4326 const struct ssh_compress *c = compressions[i];
4327 if (c != s->preferred_comp) {
4328 ssh2_pkt_addstring_str(s->pktout, ",");
4329 ssh2_pkt_addstring_str(s->pktout, c->name);
4332 /* List server->client compression algorithms. */
4333 ssh2_pkt_addstring_start(s->pktout);
4334 assert(lenof(compressions) > 1);
4335 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
4336 for (i = 0; i < lenof(compressions); i++) {
4337 const struct ssh_compress *c = compressions[i];
4338 if (c != s->preferred_comp) {
4339 ssh2_pkt_addstring_str(s->pktout, ",");
4340 ssh2_pkt_addstring_str(s->pktout, c->name);
4343 /* List client->server languages. Empty list. */
4344 ssh2_pkt_addstring_start(s->pktout);
4345 /* List server->client languages. Empty list. */
4346 ssh2_pkt_addstring_start(s->pktout);
4347 /* First KEX packet does _not_ follow, because we're not that brave. */
4348 ssh2_pkt_addbool(s->pktout, FALSE);
4350 ssh2_pkt_adduint32(s->pktout, 0);
4353 ssh->exhash = ssh->exhashbase;
4354 sha_string(&ssh->exhash, s->pktout->data + 5, s->pktout->length - 5);
4356 ssh2_pkt_send(ssh, s->pktout);
4360 if (pktin->length > 5)
4361 sha_string(&ssh->exhash, pktin->data + 5, pktin->length - 5);
4364 * Now examine the other side's KEXINIT to see what we're up
4371 if (pktin->type != SSH2_MSG_KEXINIT) {
4372 bombout(("expected key exchange packet from server"));
4376 ssh->hostkey = NULL;
4377 s->cscipher_tobe = NULL;
4378 s->sccipher_tobe = NULL;
4379 s->csmac_tobe = NULL;
4380 s->scmac_tobe = NULL;
4381 s->cscomp_tobe = NULL;
4382 s->sccomp_tobe = NULL;
4383 pktin->savedpos += 16; /* skip garbage cookie */
4384 ssh_pkt_getstring(pktin, &str, &len); /* key exchange algorithms */
4385 for (i = 0; i < lenof(kex_algs); i++) {
4386 if (kex_algs[i] == &ssh_diffiehellman_gex &&
4387 (ssh->remote_bugs & BUG_SSH2_DH_GEX))
4389 if (in_commasep_string(kex_algs[i]->name, str, len)) {
4390 ssh->kex = kex_algs[i];
4394 ssh_pkt_getstring(pktin, &str, &len); /* host key algorithms */
4395 for (i = 0; i < lenof(hostkey_algs); i++) {
4396 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
4397 ssh->hostkey = hostkey_algs[i];
4401 ssh_pkt_getstring(pktin, &str, &len); /* client->server cipher */
4403 for (i = 0; i < s->n_preferred_ciphers; i++) {
4404 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
4408 for (j = 0; j < c->nciphers; j++) {
4409 if (in_commasep_string(c->list[j]->name, str, len)) {
4410 s->cscipher_tobe = c->list[j];
4415 if (s->cscipher_tobe) {
4417 askcipher(ssh->frontend, s->cscipher_tobe->name, 1);
4421 if (!s->cscipher_tobe) {
4422 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
4423 str ? str : "(null)"));
4427 ssh_pkt_getstring(pktin, &str, &len); /* server->client cipher */
4429 for (i = 0; i < s->n_preferred_ciphers; i++) {
4430 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
4434 for (j = 0; j < c->nciphers; j++) {
4435 if (in_commasep_string(c->list[j]->name, str, len)) {
4436 s->sccipher_tobe = c->list[j];
4441 if (s->sccipher_tobe) {
4443 askcipher(ssh->frontend, s->sccipher_tobe->name, 2);
4447 if (!s->sccipher_tobe) {
4448 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
4449 str ? str : "(null)"));
4453 ssh_pkt_getstring(pktin, &str, &len); /* client->server mac */
4454 for (i = 0; i < s->nmacs; i++) {
4455 if (in_commasep_string(s->maclist[i]->name, str, len)) {
4456 s->csmac_tobe = s->maclist[i];
4460 ssh_pkt_getstring(pktin, &str, &len); /* server->client mac */
4461 for (i = 0; i < s->nmacs; i++) {
4462 if (in_commasep_string(s->maclist[i]->name, str, len)) {
4463 s->scmac_tobe = s->maclist[i];
4467 ssh_pkt_getstring(pktin, &str, &len); /* client->server compression */
4468 for (i = 0; i < lenof(compressions) + 1; i++) {
4469 const struct ssh_compress *c =
4470 i == 0 ? s->preferred_comp : compressions[i - 1];
4471 if (in_commasep_string(c->name, str, len)) {
4476 ssh_pkt_getstring(pktin, &str, &len); /* server->client compression */
4477 for (i = 0; i < lenof(compressions) + 1; i++) {
4478 const struct ssh_compress *c =
4479 i == 0 ? s->preferred_comp : compressions[i - 1];
4480 if (in_commasep_string(c->name, str, len)) {
4488 * Work out the number of bits of key we will need from the key
4489 * exchange. We start with the maximum key length of either
4495 csbits = s->cscipher_tobe->keylen;
4496 scbits = s->sccipher_tobe->keylen;
4497 s->nbits = (csbits > scbits ? csbits : scbits);
4499 /* The keys only have 160-bit entropy, since they're based on
4500 * a SHA-1 hash. So cap the key size at 160 bits. */
4505 * If we're doing Diffie-Hellman group exchange, start by
4506 * requesting a group.
4508 if (ssh->kex == &ssh_diffiehellman_gex) {
4509 logevent("Doing Diffie-Hellman group exchange");
4510 ssh->pkt_ctx |= SSH2_PKTCTX_DHGEX;
4512 * Work out how big a DH group we will need to allow that
4515 s->pbits = 512 << ((s->nbits - 1) / 64);
4516 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
4517 ssh2_pkt_adduint32(s->pktout, s->pbits);
4518 ssh2_pkt_send(ssh, s->pktout);
4521 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
4522 bombout(("expected key exchange group packet from server"));
4525 s->p = ssh2_pkt_getmp(pktin);
4526 s->g = ssh2_pkt_getmp(pktin);
4527 if (!s->p || !s->g) {
4528 bombout(("unable to read mp-ints from incoming group packet"));
4531 ssh->kex_ctx = dh_setup_group(s->p, s->g);
4532 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
4533 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
4535 ssh->pkt_ctx |= SSH2_PKTCTX_DHGROUP1;
4536 ssh->kex_ctx = dh_setup_group1();
4537 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
4538 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
4541 logevent("Doing Diffie-Hellman key exchange");
4543 * Now generate and send e for Diffie-Hellman.
4545 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
4546 s->pktout = ssh2_pkt_init(s->kex_init_value);
4547 ssh2_pkt_addmp(s->pktout, s->e);
4548 ssh2_pkt_send(ssh, s->pktout);
4551 if (pktin->type != s->kex_reply_value) {
4552 bombout(("expected key exchange reply packet from server"));
4555 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
4556 s->f = ssh2_pkt_getmp(pktin);
4558 bombout(("unable to parse key exchange reply packet"));
4561 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
4563 s->K = dh_find_K(ssh->kex_ctx, s->f);
4565 sha_string(&ssh->exhash, s->hostkeydata, s->hostkeylen);
4566 if (ssh->kex == &ssh_diffiehellman_gex) {
4567 sha_uint32(&ssh->exhash, s->pbits);
4568 sha_mpint(&ssh->exhash, s->p);
4569 sha_mpint(&ssh->exhash, s->g);
4571 sha_mpint(&ssh->exhash, s->e);
4572 sha_mpint(&ssh->exhash, s->f);
4573 sha_mpint(&ssh->exhash, s->K);
4574 SHA_Final(&ssh->exhash, s->exchange_hash);
4576 dh_cleanup(ssh->kex_ctx);
4577 ssh->kex_ctx = NULL;
4580 debug(("Exchange hash is:\n"));
4581 dmemdump(s->exchange_hash, 20);
4584 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
4586 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
4587 (char *)s->exchange_hash, 20)) {
4588 bombout(("Server's host key did not match the signature supplied"));
4593 * Authenticate remote host: verify host key. (We've already
4594 * checked the signature of the exchange hash.)
4596 s->keystr = ssh->hostkey->fmtkey(s->hkey);
4597 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
4598 verify_ssh_host_key(ssh->frontend,
4599 ssh->savedhost, ssh->savedport, ssh->hostkey->keytype,
4600 s->keystr, s->fingerprint);
4601 if (s->first_kex) { /* don't bother logging this in rekeys */
4602 logevent("Host key fingerprint is:");
4603 logevent(s->fingerprint);
4605 sfree(s->fingerprint);
4607 ssh->hostkey->freekey(s->hkey);
4610 * Send SSH2_MSG_NEWKEYS.
4612 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
4613 ssh2_pkt_send(ssh, s->pktout);
4616 * Expect SSH2_MSG_NEWKEYS from server.
4619 if (pktin->type != SSH2_MSG_NEWKEYS) {
4620 bombout(("expected new-keys packet from server"));
4625 * Create and initialise session keys.
4627 if (ssh->cs_cipher_ctx)
4628 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
4629 ssh->cscipher = s->cscipher_tobe;
4630 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
4632 if (ssh->sc_cipher_ctx)
4633 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
4634 ssh->sccipher = s->sccipher_tobe;
4635 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
4637 if (ssh->cs_mac_ctx)
4638 ssh->csmac->free_context(ssh->cs_mac_ctx);
4639 ssh->csmac = s->csmac_tobe;
4640 ssh->cs_mac_ctx = ssh->csmac->make_context();
4642 if (ssh->sc_mac_ctx)
4643 ssh->scmac->free_context(ssh->sc_mac_ctx);
4644 ssh->scmac = s->scmac_tobe;
4645 ssh->sc_mac_ctx = ssh->scmac->make_context();
4647 if (ssh->cs_comp_ctx)
4648 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
4649 ssh->cscomp = s->cscomp_tobe;
4650 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
4652 if (ssh->sc_comp_ctx)
4653 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
4654 ssh->sccomp = s->sccomp_tobe;
4655 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
4658 * Set IVs after keys. Here we use the exchange hash from the
4659 * _first_ key exchange.
4662 unsigned char keyspace[40];
4664 memcpy(ssh->v2_session_id, s->exchange_hash,
4665 sizeof(s->exchange_hash));
4666 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'C',keyspace);
4667 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
4668 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'D',keyspace);
4669 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
4670 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'A',keyspace);
4671 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
4672 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'B',keyspace);
4673 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
4674 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'E',keyspace);
4675 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
4676 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'F',keyspace);
4677 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
4679 logeventf(ssh, "Initialised %.200s client->server encryption",
4680 ssh->cscipher->text_name);
4681 logeventf(ssh, "Initialised %.200s server->client encryption",
4682 ssh->sccipher->text_name);
4683 logeventf(ssh, "Initialised %.200s client->server MAC algorithm",
4684 ssh->csmac->text_name);
4685 logeventf(ssh, "Initialised %.200s server->client MAC algorithm",
4686 ssh->scmac->text_name);
4687 if (ssh->cscomp->text_name)
4688 logeventf(ssh, "Initialised %s compression",
4689 ssh->cscomp->text_name);
4690 if (ssh->sccomp->text_name)
4691 logeventf(ssh, "Initialised %s decompression",
4692 ssh->sccomp->text_name);
4695 if (ssh->kex == &ssh_diffiehellman_gex) {
4701 * If this is the first key exchange phase, we must pass the
4702 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
4703 * wants to see it but because it will need time to initialise
4704 * itself before it sees an actual packet. In subsequent key
4705 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
4706 * it would only confuse the layer above.
4708 if (!s->first_kex) {
4714 * Now we're encrypting. Begin returning 1 to the protocol main
4715 * function so that other things can run on top of the
4716 * transport. If we ever see a KEXINIT, we must go back to the
4719 while (!(pktin && pktin->type == SSH2_MSG_KEXINIT)) {
4722 logevent("Server initiated key re-exchange");
4723 goto begin_key_exchange;
4729 * Add data to an SSH2 channel output buffer.
4731 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
4734 bufchain_add(&c->v.v2.outbuffer, buf, len);
4738 * Attempt to send data on an SSH2 channel.
4740 static int ssh2_try_send(struct ssh_channel *c)
4743 struct Packet *pktout;
4745 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
4748 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
4749 if ((unsigned)len > c->v.v2.remwindow)
4750 len = c->v.v2.remwindow;
4751 if ((unsigned)len > c->v.v2.remmaxpkt)
4752 len = c->v.v2.remmaxpkt;
4753 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
4754 ssh2_pkt_adduint32(pktout, c->remoteid);
4755 dont_log_data(ssh, pktout, PKTLOG_OMIT);
4756 ssh2_pkt_addstring_start(pktout);
4757 ssh2_pkt_addstring_data(pktout, data, len);
4758 end_log_omission(ssh, pktout);
4759 ssh2_pkt_send(ssh, pktout);
4760 bufchain_consume(&c->v.v2.outbuffer, len);
4761 c->v.v2.remwindow -= len;
4765 * After having sent as much data as we can, return the amount
4768 return bufchain_size(&c->v.v2.outbuffer);
4772 * Potentially enlarge the window on an SSH2 channel.
4774 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin)
4779 * Never send WINDOW_ADJUST for a channel that the remote side
4780 * already thinks it's closed; there's no point, since it won't
4781 * be sending any more data anyway.
4786 if (newwin > c->v.v2.locwindow) {
4787 struct Packet *pktout;
4789 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4790 ssh2_pkt_adduint32(pktout, c->remoteid);
4791 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
4792 ssh2_pkt_send(ssh, pktout);
4793 c->v.v2.locwindow = newwin;
4798 * Handle the SSH2 userauth and connection layers.
4800 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
4801 struct Packet *pktin)
4803 struct do_ssh2_authconn_state {
4805 AUTH_INVALID, AUTH_PUBLICKEY_AGENT, AUTH_PUBLICKEY_FILE,
4807 AUTH_KEYBOARD_INTERACTIVE
4811 AUTH_TYPE_PUBLICKEY,
4812 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
4813 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
4815 AUTH_TYPE_KEYBOARD_INTERACTIVE,
4816 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
4818 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
4819 int tried_pubkey_config, tried_agent, tried_keyb_inter;
4820 int kbd_inter_running;
4822 int num_prompts, curr_prompt, echo;
4827 void *publickey_blob;
4828 int publickey_bloblen;
4829 unsigned char request[5], *response, *p;
4833 char *pkblob, *alg, *commentp;
4834 int pklen, alglen, commentlen;
4835 int siglen, retlen, len;
4836 char *q, *agentreq, *ret;
4838 int num_env, env_left, env_ok;
4839 struct Packet *pktout;
4841 crState(do_ssh2_authconn_state);
4843 crBegin(ssh->do_ssh2_authconn_crstate);
4846 * Request userauth protocol, and await a response to it.
4848 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
4849 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
4850 ssh2_pkt_send(ssh, s->pktout);
4851 crWaitUntilV(pktin);
4852 if (pktin->type != SSH2_MSG_SERVICE_ACCEPT) {
4853 bombout(("Server refused user authentication protocol"));
4858 * We repeat this whole loop, including the username prompt,
4859 * until we manage a successful authentication. If the user
4860 * types the wrong _password_, they can be sent back to the
4861 * beginning to try another username, if this is configured on.
4862 * (If they specify a username in the config, they are never
4863 * asked, even if they do give a wrong password.)
4865 * I think this best serves the needs of
4867 * - the people who have no configuration, no keys, and just
4868 * want to try repeated (username,password) pairs until they
4869 * type both correctly
4871 * - people who have keys and configuration but occasionally
4872 * need to fall back to passwords
4874 * - people with a key held in Pageant, who might not have
4875 * logged in to a particular machine before; so they want to
4876 * type a username, and then _either_ their key will be
4877 * accepted, _or_ they will type a password. If they mistype
4878 * the username they will want to be able to get back and
4881 s->username[0] = '\0';
4882 s->got_username = FALSE;
4887 if (s->got_username && !ssh->cfg.change_username) {
4889 * We got a username last time round this loop, and
4890 * with change_username turned off we don't try to get
4893 } else if (!*ssh->cfg.username) {
4894 if (ssh_get_line && !ssh_getline_pw_only) {
4895 if (!ssh_get_line("login as: ",
4896 s->username, sizeof(s->username), FALSE)) {
4898 * get_line failed to get a username.
4901 logevent("No username provided. Abandoning session.");
4902 ssh_closing((Plug)ssh, NULL, 0, 0);
4906 int ret; /* need not be saved across crReturn */
4907 c_write_str(ssh, "login as: ");
4909 setup_userpass_input(ssh, s->username, sizeof(s->username), 1);
4911 crWaitUntilV(!pktin);
4912 ret = process_userpass_input(ssh, in, inlen);
4916 c_write_str(ssh, "\r\n");
4918 s->username[strcspn(s->username, "\n\r")] = '\0';
4921 strncpy(s->username, ssh->cfg.username, sizeof(s->username));
4922 s->username[sizeof(s->username)-1] = '\0';
4923 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
4924 stuff = dupprintf("Using username \"%s\".\r\n", s->username);
4925 c_write_str(ssh, stuff);
4929 s->got_username = TRUE;
4932 * Send an authentication request using method "none": (a)
4933 * just in case it succeeds, and (b) so that we know what
4934 * authentication methods we can usefully try next.
4936 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4938 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4939 ssh2_pkt_addstring(s->pktout, s->username);
4940 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
4941 ssh2_pkt_addstring(s->pktout, "none"); /* method */
4942 ssh2_pkt_send(ssh, s->pktout);
4943 s->type = AUTH_TYPE_NONE;
4945 s->we_are_in = FALSE;
4947 s->tried_pubkey_config = FALSE;
4948 s->tried_agent = FALSE;
4949 s->tried_keyb_inter = FALSE;
4950 s->kbd_inter_running = FALSE;
4951 /* Load the pub half of ssh->cfg.keyfile so we notice if it's in Pageant */
4952 if (!filename_is_null(ssh->cfg.keyfile)) {
4954 logeventf(ssh, "Reading private key file \"%.150s\"",
4955 filename_to_str(&ssh->cfg.keyfile));
4956 keytype = key_type(&ssh->cfg.keyfile);
4957 if (keytype == SSH_KEYTYPE_SSH2) {
4959 ssh2_userkey_loadpub(&ssh->cfg.keyfile, NULL,
4960 &s->publickey_bloblen, NULL);
4963 logeventf(ssh, "Unable to use this key file (%s)",
4964 key_type_to_str(keytype));
4965 msgbuf = dupprintf("Unable to use key file \"%.150s\""
4967 filename_to_str(&ssh->cfg.keyfile),
4968 key_type_to_str(keytype));
4969 c_write_str(ssh, msgbuf);
4971 s->publickey_blob = NULL;
4974 s->publickey_blob = NULL;
4978 * Wait for the result of the last authentication request.
4981 crWaitUntilV(pktin);
4982 while (pktin->type == SSH2_MSG_USERAUTH_BANNER) {
4986 * Don't show the banner if we're operating in
4987 * non-verbose non-interactive mode. (It's probably
4988 * a script, which means nobody will read the
4989 * banner _anyway_, and moreover the printing of
4990 * the banner will screw up processing on the
4991 * output of (say) plink.)
4993 if (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE)) {
4994 ssh_pkt_getstring(pktin, &banner, &size);
4996 c_write_untrusted(ssh, banner, size);
4998 crWaitUntilV(pktin);
5000 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
5001 logevent("Access granted");
5002 s->we_are_in = TRUE;
5006 if (s->kbd_inter_running &&
5007 pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
5009 * This is either a further set-of-prompts packet
5010 * in keyboard-interactive authentication, or it's
5011 * the same one and we came back here with `gotit'
5012 * set. In the former case, we must reset the
5013 * curr_prompt variable.
5017 } else if (pktin->type != SSH2_MSG_USERAUTH_FAILURE) {
5018 bombout(("Strange packet received during authentication: type %d",
5026 * OK, we're now sitting on a USERAUTH_FAILURE message, so
5027 * we can look at the string in it and know what we can
5028 * helpfully try next.
5030 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
5033 ssh_pkt_getstring(pktin, &methods, &methlen);
5034 s->kbd_inter_running = FALSE;
5035 if (!ssh2_pkt_getbool(pktin)) {
5037 * We have received an unequivocal Access
5038 * Denied. This can translate to a variety of
5041 * - if we'd just tried "none" authentication,
5042 * it's not worth printing anything at all
5044 * - if we'd just tried a public key _offer_,
5045 * the message should be "Server refused our
5046 * key" (or no message at all if the key
5047 * came from Pageant)
5049 * - if we'd just tried anything else, the
5050 * message really should be "Access denied".
5052 * Additionally, if we'd just tried password
5053 * authentication, we should break out of this
5054 * whole loop so as to go back to the username
5055 * prompt (iff we're configured to allow
5056 * username change attempts).
5058 if (s->type == AUTH_TYPE_NONE) {
5060 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
5061 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
5062 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
5063 c_write_str(ssh, "Server refused our key\r\n");
5064 logevent("Server refused public key");
5065 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
5066 /* server declined keyboard-interactive; ignore */
5068 c_write_str(ssh, "Access denied\r\n");
5069 logevent("Access denied");
5070 if (s->type == AUTH_TYPE_PASSWORD &&
5071 ssh->cfg.change_username) {
5072 /* XXX perhaps we should allow
5073 * keyboard-interactive to do this too? */
5074 s->we_are_in = FALSE;
5079 c_write_str(ssh, "Further authentication required\r\n");
5080 logevent("Further authentication required");
5084 in_commasep_string("publickey", methods, methlen);
5086 in_commasep_string("password", methods, methlen);
5087 s->can_keyb_inter = ssh->cfg.try_ki_auth &&
5088 in_commasep_string("keyboard-interactive", methods, methlen);
5092 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
5096 * Most password/passphrase prompts will be
5097 * non-echoing, so we set this to 0 by default.
5098 * Exception is that some keyboard-interactive prompts
5099 * can be echoing, in which case we'll set this to 1.
5103 if (!s->method && s->can_pubkey &&
5104 agent_exists() && !s->tried_agent) {
5106 * Attempt public-key authentication using Pageant.
5111 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
5112 ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
5114 s->tried_agent = TRUE;
5116 logevent("Pageant is running. Requesting keys.");
5118 /* Request the keys held by the agent. */
5119 PUT_32BIT(s->request, 1);
5120 s->request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
5121 if (!agent_query(s->request, 5, &r, &s->responselen,
5122 ssh_agent_callback, ssh)) {
5126 bombout(("Unexpected data from server while"
5127 " waiting for agent response"));
5130 } while (pktin || inlen > 0);
5131 r = ssh->agent_response;
5132 s->responselen = ssh->agent_response_len;
5134 s->response = (unsigned char *) r;
5135 if (s->response && s->responselen >= 5 &&
5136 s->response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
5137 s->p = s->response + 5;
5138 s->nkeys = GET_32BIT(s->p);
5142 sprintf(buf, "Pageant has %d SSH2 keys", s->nkeys);
5145 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
5150 sprintf(buf, "Trying Pageant key #%d", s->keyi);
5153 s->pklen = GET_32BIT(s->p);
5155 if (s->publickey_blob &&
5156 s->pklen == s->publickey_bloblen &&
5157 !memcmp(s->p, s->publickey_blob,
5158 s->publickey_bloblen)) {
5159 logevent("This key matches configured key file");
5160 s->tried_pubkey_config = 1;
5162 s->pkblob = (char *)s->p;
5164 s->alglen = GET_32BIT(s->pkblob);
5165 s->alg = s->pkblob + 4;
5166 s->commentlen = GET_32BIT(s->p);
5168 s->commentp = (char *)s->p;
5169 s->p += s->commentlen;
5170 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
5171 ssh2_pkt_addstring(s->pktout, s->username);
5172 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
5173 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
5174 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
5175 ssh2_pkt_addstring_start(s->pktout);
5176 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
5177 ssh2_pkt_addstring_start(s->pktout);
5178 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
5179 ssh2_pkt_send(ssh, s->pktout);
5181 crWaitUntilV(pktin);
5182 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
5183 logevent("Key refused");
5187 if (flags & FLAG_VERBOSE) {
5188 c_write_str(ssh, "Authenticating with "
5190 c_write(ssh, s->commentp, s->commentlen);
5191 c_write_str(ssh, "\" from agent\r\n");
5195 * Server is willing to accept the key.
5196 * Construct a SIGN_REQUEST.
5198 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
5199 ssh2_pkt_addstring(s->pktout, s->username);
5200 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
5201 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
5202 ssh2_pkt_addbool(s->pktout, TRUE);
5203 ssh2_pkt_addstring_start(s->pktout);
5204 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
5205 ssh2_pkt_addstring_start(s->pktout);
5206 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
5208 s->siglen = s->pktout->length - 5 + 4 + 20;
5209 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
5211 s->len = 1; /* message type */
5212 s->len += 4 + s->pklen; /* key blob */
5213 s->len += 4 + s->siglen; /* data to sign */
5214 s->len += 4; /* flags */
5215 s->agentreq = snewn(4 + s->len, char);
5216 PUT_32BIT(s->agentreq, s->len);
5217 s->q = s->agentreq + 4;
5218 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
5219 PUT_32BIT(s->q, s->pklen);
5221 memcpy(s->q, s->pkblob, s->pklen);
5223 PUT_32BIT(s->q, s->siglen);
5225 /* Now the data to be signed... */
5226 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
5227 PUT_32BIT(s->q, 20);
5230 memcpy(s->q, ssh->v2_session_id, 20);
5232 memcpy(s->q, s->pktout->data + 5,
5233 s->pktout->length - 5);
5234 s->q += s->pktout->length - 5;
5235 /* And finally the (zero) flags word. */
5237 if (!agent_query(s->agentreq, s->len + 4,
5239 ssh_agent_callback, ssh)) {
5243 bombout(("Unexpected data from server"
5244 " while waiting for agent"
5248 } while (pktin || inlen > 0);
5249 vret = ssh->agent_response;
5250 s->retlen = ssh->agent_response_len;
5255 if (s->ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
5256 logevent("Sending Pageant's response");
5257 ssh2_add_sigblob(ssh, s->pktout,
5258 s->pkblob, s->pklen,
5260 GET_32BIT(s->ret + 5));
5261 ssh2_pkt_send(ssh, s->pktout);
5266 ("Pageant failed to answer challenge");
5277 if (!s->method && s->can_pubkey && s->publickey_blob
5278 && !s->tried_pubkey_config) {
5279 unsigned char *pub_blob;
5280 char *algorithm, *comment;
5283 s->tried_pubkey_config = TRUE;
5285 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
5286 ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
5289 * Try the public key supplied in the configuration.
5291 * First, offer the public blob to see if the server is
5292 * willing to accept it.
5295 (unsigned char *)ssh2_userkey_loadpub(&ssh->cfg.keyfile,
5300 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
5301 ssh2_pkt_addstring(s->pktout, s->username);
5302 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
5303 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
5304 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
5305 ssh2_pkt_addstring(s->pktout, algorithm);
5306 ssh2_pkt_addstring_start(s->pktout);
5307 ssh2_pkt_addstring_data(s->pktout, (char *)pub_blob,
5309 ssh2_pkt_send(ssh, s->pktout);
5310 logevent("Offered public key");
5312 crWaitUntilV(pktin);
5313 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
5315 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
5316 continue; /* key refused; give up on it */
5319 logevent("Offer of public key accepted");
5321 * Actually attempt a serious authentication using
5324 if (ssh2_userkey_encrypted(&ssh->cfg.keyfile, &comment)) {
5325 sprintf(s->pwprompt,
5326 "Passphrase for key \"%.100s\": ",
5332 if (flags & FLAG_VERBOSE) {
5333 c_write_str(ssh, "Authenticating with public key \"");
5334 c_write_str(ssh, comment);
5335 c_write_str(ssh, "\"\r\n");
5337 s->method = AUTH_PUBLICKEY_FILE;
5341 if (!s->method && s->can_keyb_inter && !s->tried_keyb_inter) {
5342 s->method = AUTH_KEYBOARD_INTERACTIVE;
5343 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
5344 s->tried_keyb_inter = TRUE;
5346 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
5347 ssh->pkt_ctx |= SSH2_PKTCTX_KBDINTER;
5349 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
5350 ssh2_pkt_addstring(s->pktout, s->username);
5351 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
5352 ssh2_pkt_addstring(s->pktout, "keyboard-interactive"); /* method */
5353 ssh2_pkt_addstring(s->pktout, ""); /* lang */
5354 ssh2_pkt_addstring(s->pktout, "");
5355 ssh2_pkt_send(ssh, s->pktout);
5357 crWaitUntilV(pktin);
5358 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
5359 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE)
5361 logevent("Keyboard-interactive authentication refused");
5362 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
5366 s->kbd_inter_running = TRUE;
5370 if (s->kbd_inter_running) {
5371 s->method = AUTH_KEYBOARD_INTERACTIVE;
5372 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
5373 s->tried_keyb_inter = TRUE;
5375 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
5376 ssh->pkt_ctx |= SSH2_PKTCTX_KBDINTER;
5378 if (s->curr_prompt == 0) {
5380 * We've got a fresh USERAUTH_INFO_REQUEST.
5381 * Display header data, and start going through
5384 char *name, *inst, *lang;
5385 int name_len, inst_len, lang_len;
5387 ssh_pkt_getstring(pktin, &name, &name_len);
5388 ssh_pkt_getstring(pktin, &inst, &inst_len);
5389 ssh_pkt_getstring(pktin, &lang, &lang_len);
5391 c_write_untrusted(ssh, name, name_len);
5392 c_write_str(ssh, "\r\n");
5395 c_write_untrusted(ssh, inst, inst_len);
5396 c_write_str(ssh, "\r\n");
5398 s->num_prompts = ssh_pkt_getuint32(pktin);
5402 * If there are prompts remaining in the packet,
5403 * display one and get a response.
5405 if (s->curr_prompt < s->num_prompts) {
5409 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
5410 if (prompt_len > 0) {
5411 static const char trunc[] = "<prompt truncated>: ";
5412 static const int prlen = sizeof(s->pwprompt) -
5414 if (prompt_len > prlen) {
5415 memcpy(s->pwprompt, prompt, prlen);
5416 strcpy(s->pwprompt + prlen, trunc);
5418 memcpy(s->pwprompt, prompt, prompt_len);
5419 s->pwprompt[prompt_len] = '\0';
5423 "<server failed to send prompt>: ");
5425 s->echo = ssh2_pkt_getbool(pktin);
5431 if (!s->method && s->can_passwd) {
5432 s->method = AUTH_PASSWORD;
5433 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
5434 ssh->pkt_ctx |= SSH2_PKTCTX_PASSWORD;
5435 sprintf(s->pwprompt, "%.90s@%.90s's password: ", s->username,
5442 if (!ssh_get_line(s->pwprompt, s->password,
5443 sizeof(s->password), TRUE)) {
5445 * get_line failed to get a password (for
5446 * example because one was supplied on the
5447 * command line which has already failed to
5450 s->pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
5451 ssh2_pkt_adduint32(s->pktout,SSH2_DISCONNECT_BY_APPLICATION);
5452 ssh2_pkt_addstring(s->pktout, "No more passwords available"
5454 ssh2_pkt_addstring(s->pktout, "en"); /* language tag */
5455 ssh2_pkt_send(ssh, s->pktout);
5456 logevent("Unable to authenticate");
5457 connection_fatal(ssh->frontend,
5458 "Unable to authenticate");
5459 ssh_closing((Plug)ssh, NULL, 0, 0);
5463 int ret; /* need not be saved across crReturn */
5464 c_write_untrusted(ssh, s->pwprompt, strlen(s->pwprompt));
5467 setup_userpass_input(ssh, s->password,
5468 sizeof(s->password), s->echo);
5470 crWaitUntilV(!pktin);
5471 ret = process_userpass_input(ssh, in, inlen);
5475 c_write_str(ssh, "\r\n");
5479 if (s->method == AUTH_PUBLICKEY_FILE) {
5481 * We have our passphrase. Now try the actual authentication.
5483 struct ssh2_userkey *key;
5484 const char *error = NULL;
5486 key = ssh2_load_userkey(&ssh->cfg.keyfile, s->password,
5488 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
5489 if (key == SSH2_WRONG_PASSPHRASE) {
5490 c_write_str(ssh, "Wrong passphrase\r\n");
5491 s->tried_pubkey_config = FALSE;
5493 c_write_str(ssh, "Unable to load private key (");
5494 c_write_str(ssh, error);
5495 c_write_str(ssh, ")\r\n");
5496 s->tried_pubkey_config = TRUE;
5498 /* Send a spurious AUTH_NONE to return to the top. */
5499 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
5500 ssh2_pkt_addstring(s->pktout, s->username);
5501 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
5502 ssh2_pkt_addstring(s->pktout, "none"); /* method */
5503 ssh2_pkt_send(ssh, s->pktout);
5504 s->type = AUTH_TYPE_NONE;
5506 unsigned char *pkblob, *sigblob, *sigdata;
5507 int pkblob_len, sigblob_len, sigdata_len;
5511 * We have loaded the private key and the server
5512 * has announced that it's willing to accept it.
5513 * Hallelujah. Generate a signature and send it.
5515 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
5516 ssh2_pkt_addstring(s->pktout, s->username);
5517 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
5518 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
5519 ssh2_pkt_addbool(s->pktout, TRUE);
5520 ssh2_pkt_addstring(s->pktout, key->alg->name);
5521 pkblob = key->alg->public_blob(key->data, &pkblob_len);
5522 ssh2_pkt_addstring_start(s->pktout);
5523 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob, pkblob_len);
5526 * The data to be signed is:
5530 * followed by everything so far placed in the
5533 sigdata_len = s->pktout->length - 5 + 4 + 20;
5534 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
5536 sigdata = snewn(sigdata_len, unsigned char);
5538 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
5539 PUT_32BIT(sigdata+p, 20);
5542 memcpy(sigdata+p, ssh->v2_session_id, 20); p += 20;
5543 memcpy(sigdata+p, s->pktout->data + 5,
5544 s->pktout->length - 5);
5545 p += s->pktout->length - 5;
5546 assert(p == sigdata_len);
5547 sigblob = key->alg->sign(key->data, (char *)sigdata,
5548 sigdata_len, &sigblob_len);
5549 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
5550 sigblob, sigblob_len);
5555 ssh2_pkt_send(ssh, s->pktout);
5556 s->type = AUTH_TYPE_PUBLICKEY;
5557 key->alg->freekey(key->data);
5559 } else if (s->method == AUTH_PASSWORD) {
5561 * We send the password packet lumped tightly together with
5562 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
5563 * string long enough to make the total length of the two
5564 * packets constant. This should ensure that a passive
5565 * listener doing traffic analyis can't work out the length
5568 * For this to work, we need an assumption about the
5569 * maximum length of the password packet. I think 256 is
5570 * pretty conservative. Anyone using a password longer than
5571 * that probably doesn't have much to worry about from
5572 * people who find out how long their password is!
5574 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
5575 ssh2_pkt_addstring(s->pktout, s->username);
5576 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
5577 ssh2_pkt_addstring(s->pktout, "password");
5578 ssh2_pkt_addbool(s->pktout, FALSE);
5579 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
5580 ssh2_pkt_addstring(s->pktout, s->password);
5581 memset(s->password, 0, sizeof(s->password));
5582 end_log_omission(ssh, s->pktout);
5583 ssh2_pkt_defer(ssh, s->pktout);
5585 * We'll include a string that's an exact multiple of the
5586 * cipher block size. If the cipher is NULL for some
5587 * reason, we don't do this trick at all because we gain
5590 if (ssh->cscipher) {
5593 stringlen = (256 - ssh->deferred_len);
5594 stringlen += ssh->cscipher->blksize - 1;
5595 stringlen -= (stringlen % ssh->cscipher->blksize);
5598 * Temporarily disable actual compression,
5599 * so we can guarantee to get this string
5600 * exactly the length we want it. The
5601 * compression-disabling routine should
5602 * return an integer indicating how many
5603 * bytes we should adjust our string length
5607 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
5609 s->pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
5610 ssh2_pkt_addstring_start(s->pktout);
5611 for (i = 0; i < stringlen; i++) {
5612 char c = (char) random_byte();
5613 ssh2_pkt_addstring_data(s->pktout, &c, 1);
5615 ssh2_pkt_defer(ssh, s->pktout);
5617 ssh_pkt_defersend(ssh);
5618 logevent("Sent password");
5619 s->type = AUTH_TYPE_PASSWORD;
5620 } else if (s->method == AUTH_KEYBOARD_INTERACTIVE) {
5621 if (s->curr_prompt == 0) {
5622 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
5623 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
5625 if (s->need_pw) { /* only add pw if we just got one! */
5626 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
5627 ssh2_pkt_addstring(s->pktout, s->password);
5628 memset(s->password, 0, sizeof(s->password));
5629 end_log_omission(ssh, s->pktout);
5632 if (s->curr_prompt >= s->num_prompts) {
5633 ssh2_pkt_send(ssh, s->pktout);
5636 * If there are prompts remaining, we set
5637 * `gotit' so that we won't attempt to get
5638 * another packet. Then we go back round the
5639 * loop and will end up retrieving another
5640 * prompt out of the existing packet. Funky or
5645 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
5647 c_write_str(ssh, "No supported authentication methods"
5648 " left to try!\r\n");
5649 logevent("No supported authentications offered."
5651 s->pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
5652 ssh2_pkt_adduint32(s->pktout, SSH2_DISCONNECT_BY_APPLICATION);
5653 ssh2_pkt_addstring(s->pktout, "No supported authentication"
5654 " methods available");
5655 ssh2_pkt_addstring(s->pktout, "en"); /* language tag */
5656 ssh2_pkt_send(ssh, s->pktout);
5657 ssh_closing((Plug)ssh, NULL, 0, 0);
5661 } while (!s->we_are_in);
5664 * Now we're authenticated for the connection protocol. The
5665 * connection protocol will automatically have started at this
5666 * point; there's no need to send SERVICE_REQUEST.
5669 ssh->channels = newtree234(ssh_channelcmp);
5672 * Create the main session channel.
5674 if (!ssh->cfg.ssh_no_shell) {
5675 ssh->mainchan = snew(struct ssh_channel);
5676 ssh->mainchan->ssh = ssh;
5677 ssh->mainchan->localid = alloc_channel_id(ssh);
5678 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
5679 ssh2_pkt_addstring(s->pktout, "session");
5680 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
5681 ssh->mainchan->v.v2.locwindow = OUR_V2_WINSIZE;
5682 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
5683 ssh2_pkt_adduint32(s->pktout, 0x4000UL); /* our max pkt size */
5684 ssh2_pkt_send(ssh, s->pktout);
5685 crWaitUntilV(pktin);
5686 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
5687 bombout(("Server refused to open a session"));
5689 /* FIXME: error data comes back in FAILURE packet */
5691 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
5692 bombout(("Server's channel confirmation cited wrong channel"));
5695 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
5696 ssh->mainchan->type = CHAN_MAINSESSION;
5697 ssh->mainchan->closes = 0;
5698 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
5699 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
5700 bufchain_init(&ssh->mainchan->v.v2.outbuffer);
5701 add234(ssh->channels, ssh->mainchan);
5702 update_specials_menu(ssh->frontend);
5703 logevent("Opened channel for session");
5705 ssh->mainchan = NULL;
5708 * Potentially enable X11 forwarding.
5710 if (ssh->mainchan && ssh->cfg.x11_forward) {
5711 char proto[20], data[64];
5712 logevent("Requesting X11 forwarding");
5713 ssh->x11auth = x11_invent_auth(proto, sizeof(proto),
5714 data, sizeof(data), ssh->cfg.x11_auth);
5715 x11_get_real_auth(ssh->x11auth, ssh->cfg.x11_display);
5716 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
5717 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
5718 ssh2_pkt_addstring(s->pktout, "x11-req");
5719 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
5720 ssh2_pkt_addbool(s->pktout, 0); /* many connections */
5721 ssh2_pkt_addstring(s->pktout, proto);
5722 ssh2_pkt_addstring(s->pktout, data);
5723 ssh2_pkt_adduint32(s->pktout, x11_get_screen_number(ssh->cfg.x11_display));
5724 ssh2_pkt_send(ssh, s->pktout);
5727 crWaitUntilV(pktin);
5728 if (pktin->type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5729 unsigned i = ssh_pkt_getuint32(pktin);
5730 struct ssh_channel *c;
5731 c = find234(ssh->channels, &i, ssh_channelfind);
5733 continue; /* nonexistent channel */
5734 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
5736 } while (pktin->type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5738 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
5739 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
5740 bombout(("Unexpected response to X11 forwarding request:"
5741 " packet type %d", pktin->type));
5744 logevent("X11 forwarding refused");
5746 logevent("X11 forwarding enabled");
5747 ssh->X11_fwd_enabled = TRUE;
5752 * Enable port forwardings.
5757 int sport,dport,sserv,dserv;
5758 char sports[256], dports[256], saddr[256], host[256];
5760 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5761 /* Add port forwardings. */
5762 ssh->portfwd_strptr = ssh->cfg.portfwd;
5763 while (*ssh->portfwd_strptr) {
5764 type = *ssh->portfwd_strptr++;
5767 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != '\t') {
5768 if (*ssh->portfwd_strptr == ':') {
5770 * We've seen a colon in the middle of the
5771 * source port number. This means that
5772 * everything we've seen until now is the
5773 * source _address_, so we'll move it into
5774 * saddr and start sports from the beginning
5777 ssh->portfwd_strptr++;
5779 strcpy(saddr, sports);
5782 if (n < 255) sports[n++] = *ssh->portfwd_strptr++;
5786 if (*ssh->portfwd_strptr == '\t')
5787 ssh->portfwd_strptr++;
5789 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != ':') {
5790 if (n < 255) host[n++] = *ssh->portfwd_strptr++;
5793 if (*ssh->portfwd_strptr == ':')
5794 ssh->portfwd_strptr++;
5796 while (*ssh->portfwd_strptr) {
5797 if (n < 255) dports[n++] = *ssh->portfwd_strptr++;
5800 ssh->portfwd_strptr++;
5801 dport = atoi(dports);
5805 dport = net_service_lookup(dports);
5807 logeventf(ssh, "Service lookup failed for destination"
5808 " port \"%s\"", dports);
5812 while (*ssh->portfwd_strptr) ssh->portfwd_strptr++;
5814 ssh->portfwd_strptr++; /* eat the NUL and move to next one */
5816 sport = atoi(sports);
5820 sport = net_service_lookup(sports);
5822 logeventf(ssh, "Service lookup failed for source"
5823 " port \"%s\"", sports);
5826 if (sport && dport) {
5827 /* Set up a description of the source port. */
5828 static char *sportdesc;
5829 sportdesc = dupprintf("%.*s%.*s%.*s%.*s%d%.*s",
5830 (int)(*saddr?strlen(saddr):0), *saddr?saddr:NULL,
5831 (int)(*saddr?1:0), ":",
5832 (int)(sserv ? strlen(sports) : 0), sports,
5833 sserv, "(", sport, sserv, ")");
5835 /* Verbose description of the destination port */
5836 char *dportdesc = dupprintf("%s:%.*s%.*s%d%.*s",
5838 (int)(dserv ? strlen(dports) : 0), dports,
5839 dserv, "(", dport, dserv, ")");
5840 const char *err = pfd_addforward(host, dport,
5841 *saddr ? saddr : NULL,
5842 sport, ssh, &ssh->cfg);
5844 logeventf(ssh, "Local port %s forward to %s"
5845 " failed: %s", sportdesc, dportdesc, err);
5847 logeventf(ssh, "Local port %s forwarding to %s",
5848 sportdesc, dportdesc);
5851 } else if (type == 'D') {
5852 const char *err = pfd_addforward(NULL, -1,
5853 *saddr ? saddr : NULL,
5854 sport, ssh, &ssh->cfg);
5856 logeventf(ssh, "Local port %s SOCKS dynamic forward"
5857 " setup failed: %s", sportdesc, err);
5859 logeventf(ssh, "Local port %s doing SOCKS"
5860 " dynamic forwarding", sportdesc);
5863 struct ssh_rportfwd *pf;
5864 pf = snew(struct ssh_rportfwd);
5865 strcpy(pf->dhost, host);
5868 if (add234(ssh->rportfwds, pf) != pf) {
5869 logeventf(ssh, "Duplicate remote port forwarding"
5870 " to %s:%d", host, dport);
5873 logeventf(ssh, "Requesting remote port %s"
5874 " forward to %s:%.*s%.*s%d%.*s",
5877 (int)(dserv ? strlen(dports) : 0), dports,
5878 dserv, "(", dport, dserv, ")");
5879 s->pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5880 ssh2_pkt_addstring(s->pktout, "tcpip-forward");
5881 ssh2_pkt_addbool(s->pktout, 1);/* want reply */
5883 ssh2_pkt_addstring(s->pktout, saddr);
5884 } else if (ssh->cfg.rport_acceptall) {
5885 ssh2_pkt_addstring(s->pktout, "0.0.0.0");
5887 ssh2_pkt_addstring(s->pktout, "127.0.0.1");
5889 ssh2_pkt_adduint32(s->pktout, sport);
5890 ssh2_pkt_send(ssh, s->pktout);
5893 crWaitUntilV(pktin);
5894 if (pktin->type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5895 unsigned i = ssh_pkt_getuint32(pktin);
5896 struct ssh_channel *c;
5897 c = find234(ssh->channels, &i, ssh_channelfind);
5899 continue;/* nonexistent channel */
5900 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
5902 } while (pktin->type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5904 if (pktin->type != SSH2_MSG_REQUEST_SUCCESS) {
5905 if (pktin->type != SSH2_MSG_REQUEST_FAILURE) {
5906 bombout(("Unexpected response to port "
5907 "forwarding request: packet type %d",
5911 logevent("Server refused this port forwarding");
5913 logevent("Remote port forwarding enabled");
5923 * Potentially enable agent forwarding.
5925 if (ssh->mainchan && ssh->cfg.agentfwd && agent_exists()) {
5926 logevent("Requesting OpenSSH-style agent forwarding");
5927 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
5928 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
5929 ssh2_pkt_addstring(s->pktout, "auth-agent-req@openssh.com");
5930 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
5931 ssh2_pkt_send(ssh, s->pktout);
5934 crWaitUntilV(pktin);
5935 if (pktin->type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5936 unsigned i = ssh_pkt_getuint32(pktin);
5937 struct ssh_channel *c;
5938 c = find234(ssh->channels, &i, ssh_channelfind);
5940 continue; /* nonexistent channel */
5941 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
5943 } while (pktin->type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5945 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
5946 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
5947 bombout(("Unexpected response to agent forwarding request:"
5948 " packet type %d", pktin->type));
5951 logevent("Agent forwarding refused");
5953 logevent("Agent forwarding enabled");
5954 ssh->agentfwd_enabled = TRUE;
5959 * Now allocate a pty for the session.
5961 if (ssh->mainchan && !ssh->cfg.nopty) {
5962 /* Unpick the terminal-speed string. */
5963 /* XXX perhaps we should allow no speeds to be sent. */
5964 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5965 sscanf(ssh->cfg.termspeed, "%d,%d", &ssh->ospeed, &ssh->ispeed);
5966 /* Build the pty request. */
5967 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
5968 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
5969 ssh2_pkt_addstring(s->pktout, "pty-req");
5970 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
5971 ssh2_pkt_addstring(s->pktout, ssh->cfg.termtype);
5972 ssh2_pkt_adduint32(s->pktout, ssh->term_width);
5973 ssh2_pkt_adduint32(s->pktout, ssh->term_height);
5974 ssh2_pkt_adduint32(s->pktout, 0); /* pixel width */
5975 ssh2_pkt_adduint32(s->pktout, 0); /* pixel height */
5976 ssh2_pkt_addstring_start(s->pktout);
5977 ssh2_pkt_addbyte(s->pktout, 128); /* TTY_OP_ISPEED */
5978 ssh2_pkt_adduint32(s->pktout, ssh->ispeed);
5979 ssh2_pkt_addbyte(s->pktout, 129); /* TTY_OP_OSPEED */
5980 ssh2_pkt_adduint32(s->pktout, ssh->ospeed);
5981 ssh2_pkt_addstring_data(s->pktout, "\0", 1); /* TTY_OP_END */
5982 ssh2_pkt_send(ssh, s->pktout);
5983 ssh->state = SSH_STATE_INTERMED;
5986 crWaitUntilV(pktin);
5987 if (pktin->type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5988 unsigned i = ssh_pkt_getuint32(pktin);
5989 struct ssh_channel *c;
5990 c = find234(ssh->channels, &i, ssh_channelfind);
5992 continue; /* nonexistent channel */
5993 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
5995 } while (pktin->type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5997 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
5998 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
5999 bombout(("Unexpected response to pty request:"
6000 " packet type %d", pktin->type));
6003 c_write_str(ssh, "Server refused to allocate pty\r\n");
6004 ssh->editing = ssh->echoing = 1;
6006 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
6007 ssh->ospeed, ssh->ispeed);
6010 ssh->editing = ssh->echoing = 1;
6014 * Send environment variables.
6016 * Simplest thing here is to send all the requests at once, and
6017 * then wait for a whole bunch of successes or failures.
6019 if (ssh->mainchan && *ssh->cfg.environmt) {
6020 char *e = ssh->cfg.environmt;
6021 char *var, *varend, *val;
6027 while (*e && *e != '\t') e++;
6029 if (*e == '\t') e++;
6034 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6035 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
6036 ssh2_pkt_addstring(s->pktout, "env");
6037 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
6038 ssh2_pkt_addstring_start(s->pktout);
6039 ssh2_pkt_addstring_data(s->pktout, var, varend-var);
6040 ssh2_pkt_addstring(s->pktout, val);
6041 ssh2_pkt_send(ssh, s->pktout);
6046 logeventf(ssh, "Sent %d environment variables", s->num_env);
6049 s->env_left = s->num_env;
6051 while (s->env_left > 0) {
6053 crWaitUntilV(pktin);
6054 if (pktin->type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
6055 unsigned i = ssh_pkt_getuint32(pktin);
6056 struct ssh_channel *c;
6057 c = find234(ssh->channels, &i, ssh_channelfind);
6059 continue; /* nonexistent channel */
6060 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
6062 } while (pktin->type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
6064 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
6065 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
6066 bombout(("Unexpected response to environment request:"
6067 " packet type %d", pktin->type));
6077 if (s->env_ok == s->num_env) {
6078 logevent("All environment variables successfully set");
6079 } else if (s->env_ok == 0) {
6080 logevent("All environment variables refused");
6081 c_write_str(ssh, "Server refused to set environment variables\r\n");
6083 logeventf(ssh, "%d environment variables refused",
6084 s->num_env - s->env_ok);
6085 c_write_str(ssh, "Server refused to set all environment variables\r\n");
6090 * Start a shell or a remote command. We may have to attempt
6091 * this twice if the config data has provided a second choice
6094 if (ssh->mainchan) while (1) {
6098 if (ssh->fallback_cmd) {
6099 subsys = ssh->cfg.ssh_subsys2;
6100 cmd = ssh->cfg.remote_cmd_ptr2;
6102 subsys = ssh->cfg.ssh_subsys;
6103 cmd = ssh->cfg.remote_cmd_ptr;
6106 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6107 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
6109 ssh2_pkt_addstring(s->pktout, "subsystem");
6110 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
6111 ssh2_pkt_addstring(s->pktout, cmd);
6113 ssh2_pkt_addstring(s->pktout, "exec");
6114 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
6115 ssh2_pkt_addstring(s->pktout, cmd);
6117 ssh2_pkt_addstring(s->pktout, "shell");
6118 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
6120 ssh2_pkt_send(ssh, s->pktout);
6122 crWaitUntilV(pktin);
6123 if (pktin->type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
6124 unsigned i = ssh_pkt_getuint32(pktin);
6125 struct ssh_channel *c;
6126 c = find234(ssh->channels, &i, ssh_channelfind);
6128 continue; /* nonexistent channel */
6129 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
6131 } while (pktin->type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
6132 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
6133 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
6134 bombout(("Unexpected response to shell/command request:"
6135 " packet type %d", pktin->type));
6139 * We failed to start the command. If this is the
6140 * fallback command, we really are finished; if it's
6141 * not, and if the fallback command exists, try falling
6142 * back to it before complaining.
6144 if (!ssh->fallback_cmd && ssh->cfg.remote_cmd_ptr2 != NULL) {
6145 logevent("Primary command failed; attempting fallback");
6146 ssh->fallback_cmd = TRUE;
6149 bombout(("Server refused to start a shell/command"));
6152 logevent("Started a shell/command");
6157 ssh->state = SSH_STATE_SESSION;
6158 if (ssh->size_needed)
6159 ssh_size(ssh, ssh->term_width, ssh->term_height);
6160 if (ssh->eof_needed)
6161 ssh_special(ssh, TS_EOF);
6167 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
6172 s->try_send = FALSE;
6174 if (pktin->type == SSH2_MSG_CHANNEL_DATA ||
6175 pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
6178 unsigned i = ssh_pkt_getuint32(pktin);
6179 struct ssh_channel *c;
6180 c = find234(ssh->channels, &i, ssh_channelfind);
6182 continue; /* nonexistent channel */
6183 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
6184 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
6185 continue; /* extended but not stderr */
6186 ssh_pkt_getstring(pktin, &data, &length);
6189 c->v.v2.locwindow -= length;
6191 case CHAN_MAINSESSION:
6193 from_backend(ssh->frontend, pktin->type ==
6194 SSH2_MSG_CHANNEL_EXTENDED_DATA,
6198 bufsize = x11_send(c->u.x11.s, data, length);
6201 bufsize = pfd_send(c->u.pfd.s, data, length);
6204 while (length > 0) {
6205 if (c->u.a.lensofar < 4) {
6206 int l = min(4 - c->u.a.lensofar, length);
6207 memcpy(c->u.a.msglen + c->u.a.lensofar,
6211 c->u.a.lensofar += l;
6213 if (c->u.a.lensofar == 4) {
6215 4 + GET_32BIT(c->u.a.msglen);
6216 c->u.a.message = snewn(c->u.a.totallen,
6218 memcpy(c->u.a.message, c->u.a.msglen, 4);
6220 if (c->u.a.lensofar >= 4 && length > 0) {
6222 min(c->u.a.totallen - c->u.a.lensofar,
6224 memcpy(c->u.a.message + c->u.a.lensofar,
6228 c->u.a.lensofar += l;
6230 if (c->u.a.lensofar == c->u.a.totallen) {
6233 if (agent_query(c->u.a.message,
6236 ssh_agentf_callback, c))
6237 ssh_agentf_callback(c, reply, replylen);
6238 sfree(c->u.a.message);
6239 c->u.a.lensofar = 0;
6246 * If we are not buffering too much data,
6247 * enlarge the window again at the remote side.
6249 if (bufsize < OUR_V2_WINSIZE)
6250 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
6252 } else if (pktin->type == SSH2_MSG_CHANNEL_EOF) {
6253 unsigned i = ssh_pkt_getuint32(pktin);
6254 struct ssh_channel *c;
6256 c = find234(ssh->channels, &i, ssh_channelfind);
6258 continue; /* nonexistent channel */
6260 if (c->type == CHAN_X11) {
6262 * Remote EOF on an X11 channel means we should
6263 * wrap up and close the channel ourselves.
6265 x11_close(c->u.x11.s);
6267 } else if (c->type == CHAN_AGENT) {
6269 } else if (c->type == CHAN_SOCKDATA) {
6270 pfd_close(c->u.pfd.s);
6273 } else if (pktin->type == SSH2_MSG_CHANNEL_CLOSE) {
6274 unsigned i = ssh_pkt_getuint32(pktin);
6275 struct ssh_channel *c;
6277 c = find234(ssh->channels, &i, ssh_channelfind);
6278 if (!c || ((int)c->remoteid) == -1) {
6279 bombout(("Received CHANNEL_CLOSE for %s channel %d\n",
6280 c ? "half-open" : "nonexistent", i));
6283 /* Do pre-close processing on the channel. */
6285 case CHAN_MAINSESSION:
6286 ssh->mainchan = NULL;
6287 update_specials_menu(ssh->frontend);
6290 if (c->u.x11.s != NULL)
6291 x11_close(c->u.x11.s);
6298 if (c->u.pfd.s != NULL)
6299 pfd_close(c->u.pfd.s);
6303 if (c->closes == 0) {
6304 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
6305 ssh2_pkt_adduint32(s->pktout, c->remoteid);
6306 ssh2_pkt_send(ssh, s->pktout);
6308 del234(ssh->channels, c);
6309 bufchain_clear(&c->v.v2.outbuffer);
6313 * See if that was the last channel left open.
6314 * (This is only our termination condition if we're
6315 * not running in -N mode.)
6317 if (!ssh->cfg.ssh_no_shell && count234(ssh->channels) == 0) {
6318 logevent("All channels closed. Disconnecting");
6321 * We used to send SSH_MSG_DISCONNECT here,
6322 * because I'd believed that _every_ conforming
6323 * SSH2 connection had to end with a disconnect
6324 * being sent by at least one side; apparently
6325 * I was wrong and it's perfectly OK to
6326 * unceremoniously slam the connection shut
6327 * when you're done, and indeed OpenSSH feels
6328 * this is more polite than sending a
6329 * DISCONNECT. So now we don't.
6331 s->pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
6332 ssh2_pkt_adduint32(s->pktout, SSH2_DISCONNECT_BY_APPLICATION);
6333 ssh2_pkt_addstring(s->pktout, "All open channels closed");
6334 ssh2_pkt_addstring(s->pktout, "en"); /* language tag */
6335 ssh2_pkt_send(ssh, s->pktout);
6337 ssh_closing((Plug)ssh, NULL, 0, 0);
6340 continue; /* remote sends close; ignore (FIXME) */
6341 } else if (pktin->type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
6342 unsigned i = ssh_pkt_getuint32(pktin);
6343 struct ssh_channel *c;
6344 c = find234(ssh->channels, &i, ssh_channelfind);
6345 if (!c || c->closes)
6346 continue; /* nonexistent or closing channel */
6347 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
6349 } else if (pktin->type == SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
6350 unsigned i = ssh_pkt_getuint32(pktin);
6351 struct ssh_channel *c;
6352 c = find234(ssh->channels, &i, ssh_channelfind);
6354 continue; /* nonexistent channel */
6355 if (c->type != CHAN_SOCKDATA_DORMANT)
6356 continue; /* dunno why they're confirming this */
6357 c->remoteid = ssh_pkt_getuint32(pktin);
6358 c->type = CHAN_SOCKDATA;
6359 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
6360 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
6362 pfd_confirm(c->u.pfd.s);
6365 * We have a pending close on this channel,
6366 * which we decided on before the server acked
6367 * the channel open. So now we know the
6368 * remoteid, we can close it again.
6370 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
6371 ssh2_pkt_adduint32(s->pktout, c->remoteid);
6372 ssh2_pkt_send(ssh, s->pktout);
6374 } else if (pktin->type == SSH2_MSG_CHANNEL_OPEN_FAILURE) {
6375 static const char *const reasons[] = {
6376 "<unknown reason code>",
6377 "Administratively prohibited",
6379 "Unknown channel type",
6380 "Resource shortage",
6382 unsigned i = ssh_pkt_getuint32(pktin);
6383 unsigned reason_code;
6384 char *reason_string;
6387 struct ssh_channel *c;
6388 c = find234(ssh->channels, &i, ssh_channelfind);
6390 continue; /* nonexistent channel */
6391 if (c->type != CHAN_SOCKDATA_DORMANT)
6392 continue; /* dunno why they're failing this */
6394 reason_code = ssh_pkt_getuint32(pktin);
6395 if (reason_code >= lenof(reasons))
6396 reason_code = 0; /* ensure reasons[reason_code] in range */
6397 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
6398 message = dupprintf("Forwarded connection refused by"
6399 " server: %s [%.*s]", reasons[reason_code],
6400 reason_length, reason_string);
6404 pfd_close(c->u.pfd.s);
6406 del234(ssh->channels, c);
6408 } else if (pktin->type == SSH2_MSG_CHANNEL_REQUEST) {
6411 int typelen, want_reply;
6412 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
6413 struct ssh_channel *c;
6415 localid = ssh_pkt_getuint32(pktin);
6416 ssh_pkt_getstring(pktin, &type, &typelen);
6417 want_reply = ssh2_pkt_getbool(pktin);
6420 * First, check that the channel exists. Otherwise,
6421 * we can instantly disconnect with a rude message.
6423 c = find234(ssh->channels, &localid, ssh_channelfind);
6426 sprintf(buf, "Received channel request for nonexistent"
6427 " channel %d", localid);
6429 s->pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
6430 ssh2_pkt_adduint32(s->pktout, SSH2_DISCONNECT_BY_APPLICATION);
6431 ssh2_pkt_addstring(s->pktout, buf);
6432 ssh2_pkt_addstring(s->pktout, "en"); /* language tag */
6433 ssh2_pkt_send(ssh, s->pktout);
6434 connection_fatal(ssh->frontend, "%s", buf);
6435 ssh_closing((Plug)ssh, NULL, 0, 0);
6440 * Having got the channel number, we now look at
6441 * the request type string to see if it's something
6444 if (c == ssh->mainchan) {
6446 * We recognise "exit-status" and "exit-signal" on
6447 * the primary channel.
6449 if (typelen == 11 &&
6450 !memcmp(type, "exit-status", 11)) {
6452 ssh->exitcode = ssh_pkt_getuint32(pktin);
6453 logeventf(ssh, "Server sent command exit status %d",
6455 reply = SSH2_MSG_CHANNEL_SUCCESS;
6457 } else if (typelen == 11 &&
6458 !memcmp(type, "exit-signal", 11)) {
6460 int is_plausible = TRUE, is_int = FALSE;
6461 char *fmt_sig = "", *fmt_msg = "";
6463 int msglen = 0, core = FALSE;
6464 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
6465 * provide an `int' for the signal, despite its
6466 * having been a `string' in the drafts since at
6467 * least 2001. (Fixed in session.c 1.147.) Try to
6468 * infer which we can safely parse it as. */
6470 unsigned char *p = pktin->body +
6472 long len = pktin->length - pktin->savedpos;
6473 unsigned long num = GET_32BIT(p); /* what is it? */
6474 /* If it's 0, it hardly matters; assume string */
6478 int maybe_int = FALSE, maybe_str = FALSE;
6479 #define CHECK_HYPOTHESIS(offset, result) \
6482 if (q >= 0 && q+4 <= len) { \
6483 q = q + 4 + GET_32BIT(p+q); \
6484 if (q >= 0 && q+4 <= len && \
6485 (q = q + 4 + GET_32BIT(p+q)) && q == len) \
6489 CHECK_HYPOTHESIS(4+1, maybe_int);
6490 CHECK_HYPOTHESIS(4+num+1, maybe_str);
6491 #undef CHECK_HYPOTHESIS
6492 if (maybe_int && !maybe_str)
6494 else if (!maybe_int && maybe_str)
6497 /* Crikey. Either or neither. Panic. */
6498 is_plausible = FALSE;
6503 /* Old non-standard OpenSSH. */
6504 int signum = ssh_pkt_getuint32(pktin);
6505 fmt_sig = dupprintf(" %d", signum);
6507 /* As per the drafts. */
6510 ssh_pkt_getstring(pktin, &sig, &siglen);
6511 /* Signal name isn't supposed to be blank, but
6512 * let's cope gracefully if it is. */
6514 fmt_sig = dupprintf(" \"%.*s\"",
6518 core = ssh2_pkt_getbool(pktin);
6519 ssh_pkt_getstring(pktin, &msg, &msglen);
6521 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
6523 /* ignore lang tag */
6524 } /* else don't attempt to parse */
6525 logeventf(ssh, "Server exited on signal%s%s%s",
6526 fmt_sig, core ? " (core dumped)" : "",
6528 if (*fmt_sig) sfree(fmt_sig);
6529 if (*fmt_msg) sfree(fmt_msg);
6530 reply = SSH2_MSG_CHANNEL_SUCCESS;
6535 * This is a channel request we don't know
6536 * about, so we now either ignore the request
6537 * or respond with CHANNEL_FAILURE, depending
6540 reply = SSH2_MSG_CHANNEL_FAILURE;
6543 s->pktout = ssh2_pkt_init(reply);
6544 ssh2_pkt_adduint32(s->pktout, c->remoteid);
6545 ssh2_pkt_send(ssh, s->pktout);
6547 } else if (pktin->type == SSH2_MSG_GLOBAL_REQUEST) {
6549 int typelen, want_reply;
6551 ssh_pkt_getstring(pktin, &type, &typelen);
6552 want_reply = ssh2_pkt_getbool(pktin);
6555 * We currently don't support any global requests
6556 * at all, so we either ignore the request or
6557 * respond with REQUEST_FAILURE, depending on
6561 s->pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
6562 ssh2_pkt_send(ssh, s->pktout);
6564 } else if (pktin->type == SSH2_MSG_CHANNEL_OPEN) {
6571 struct ssh_channel *c;
6572 unsigned remid, winsize, pktsize;
6573 ssh_pkt_getstring(pktin, &type, &typelen);
6574 c = snew(struct ssh_channel);
6577 remid = ssh_pkt_getuint32(pktin);
6578 winsize = ssh_pkt_getuint32(pktin);
6579 pktsize = ssh_pkt_getuint32(pktin);
6581 if (typelen == 3 && !memcmp(type, "x11", 3)) {
6584 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
6585 addrstr = snewn(peeraddrlen+1, char);
6586 memcpy(addrstr, peeraddr, peeraddrlen);
6587 addrstr[peeraddrlen] = '\0';
6588 peerport = ssh_pkt_getuint32(pktin);
6590 logeventf(ssh, "Received X11 connect request from %s:%d",
6593 if (!ssh->X11_fwd_enabled)
6594 error = "X11 forwarding is not enabled";
6595 else if (x11_init(&c->u.x11.s, ssh->cfg.x11_display, c,
6596 ssh->x11auth, addrstr, peerport,
6597 &ssh->cfg) != NULL) {
6598 error = "Unable to open an X11 connection";
6600 logevent("Opening X11 forward connection succeeded");
6605 } else if (typelen == 15 &&
6606 !memcmp(type, "forwarded-tcpip", 15)) {
6607 struct ssh_rportfwd pf, *realpf;
6610 ssh_pkt_getstring(pktin, &dummy, &dummylen);/* skip address */
6611 pf.sport = ssh_pkt_getuint32(pktin);
6612 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
6613 peerport = ssh_pkt_getuint32(pktin);
6614 realpf = find234(ssh->rportfwds, &pf, NULL);
6615 logeventf(ssh, "Received remote port %d open request "
6616 "from %s:%d", pf.sport, peeraddr, peerport);
6617 if (realpf == NULL) {
6618 error = "Remote port is not recognised";
6620 const char *e = pfd_newconnect(&c->u.pfd.s,
6624 logeventf(ssh, "Attempting to forward remote port to "
6625 "%s:%d", realpf->dhost, realpf->dport);
6627 logeventf(ssh, "Port open failed: %s", e);
6628 error = "Port open failed";
6630 logevent("Forwarded port opened successfully");
6631 c->type = CHAN_SOCKDATA;
6634 } else if (typelen == 22 &&
6635 !memcmp(type, "auth-agent@openssh.com", 3)) {
6636 if (!ssh->agentfwd_enabled)
6637 error = "Agent forwarding is not enabled";
6639 c->type = CHAN_AGENT; /* identify channel type */
6640 c->u.a.lensofar = 0;
6643 error = "Unsupported channel type requested";
6646 c->remoteid = remid;
6648 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
6649 ssh2_pkt_adduint32(s->pktout, c->remoteid);
6650 ssh2_pkt_adduint32(s->pktout, SSH2_OPEN_CONNECT_FAILED);
6651 ssh2_pkt_addstring(s->pktout, error);
6652 ssh2_pkt_addstring(s->pktout, "en"); /* language tag */
6653 ssh2_pkt_send(ssh, s->pktout);
6654 logeventf(ssh, "Rejected channel open: %s", error);
6657 c->localid = alloc_channel_id(ssh);
6659 c->v.v2.locwindow = OUR_V2_WINSIZE;
6660 c->v.v2.remwindow = winsize;
6661 c->v.v2.remmaxpkt = pktsize;
6662 bufchain_init(&c->v.v2.outbuffer);
6663 add234(ssh->channels, c);
6664 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
6665 ssh2_pkt_adduint32(s->pktout, c->remoteid);
6666 ssh2_pkt_adduint32(s->pktout, c->localid);
6667 ssh2_pkt_adduint32(s->pktout, c->v.v2.locwindow);
6668 ssh2_pkt_adduint32(s->pktout, 0x4000UL); /* our max pkt size */
6669 ssh2_pkt_send(ssh, s->pktout);
6672 bombout(("Strange packet received: type %d", pktin->type));
6675 } else if (ssh->mainchan) {
6677 * We have spare data. Add it to the channel buffer.
6679 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
6684 struct ssh_channel *c;
6686 * Try to send data on all channels if we can.
6688 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
6691 continue; /* don't send on closing channels */
6692 bufsize = ssh2_try_send(c);
6695 case CHAN_MAINSESSION:
6696 /* stdin need not receive an unthrottle
6697 * notification since it will be polled */
6700 x11_unthrottle(c->u.x11.s);
6703 /* agent sockets are request/response and need no
6704 * buffer management */
6707 pfd_unthrottle(c->u.pfd.s);
6719 * Handle the top-level SSH2 protocol.
6721 static void ssh2_protocol(Ssh ssh, unsigned char *in, int inlen,
6722 struct Packet *pktin)
6724 if (do_ssh2_transport(ssh, in, inlen, pktin) == 0)
6726 do_ssh2_authconn(ssh, in, inlen, pktin);
6730 * Called to set up the connection.
6732 * Returns an error message, or NULL on success.
6734 static const char *ssh_init(void *frontend_handle, void **backend_handle,
6736 char *host, int port, char **realhost, int nodelay,
6742 ssh = snew(struct ssh_tag);
6743 ssh->cfg = *cfg; /* STRUCTURE COPY */
6744 ssh->version = 0; /* when not ready yet */
6747 ssh->v1_cipher_ctx = NULL;
6748 ssh->crcda_ctx = NULL;
6749 ssh->cscipher = NULL;
6750 ssh->cs_cipher_ctx = NULL;
6751 ssh->sccipher = NULL;
6752 ssh->sc_cipher_ctx = NULL;
6754 ssh->cs_mac_ctx = NULL;
6756 ssh->sc_mac_ctx = NULL;
6758 ssh->cs_comp_ctx = NULL;
6760 ssh->sc_comp_ctx = NULL;
6762 ssh->kex_ctx = NULL;
6763 ssh->hostkey = NULL;
6765 ssh->state = SSH_STATE_PREPACKET;
6766 ssh->size_needed = FALSE;
6767 ssh->eof_needed = FALSE;
6770 ssh->deferred_send_data = NULL;
6771 ssh->deferred_len = 0;
6772 ssh->deferred_size = 0;
6773 ssh->fallback_cmd = 0;
6775 ssh->x11auth = NULL;
6776 ssh->v1_compressing = FALSE;
6777 ssh->v2_outgoing_sequence = 0;
6778 ssh->ssh1_rdpkt_crstate = 0;
6779 ssh->ssh2_rdpkt_crstate = 0;
6780 ssh->do_ssh_init_crstate = 0;
6781 ssh->ssh_gotdata_crstate = 0;
6782 ssh->ssh1_protocol_crstate = 0;
6783 ssh->do_ssh1_login_crstate = 0;
6784 ssh->do_ssh2_transport_crstate = 0;
6785 ssh->do_ssh2_authconn_crstate = 0;
6786 ssh->do_ssh_init_state = NULL;
6787 ssh->do_ssh1_login_state = NULL;
6788 ssh->do_ssh2_transport_state = NULL;
6789 ssh->do_ssh2_authconn_state = NULL;
6790 ssh->mainchan = NULL;
6791 ssh->throttled_all = 0;
6792 ssh->v1_stdout_throttling = 0;
6794 *backend_handle = ssh;
6797 if (crypto_startup() == 0)
6798 return "Microsoft high encryption pack not installed!";
6801 ssh->frontend = frontend_handle;
6802 ssh->term_width = ssh->cfg.width;
6803 ssh->term_height = ssh->cfg.height;
6805 ssh->channels = NULL;
6806 ssh->rportfwds = NULL;
6811 ssh->v1_throttle_count = 0;
6812 ssh->overall_bufsize = 0;
6813 ssh->fallback_cmd = 0;
6815 ssh->protocol = NULL;
6817 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
6824 static void ssh_free(void *handle)
6826 Ssh ssh = (Ssh) handle;
6827 struct ssh_channel *c;
6828 struct ssh_rportfwd *pf;
6830 if (ssh->v1_cipher_ctx)
6831 ssh->cipher->free_context(ssh->v1_cipher_ctx);
6832 if (ssh->cs_cipher_ctx)
6833 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
6834 if (ssh->sc_cipher_ctx)
6835 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
6836 if (ssh->cs_mac_ctx)
6837 ssh->csmac->free_context(ssh->cs_mac_ctx);
6838 if (ssh->sc_mac_ctx)
6839 ssh->scmac->free_context(ssh->sc_mac_ctx);
6840 if (ssh->cs_comp_ctx) {
6842 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
6844 zlib_compress_cleanup(ssh->cs_comp_ctx);
6846 if (ssh->sc_comp_ctx) {
6848 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
6850 zlib_decompress_cleanup(ssh->sc_comp_ctx);
6853 dh_cleanup(ssh->kex_ctx);
6854 sfree(ssh->savedhost);
6856 if (ssh->channels) {
6857 while ((c = delpos234(ssh->channels, 0)) != NULL) {
6860 if (c->u.x11.s != NULL)
6861 x11_close(c->u.x11.s);
6864 if (c->u.pfd.s != NULL)
6865 pfd_close(c->u.pfd.s);
6870 freetree234(ssh->channels);
6873 if (ssh->rportfwds) {
6874 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
6876 freetree234(ssh->rportfwds);
6878 sfree(ssh->deferred_send_data);
6880 x11_free_auth(ssh->x11auth);
6881 sfree(ssh->do_ssh_init_state);
6882 sfree(ssh->do_ssh1_login_state);
6883 sfree(ssh->do_ssh2_transport_state);
6884 sfree(ssh->do_ssh2_authconn_state);
6885 if (ssh->crcda_ctx) {
6886 crcda_free_context(ssh->crcda_ctx);
6887 ssh->crcda_ctx = NULL;
6895 * Reconfigure the SSH backend.
6897 * Currently, this function does nothing very useful. In future,
6898 * however, we could do some handy things with it. For example, we
6899 * could make the port forwarding configurer active in the Change
6900 * Settings box, and this routine could close down existing
6901 * forwardings and open up new ones in response to changes.
6903 static void ssh_reconfig(void *handle, Config *cfg)
6905 Ssh ssh = (Ssh) handle;
6906 ssh->cfg = *cfg; /* STRUCTURE COPY */
6910 * Called to send data down the Telnet connection.
6912 static int ssh_send(void *handle, char *buf, int len)
6914 Ssh ssh = (Ssh) handle;
6916 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
6919 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
6921 return ssh_sendbuffer(ssh);
6925 * Called to query the current amount of buffered stdin data.
6927 static int ssh_sendbuffer(void *handle)
6929 Ssh ssh = (Ssh) handle;
6932 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
6936 * If the SSH socket itself has backed up, add the total backup
6937 * size on that to any individual buffer on the stdin channel.
6940 if (ssh->throttled_all)
6941 override_value = ssh->overall_bufsize;
6943 if (ssh->version == 1) {
6944 return override_value;
6945 } else if (ssh->version == 2) {
6946 if (!ssh->mainchan || ssh->mainchan->closes > 0)
6947 return override_value;
6949 return (override_value +
6950 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
6957 * Called to set the size of the window from SSH's POV.
6959 static void ssh_size(void *handle, int width, int height)
6961 Ssh ssh = (Ssh) handle;
6962 struct Packet *pktout;
6964 ssh->term_width = width;
6965 ssh->term_height = height;
6967 switch (ssh->state) {
6968 case SSH_STATE_BEFORE_SIZE:
6969 case SSH_STATE_PREPACKET:
6970 case SSH_STATE_CLOSED:
6971 break; /* do nothing */
6972 case SSH_STATE_INTERMED:
6973 ssh->size_needed = TRUE; /* buffer for later */
6975 case SSH_STATE_SESSION:
6976 if (!ssh->cfg.nopty) {
6977 if (ssh->version == 1) {
6978 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
6979 PKT_INT, ssh->term_height,
6980 PKT_INT, ssh->term_width,
6981 PKT_INT, 0, PKT_INT, 0, PKT_END);
6982 } else if (ssh->mainchan) {
6983 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6984 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
6985 ssh2_pkt_addstring(pktout, "window-change");
6986 ssh2_pkt_addbool(pktout, 0);
6987 ssh2_pkt_adduint32(pktout, ssh->term_width);
6988 ssh2_pkt_adduint32(pktout, ssh->term_height);
6989 ssh2_pkt_adduint32(pktout, 0);
6990 ssh2_pkt_adduint32(pktout, 0);
6991 ssh2_pkt_send(ssh, pktout);
6999 * Return a list of the special codes that make sense in this
7002 static const struct telnet_special *ssh_get_specials(void *handle)
7004 static const struct telnet_special ignore_special[] = {
7005 {"IGNORE message", TS_NOP},
7007 static const struct telnet_special ssh2_session_specials[] = {
7010 /* These are the signal names defined by draft-ietf-secsh-connect-19.
7011 * They include all the ISO C signals, but are a subset of the POSIX
7012 * required signals. */
7013 {"SIGINT (Interrupt)", TS_SIGINT},
7014 {"SIGTERM (Terminate)", TS_SIGTERM},
7015 {"SIGKILL (Kill)", TS_SIGKILL},
7016 {"SIGQUIT (Quit)", TS_SIGQUIT},
7017 {"SIGHUP (Hangup)", TS_SIGHUP},
7018 {"More signals", TS_SUBMENU},
7019 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
7020 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
7021 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
7022 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
7025 static const struct telnet_special specials_end[] = {
7028 static struct telnet_special ssh_specials[lenof(ignore_special) +
7029 lenof(ssh2_session_specials) +
7030 lenof(specials_end)];
7031 Ssh ssh = (Ssh) handle;
7033 #define ADD_SPECIALS(name) \
7035 assert((i + lenof(name)) <= lenof(ssh_specials)); \
7036 memcpy(&ssh_specials[i], name, sizeof name); \
7040 if (ssh->version == 1) {
7041 /* Don't bother offering IGNORE if we've decided the remote
7042 * won't cope with it, since we wouldn't bother sending it if
7044 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
7045 ADD_SPECIALS(ignore_special);
7046 } else if (ssh->version == 2) {
7047 /* XXX add rekey, when implemented */
7048 ADD_SPECIALS(ignore_special);
7050 ADD_SPECIALS(ssh2_session_specials);
7051 } /* else we're not ready yet */
7054 ADD_SPECIALS(specials_end);
7055 return ssh_specials;
7063 * Send Telnet special codes. TS_EOF is useful for `plink', so you
7064 * can send an EOF and collect resulting output (e.g. `plink
7067 static void ssh_special(void *handle, Telnet_Special code)
7069 Ssh ssh = (Ssh) handle;
7070 struct Packet *pktout;
7072 if (code == TS_EOF) {
7073 if (ssh->state != SSH_STATE_SESSION) {
7075 * Buffer the EOF in case we are pre-SESSION, so we can
7076 * send it as soon as we reach SESSION.
7079 ssh->eof_needed = TRUE;
7082 if (ssh->version == 1) {
7083 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
7084 } else if (ssh->mainchan) {
7085 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
7086 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
7087 ssh2_pkt_send(ssh, pktout);
7089 logevent("Sent EOF message");
7090 } else if (code == TS_PING || code == TS_NOP) {
7091 if (ssh->state == SSH_STATE_CLOSED
7092 || ssh->state == SSH_STATE_PREPACKET) return;
7093 if (ssh->version == 1) {
7094 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
7095 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
7097 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
7098 ssh2_pkt_addstring_start(pktout);
7099 ssh2_pkt_send(ssh, pktout);
7101 } else if (code == TS_BRK) {
7102 if (ssh->state == SSH_STATE_CLOSED
7103 || ssh->state == SSH_STATE_PREPACKET) return;
7104 if (ssh->version == 1) {
7105 logevent("Unable to send BREAK signal in SSH1");
7106 } else if (ssh->mainchan) {
7107 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7108 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
7109 ssh2_pkt_addstring(pktout, "break");
7110 ssh2_pkt_addbool(pktout, 0);
7111 ssh2_pkt_adduint32(pktout, 0); /* default break length */
7112 ssh2_pkt_send(ssh, pktout);
7115 /* Is is a POSIX signal? */
7116 char *signame = NULL;
7117 if (code == TS_SIGABRT) signame = "ABRT";
7118 if (code == TS_SIGALRM) signame = "ALRM";
7119 if (code == TS_SIGFPE) signame = "FPE";
7120 if (code == TS_SIGHUP) signame = "HUP";
7121 if (code == TS_SIGILL) signame = "ILL";
7122 if (code == TS_SIGINT) signame = "INT";
7123 if (code == TS_SIGKILL) signame = "KILL";
7124 if (code == TS_SIGPIPE) signame = "PIPE";
7125 if (code == TS_SIGQUIT) signame = "QUIT";
7126 if (code == TS_SIGSEGV) signame = "SEGV";
7127 if (code == TS_SIGTERM) signame = "TERM";
7128 if (code == TS_SIGUSR1) signame = "USR1";
7129 if (code == TS_SIGUSR2) signame = "USR2";
7130 /* The SSH-2 protocol does in principle support arbitrary named
7131 * signals, including signame@domain, but we don't support those. */
7133 /* It's a signal. */
7134 if (ssh->version == 2 && ssh->mainchan) {
7135 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7136 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
7137 ssh2_pkt_addstring(pktout, "signal");
7138 ssh2_pkt_addbool(pktout, 0);
7139 ssh2_pkt_addstring(pktout, signame);
7140 ssh2_pkt_send(ssh, pktout);
7141 logeventf(ssh, "Sent signal SIG%s", signame);
7144 /* Never heard of it. Do nothing */
7149 void *new_sock_channel(void *handle, Socket s)
7151 Ssh ssh = (Ssh) handle;
7152 struct ssh_channel *c;
7153 c = snew(struct ssh_channel);
7157 c->remoteid = -1; /* to be set when open confirmed */
7158 c->localid = alloc_channel_id(ssh);
7160 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
7162 bufchain_init(&c->v.v2.outbuffer);
7163 add234(ssh->channels, c);
7169 * This is called when stdout/stderr (the entity to which
7170 * from_backend sends data) manages to clear some backlog.
7172 static void ssh_unthrottle(void *handle, int bufsize)
7174 Ssh ssh = (Ssh) handle;
7175 if (ssh->version == 1) {
7176 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
7177 ssh->v1_stdout_throttling = 0;
7178 ssh1_throttle(ssh, -1);
7181 if (ssh->mainchan && ssh->mainchan->closes == 0)
7182 ssh2_set_window(ssh->mainchan, OUR_V2_WINSIZE - bufsize);
7186 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
7188 struct ssh_channel *c = (struct ssh_channel *)channel;
7190 struct Packet *pktout;
7192 logeventf(ssh, "Opening forwarded connection to %s:%d", hostname, port);
7194 if (ssh->version == 1) {
7195 send_packet(ssh, SSH1_MSG_PORT_OPEN,
7196 PKT_INT, c->localid,
7199 //PKT_STR, <org:orgport>,
7202 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7203 ssh2_pkt_addstring(pktout, "direct-tcpip");
7204 ssh2_pkt_adduint32(pktout, c->localid);
7205 c->v.v2.locwindow = OUR_V2_WINSIZE;
7206 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
7207 ssh2_pkt_adduint32(pktout, 0x4000UL); /* our max pkt size */
7208 ssh2_pkt_addstring(pktout, hostname);
7209 ssh2_pkt_adduint32(pktout, port);
7211 * We make up values for the originator data; partly it's
7212 * too much hassle to keep track, and partly I'm not
7213 * convinced the server should be told details like that
7214 * about my local network configuration.
7216 ssh2_pkt_addstring(pktout, "client-side-connection");
7217 ssh2_pkt_adduint32(pktout, 0);
7218 ssh2_pkt_send(ssh, pktout);
7222 static Socket ssh_socket(void *handle)
7224 Ssh ssh = (Ssh) handle;
7228 static int ssh_sendok(void *handle)
7230 Ssh ssh = (Ssh) handle;
7231 return ssh->send_ok;
7234 static int ssh_ldisc(void *handle, int option)
7236 Ssh ssh = (Ssh) handle;
7237 if (option == LD_ECHO)
7238 return ssh->echoing;
7239 if (option == LD_EDIT)
7240 return ssh->editing;
7244 static void ssh_provide_ldisc(void *handle, void *ldisc)
7246 Ssh ssh = (Ssh) handle;
7250 static void ssh_provide_logctx(void *handle, void *logctx)
7252 Ssh ssh = (Ssh) handle;
7253 ssh->logctx = logctx;
7256 static int ssh_return_exitcode(void *handle)
7258 Ssh ssh = (Ssh) handle;
7262 return (ssh->exitcode >= 0 ? ssh->exitcode : 0);
7266 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
7267 * that fails. This variable is the means by which scp.c can reach
7268 * into the SSH code and find out which one it got.
7270 extern int ssh_fallback_cmd(void *handle)
7272 Ssh ssh = (Ssh) handle;
7273 return ssh->fallback_cmd;
7276 Backend ssh_backend = {
7286 ssh_return_exitcode,