17 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
18 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
19 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
20 #define SSH1_CMSG_USER 4 /* 0x4 */
21 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
22 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
23 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
24 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
25 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
26 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
27 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
28 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
29 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
30 #define SSH1_SMSG_FAILURE 15 /* 0xf */
31 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
32 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
33 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
34 #define SSH1_CMSG_EOF 19 /* 0x13 */
35 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
36 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
37 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
38 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
39 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
40 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
41 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
42 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
43 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
44 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
45 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
46 #define SSH1_MSG_IGNORE 32 /* 0x20 */
47 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
48 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
49 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
50 #define SSH1_MSG_DEBUG 36 /* 0x24 */
51 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
52 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
53 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
54 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
55 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
56 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
57 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
59 #define SSH1_AUTH_TIS 5 /* 0x5 */
60 #define SSH1_AUTH_CCARD 16 /* 0x10 */
62 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
63 /* Mask for protoflags we will echo back to server if seen */
64 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
66 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
67 #define SSH2_MSG_IGNORE 2 /* 0x2 */
68 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
69 #define SSH2_MSG_DEBUG 4 /* 0x4 */
70 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
71 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
72 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
73 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
74 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
75 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
76 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
77 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
78 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
79 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
80 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
81 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
82 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
83 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
84 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
85 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
86 #define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */
87 #define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */
88 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
89 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
90 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
91 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
92 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
93 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
94 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
95 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
96 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
97 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
98 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
99 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
100 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
101 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
104 * Packet type contexts, so that ssh2_pkt_type can correctly decode
105 * the ambiguous type numbers back into the correct type strings.
107 #define SSH2_PKTCTX_DHGROUP 0x0001
108 #define SSH2_PKTCTX_DHGEX 0x0002
109 #define SSH2_PKTCTX_PUBLICKEY 0x0010
110 #define SSH2_PKTCTX_PASSWORD 0x0020
111 #define SSH2_PKTCTX_KBDINTER 0x0040
112 #define SSH2_PKTCTX_AUTH_MASK 0x00F0
114 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
115 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
116 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
117 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
118 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
119 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
120 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
121 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
122 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
123 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
124 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
125 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
126 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
127 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
128 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
130 static const char *const ssh2_disconnect_reasons[] = {
132 "SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT",
133 "SSH_DISCONNECT_PROTOCOL_ERROR",
134 "SSH_DISCONNECT_KEY_EXCHANGE_FAILED",
135 "SSH_DISCONNECT_HOST_AUTHENTICATION_FAILED",
136 "SSH_DISCONNECT_MAC_ERROR",
137 "SSH_DISCONNECT_COMPRESSION_ERROR",
138 "SSH_DISCONNECT_SERVICE_NOT_AVAILABLE",
139 "SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED",
140 "SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE",
141 "SSH_DISCONNECT_CONNECTION_LOST",
142 "SSH_DISCONNECT_BY_APPLICATION",
143 "SSH_DISCONNECT_TOO_MANY_CONNECTIONS",
144 "SSH_DISCONNECT_AUTH_CANCELLED_BY_USER",
145 "SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE",
146 "SSH_DISCONNECT_ILLEGAL_USER_NAME",
149 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
150 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
151 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
152 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
154 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
157 * Various remote-bug flags.
159 #define BUG_CHOKES_ON_SSH1_IGNORE 1
160 #define BUG_SSH2_HMAC 2
161 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
162 #define BUG_CHOKES_ON_RSA 8
163 #define BUG_SSH2_RSA_PADDING 16
164 #define BUG_SSH2_DERIVEKEY 32
165 #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_DHGROUP);
226 translatec(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP);
227 translatec(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
228 translatec(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
229 translatec(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
230 translatec(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
231 translate(SSH2_MSG_USERAUTH_REQUEST);
232 translate(SSH2_MSG_USERAUTH_FAILURE);
233 translate(SSH2_MSG_USERAUTH_SUCCESS);
234 translate(SSH2_MSG_USERAUTH_BANNER);
235 translatec(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
236 translatec(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
237 translatec(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
238 translatec(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
239 translate(SSH2_MSG_GLOBAL_REQUEST);
240 translate(SSH2_MSG_REQUEST_SUCCESS);
241 translate(SSH2_MSG_REQUEST_FAILURE);
242 translate(SSH2_MSG_CHANNEL_OPEN);
243 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
244 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
245 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
246 translate(SSH2_MSG_CHANNEL_DATA);
247 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
248 translate(SSH2_MSG_CHANNEL_EOF);
249 translate(SSH2_MSG_CHANNEL_CLOSE);
250 translate(SSH2_MSG_CHANNEL_REQUEST);
251 translate(SSH2_MSG_CHANNEL_SUCCESS);
252 translate(SSH2_MSG_CHANNEL_FAILURE);
258 #define GET_32BIT(cp) \
259 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
260 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
261 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
262 ((unsigned long)(unsigned char)(cp)[3]))
264 #define PUT_32BIT(cp, value) { \
265 (cp)[0] = (unsigned char)((value) >> 24); \
266 (cp)[1] = (unsigned char)((value) >> 16); \
267 (cp)[2] = (unsigned char)((value) >> 8); \
268 (cp)[3] = (unsigned char)(value); }
270 /* Enumeration values for fields in SSH-1 packets */
272 PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
273 /* These values are for communicating relevant semantics of
274 * fields to the packet logging code. */
275 PKTT_OTHER, PKTT_PASSWORD, PKTT_DATA
279 * Coroutine mechanics for the sillier bits of the code. If these
280 * macros look impenetrable to you, you might find it helpful to
283 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
285 * which explains the theory behind these macros.
287 * In particular, if you are getting `case expression not constant'
288 * errors when building with MS Visual Studio, this is because MS's
289 * Edit and Continue debugging feature causes their compiler to
290 * violate ANSI C. To disable Edit and Continue debugging:
292 * - right-click ssh.c in the FileView
294 * - select the C/C++ tab and the General category
295 * - under `Debug info:', select anything _other_ than `Program
296 * Database for Edit and Continue'.
298 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
301 if (!ssh->t) ssh->t = snew(struct t); \
303 #define crFinish(z) } *crLine = 0; return (z); }
304 #define crFinishV } *crLine = 0; return; }
305 #define crReturn(z) \
307 *crLine =__LINE__; return (z); case __LINE__:;\
311 *crLine=__LINE__; return; case __LINE__:;\
313 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
314 #define crStopV do{ *crLine = 0; return; }while(0)
315 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
316 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
318 typedef struct ssh_tag *Ssh;
321 static struct Packet *ssh2_pkt_init(int pkt_type);
322 static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
323 static void ssh2_pkt_adduint32(struct Packet *, unsigned long value);
324 static void ssh2_pkt_addstring_start(struct Packet *);
325 static void ssh2_pkt_addstring_str(struct Packet *, char *data);
326 static void ssh2_pkt_addstring_data(struct Packet *, char *data, int len);
327 static void ssh2_pkt_addstring(struct Packet *, char *data);
328 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
329 static void ssh2_pkt_addmp(struct Packet *, Bignum b);
330 static int ssh2_pkt_construct(Ssh, struct Packet *);
331 static void ssh2_pkt_send(Ssh, struct Packet *);
332 static void ssh2_pkt_send_noqueue(Ssh, struct Packet *);
333 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
334 struct Packet *pktin);
335 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
336 struct Packet *pktin);
339 * Buffer management constants. There are several of these for
340 * various different purposes:
342 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
343 * on a local data stream before we throttle the whole SSH
344 * connection (in SSH1 only). Throttling the whole connection is
345 * pretty drastic so we set this high in the hope it won't
348 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
349 * on the SSH connection itself before we defensively throttle
350 * _all_ local data streams. This is pretty drastic too (though
351 * thankfully unlikely in SSH2 since the window mechanism should
352 * ensure that the server never has any need to throttle its end
353 * of the connection), so we set this high as well.
355 * - OUR_V2_WINSIZE is the maximum window size we present on SSH2
359 #define SSH1_BUFFER_LIMIT 32768
360 #define SSH_MAX_BACKLOG 32768
361 #define OUR_V2_WINSIZE 16384
363 const static struct ssh_kex *kex_algs[] = {
364 &ssh_diffiehellman_gex,
365 &ssh_diffiehellman_group14,
366 &ssh_diffiehellman_group1,
369 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
371 static void *nullmac_make_context(void)
375 static void nullmac_free_context(void *handle)
378 static void nullmac_key(void *handle, unsigned char *key)
381 static void nullmac_generate(void *handle, unsigned char *blk, int len,
385 static int nullmac_verify(void *handle, unsigned char *blk, int len,
390 const static struct ssh_mac ssh_mac_none = {
391 nullmac_make_context, nullmac_free_context, nullmac_key,
392 nullmac_generate, nullmac_verify, "none", 0
394 const static struct ssh_mac *macs[] = {
395 &ssh_sha1, &ssh_md5, &ssh_mac_none
397 const static struct ssh_mac *buggymacs[] = {
398 &ssh_sha1_buggy, &ssh_md5, &ssh_mac_none
401 static void *ssh_comp_none_init(void)
405 static void ssh_comp_none_cleanup(void *handle)
408 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
409 unsigned char **outblock, int *outlen)
413 static int ssh_comp_none_disable(void *handle)
417 const static struct ssh_compress ssh_comp_none = {
419 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
420 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
421 ssh_comp_none_disable, NULL
423 extern const struct ssh_compress ssh_zlib;
424 const static struct ssh_compress *compressions[] = {
425 &ssh_zlib, &ssh_comp_none
428 enum { /* channel types */
433 CHAN_SOCKDATA_DORMANT /* one the remote hasn't confirmed */
437 * 2-3-4 tree storing channels.
440 Ssh ssh; /* pointer back to main context */
441 unsigned remoteid, localid;
444 * In SSH1, this value contains four bits:
446 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
447 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
448 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
449 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
451 * A channel is completely finished with when all four bits are set.
455 struct ssh1_data_channel {
458 struct ssh2_data_channel {
460 unsigned remwindow, remmaxpkt;
465 struct ssh_agent_channel {
466 unsigned char *message;
467 unsigned char msglen[4];
468 unsigned lensofar, totallen;
470 struct ssh_x11_channel {
473 struct ssh_pfd_channel {
480 * 2-3-4 tree storing remote->local port forwardings. SSH 1 and SSH
481 * 2 use this structure in different ways, reflecting SSH 2's
482 * altogether saner approach to port forwarding.
484 * In SSH 1, you arrange a remote forwarding by sending the server
485 * the remote port number, and the local destination host:port.
486 * When a connection comes in, the server sends you back that
487 * host:port pair, and you connect to it. This is a ready-made
488 * security hole if you're not on the ball: a malicious server
489 * could send you back _any_ host:port pair, so if you trustingly
490 * connect to the address it gives you then you've just opened the
491 * entire inside of your corporate network just by connecting
492 * through it to a dodgy SSH server. Hence, we must store a list of
493 * host:port pairs we _are_ trying to forward to, and reject a
494 * connection request from the server if it's not in the list.
496 * In SSH 2, each side of the connection minds its own business and
497 * doesn't send unnecessary information to the other. You arrange a
498 * remote forwarding by sending the server just the remote port
499 * number. When a connection comes in, the server tells you which
500 * of its ports was connected to; and _you_ have to remember what
501 * local host:port pair went with that port number.
503 * Hence: in SSH 1 this structure stores host:port pairs we intend
504 * to allow connections to, and is indexed by those host:port
505 * pairs. In SSH 2 it stores a mapping from source port to
506 * destination host:port pair, and is indexed by source port.
508 struct ssh_rportfwd {
509 unsigned sport, dport;
516 unsigned long sequence;
521 long encrypted_len; /* for SSH2 total-size counting */
524 * State associated with packet logging
528 struct logblank_t *blanks;
531 static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen,
532 struct Packet *pktin);
533 static void ssh2_protocol(Ssh ssh, unsigned char *in, int inlen,
534 struct Packet *pktin);
535 static void ssh1_protocol_setup(Ssh ssh);
536 static void ssh2_protocol_setup(Ssh ssh);
537 static void ssh_size(void *handle, int width, int height);
538 static void ssh_special(void *handle, Telnet_Special);
539 static int ssh2_try_send(struct ssh_channel *c);
540 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
541 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
542 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin);
543 static int ssh_sendbuffer(void *handle);
544 static void ssh_do_close(Ssh ssh);
545 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
546 static int ssh2_pkt_getbool(struct Packet *pkt);
547 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
548 static void ssh2_timer(void *ctx, long now);
549 static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen,
550 struct Packet *pktin);
552 struct rdpkt1_state_tag {
553 long len, pad, biglen, to_read;
554 unsigned long realcrc, gotcrc;
558 struct Packet *pktin;
561 struct rdpkt2_state_tag {
562 long len, pad, payload, packetlen, maclen;
565 unsigned long incoming_sequence;
566 struct Packet *pktin;
569 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
572 const struct plug_function_table *fn;
573 /* the above field _must_ be first in the structure */
575 SHA_State exhash, exhashbase;
582 unsigned char session_key[32];
584 int v1_remote_protoflags;
585 int v1_local_protoflags;
586 int agentfwd_enabled;
589 const struct ssh_cipher *cipher;
592 const struct ssh2_cipher *cscipher, *sccipher;
593 void *cs_cipher_ctx, *sc_cipher_ctx;
594 const struct ssh_mac *csmac, *scmac;
595 void *cs_mac_ctx, *sc_mac_ctx;
596 const struct ssh_compress *cscomp, *sccomp;
597 void *cs_comp_ctx, *sc_comp_ctx;
598 const struct ssh_kex *kex;
599 const struct ssh_signkey *hostkey;
600 unsigned char v2_session_id[20];
606 int echoing, editing;
610 int ospeed, ispeed; /* temporaries */
611 int term_width, term_height;
613 tree234 *channels; /* indexed by local id */
614 struct ssh_channel *mainchan; /* primary session channel */
621 SSH_STATE_BEFORE_SIZE,
627 int size_needed, eof_needed;
629 struct Packet **queue;
630 int queuelen, queuesize;
632 unsigned char *deferred_send_data;
633 int deferred_len, deferred_size;
636 * Gross hack: pscp will try to start SFTP but fall back to
637 * scp1 if that fails. This variable is the means by which
638 * scp.c can reach into the SSH code and find out which one it
644 * Used for username and password input.
646 char *userpass_input_buffer;
647 int userpass_input_buflen;
648 int userpass_input_bufpos;
649 int userpass_input_echo;
651 char *portfwd_strptr;
657 int v1_throttle_count;
660 int v1_stdout_throttling;
661 int v2_outgoing_sequence;
663 int ssh1_rdpkt_crstate;
664 int ssh2_rdpkt_crstate;
665 int do_ssh_init_crstate;
666 int ssh_gotdata_crstate;
667 int do_ssh1_login_crstate;
668 int do_ssh1_connection_crstate;
669 int do_ssh2_transport_crstate;
670 int do_ssh2_authconn_crstate;
672 void *do_ssh_init_state;
673 void *do_ssh1_login_state;
674 void *do_ssh2_transport_state;
675 void *do_ssh2_authconn_state;
677 struct rdpkt1_state_tag rdpkt1_state;
678 struct rdpkt2_state_tag rdpkt2_state;
680 /* ssh1 and ssh2 use this for different things, but both use it */
681 int protocol_initial_phase_done;
683 void (*protocol) (Ssh ssh, unsigned char *in, int inlen,
685 struct Packet *(*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
688 * We maintain a full _copy_ of a Config structure here, not
689 * merely a pointer to it. That way, when we're passed a new
690 * one for reconfiguration, we can check the differences and
691 * potentially reconfigure port forwardings etc in mid-session.
696 * Used to transfer data back from async agent callbacks.
698 void *agent_response;
699 int agent_response_len;
702 * Dispatch table for packet types that we may have to deal
705 handler_fn_t packet_dispatch[256];
708 * This module deals with sending keepalives.
713 * Track incoming and outgoing data sizes and time, for
716 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
721 #define MAX_DATA_BEFORE_REKEY (0x40000000UL)
722 #define REKEY_TIMEOUT (3600 * TICKSPERSEC)
724 #define logevent(s) logevent(ssh->frontend, s)
726 /* logevent, only printf-formatted. */
727 static void logeventf(Ssh ssh, const char *fmt, ...)
733 buf = dupvprintf(fmt, ap);
739 #define bombout(msg) \
741 char *text = dupprintf msg; \
744 connection_fatal(ssh->frontend, "%s", text); \
748 /* Functions to leave bits out of the SSH packet log file. */
750 static void dont_log_password(Ssh ssh, struct Packet *pkt, int blanktype)
752 if (ssh->cfg.logomitpass)
753 pkt->logmode = blanktype;
756 static void dont_log_data(Ssh ssh, struct Packet *pkt, int blanktype)
758 if (ssh->cfg.logomitdata)
759 pkt->logmode = blanktype;
762 static void end_log_omission(Ssh ssh, struct Packet *pkt)
764 pkt->logmode = PKTLOG_EMIT;
767 static int ssh_channelcmp(void *av, void *bv)
769 struct ssh_channel *a = (struct ssh_channel *) av;
770 struct ssh_channel *b = (struct ssh_channel *) bv;
771 if (a->localid < b->localid)
773 if (a->localid > b->localid)
777 static int ssh_channelfind(void *av, void *bv)
779 unsigned *a = (unsigned *) av;
780 struct ssh_channel *b = (struct ssh_channel *) bv;
788 static int ssh_rportcmp_ssh1(void *av, void *bv)
790 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
791 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
793 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
794 return i < 0 ? -1 : +1;
795 if (a->dport > b->dport)
797 if (a->dport < b->dport)
802 static int ssh_rportcmp_ssh2(void *av, void *bv)
804 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
805 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
807 if (a->sport > b->sport)
809 if (a->sport < b->sport)
814 static int alloc_channel_id(Ssh ssh)
816 const unsigned CHANNEL_NUMBER_OFFSET = 256;
817 unsigned low, high, mid;
819 struct ssh_channel *c;
822 * First-fit allocation of channel numbers: always pick the
823 * lowest unused one. To do this, binary-search using the
824 * counted B-tree to find the largest channel ID which is in a
825 * contiguous sequence from the beginning. (Precisely
826 * everything in that sequence must have ID equal to its tree
827 * index plus CHANNEL_NUMBER_OFFSET.)
829 tsize = count234(ssh->channels);
833 while (high - low > 1) {
834 mid = (high + low) / 2;
835 c = index234(ssh->channels, mid);
836 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
837 low = mid; /* this one is fine */
839 high = mid; /* this one is past it */
842 * Now low points to either -1, or the tree index of the
843 * largest ID in the initial sequence.
846 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
847 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
849 return low + 1 + CHANNEL_NUMBER_OFFSET;
852 static void c_write(Ssh ssh, const char *buf, int len)
854 if ((flags & FLAG_STDERR)) {
856 for (i = 0; i < len; i++)
858 fputc(buf[i], stderr);
861 from_backend(ssh->frontend, 1, buf, len);
864 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
867 for (i = 0; i < len; i++) {
869 c_write(ssh, "\r\n", 2);
870 else if ((buf[i] & 0x60) || (buf[i] == '\r'))
871 c_write(ssh, buf + i, 1);
875 static void c_write_str(Ssh ssh, const char *buf)
877 c_write(ssh, buf, strlen(buf));
880 static void ssh_free_packet(struct Packet *pkt)
885 static struct Packet *ssh_new_packet(void)
887 struct Packet *pkt = snew(struct Packet);
891 pkt->logmode = PKTLOG_EMIT;
899 * Collect incoming data in the incoming packet buffer.
900 * Decipher and verify the packet when it is completely read.
901 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
902 * Update the *data and *datalen variables.
903 * Return a Packet structure when a packet is completed.
905 static struct Packet *ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
907 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
909 crBegin(ssh->ssh1_rdpkt_crstate);
911 st->pktin = ssh_new_packet();
914 st->pktin->length = 0;
916 for (st->i = st->len = 0; st->i < 4; st->i++) {
917 while ((*datalen) == 0)
919 st->len = (st->len << 8) + **data;
920 (*data)++, (*datalen)--;
923 st->pad = 8 - (st->len % 8);
924 st->biglen = st->len + st->pad;
925 st->pktin->length = st->len - 5;
927 if (st->biglen < 0) {
928 bombout(("Extremely large packet length from server suggests"
929 " data stream corruption"));
930 ssh_free_packet(st->pktin);
934 st->pktin->maxlen = st->biglen;
935 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
937 st->to_read = st->biglen;
938 st->p = st->pktin->data;
939 while (st->to_read > 0) {
940 st->chunk = st->to_read;
941 while ((*datalen) == 0)
943 if (st->chunk > (*datalen))
944 st->chunk = (*datalen);
945 memcpy(st->p, *data, st->chunk);
947 *datalen -= st->chunk;
949 st->to_read -= st->chunk;
952 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
954 bombout(("Network attack (CRC compensation) detected!"));
955 ssh_free_packet(st->pktin);
960 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
962 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
963 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
964 if (st->gotcrc != st->realcrc) {
965 bombout(("Incorrect CRC received on packet"));
966 ssh_free_packet(st->pktin);
970 st->pktin->body = st->pktin->data + st->pad + 1;
971 st->pktin->savedpos = 0;
973 if (ssh->v1_compressing) {
974 unsigned char *decompblk;
976 if (!zlib_decompress_block(ssh->sc_comp_ctx,
977 st->pktin->body - 1, st->pktin->length + 1,
978 &decompblk, &decomplen)) {
979 bombout(("Zlib decompression encountered invalid data"));
980 ssh_free_packet(st->pktin);
984 if (st->pktin->maxlen < st->pad + decomplen) {
985 st->pktin->maxlen = st->pad + decomplen;
986 st->pktin->data = sresize(st->pktin->data,
987 st->pktin->maxlen + APIEXTRA,
989 st->pktin->body = st->pktin->data + st->pad + 1;
992 memcpy(st->pktin->body - 1, decompblk, decomplen);
994 st->pktin->length = decomplen - 1;
997 st->pktin->type = st->pktin->body[-1];
1000 * Log incoming packet, possibly omitting sensitive fields.
1004 struct logblank_t blank;
1005 if (ssh->cfg.logomitdata) {
1006 int do_blank = FALSE, blank_prefix = 0;
1007 /* "Session data" packets - omit the data field */
1008 if ((st->pktin->type == SSH1_SMSG_STDOUT_DATA) ||
1009 (st->pktin->type == SSH1_SMSG_STDERR_DATA)) {
1010 do_blank = TRUE; blank_prefix = 0;
1011 } else if (st->pktin->type == SSH1_MSG_CHANNEL_DATA) {
1012 do_blank = TRUE; blank_prefix = 4;
1015 blank.offset = blank_prefix;
1016 blank.len = st->pktin->length;
1017 blank.type = PKTLOG_OMIT;
1021 log_packet(ssh->logctx,
1022 PKT_INCOMING, st->pktin->type,
1023 ssh1_pkt_type(st->pktin->type),
1024 st->pktin->body, st->pktin->length,
1028 crFinish(st->pktin);
1031 static struct Packet *ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1033 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1035 crBegin(ssh->ssh2_rdpkt_crstate);
1037 st->pktin = ssh_new_packet();
1039 st->pktin->type = 0;
1040 st->pktin->length = 0;
1042 st->cipherblk = ssh->sccipher->blksize;
1045 if (st->cipherblk < 8)
1048 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1051 * Acquire and decrypt the first block of the packet. This will
1052 * contain the length and padding details.
1054 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1055 while ((*datalen) == 0)
1057 st->pktin->data[st->i] = *(*data)++;
1062 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1063 st->pktin->data, st->cipherblk);
1066 * Now get the length and padding figures.
1068 st->len = GET_32BIT(st->pktin->data);
1069 st->pad = st->pktin->data[4];
1072 * _Completely_ silly lengths should be stomped on before they
1073 * do us any more damage.
1075 if (st->len < 0 || st->pad < 0 || st->len + st->pad < 0) {
1076 bombout(("Incoming packet was garbled on decryption"));
1077 ssh_free_packet(st->pktin);
1082 * This enables us to deduce the payload length.
1084 st->payload = st->len - st->pad - 1;
1086 st->pktin->length = st->payload + 5;
1089 * So now we can work out the total packet length.
1091 st->packetlen = st->len + 4;
1092 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1095 * Allocate memory for the rest of the packet.
1097 st->pktin->maxlen = st->packetlen + st->maclen;
1098 st->pktin->data = sresize(st->pktin->data,
1099 st->pktin->maxlen + APIEXTRA,
1103 * Read and decrypt the remainder of the packet.
1105 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1107 while ((*datalen) == 0)
1109 st->pktin->data[st->i] = *(*data)++;
1112 /* Decrypt everything _except_ the MAC. */
1114 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1115 st->pktin->data + st->cipherblk,
1116 st->packetlen - st->cipherblk);
1118 st->pktin->encrypted_len = st->packetlen;
1124 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data, st->len + 4,
1125 st->incoming_sequence)) {
1126 bombout(("Incorrect MAC received on packet"));
1127 ssh_free_packet(st->pktin);
1131 st->pktin->sequence = st->incoming_sequence++;
1134 * Decompress packet payload.
1137 unsigned char *newpayload;
1140 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1141 st->pktin->data + 5, st->pktin->length - 5,
1142 &newpayload, &newlen)) {
1143 if (st->pktin->maxlen < newlen + 5) {
1144 st->pktin->maxlen = newlen + 5;
1145 st->pktin->data = sresize(st->pktin->data,
1146 st->pktin->maxlen + APIEXTRA,
1149 st->pktin->length = 5 + newlen;
1150 memcpy(st->pktin->data + 5, newpayload, newlen);
1155 st->pktin->savedpos = 6;
1156 st->pktin->body = st->pktin->data;
1157 st->pktin->type = st->pktin->data[5];
1160 * Log incoming packet, possibly omitting sensitive fields.
1164 struct logblank_t blank;
1165 if (ssh->cfg.logomitdata) {
1166 int do_blank = FALSE, blank_prefix = 0;
1167 /* "Session data" packets - omit the data field */
1168 if (st->pktin->type == SSH2_MSG_CHANNEL_DATA) {
1169 do_blank = TRUE; blank_prefix = 4;
1170 } else if (st->pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
1171 do_blank = TRUE; blank_prefix = 8;
1174 blank.offset = blank_prefix;
1175 blank.len = (st->pktin->length-6) - blank_prefix;
1176 blank.type = PKTLOG_OMIT;
1180 log_packet(ssh->logctx, PKT_INCOMING, st->pktin->type,
1181 ssh2_pkt_type(ssh->pkt_ctx, st->pktin->type),
1182 st->pktin->data+6, st->pktin->length-6,
1186 crFinish(st->pktin);
1189 static void ssh1_pktout_size(struct Packet *pkt, int len)
1193 len += 5; /* type and CRC */
1194 pad = 8 - (len % 8);
1197 pkt->length = len - 5;
1198 if (pkt->maxlen < biglen) {
1199 pkt->maxlen = biglen;
1200 pkt->data = sresize(pkt->data, biglen + 4 + APIEXTRA, unsigned char);
1202 pkt->body = pkt->data + 4 + pad + 1;
1205 static struct Packet *s_wrpkt_start(int type, int len)
1207 struct Packet *pkt = ssh_new_packet();
1208 ssh1_pktout_size(pkt, len);
1210 /* Initialise log omission state */
1216 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt)
1222 * XXX various versions of SC (including 8.8.4) screw up the
1223 * register allocation in this function and use the same register
1224 * (D6) for len and as a temporary, with predictable results. The
1225 * following sledgehammer prevents this.
1231 pkt->body[-1] = pkt->type;
1234 log_packet(ssh->logctx, PKT_OUTGOING, pkt->type,
1235 ssh1_pkt_type(pkt->type),
1236 pkt->body, pkt->length,
1237 pkt->nblanks, pkt->blanks);
1238 sfree(pkt->blanks); pkt->blanks = NULL;
1241 if (ssh->v1_compressing) {
1242 unsigned char *compblk;
1244 zlib_compress_block(ssh->cs_comp_ctx,
1245 pkt->body - 1, pkt->length + 1,
1246 &compblk, &complen);
1247 ssh1_pktout_size(pkt, complen - 1);
1248 memcpy(pkt->body - 1, compblk, complen);
1252 len = pkt->length + 5; /* type and CRC */
1253 pad = 8 - (len % 8);
1256 for (i = 0; i < pad; i++)
1257 pkt->data[i + 4] = random_byte();
1258 crc = crc32_compute(pkt->data + 4, biglen - 4);
1259 PUT_32BIT(pkt->data + biglen, crc);
1260 PUT_32BIT(pkt->data, len);
1263 ssh->cipher->encrypt(ssh->v1_cipher_ctx, pkt->data + 4, biglen);
1268 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1271 len = s_wrpkt_prepare(ssh, pkt);
1272 backlog = sk_write(ssh->s, (char *)pkt->data, len);
1273 if (backlog > SSH_MAX_BACKLOG)
1274 ssh_throttle_all(ssh, 1, backlog);
1277 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1280 len = s_wrpkt_prepare(ssh, pkt);
1281 if (ssh->deferred_len + len > ssh->deferred_size) {
1282 ssh->deferred_size = ssh->deferred_len + len + 128;
1283 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1287 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->data, len);
1288 ssh->deferred_len += len;
1292 * Construct a packet with the specified contents.
1294 static struct Packet *construct_packet(Ssh ssh, int pkttype,
1295 va_list ap1, va_list ap2)
1297 unsigned char *p, *argp, argchar;
1298 unsigned long argint;
1299 int pktlen, argtype, arglen;
1304 while ((argtype = va_arg(ap1, int)) != PKT_END) {
1307 (void) va_arg(ap1, int);
1311 (void) va_arg(ap1, int);
1315 (void) va_arg(ap1, unsigned char *);
1316 arglen = va_arg(ap1, int);
1320 argp = va_arg(ap1, unsigned char *);
1321 arglen = strlen((char *)argp);
1322 pktlen += 4 + arglen;
1325 bn = va_arg(ap1, Bignum);
1326 pktlen += ssh1_bignum_length(bn);
1331 /* ignore this pass */
1338 pkt = s_wrpkt_start(pkttype, pktlen);
1341 while ((argtype = va_arg(ap2, int)) != PKT_END) {
1342 int offset = p - pkt->body, len = 0;
1344 /* Actual fields in the packet */
1346 argint = va_arg(ap2, int);
1347 PUT_32BIT(p, argint);
1351 argchar = (unsigned char) va_arg(ap2, int);
1356 argp = va_arg(ap2, unsigned char *);
1357 arglen = va_arg(ap2, int);
1358 memcpy(p, argp, arglen);
1362 argp = va_arg(ap2, unsigned char *);
1363 arglen = strlen((char *)argp);
1364 PUT_32BIT(p, arglen);
1365 memcpy(p + 4, argp, arglen);
1369 bn = va_arg(ap2, Bignum);
1370 len = ssh1_write_bignum(p, bn);
1372 /* Tokens for modifications to packet logging */
1374 dont_log_password(ssh, pkt, PKTLOG_BLANK);
1377 dont_log_data(ssh, pkt, PKTLOG_OMIT);
1380 end_log_omission(ssh, pkt);
1384 /* Deal with logfile omission, if required. */
1385 if (len && (pkt->logmode != PKTLOG_EMIT)) {
1387 pkt->blanks = sresize(pkt->blanks, pkt->nblanks,
1389 pkt->blanks[pkt->nblanks-1].offset = offset;
1390 pkt->blanks[pkt->nblanks-1].len = len;
1391 pkt->blanks[pkt->nblanks-1].type = pkt->logmode;
1398 static void send_packet(Ssh ssh, int pkttype, ...)
1402 va_start(ap1, pkttype);
1403 va_start(ap2, pkttype);
1404 pkt = construct_packet(ssh, pkttype, ap1, ap2);
1408 ssh_free_packet(pkt);
1411 static void defer_packet(Ssh ssh, int pkttype, ...)
1415 va_start(ap1, pkttype);
1416 va_start(ap2, pkttype);
1417 pkt = construct_packet(ssh, pkttype, ap1, ap2);
1420 s_wrpkt_defer(ssh, pkt);
1421 ssh_free_packet(pkt);
1424 static int ssh_versioncmp(char *a, char *b)
1427 unsigned long av, bv;
1429 av = strtoul(a, &ae, 10);
1430 bv = strtoul(b, &be, 10);
1432 return (av < bv ? -1 : +1);
1437 av = strtoul(ae, &ae, 10);
1438 bv = strtoul(be, &be, 10);
1440 return (av < bv ? -1 : +1);
1445 * Utility routines for putting an SSH-protocol `string' and
1446 * `uint32' into a SHA state.
1449 static void sha_string(SHA_State * s, void *str, int len)
1451 unsigned char lenblk[4];
1452 PUT_32BIT(lenblk, len);
1453 SHA_Bytes(s, lenblk, 4);
1454 SHA_Bytes(s, str, len);
1457 static void sha_uint32(SHA_State * s, unsigned i)
1459 unsigned char intblk[4];
1460 PUT_32BIT(intblk, i);
1461 SHA_Bytes(s, intblk, 4);
1465 * SSH2 packet construction functions.
1467 static void ssh2_pkt_ensure(struct Packet *pkt, int length)
1469 if (pkt->maxlen < length) {
1470 pkt->maxlen = length + 256;
1471 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
1474 static void ssh2_pkt_adddata(struct Packet *pkt, void *data, int len)
1476 if (pkt->logmode != PKTLOG_EMIT) {
1478 pkt->blanks = sresize(pkt->blanks, pkt->nblanks, struct logblank_t);
1479 pkt->blanks[pkt->nblanks-1].offset = pkt->length - 6;
1480 pkt->blanks[pkt->nblanks-1].len = len;
1481 pkt->blanks[pkt->nblanks-1].type = pkt->logmode;
1484 ssh2_pkt_ensure(pkt, pkt->length);
1485 memcpy(pkt->data + pkt->length - len, data, len);
1487 static void ssh2_pkt_addbyte(struct Packet *pkt, unsigned char byte)
1489 ssh2_pkt_adddata(pkt, &byte, 1);
1491 static struct Packet *ssh2_pkt_init(int pkt_type)
1493 struct Packet *pkt = ssh_new_packet();
1495 ssh2_pkt_addbyte(pkt, (unsigned char) pkt_type);
1498 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
1500 ssh2_pkt_adddata(pkt, &value, 1);
1502 static void ssh2_pkt_adduint32(struct Packet *pkt, unsigned long value)
1505 PUT_32BIT(x, value);
1506 ssh2_pkt_adddata(pkt, x, 4);
1508 static void ssh2_pkt_addstring_start(struct Packet *pkt)
1510 ssh2_pkt_adduint32(pkt, 0);
1511 pkt->savedpos = pkt->length;
1513 static void ssh2_pkt_addstring_str(struct Packet *pkt, char *data)
1515 ssh2_pkt_adddata(pkt, data, strlen(data));
1516 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1518 static void ssh2_pkt_addstring_data(struct Packet *pkt, char *data, int len)
1520 ssh2_pkt_adddata(pkt, data, len);
1521 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1523 static void ssh2_pkt_addstring(struct Packet *pkt, char *data)
1525 ssh2_pkt_addstring_start(pkt);
1526 ssh2_pkt_addstring_str(pkt, data);
1528 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
1531 int i, n = (bignum_bitcount(b) + 7) / 8;
1532 p = snewn(n + 1, unsigned char);
1534 fatalbox("out of memory");
1536 for (i = 1; i <= n; i++)
1537 p[i] = bignum_byte(b, n - i);
1539 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1541 memmove(p, p + i, n + 1 - i);
1545 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
1549 p = ssh2_mpint_fmt(b, &len);
1550 ssh2_pkt_addstring_start(pkt);
1551 ssh2_pkt_addstring_data(pkt, (char *)p, len);
1556 * Construct an SSH2 final-form packet: compress it, encrypt it,
1557 * put the MAC on it. Final packet, ready to be sent, is stored in
1558 * pkt->data. Total length is returned.
1560 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
1562 int cipherblk, maclen, padding, i;
1565 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1566 ssh2_pkt_type(ssh->pkt_ctx, pkt->data[5]),
1567 pkt->data + 6, pkt->length - 6,
1568 pkt->nblanks, pkt->blanks);
1569 sfree(pkt->blanks); pkt->blanks = NULL;
1573 * Compress packet payload.
1576 unsigned char *newpayload;
1579 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
1581 &newpayload, &newlen)) {
1583 ssh2_pkt_adddata(pkt, newpayload, newlen);
1589 * Add padding. At least four bytes, and must also bring total
1590 * length (minus MAC) up to a multiple of the block size.
1592 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
1593 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1596 (cipherblk - (pkt->length + padding) % cipherblk) % cipherblk;
1597 maclen = ssh->csmac ? ssh->csmac->len : 0;
1598 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
1599 pkt->data[4] = padding;
1600 for (i = 0; i < padding; i++)
1601 pkt->data[pkt->length + i] = random_byte();
1602 PUT_32BIT(pkt->data, pkt->length + padding - 4);
1604 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
1605 pkt->length + padding,
1606 ssh->v2_outgoing_sequence);
1607 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
1610 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
1611 pkt->data, pkt->length + padding);
1613 pkt->encrypted_len = pkt->length + padding;
1615 /* Ready-to-send packet starts at pkt->data. We return length. */
1616 return pkt->length + padding + maclen;
1620 * Routines called from the main SSH code to send packets. There
1621 * are quite a few of these, because we have two separate
1622 * mechanisms for delaying the sending of packets:
1624 * - In order to send an IGNORE message and a password message in
1625 * a single fixed-length blob, we require the ability to
1626 * concatenate the encrypted forms of those two packets _into_ a
1627 * single blob and then pass it to our <network.h> transport
1628 * layer in one go. Hence, there's a deferment mechanism which
1629 * works after packet encryption.
1631 * - In order to avoid sending any connection-layer messages
1632 * during repeat key exchange, we have to queue up any such
1633 * outgoing messages _before_ they are encrypted (and in
1634 * particular before they're allocated sequence numbers), and
1635 * then send them once we've finished.
1637 * I call these mechanisms `defer' and `queue' respectively, so as
1638 * to distinguish them reasonably easily.
1640 * The functions send_noqueue() and defer_noqueue() free the packet
1641 * structure they are passed. Every outgoing packet goes through
1642 * precisely one of these functions in its life; packets passed to
1643 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
1644 * these or get queued, and then when the queue is later emptied
1645 * the packets are all passed to defer_noqueue().
1649 * Send an SSH2 packet immediately, without queuing or deferring.
1651 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
1655 len = ssh2_pkt_construct(ssh, pkt);
1656 backlog = sk_write(ssh->s, (char *)pkt->data, len);
1657 if (backlog > SSH_MAX_BACKLOG)
1658 ssh_throttle_all(ssh, 1, backlog);
1660 ssh->outgoing_data_size += pkt->encrypted_len;
1661 if (!ssh->kex_in_progress &&
1662 ssh->outgoing_data_size > MAX_DATA_BEFORE_REKEY)
1663 do_ssh2_transport(ssh, "Initiating key re-exchange "
1664 "(too much data sent)", -1, NULL);
1666 ssh_free_packet(pkt);
1670 * Defer an SSH2 packet.
1672 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt)
1674 int len = ssh2_pkt_construct(ssh, pkt);
1675 if (ssh->deferred_len + len > ssh->deferred_size) {
1676 ssh->deferred_size = ssh->deferred_len + len + 128;
1677 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1681 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->data, len);
1682 ssh->deferred_len += len;
1683 ssh->deferred_data_size += pkt->encrypted_len;
1684 ssh_free_packet(pkt);
1688 * Queue an SSH2 packet.
1690 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
1692 assert(ssh->queueing);
1694 if (ssh->queuelen >= ssh->queuesize) {
1695 ssh->queuesize = ssh->queuelen + 32;
1696 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
1699 ssh->queue[ssh->queuelen++] = pkt;
1703 * Either queue or send a packet, depending on whether queueing is
1706 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
1709 ssh2_pkt_queue(ssh, pkt);
1711 ssh2_pkt_send_noqueue(ssh, pkt);
1715 * Either queue or defer a packet, depending on whether queueing is
1718 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
1721 ssh2_pkt_queue(ssh, pkt);
1723 ssh2_pkt_defer_noqueue(ssh, pkt);
1727 * Send the whole deferred data block constructed by
1728 * ssh2_pkt_defer() or SSH1's defer_packet().
1730 * The expected use of the defer mechanism is that you call
1731 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
1732 * not currently queueing, this simply sets up deferred_send_data
1733 * and then sends it. If we _are_ currently queueing, the calls to
1734 * ssh2_pkt_defer() put the deferred packets on to the queue
1735 * instead, and therefore ssh_pkt_defersend() has no deferred data
1736 * to send. Hence, there's no need to make it conditional on
1739 static void ssh_pkt_defersend(Ssh ssh)
1742 backlog = sk_write(ssh->s, (char *)ssh->deferred_send_data,
1744 ssh->deferred_len = ssh->deferred_size = 0;
1745 sfree(ssh->deferred_send_data);
1746 ssh->deferred_send_data = NULL;
1747 if (backlog > SSH_MAX_BACKLOG)
1748 ssh_throttle_all(ssh, 1, backlog);
1750 ssh->outgoing_data_size += ssh->deferred_data_size;
1751 if (!ssh->kex_in_progress &&
1752 ssh->outgoing_data_size > MAX_DATA_BEFORE_REKEY)
1753 do_ssh2_transport(ssh, "Initiating key re-exchange "
1754 "(too much data sent)", -1, NULL);
1755 ssh->deferred_data_size = 0;
1759 * Send all queued SSH2 packets. We send them by means of
1760 * ssh2_pkt_defer_noqueue(), in case they included a pair of
1761 * packets that needed to be lumped together.
1763 static void ssh2_pkt_queuesend(Ssh ssh)
1767 assert(!ssh->queueing);
1769 for (i = 0; i < ssh->queuelen; i++)
1770 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i]);
1773 ssh_pkt_defersend(ssh);
1777 void bndebug(char *string, Bignum b)
1781 p = ssh2_mpint_fmt(b, &len);
1782 debug(("%s", string));
1783 for (i = 0; i < len; i++)
1784 debug((" %02x", p[i]));
1790 static void sha_mpint(SHA_State * s, Bignum b)
1794 p = ssh2_mpint_fmt(b, &len);
1795 sha_string(s, p, len);
1800 * Packet decode functions for both SSH1 and SSH2.
1802 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
1804 unsigned long value;
1805 if (pkt->length - pkt->savedpos < 4)
1806 return 0; /* arrgh, no way to decline (FIXME?) */
1807 value = GET_32BIT(pkt->body + pkt->savedpos);
1811 static int ssh2_pkt_getbool(struct Packet *pkt)
1813 unsigned long value;
1814 if (pkt->length - pkt->savedpos < 1)
1815 return 0; /* arrgh, no way to decline (FIXME?) */
1816 value = pkt->body[pkt->savedpos] != 0;
1820 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
1825 if (pkt->length - pkt->savedpos < 4)
1827 len = GET_32BIT(pkt->body + pkt->savedpos);
1832 if (pkt->length - pkt->savedpos < *length)
1834 *p = (char *)(pkt->body + pkt->savedpos);
1835 pkt->savedpos += *length;
1837 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
1839 if (pkt->length - pkt->savedpos < length)
1841 pkt->savedpos += length;
1842 return pkt->body + (pkt->savedpos - length);
1844 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
1845 unsigned char **keystr)
1849 j = makekey(pkt->body + pkt->savedpos,
1850 pkt->length - pkt->savedpos,
1857 assert(pkt->savedpos < pkt->length);
1861 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
1866 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
1867 pkt->length - pkt->savedpos, &b);
1875 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
1881 ssh_pkt_getstring(pkt, &p, &length);
1886 b = bignum_from_bytes((unsigned char *)p, length);
1891 * Helper function to add an SSH2 signature blob to a packet.
1892 * Expects to be shown the public key blob as well as the signature
1893 * blob. Normally works just like ssh2_pkt_addstring, but will
1894 * fiddle with the signature packet if necessary for
1895 * BUG_SSH2_RSA_PADDING.
1897 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
1898 void *pkblob_v, int pkblob_len,
1899 void *sigblob_v, int sigblob_len)
1901 unsigned char *pkblob = (unsigned char *)pkblob_v;
1902 unsigned char *sigblob = (unsigned char *)sigblob_v;
1904 /* dmemdump(pkblob, pkblob_len); */
1905 /* dmemdump(sigblob, sigblob_len); */
1908 * See if this is in fact an ssh-rsa signature and a buggy
1909 * server; otherwise we can just do this the easy way.
1911 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) &&
1912 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
1913 int pos, len, siglen;
1916 * Find the byte length of the modulus.
1919 pos = 4+7; /* skip over "ssh-rsa" */
1920 pos += 4 + GET_32BIT(pkblob+pos); /* skip over exponent */
1921 len = GET_32BIT(pkblob+pos); /* find length of modulus */
1922 pos += 4; /* find modulus itself */
1923 while (len > 0 && pkblob[pos] == 0)
1925 /* debug(("modulus length is %d\n", len)); */
1928 * Now find the signature integer.
1930 pos = 4+7; /* skip over "ssh-rsa" */
1931 siglen = GET_32BIT(sigblob+pos);
1932 /* debug(("signature length is %d\n", siglen)); */
1934 if (len != siglen) {
1935 unsigned char newlen[4];
1936 ssh2_pkt_addstring_start(pkt);
1937 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
1938 /* dmemdump(sigblob, pos); */
1939 pos += 4; /* point to start of actual sig */
1940 PUT_32BIT(newlen, len);
1941 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
1942 /* dmemdump(newlen, 4); */
1944 while (len-- > siglen) {
1945 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
1946 /* dmemdump(newlen, 1); */
1948 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
1949 /* dmemdump(sigblob+pos, siglen); */
1953 /* Otherwise fall through and do it the easy way. */
1956 ssh2_pkt_addstring_start(pkt);
1957 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
1961 * Examine the remote side's version string and compare it against
1962 * a list of known buggy implementations.
1964 static void ssh_detect_bugs(Ssh ssh, char *vstring)
1966 char *imp; /* pointer to implementation part */
1968 imp += strcspn(imp, "-");
1970 imp += strcspn(imp, "-");
1973 ssh->remote_bugs = 0;
1975 if (ssh->cfg.sshbug_ignore1 == FORCE_ON ||
1976 (ssh->cfg.sshbug_ignore1 == AUTO &&
1977 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
1978 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
1979 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
1980 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
1982 * These versions don't support SSH1_MSG_IGNORE, so we have
1983 * to use a different defence against password length
1986 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
1987 logevent("We believe remote version has SSH1 ignore bug");
1990 if (ssh->cfg.sshbug_plainpw1 == FORCE_ON ||
1991 (ssh->cfg.sshbug_plainpw1 == AUTO &&
1992 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
1994 * These versions need a plain password sent; they can't
1995 * handle having a null and a random length of data after
1998 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
1999 logevent("We believe remote version needs a plain SSH1 password");
2002 if (ssh->cfg.sshbug_rsa1 == FORCE_ON ||
2003 (ssh->cfg.sshbug_rsa1 == AUTO &&
2004 (!strcmp(imp, "Cisco-1.25")))) {
2006 * These versions apparently have no clue whatever about
2007 * RSA authentication and will panic and die if they see
2008 * an AUTH_RSA message.
2010 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2011 logevent("We believe remote version can't handle RSA authentication");
2014 if (ssh->cfg.sshbug_hmac2 == FORCE_ON ||
2015 (ssh->cfg.sshbug_hmac2 == AUTO &&
2016 !wc_match("* VShell", imp) &&
2017 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2018 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2019 wc_match("2.1 *", imp)))) {
2021 * These versions have the HMAC bug.
2023 ssh->remote_bugs |= BUG_SSH2_HMAC;
2024 logevent("We believe remote version has SSH2 HMAC bug");
2027 if (ssh->cfg.sshbug_derivekey2 == FORCE_ON ||
2028 (ssh->cfg.sshbug_derivekey2 == AUTO &&
2029 !wc_match("* VShell", imp) &&
2030 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2032 * These versions have the key-derivation bug (failing to
2033 * include the literal shared secret in the hashes that
2034 * generate the keys).
2036 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2037 logevent("We believe remote version has SSH2 key-derivation bug");
2040 if (ssh->cfg.sshbug_rsapad2 == FORCE_ON ||
2041 (ssh->cfg.sshbug_rsapad2 == AUTO &&
2042 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2043 wc_match("OpenSSH_3.[0-2]*", imp)))) {
2045 * These versions have the SSH2 RSA padding bug.
2047 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2048 logevent("We believe remote version has SSH2 RSA padding bug");
2051 if (ssh->cfg.sshbug_pksessid2 == FORCE_ON ||
2052 (ssh->cfg.sshbug_pksessid2 == AUTO &&
2053 wc_match("OpenSSH_2.[0-2]*", imp))) {
2055 * These versions have the SSH2 session-ID bug in
2056 * public-key authentication.
2058 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2059 logevent("We believe remote version has SSH2 public-key-session-ID bug");
2062 if (ssh->cfg.sshbug_dhgex2 == FORCE_ON) {
2064 * User specified the SSH2 DH GEX bug.
2066 ssh->remote_bugs |= BUG_SSH2_DH_GEX;
2067 logevent("We believe remote version has SSH2 DH group exchange bug");
2072 * The `software version' part of an SSH version string is required
2073 * to contain no spaces or minus signs.
2075 static void ssh_fix_verstring(char *str)
2077 /* Eat "SSH-<protoversion>-". */
2078 assert(*str == 'S'); str++;
2079 assert(*str == 'S'); str++;
2080 assert(*str == 'H'); str++;
2081 assert(*str == '-'); str++;
2082 while (*str && *str != '-') str++;
2083 assert(*str == '-'); str++;
2085 /* Convert minus signs and spaces in the remaining string into
2088 if (*str == '-' || *str == ' ')
2094 static int do_ssh_init(Ssh ssh, unsigned char c)
2096 struct do_ssh_init_state {
2104 crState(do_ssh_init_state);
2106 crBegin(ssh->do_ssh_init_crstate);
2108 /* Search for the string "SSH-" in the input. */
2111 static const int transS[] = { 1, 2, 2, 1 };
2112 static const int transH[] = { 0, 0, 3, 0 };
2113 static const int transminus[] = { 0, 0, 0, -1 };
2115 s->i = transS[s->i];
2117 s->i = transH[s->i];
2119 s->i = transminus[s->i];
2124 crReturn(1); /* get another character */
2128 s->vstring = snewn(s->vstrsize, char);
2129 strcpy(s->vstring, "SSH-");
2133 crReturn(1); /* get another char */
2134 if (s->vslen >= s->vstrsize - 1) {
2136 s->vstring = sresize(s->vstring, s->vstrsize, char);
2138 s->vstring[s->vslen++] = c;
2141 s->version[s->i] = '\0';
2143 } else if (s->i < sizeof(s->version) - 1)
2144 s->version[s->i++] = c;
2145 } else if (c == '\012')
2149 ssh->agentfwd_enabled = FALSE;
2150 ssh->rdpkt2_state.incoming_sequence = 0;
2152 s->vstring[s->vslen] = 0;
2153 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
2156 vlog = snewn(20 + s->vslen, char);
2157 sprintf(vlog, "Server version: %s", s->vstring);
2161 ssh_detect_bugs(ssh, s->vstring);
2164 * Decide which SSH protocol version to support.
2167 /* Anything strictly below "2.0" means protocol 1 is supported. */
2168 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
2169 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2170 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
2172 if (ssh->cfg.sshprot == 0 && !s->proto1) {
2173 bombout(("SSH protocol version 1 required by user but not provided by server"));
2176 if (ssh->cfg.sshprot == 3 && !s->proto2) {
2177 bombout(("SSH protocol version 2 required by user but not provided by server"));
2184 if (s->proto2 && (ssh->cfg.sshprot >= 2 || !s->proto1)) {
2186 * Construct a v2 version string.
2188 verstring = dupprintf("SSH-2.0-%s\015\012", sshver);
2192 * Construct a v1 version string.
2194 verstring = dupprintf("SSH-%s-%s\012",
2195 (ssh_versioncmp(s->version, "1.5") <= 0 ?
2196 s->version : "1.5"),
2201 ssh_fix_verstring(verstring);
2203 if (ssh->version == 2) {
2205 * Hash our version string and their version string.
2207 SHA_Init(&ssh->exhashbase);
2208 sha_string(&ssh->exhashbase, verstring,
2209 strcspn(verstring, "\015\012"));
2210 sha_string(&ssh->exhashbase, s->vstring,
2211 strcspn(s->vstring, "\015\012"));
2214 * Initialise SSHv2 protocol.
2216 ssh->protocol = ssh2_protocol;
2217 ssh2_protocol_setup(ssh);
2218 ssh->s_rdpkt = ssh2_rdpkt;
2221 * Initialise SSHv1 protocol.
2223 ssh->protocol = ssh1_protocol;
2224 ssh1_protocol_setup(ssh);
2225 ssh->s_rdpkt = ssh1_rdpkt;
2227 logeventf(ssh, "We claim version: %.*s",
2228 strcspn(verstring, "\015\012"), verstring);
2229 sk_write(ssh->s, verstring, strlen(verstring));
2233 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
2235 update_specials_menu(ssh->frontend);
2236 ssh->state = SSH_STATE_BEFORE_SIZE;
2237 ssh->pinger = pinger_new(&ssh->cfg, &ssh_backend, ssh);
2244 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
2246 crBegin(ssh->ssh_gotdata_crstate);
2249 * To begin with, feed the characters one by one to the
2250 * protocol initialisation / selection function do_ssh_init().
2251 * When that returns 0, we're done with the initial greeting
2252 * exchange and can move on to packet discipline.
2255 int ret; /* need not be kept across crReturn */
2257 crReturnV; /* more data please */
2258 ret = do_ssh_init(ssh, *data);
2266 * We emerge from that loop when the initial negotiation is
2267 * over and we have selected an s_rdpkt function. Now pass
2268 * everything to s_rdpkt, and then pass the resulting packets
2269 * to the proper protocol handler.
2274 while (datalen > 0) {
2275 struct Packet *pktin = ssh->s_rdpkt(ssh, &data, &datalen);
2277 ssh->protocol(ssh, NULL, 0, pktin);
2278 ssh_free_packet(pktin);
2280 if (ssh->state == SSH_STATE_CLOSED)
2288 static void ssh_do_close(Ssh ssh)
2291 struct ssh_channel *c;
2293 ssh->state = SSH_STATE_CLOSED;
2297 notify_remote_exit(ssh->frontend);
2300 * Now we must shut down any port and X forwardings going
2301 * through this connection.
2303 if (ssh->channels) {
2304 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
2307 x11_close(c->u.x11.s);
2310 pfd_close(c->u.pfd.s);
2313 del234(ssh->channels, c);
2314 if (ssh->version == 2)
2315 bufchain_clear(&c->v.v2.outbuffer);
2321 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
2324 Ssh ssh = (Ssh) plug;
2327 /* A socket error has occurred. */
2328 logevent(error_msg);
2329 connection_fatal(ssh->frontend, "%s", error_msg);
2331 /* Otherwise, the remote side closed the connection normally. */
2336 static int ssh_receive(Plug plug, int urgent, char *data, int len)
2338 Ssh ssh = (Ssh) plug;
2339 ssh_gotdata(ssh, (unsigned char *)data, len);
2340 if (ssh->state == SSH_STATE_CLOSED) {
2347 static void ssh_sent(Plug plug, int bufsize)
2349 Ssh ssh = (Ssh) plug;
2351 * If the send backlog on the SSH socket itself clears, we
2352 * should unthrottle the whole world if it was throttled.
2354 if (bufsize < SSH_MAX_BACKLOG)
2355 ssh_throttle_all(ssh, 0, bufsize);
2359 * Connect to specified host and port.
2360 * Returns an error message, or NULL on success.
2361 * Also places the canonical host name into `realhost'. It must be
2362 * freed by the caller.
2364 static const char *connect_to_host(Ssh ssh, char *host, int port,
2365 char **realhost, int nodelay, int keepalive)
2367 static const struct plug_function_table fn_table = {
2377 ssh->savedhost = snewn(1 + strlen(host), char);
2378 if (!ssh->savedhost)
2379 fatalbox("Out of memory");
2380 strcpy(ssh->savedhost, host);
2383 port = 22; /* default ssh port */
2384 ssh->savedport = port;
2389 logeventf(ssh, "Looking up host \"%s\"", host);
2390 addr = name_lookup(host, port, realhost, &ssh->cfg);
2391 if ((err = sk_addr_error(addr)) != NULL) {
2401 sk_getaddr(addr, addrbuf, 100);
2402 logeventf(ssh, "Connecting to %s port %d", addrbuf, port);
2404 ssh->fn = &fn_table;
2405 ssh->s = new_connection(addr, *realhost, port,
2406 0, 1, nodelay, keepalive, (Plug) ssh, &ssh->cfg);
2407 if ((err = sk_socket_error(ssh->s)) != NULL) {
2409 notify_remote_exit(ssh->frontend);
2417 * Throttle or unthrottle the SSH connection.
2419 static void ssh1_throttle(Ssh ssh, int adjust)
2421 int old_count = ssh->v1_throttle_count;
2422 ssh->v1_throttle_count += adjust;
2423 assert(ssh->v1_throttle_count >= 0);
2424 if (ssh->v1_throttle_count && !old_count) {
2425 sk_set_frozen(ssh->s, 1);
2426 } else if (!ssh->v1_throttle_count && old_count) {
2427 sk_set_frozen(ssh->s, 0);
2432 * Throttle or unthrottle _all_ local data streams (for when sends
2433 * on the SSH connection itself back up).
2435 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
2438 struct ssh_channel *c;
2440 if (enable == ssh->throttled_all)
2442 ssh->throttled_all = enable;
2443 ssh->overall_bufsize = bufsize;
2446 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
2448 case CHAN_MAINSESSION:
2450 * This is treated separately, outside the switch.
2454 x11_override_throttle(c->u.x11.s, enable);
2457 /* Agent channels require no buffer management. */
2460 pfd_override_throttle(c->u.pfd.s, enable);
2467 * Username and password input, abstracted off into routines
2468 * reusable in several places - even between SSH1 and SSH2.
2471 /* Set up a username or password input loop on a given buffer. */
2472 static void setup_userpass_input(Ssh ssh, char *buffer, int buflen, int echo)
2474 ssh->userpass_input_buffer = buffer;
2475 ssh->userpass_input_buflen = buflen;
2476 ssh->userpass_input_bufpos = 0;
2477 ssh->userpass_input_echo = echo;
2481 * Process some terminal data in the course of username/password
2482 * input. Returns >0 for success (line of input returned in
2483 * buffer), <0 for failure (user hit ^C/^D, bomb out and exit), 0
2484 * for inconclusive (keep waiting for more input please).
2486 static int process_userpass_input(Ssh ssh, unsigned char *in, int inlen)
2491 switch (c = *in++) {
2494 ssh->userpass_input_buffer[ssh->userpass_input_bufpos] = 0;
2495 ssh->userpass_input_buffer[ssh->userpass_input_buflen-1] = 0;
2500 if (ssh->userpass_input_bufpos > 0) {
2501 if (ssh->userpass_input_echo)
2502 c_write_str(ssh, "\b \b");
2503 ssh->userpass_input_bufpos--;
2508 while (ssh->userpass_input_bufpos > 0) {
2509 if (ssh->userpass_input_echo)
2510 c_write_str(ssh, "\b \b");
2511 ssh->userpass_input_bufpos--;
2520 * This simplistic check for printability is disabled
2521 * when we're doing password input, because some people
2522 * have control characters in their passwords.o
2524 if ((!ssh->userpass_input_echo ||
2525 (c >= ' ' && c <= '~') ||
2526 ((unsigned char) c >= 160))
2527 && ssh->userpass_input_bufpos < ssh->userpass_input_buflen-1) {
2528 ssh->userpass_input_buffer[ssh->userpass_input_bufpos++] = c;
2529 if (ssh->userpass_input_echo)
2530 c_write(ssh, &c, 1);
2538 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
2540 Ssh ssh = (Ssh) sshv;
2542 ssh->agent_response = reply;
2543 ssh->agent_response_len = replylen;
2545 if (ssh->version == 1)
2546 do_ssh1_login(ssh, NULL, -1, NULL);
2548 do_ssh2_authconn(ssh, NULL, -1, NULL);
2551 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
2553 struct ssh_channel *c = (struct ssh_channel *)cv;
2555 void *sentreply = reply;
2558 /* Fake SSH_AGENT_FAILURE. */
2559 sentreply = "\0\0\0\1\5";
2562 if (ssh->version == 2) {
2563 ssh2_add_channel_data(c, sentreply, replylen);
2566 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
2567 PKT_INT, c->remoteid,
2570 PKT_DATA, sentreply, replylen,
2579 * Handle the key exchange and user authentication phases.
2581 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
2582 struct Packet *pktin)
2585 unsigned char cookie[8], *ptr;
2586 struct RSAKey servkey, hostkey;
2587 struct MD5Context md5c;
2588 struct do_ssh1_login_state {
2590 unsigned char *rsabuf, *keystr1, *keystr2;
2591 unsigned long supported_ciphers_mask, supported_auths_mask;
2592 int tried_publickey, tried_agent;
2593 int tis_auth_refused, ccard_auth_refused;
2594 unsigned char session_id[16];
2597 void *publickey_blob;
2598 int publickey_bloblen;
2604 unsigned char request[5], *response, *p;
2613 crState(do_ssh1_login_state);
2615 crBegin(ssh->do_ssh1_login_crstate);
2620 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
2621 bombout(("Public key packet not received"));
2625 logevent("Received public keys");
2627 ptr = ssh_pkt_getdata(pktin, 8);
2629 bombout(("SSH1 public key packet stopped before random cookie"));
2632 memcpy(cookie, ptr, 8);
2634 if (!ssh1_pkt_getrsakey(pktin, &servkey, &s->keystr1) ||
2635 !ssh1_pkt_getrsakey(pktin, &hostkey, &s->keystr2)) {
2636 bombout(("Failed to read SSH1 public keys from public key packet"));
2641 * Log the host key fingerprint.
2645 logevent("Host key fingerprint is:");
2646 strcpy(logmsg, " ");
2647 hostkey.comment = NULL;
2648 rsa_fingerprint(logmsg + strlen(logmsg),
2649 sizeof(logmsg) - strlen(logmsg), &hostkey);
2653 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
2654 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
2655 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
2657 ssh->v1_local_protoflags =
2658 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
2659 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
2662 MD5Update(&md5c, s->keystr2, hostkey.bytes);
2663 MD5Update(&md5c, s->keystr1, servkey.bytes);
2664 MD5Update(&md5c, cookie, 8);
2665 MD5Final(s->session_id, &md5c);
2667 for (i = 0; i < 32; i++)
2668 ssh->session_key[i] = random_byte();
2671 * Verify that the `bits' and `bytes' parameters match.
2673 if (hostkey.bits > hostkey.bytes * 8 ||
2674 servkey.bits > servkey.bytes * 8) {
2675 bombout(("SSH1 public keys were badly formatted"));
2679 s->len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
2681 s->rsabuf = snewn(s->len, unsigned char);
2683 fatalbox("Out of memory");
2686 * Verify the host key.
2690 * First format the key into a string.
2692 int len = rsastr_len(&hostkey);
2693 char fingerprint[100];
2694 char *keystr = snewn(len, char);
2696 fatalbox("Out of memory");
2697 rsastr_fmt(keystr, &hostkey);
2698 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
2699 verify_ssh_host_key(ssh->frontend,
2700 ssh->savedhost, ssh->savedport, "rsa", keystr,
2705 for (i = 0; i < 32; i++) {
2706 s->rsabuf[i] = ssh->session_key[i];
2708 s->rsabuf[i] ^= s->session_id[i];
2711 if (hostkey.bytes > servkey.bytes) {
2712 ret = rsaencrypt(s->rsabuf, 32, &servkey);
2714 ret = rsaencrypt(s->rsabuf, servkey.bytes, &hostkey);
2716 ret = rsaencrypt(s->rsabuf, 32, &hostkey);
2718 ret = rsaencrypt(s->rsabuf, hostkey.bytes, &servkey);
2721 bombout(("SSH1 public key encryptions failed due to bad formatting"));
2725 logevent("Encrypted session key");
2728 int cipher_chosen = 0, warn = 0;
2729 char *cipher_string = NULL;
2731 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
2732 int next_cipher = ssh->cfg.ssh_cipherlist[i];
2733 if (next_cipher == CIPHER_WARN) {
2734 /* If/when we choose a cipher, warn about it */
2736 } else if (next_cipher == CIPHER_AES) {
2737 /* XXX Probably don't need to mention this. */
2738 logevent("AES not supported in SSH1, skipping");
2740 switch (next_cipher) {
2741 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
2742 cipher_string = "3DES"; break;
2743 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
2744 cipher_string = "Blowfish"; break;
2745 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
2746 cipher_string = "single-DES"; break;
2748 if (s->supported_ciphers_mask & (1 << s->cipher_type))
2752 if (!cipher_chosen) {
2753 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
2754 bombout(("Server violates SSH 1 protocol by not "
2755 "supporting 3DES encryption"));
2757 /* shouldn't happen */
2758 bombout(("No supported ciphers found"));
2762 /* Warn about chosen cipher if necessary. */
2764 askcipher(ssh->frontend, cipher_string, 0);
2767 switch (s->cipher_type) {
2768 case SSH_CIPHER_3DES:
2769 logevent("Using 3DES encryption");
2771 case SSH_CIPHER_DES:
2772 logevent("Using single-DES encryption");
2774 case SSH_CIPHER_BLOWFISH:
2775 logevent("Using Blowfish encryption");
2779 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
2780 PKT_CHAR, s->cipher_type,
2781 PKT_DATA, cookie, 8,
2782 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
2783 PKT_DATA, s->rsabuf, s->len,
2784 PKT_INT, ssh->v1_local_protoflags, PKT_END);
2786 logevent("Trying to enable encryption...");
2790 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
2791 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
2793 ssh->v1_cipher_ctx = ssh->cipher->make_context();
2794 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
2795 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
2797 ssh->crcda_ctx = crcda_make_context();
2798 logevent("Installing CRC compensation attack detector");
2800 if (servkey.modulus) {
2801 sfree(servkey.modulus);
2802 servkey.modulus = NULL;
2804 if (servkey.exponent) {
2805 sfree(servkey.exponent);
2806 servkey.exponent = NULL;
2808 if (hostkey.modulus) {
2809 sfree(hostkey.modulus);
2810 hostkey.modulus = NULL;
2812 if (hostkey.exponent) {
2813 sfree(hostkey.exponent);
2814 hostkey.exponent = NULL;
2818 if (pktin->type != SSH1_SMSG_SUCCESS) {
2819 bombout(("Encryption not successfully enabled"));
2823 logevent("Successfully started encryption");
2827 if (!*ssh->cfg.username) {
2828 if (ssh_get_line && !ssh_getline_pw_only) {
2829 if (!ssh_get_line("login as: ",
2830 s->username, sizeof(s->username), FALSE)) {
2832 * get_line failed to get a username.
2835 logevent("No username provided. Abandoning session.");
2836 ssh_closing((Plug)ssh, NULL, 0, 0);
2840 int ret; /* need not be kept over crReturn */
2841 c_write_str(ssh, "login as: ");
2844 setup_userpass_input(ssh, s->username, sizeof(s->username), 1);
2846 crWaitUntil(!pktin);
2847 ret = process_userpass_input(ssh, in, inlen);
2851 c_write_str(ssh, "\r\n");
2854 strncpy(s->username, ssh->cfg.username, sizeof(s->username));
2855 s->username[sizeof(s->username)-1] = '\0';
2858 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, s->username, PKT_END);
2860 char userlog[22 + sizeof(s->username)];
2861 sprintf(userlog, "Sent username \"%s\"", s->username);
2863 if (flags & FLAG_INTERACTIVE &&
2864 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
2865 strcat(userlog, "\r\n");
2866 c_write_str(ssh, userlog);
2873 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA)) {
2874 /* We must not attempt PK auth. Pretend we've already tried it. */
2875 s->tried_publickey = s->tried_agent = 1;
2877 s->tried_publickey = s->tried_agent = 0;
2879 s->tis_auth_refused = s->ccard_auth_refused = 0;
2880 /* Load the public half of ssh->cfg.keyfile so we notice if it's in Pageant */
2881 if (!filename_is_null(ssh->cfg.keyfile)) {
2882 if (!rsakey_pubblob(&ssh->cfg.keyfile,
2883 &s->publickey_blob, &s->publickey_bloblen, NULL))
2884 s->publickey_blob = NULL;
2886 s->publickey_blob = NULL;
2888 while (pktin->type == SSH1_SMSG_FAILURE) {
2889 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
2891 if (agent_exists() && !s->tried_agent) {
2893 * Attempt RSA authentication using Pageant.
2899 logevent("Pageant is running. Requesting keys.");
2901 /* Request the keys held by the agent. */
2902 PUT_32BIT(s->request, 1);
2903 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
2904 if (!agent_query(s->request, 5, &r, &s->responselen,
2905 ssh_agent_callback, ssh)) {
2909 bombout(("Unexpected data from server while waiting"
2910 " for agent response"));
2913 } while (pktin || inlen > 0);
2914 r = ssh->agent_response;
2915 s->responselen = ssh->agent_response_len;
2917 s->response = (unsigned char *) r;
2918 if (s->response && s->responselen >= 5 &&
2919 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
2920 s->p = s->response + 5;
2921 s->nkeys = GET_32BIT(s->p);
2925 sprintf(buf, "Pageant has %d SSH1 keys", s->nkeys);
2928 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
2931 sprintf(buf, "Trying Pageant key #%d", s->keyi);
2934 if (s->publickey_blob &&
2935 !memcmp(s->p, s->publickey_blob,
2936 s->publickey_bloblen)) {
2937 logevent("This key matches configured key file");
2938 s->tried_publickey = 1;
2943 do { /* do while (0) to make breaking easy */
2944 n = ssh1_read_bignum
2945 (s->p, s->responselen-(s->p-s->response),
2950 n = ssh1_read_bignum
2951 (s->p, s->responselen-(s->p-s->response),
2956 if (s->responselen - (s->p-s->response) < 4)
2958 s->commentlen = GET_32BIT(s->p);
2960 if (s->responselen - (s->p-s->response) <
2963 s->commentp = (char *)s->p;
2964 s->p += s->commentlen;
2968 logevent("Pageant key list packet was truncated");
2972 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
2973 PKT_BIGNUM, s->key.modulus, PKT_END);
2975 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
2976 logevent("Key refused");
2979 logevent("Received RSA challenge");
2980 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
2981 bombout(("Server's RSA challenge was badly formatted"));
2986 char *agentreq, *q, *ret;
2989 len = 1 + 4; /* message type, bit count */
2990 len += ssh1_bignum_length(s->key.exponent);
2991 len += ssh1_bignum_length(s->key.modulus);
2992 len += ssh1_bignum_length(s->challenge);
2993 len += 16; /* session id */
2994 len += 4; /* response format */
2995 agentreq = snewn(4 + len, char);
2996 PUT_32BIT(agentreq, len);
2998 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
2999 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
3001 q += ssh1_write_bignum(q, s->key.exponent);
3002 q += ssh1_write_bignum(q, s->key.modulus);
3003 q += ssh1_write_bignum(q, s->challenge);
3004 memcpy(q, s->session_id, 16);
3006 PUT_32BIT(q, 1); /* response format */
3007 if (!agent_query(agentreq, len + 4, &vret, &retlen,
3008 ssh_agent_callback, ssh)) {
3013 bombout(("Unexpected data from server"
3014 " while waiting for agent"
3018 } while (pktin || inlen > 0);
3019 vret = ssh->agent_response;
3020 retlen = ssh->agent_response_len;
3025 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
3026 logevent("Sending Pageant's response");
3027 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3028 PKT_DATA, ret + 5, 16,
3032 if (pktin->type == SSH1_SMSG_SUCCESS) {
3034 ("Pageant's response accepted");
3035 if (flags & FLAG_VERBOSE) {
3036 c_write_str(ssh, "Authenticated using"
3038 c_write(ssh, s->commentp,
3040 c_write_str(ssh, "\" from agent\r\n");
3045 ("Pageant's response not accepted");
3048 ("Pageant failed to answer challenge");
3052 logevent("No reply received from Pageant");
3055 freebn(s->key.exponent);
3056 freebn(s->key.modulus);
3057 freebn(s->challenge);
3066 if (!filename_is_null(ssh->cfg.keyfile) && !s->tried_publickey)
3067 s->pwpkt_type = SSH1_CMSG_AUTH_RSA;
3069 if (ssh->cfg.try_tis_auth &&
3070 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
3071 !s->tis_auth_refused) {
3072 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
3073 logevent("Requested TIS authentication");
3074 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
3076 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
3077 logevent("TIS authentication declined");
3078 if (flags & FLAG_INTERACTIVE)
3079 c_write_str(ssh, "TIS authentication refused.\r\n");
3080 s->tis_auth_refused = 1;
3086 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3088 bombout(("TIS challenge packet was badly formed"));
3091 logevent("Received TIS challenge");
3092 if (challengelen > sizeof(s->prompt) - 1)
3093 challengelen = sizeof(s->prompt) - 1;/* prevent overrun */
3094 memcpy(s->prompt, challenge, challengelen);
3095 /* Prompt heuristic comes from OpenSSH */
3096 strncpy(s->prompt + challengelen,
3097 memchr(s->prompt, '\n', challengelen) ?
3098 "": "\r\nResponse: ",
3099 (sizeof s->prompt) - challengelen);
3100 s->prompt[(sizeof s->prompt) - 1] = '\0';
3103 if (ssh->cfg.try_tis_auth &&
3104 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
3105 !s->ccard_auth_refused) {
3106 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
3107 logevent("Requested CryptoCard authentication");
3108 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
3110 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
3111 logevent("CryptoCard authentication declined");
3112 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
3113 s->ccard_auth_refused = 1;
3119 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3121 bombout(("CryptoCard challenge packet was badly formed"));
3124 logevent("Received CryptoCard challenge");
3125 if (challengelen > sizeof(s->prompt) - 1)
3126 challengelen = sizeof(s->prompt) - 1;/* prevent overrun */
3127 memcpy(s->prompt, challenge, challengelen);
3128 strncpy(s->prompt + challengelen,
3129 memchr(s->prompt, '\n', challengelen) ?
3130 "" : "\r\nResponse: ",
3131 sizeof(s->prompt) - challengelen);
3132 s->prompt[sizeof(s->prompt) - 1] = '\0';
3135 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
3136 sprintf(s->prompt, "%.90s@%.90s's password: ",
3137 s->username, ssh->savedhost);
3139 if (s->pwpkt_type == SSH1_CMSG_AUTH_RSA) {
3140 char *comment = NULL;
3143 if (flags & FLAG_VERBOSE)
3144 c_write_str(ssh, "Trying public key authentication.\r\n");
3145 logeventf(ssh, "Trying public key \"%s\"",
3146 filename_to_str(&ssh->cfg.keyfile));
3147 type = key_type(&ssh->cfg.keyfile);
3148 if (type != SSH_KEYTYPE_SSH1) {
3149 sprintf(msgbuf, "Key is of wrong type (%s)",
3150 key_type_to_str(type));
3152 c_write_str(ssh, msgbuf);
3153 c_write_str(ssh, "\r\n");
3154 s->tried_publickey = 1;
3157 if (!rsakey_encrypted(&ssh->cfg.keyfile, &comment)) {
3158 if (flags & FLAG_VERBOSE)
3159 c_write_str(ssh, "No passphrase required.\r\n");
3162 sprintf(s->prompt, "Passphrase for key \"%.100s\": ", comment);
3167 * Show password prompt, having first obtained it via a TIS
3168 * or CryptoCard exchange if we're doing TIS or CryptoCard
3172 if (!ssh_get_line(s->prompt, s->password,
3173 sizeof(s->password), TRUE)) {
3175 * get_line failed to get a password (for example
3176 * because one was supplied on the command line
3177 * which has already failed to work). Terminate.
3179 send_packet(ssh, SSH1_MSG_DISCONNECT,
3180 PKT_STR, "No more passwords available to try",
3182 logevent("Unable to authenticate");
3183 connection_fatal(ssh->frontend, "Unable to authenticate");
3184 ssh_closing((Plug)ssh, NULL, 0, 0);
3188 /* Prompt may have come from server. We've munged it a bit, so
3189 * we know it to be zero-terminated at least once. */
3190 int ret; /* need not be saved over crReturn */
3191 c_write_untrusted(ssh, s->prompt, strlen(s->prompt));
3194 setup_userpass_input(ssh, s->password, sizeof(s->password), 0);
3196 crWaitUntil(!pktin);
3197 ret = process_userpass_input(ssh, in, inlen);
3201 c_write_str(ssh, "\r\n");
3205 if (s->pwpkt_type == SSH1_CMSG_AUTH_RSA) {
3207 * Try public key authentication with the specified
3210 s->tried_publickey = 1;
3213 const char *error = NULL;
3214 int ret = loadrsakey(&ssh->cfg.keyfile, &s->key, s->password,
3217 c_write_str(ssh, "Couldn't load private key from ");
3218 c_write_str(ssh, filename_to_str(&ssh->cfg.keyfile));
3219 c_write_str(ssh, " (");
3220 c_write_str(ssh, error);
3221 c_write_str(ssh, ").\r\n");
3222 continue; /* go and try password */
3225 c_write_str(ssh, "Wrong passphrase.\r\n");
3226 s->tried_publickey = 0;
3227 continue; /* try again */
3232 * Send a public key attempt.
3234 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3235 PKT_BIGNUM, s->key.modulus, PKT_END);
3238 if (pktin->type == SSH1_SMSG_FAILURE) {
3239 c_write_str(ssh, "Server refused our public key.\r\n");
3240 continue; /* go and try password */
3242 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3243 bombout(("Bizarre response to offer of public key"));
3249 unsigned char buffer[32];
3250 Bignum challenge, response;
3252 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3253 bombout(("Server's RSA challenge was badly formatted"));
3256 response = rsadecrypt(challenge, &s->key);
3257 freebn(s->key.private_exponent);/* burn the evidence */
3259 for (i = 0; i < 32; i++) {
3260 buffer[i] = bignum_byte(response, 31 - i);
3264 MD5Update(&md5c, buffer, 32);
3265 MD5Update(&md5c, s->session_id, 16);
3266 MD5Final(buffer, &md5c);
3268 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3269 PKT_DATA, buffer, 16, PKT_END);
3276 if (pktin->type == SSH1_SMSG_FAILURE) {
3277 if (flags & FLAG_VERBOSE)
3278 c_write_str(ssh, "Failed to authenticate with"
3279 " our public key.\r\n");
3280 continue; /* go and try password */
3281 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
3282 bombout(("Bizarre response to RSA authentication response"));
3286 break; /* we're through! */
3288 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
3290 * Defence against traffic analysis: we send a
3291 * whole bunch of packets containing strings of
3292 * different lengths. One of these strings is the
3293 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
3294 * The others are all random data in
3295 * SSH1_MSG_IGNORE packets. This way a passive
3296 * listener can't tell which is the password, and
3297 * hence can't deduce the password length.
3299 * Anybody with a password length greater than 16
3300 * bytes is going to have enough entropy in their
3301 * password that a listener won't find it _that_
3302 * much help to know how long it is. So what we'll
3305 * - if password length < 16, we send 15 packets
3306 * containing string lengths 1 through 15
3308 * - otherwise, we let N be the nearest multiple
3309 * of 8 below the password length, and send 8
3310 * packets containing string lengths N through
3311 * N+7. This won't obscure the order of
3312 * magnitude of the password length, but it will
3313 * introduce a bit of extra uncertainty.
3315 * A few servers (the old 1.2.18 through 1.2.22)
3316 * can't deal with SSH1_MSG_IGNORE. For these
3317 * servers, we need an alternative defence. We make
3318 * use of the fact that the password is interpreted
3319 * as a C string: so we can append a NUL, then some
3322 * One server (a Cisco one) can deal with neither
3323 * SSH1_MSG_IGNORE _nor_ a padded password string.
3324 * For this server we are left with no defences
3325 * against password length sniffing.
3327 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE)) {
3329 * The server can deal with SSH1_MSG_IGNORE, so
3330 * we can use the primary defence.
3332 int bottom, top, pwlen, i;
3335 pwlen = strlen(s->password);
3337 bottom = 0; /* zero length passwords are OK! :-) */
3340 bottom = pwlen & ~7;
3344 assert(pwlen >= bottom && pwlen <= top);
3346 randomstr = snewn(top + 1, char);
3348 for (i = bottom; i <= top; i++) {
3350 defer_packet(ssh, s->pwpkt_type,
3351 PKTT_PASSWORD, PKT_STR, s->password,
3352 PKTT_OTHER, PKT_END);
3354 for (j = 0; j < i; j++) {
3356 randomstr[j] = random_byte();
3357 } while (randomstr[j] == '\0');
3359 randomstr[i] = '\0';
3360 defer_packet(ssh, SSH1_MSG_IGNORE,
3361 PKT_STR, randomstr, PKT_END);
3364 logevent("Sending password with camouflage packets");
3365 ssh_pkt_defersend(ssh);
3368 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
3370 * The server can't deal with SSH1_MSG_IGNORE
3371 * but can deal with padded passwords, so we
3372 * can use the secondary defence.
3378 len = strlen(s->password);
3379 if (len < sizeof(string)) {
3381 strcpy(string, s->password);
3382 len++; /* cover the zero byte */
3383 while (len < sizeof(string)) {
3384 string[len++] = (char) random_byte();
3389 logevent("Sending length-padded password");
3390 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
3391 PKT_INT, len, PKT_DATA, ss, len,
3392 PKTT_OTHER, PKT_END);
3395 * The server has _both_
3396 * BUG_CHOKES_ON_SSH1_IGNORE and
3397 * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
3398 * therefore nothing we can do.
3401 len = strlen(s->password);
3402 logevent("Sending unpadded password");
3403 send_packet(ssh, s->pwpkt_type,
3404 PKTT_PASSWORD, PKT_INT, len,
3405 PKT_DATA, s->password, len,
3406 PKTT_OTHER, PKT_END);
3409 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
3410 PKT_STR, s->password, PKTT_OTHER, PKT_END);
3413 logevent("Sent password");
3414 memset(s->password, 0, strlen(s->password));
3416 if (pktin->type == SSH1_SMSG_FAILURE) {
3417 if (flags & FLAG_VERBOSE)
3418 c_write_str(ssh, "Access denied\r\n");
3419 logevent("Authentication refused");
3420 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
3421 bombout(("Strange packet received, type %d", pktin->type));
3426 logevent("Authentication successful");
3431 void sshfwd_close(struct ssh_channel *c)
3435 if (ssh->state != SSH_STATE_SESSION) {
3436 assert(ssh->state == SSH_STATE_CLOSED);
3440 if (c && !c->closes) {
3442 * If the channel's remoteid is -1, we have sent
3443 * CHANNEL_OPEN for this channel, but it hasn't even been
3444 * acknowledged by the server. So we must set a close flag
3445 * on it now, and then when the server acks the channel
3446 * open, we can close it then.
3448 if (((int)c->remoteid) != -1) {
3449 if (ssh->version == 1) {
3450 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
3453 struct Packet *pktout;
3454 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
3455 ssh2_pkt_adduint32(pktout, c->remoteid);
3456 ssh2_pkt_send(ssh, pktout);
3459 c->closes = 1; /* sent MSG_CLOSE */
3460 if (c->type == CHAN_X11) {
3462 logevent("Forwarded X11 connection terminated");
3463 } else if (c->type == CHAN_SOCKDATA ||
3464 c->type == CHAN_SOCKDATA_DORMANT) {
3466 logevent("Forwarded port closed");
3471 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
3475 if (ssh->state != SSH_STATE_SESSION) {
3476 assert(ssh->state == SSH_STATE_CLOSED);
3480 if (ssh->version == 1) {
3481 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3482 PKT_INT, c->remoteid,
3484 PKT_INT, len, PKT_DATA, buf, len,
3485 PKTT_OTHER, PKT_END);
3487 * In SSH1 we can return 0 here - implying that forwarded
3488 * connections are never individually throttled - because
3489 * the only circumstance that can cause throttling will be
3490 * the whole SSH connection backing up, in which case
3491 * _everything_ will be throttled as a whole.
3495 ssh2_add_channel_data(c, buf, len);
3496 return ssh2_try_send(c);
3500 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
3504 if (ssh->state != SSH_STATE_SESSION) {
3505 assert(ssh->state == SSH_STATE_CLOSED);
3509 if (ssh->version == 1) {
3510 if (c->v.v1.throttling && bufsize < SSH1_BUFFER_LIMIT) {
3511 c->v.v1.throttling = 0;
3512 ssh1_throttle(ssh, -1);
3515 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
3519 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
3522 int stringlen, bufsize;
3524 ssh_pkt_getstring(pktin, &string, &stringlen);
3525 if (string == NULL) {
3526 bombout(("Incoming terminal data packet was badly formed"));
3530 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
3532 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
3533 ssh->v1_stdout_throttling = 1;
3534 ssh1_throttle(ssh, +1);
3538 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
3540 /* Remote side is trying to open a channel to talk to our
3541 * X-Server. Give them back a local channel number. */
3542 struct ssh_channel *c;
3543 int remoteid = ssh_pkt_getuint32(pktin);
3545 logevent("Received X11 connect request");
3546 /* Refuse if X11 forwarding is disabled. */
3547 if (!ssh->X11_fwd_enabled) {
3548 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3549 PKT_INT, remoteid, PKT_END);
3550 logevent("Rejected X11 connect request");
3552 c = snew(struct ssh_channel);
3555 if (x11_init(&c->u.x11.s, ssh->cfg.x11_display, c,
3556 ssh->x11auth, NULL, -1, &ssh->cfg) != NULL) {
3557 logevent("Opening X11 forward connection failed");
3559 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3560 PKT_INT, remoteid, PKT_END);
3563 ("Opening X11 forward connection succeeded");
3564 c->remoteid = remoteid;
3565 c->localid = alloc_channel_id(ssh);
3567 c->v.v1.throttling = 0;
3568 c->type = CHAN_X11; /* identify channel type */
3569 add234(ssh->channels, c);
3570 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3571 PKT_INT, c->remoteid, PKT_INT,
3572 c->localid, PKT_END);
3573 logevent("Opened X11 forward channel");
3578 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
3580 /* Remote side is trying to open a channel to talk to our
3581 * agent. Give them back a local channel number. */
3582 struct ssh_channel *c;
3583 int remoteid = ssh_pkt_getuint32(pktin);
3585 /* Refuse if agent forwarding is disabled. */
3586 if (!ssh->agentfwd_enabled) {
3587 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3588 PKT_INT, remoteid, PKT_END);
3590 c = snew(struct ssh_channel);
3592 c->remoteid = remoteid;
3593 c->localid = alloc_channel_id(ssh);
3595 c->v.v1.throttling = 0;
3596 c->type = CHAN_AGENT; /* identify channel type */
3597 c->u.a.lensofar = 0;
3598 add234(ssh->channels, c);
3599 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3600 PKT_INT, c->remoteid, PKT_INT, c->localid,
3605 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
3607 /* Remote side is trying to open a channel to talk to a
3608 * forwarded port. Give them back a local channel number. */
3609 struct ssh_channel *c;
3610 struct ssh_rportfwd pf;
3613 char *host, buf[1024];
3615 c = snew(struct ssh_channel);
3618 remoteid = ssh_pkt_getuint32(pktin);
3619 ssh_pkt_getstring(pktin, &host, &hostsize);
3620 port = ssh_pkt_getuint32(pktin);
3622 if (hostsize >= lenof(pf.dhost))
3623 hostsize = lenof(pf.dhost)-1;
3624 memcpy(pf.dhost, host, hostsize);
3625 pf.dhost[hostsize] = '\0';
3628 if (find234(ssh->rportfwds, &pf, NULL) == NULL) {
3629 sprintf(buf, "Rejected remote port open request for %s:%d",
3632 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3633 PKT_INT, remoteid, PKT_END);
3635 sprintf(buf, "Received remote port open request for %s:%d",
3638 e = pfd_newconnect(&c->u.pfd.s, pf.dhost, port,
3642 sprintf(buf, "Port open failed: %s", e);
3645 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3646 PKT_INT, remoteid, PKT_END);
3648 c->remoteid = remoteid;
3649 c->localid = alloc_channel_id(ssh);
3651 c->v.v1.throttling = 0;
3652 c->type = CHAN_SOCKDATA; /* identify channel type */
3653 add234(ssh->channels, c);
3654 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3655 PKT_INT, c->remoteid, PKT_INT,
3656 c->localid, PKT_END);
3657 logevent("Forwarded port opened successfully");
3662 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
3664 unsigned int remoteid = ssh_pkt_getuint32(pktin);
3665 unsigned int localid = ssh_pkt_getuint32(pktin);
3666 struct ssh_channel *c;
3668 c = find234(ssh->channels, &remoteid, ssh_channelfind);
3669 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
3670 c->remoteid = localid;
3671 c->type = CHAN_SOCKDATA;
3672 c->v.v1.throttling = 0;
3673 pfd_confirm(c->u.pfd.s);
3676 if (c && c->closes) {
3678 * We have a pending close on this channel,
3679 * which we decided on before the server acked
3680 * the channel open. So now we know the
3681 * remoteid, we can close it again.
3683 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE,
3684 PKT_INT, c->remoteid, PKT_END);
3688 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
3690 unsigned int remoteid = ssh_pkt_getuint32(pktin);
3691 struct ssh_channel *c;
3693 c = find234(ssh->channels, &remoteid, ssh_channelfind);
3694 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
3695 logevent("Forwarded connection refused by server");
3696 pfd_close(c->u.pfd.s);
3697 del234(ssh->channels, c);
3702 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
3704 /* Remote side closes a channel. */
3705 unsigned i = ssh_pkt_getuint32(pktin);
3706 struct ssh_channel *c;
3707 c = find234(ssh->channels, &i, ssh_channelfind);
3708 if (c && ((int)c->remoteid) != -1) {
3711 (pktin->type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
3713 if ((c->closes == 0) && (c->type == CHAN_X11)) {
3714 logevent("Forwarded X11 connection terminated");
3715 assert(c->u.x11.s != NULL);
3716 x11_close(c->u.x11.s);
3719 if ((c->closes == 0) && (c->type == CHAN_SOCKDATA)) {
3720 logevent("Forwarded port closed");
3721 assert(c->u.pfd.s != NULL);
3722 pfd_close(c->u.pfd.s);
3726 c->closes |= (closetype << 2); /* seen this message */
3727 if (!(c->closes & closetype)) {
3728 send_packet(ssh, pktin->type, PKT_INT, c->remoteid,
3730 c->closes |= closetype; /* sent it too */
3733 if (c->closes == 15) {
3734 del234(ssh->channels, c);
3738 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
3739 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
3740 "_CONFIRMATION", c ? "half-open" : "nonexistent",
3745 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
3747 /* Data sent down one of our channels. */
3748 int i = ssh_pkt_getuint32(pktin);
3751 struct ssh_channel *c;
3753 ssh_pkt_getstring(pktin, &p, &len);
3755 c = find234(ssh->channels, &i, ssh_channelfind);
3760 bufsize = x11_send(c->u.x11.s, p, len);
3763 bufsize = pfd_send(c->u.pfd.s, p, len);
3766 /* Data for an agent message. Buffer it. */
3768 if (c->u.a.lensofar < 4) {
3769 int l = min(4 - c->u.a.lensofar, len);
3770 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
3774 c->u.a.lensofar += l;
3776 if (c->u.a.lensofar == 4) {
3778 4 + GET_32BIT(c->u.a.msglen);
3779 c->u.a.message = snewn(c->u.a.totallen,
3781 memcpy(c->u.a.message, c->u.a.msglen, 4);
3783 if (c->u.a.lensofar >= 4 && len > 0) {
3785 min(c->u.a.totallen - c->u.a.lensofar,
3787 memcpy(c->u.a.message + c->u.a.lensofar, p,
3791 c->u.a.lensofar += l;
3793 if (c->u.a.lensofar == c->u.a.totallen) {
3796 if (agent_query(c->u.a.message,
3799 ssh_agentf_callback, c))
3800 ssh_agentf_callback(c, reply, replylen);
3801 sfree(c->u.a.message);
3802 c->u.a.lensofar = 0;
3805 bufsize = 0; /* agent channels never back up */
3808 if (!c->v.v1.throttling && bufsize > SSH1_BUFFER_LIMIT) {
3809 c->v.v1.throttling = 1;
3810 ssh1_throttle(ssh, +1);
3815 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
3818 ssh->exitcode = ssh_pkt_getuint32(pktin);
3819 sprintf(buf, "Server sent command exit status %d",
3822 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
3824 * In case `helpful' firewalls or proxies tack
3825 * extra human-readable text on the end of the
3826 * session which we might mistake for another
3827 * encrypted packet, we close the session once
3828 * we've sent EXIT_CONFIRMATION.
3830 ssh_closing((Plug)ssh, NULL, 0, 0);
3833 static void do_ssh1_connection(Ssh ssh, unsigned char *in, int inlen,
3834 struct Packet *pktin)
3836 crBegin(ssh->do_ssh1_connection_crstate);
3838 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
3839 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
3840 ssh1_smsg_stdout_stderr_data;
3842 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
3843 ssh1_msg_channel_open_confirmation;
3844 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
3845 ssh1_msg_channel_open_failure;
3846 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
3847 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
3848 ssh1_msg_channel_close;
3849 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
3850 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
3852 if (ssh->cfg.agentfwd && agent_exists()) {
3853 logevent("Requesting agent forwarding");
3854 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
3858 if (pktin->type != SSH1_SMSG_SUCCESS
3859 && pktin->type != SSH1_SMSG_FAILURE) {
3860 bombout(("Protocol confusion"));
3862 } else if (pktin->type == SSH1_SMSG_FAILURE) {
3863 logevent("Agent forwarding refused");
3865 logevent("Agent forwarding enabled");
3866 ssh->agentfwd_enabled = TRUE;
3867 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
3871 if (ssh->cfg.x11_forward) {
3872 char proto[20], data[64];
3873 logevent("Requesting X11 forwarding");
3874 ssh->x11auth = x11_invent_auth(proto, sizeof(proto),
3875 data, sizeof(data), ssh->cfg.x11_auth);
3876 x11_get_real_auth(ssh->x11auth, ssh->cfg.x11_display);
3877 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
3878 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
3879 PKT_STR, proto, PKT_STR, data,
3880 PKT_INT, x11_get_screen_number(ssh->cfg.x11_display),
3883 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
3884 PKT_STR, proto, PKT_STR, data, PKT_END);
3889 if (pktin->type != SSH1_SMSG_SUCCESS
3890 && pktin->type != SSH1_SMSG_FAILURE) {
3891 bombout(("Protocol confusion"));
3893 } else if (pktin->type == SSH1_SMSG_FAILURE) {
3894 logevent("X11 forwarding refused");
3896 logevent("X11 forwarding enabled");
3897 ssh->X11_fwd_enabled = TRUE;
3898 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
3905 int sport,dport,sserv,dserv;
3906 char sports[256], dports[256], saddr[256], host[256];
3908 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
3909 /* Add port forwardings. */
3910 ssh->portfwd_strptr = ssh->cfg.portfwd;
3911 while (*ssh->portfwd_strptr) {
3912 type = *ssh->portfwd_strptr++;
3915 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != '\t') {
3916 if (*ssh->portfwd_strptr == ':') {
3918 * We've seen a colon in the middle of the
3919 * source port number. This means that
3920 * everything we've seen until now is the
3921 * source _address_, so we'll move it into
3922 * saddr and start sports from the beginning
3925 ssh->portfwd_strptr++;
3927 strcpy(saddr, sports);
3930 if (n < 255) sports[n++] = *ssh->portfwd_strptr++;
3934 if (*ssh->portfwd_strptr == '\t')
3935 ssh->portfwd_strptr++;
3937 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != ':') {
3938 if (n < 255) host[n++] = *ssh->portfwd_strptr++;
3941 if (*ssh->portfwd_strptr == ':')
3942 ssh->portfwd_strptr++;
3944 while (*ssh->portfwd_strptr) {
3945 if (n < 255) dports[n++] = *ssh->portfwd_strptr++;
3948 ssh->portfwd_strptr++;
3949 dport = atoi(dports);
3953 dport = net_service_lookup(dports);
3955 logeventf(ssh, "Service lookup failed for"
3956 " destination port \"%s\"", dports);
3960 while (*ssh->portfwd_strptr) ssh->portfwd_strptr++;
3962 ssh->portfwd_strptr++; /* eat the NUL and move to next one */
3964 sport = atoi(sports);
3968 sport = net_service_lookup(sports);
3970 logeventf(ssh, "Service lookup failed for source"
3971 " port \"%s\"", sports);
3974 if (sport && dport) {
3975 /* Set up a description of the source port. */
3976 static char *sportdesc;
3977 sportdesc = dupprintf("%.*s%.*s%.*s%.*s%d%.*s",
3978 (int)(*saddr?strlen(saddr):0), *saddr?saddr:NULL,
3979 (int)(*saddr?1:0), ":",
3980 (int)(sserv ? strlen(sports) : 0), sports,
3981 sserv, "(", sport, sserv, ")");
3983 /* Verbose description of the destination port */
3984 char *dportdesc = dupprintf("%s:%.*s%.*s%d%.*s",
3986 (int)(dserv ? strlen(dports) : 0), dports,
3987 dserv, "(", dport, dserv, ")");
3988 const char *err = pfd_addforward(host, dport,
3989 *saddr ? saddr : NULL,
3990 sport, ssh, &ssh->cfg);
3992 logeventf(ssh, "Local port %s forward to %s"
3993 " failed: %s", sportdesc, dportdesc, err);
3995 logeventf(ssh, "Local port %s forwarding to %s",
3996 sportdesc, dportdesc);
3999 } else if (type == 'D') {
4000 const char *err = pfd_addforward(NULL, -1,
4001 *saddr ? saddr : NULL,
4002 sport, ssh, &ssh->cfg);
4004 logeventf(ssh, "Local port %s SOCKS dynamic forward"
4005 " setup failed: %s", sportdesc, err);
4007 logeventf(ssh, "Local port %s doing SOCKS"
4008 " dynamic forwarding", sportdesc);
4011 struct ssh_rportfwd *pf;
4012 pf = snew(struct ssh_rportfwd);
4013 strcpy(pf->dhost, host);
4017 "SSH1 cannot handle source address spec \"%s:%d\"; ignoring",
4020 if (add234(ssh->rportfwds, pf) != pf) {
4022 "Duplicate remote port forwarding to %s:%d",
4026 logeventf(ssh, "Requesting remote port %.*s%.*s%d%.*s"
4027 " forward to %s:%.*s%.*s%d%.*s",
4028 (int)(sserv ? strlen(sports) : 0), sports,
4029 sserv, "(", sport, sserv, ")",
4031 (int)(dserv ? strlen(dports) : 0), dports,
4032 dserv, "(", dport, dserv, ")");
4033 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
4041 if (pktin->type != SSH1_SMSG_SUCCESS
4042 && pktin->type != SSH1_SMSG_FAILURE) {
4043 bombout(("Protocol confusion"));
4045 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4046 c_write_str(ssh, "Server refused port"
4048 logevent("Server refused this port forwarding");
4050 logevent("Remote port forwarding enabled");
4051 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] =
4061 if (!ssh->cfg.nopty) {
4062 /* Unpick the terminal-speed string. */
4063 /* XXX perhaps we should allow no speeds to be sent. */
4064 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
4065 sscanf(ssh->cfg.termspeed, "%d,%d", &ssh->ospeed, &ssh->ispeed);
4066 /* Send the pty request. */
4067 send_packet(ssh, SSH1_CMSG_REQUEST_PTY,
4068 PKT_STR, ssh->cfg.termtype,
4069 PKT_INT, ssh->term_height,
4070 PKT_INT, ssh->term_width,
4071 PKT_INT, 0, PKT_INT, 0, /* width,height in pixels */
4072 PKT_CHAR, 192, PKT_INT, ssh->ispeed, /* TTY_OP_ISPEED */
4073 PKT_CHAR, 193, PKT_INT, ssh->ospeed, /* TTY_OP_OSPEED */
4074 PKT_CHAR, 0, PKT_END);
4075 ssh->state = SSH_STATE_INTERMED;
4079 if (pktin->type != SSH1_SMSG_SUCCESS
4080 && pktin->type != SSH1_SMSG_FAILURE) {
4081 bombout(("Protocol confusion"));
4083 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4084 c_write_str(ssh, "Server refused to allocate pty\r\n");
4085 ssh->editing = ssh->echoing = 1;
4087 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
4088 ssh->ospeed, ssh->ispeed);
4090 ssh->editing = ssh->echoing = 1;
4093 if (ssh->cfg.compression) {
4094 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
4098 if (pktin->type != SSH1_SMSG_SUCCESS
4099 && pktin->type != SSH1_SMSG_FAILURE) {
4100 bombout(("Protocol confusion"));
4102 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4103 c_write_str(ssh, "Server refused to compress\r\n");
4105 logevent("Started compression");
4106 ssh->v1_compressing = TRUE;
4107 ssh->cs_comp_ctx = zlib_compress_init();
4108 logevent("Initialised zlib (RFC1950) compression");
4109 ssh->sc_comp_ctx = zlib_decompress_init();
4110 logevent("Initialised zlib (RFC1950) decompression");
4114 * Start the shell or command.
4116 * Special case: if the first-choice command is an SSH2
4117 * subsystem (hence not usable here) and the second choice
4118 * exists, we fall straight back to that.
4121 char *cmd = ssh->cfg.remote_cmd_ptr;
4123 if (ssh->cfg.ssh_subsys && ssh->cfg.remote_cmd_ptr2) {
4124 cmd = ssh->cfg.remote_cmd_ptr2;
4125 ssh->fallback_cmd = TRUE;
4128 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
4130 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
4131 logevent("Started session");
4134 ssh->state = SSH_STATE_SESSION;
4135 if (ssh->size_needed)
4136 ssh_size(ssh, ssh->term_width, ssh->term_height);
4137 if (ssh->eof_needed)
4138 ssh_special(ssh, TS_EOF);
4141 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
4143 ssh->channels = newtree234(ssh_channelcmp);
4147 * By this point, most incoming packets are already being
4148 * handled by the dispatch table, and we need only pay
4149 * attention to the unusual ones.
4154 if (pktin->type == SSH1_SMSG_SUCCESS) {
4155 /* may be from EXEC_SHELL on some servers */
4156 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4157 /* may be from EXEC_SHELL on some servers
4158 * if no pty is available or in other odd cases. Ignore */
4160 bombout(("Strange packet received: type %d", pktin->type));
4165 int len = min(inlen, 512);
4166 send_packet(ssh, SSH1_CMSG_STDIN_DATA, PKTT_DATA,
4167 PKT_INT, len, PKT_DATA, in, len,
4168 PKTT_OTHER, PKT_END);
4179 * Handle the top-level SSH2 protocol.
4181 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
4186 ssh_pkt_getstring(pktin, &msg, &msglen);
4187 buf = dupprintf("Remote debug message: %.*s", msglen, msg);
4192 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
4194 /* log reason code in disconnect message */
4198 ssh_pkt_getstring(pktin, &msg, &msglen);
4199 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
4202 void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
4204 /* Do nothing, because we're ignoring it! Duhh. */
4207 static void ssh1_protocol_setup(Ssh ssh)
4212 * Most messages are handled by the coroutines.
4214 for (i = 0; i < 256; i++)
4215 ssh->packet_dispatch[i] = NULL;
4218 * These special message types we install handlers for.
4220 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
4221 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
4222 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
4225 static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen,
4226 struct Packet *pktin)
4228 if (ssh->state == SSH_STATE_CLOSED)
4231 if (pktin && ssh->packet_dispatch[pktin->type]) {
4232 ssh->packet_dispatch[pktin->type](ssh, pktin);
4236 if (!ssh->protocol_initial_phase_done) {
4237 if (do_ssh1_login(ssh, in, inlen, pktin))
4238 ssh->protocol_initial_phase_done = TRUE;
4243 do_ssh1_connection(ssh, in, inlen, pktin);
4247 * Utility routine for decoding comma-separated strings in KEXINIT.
4249 static int in_commasep_string(char *needle, char *haystack, int haylen)
4252 if (!needle || !haystack) /* protect against null pointers */
4254 needlen = strlen(needle);
4257 * Is it at the start of the string?
4259 if (haylen >= needlen && /* haystack is long enough */
4260 !memcmp(needle, haystack, needlen) && /* initial match */
4261 (haylen == needlen || haystack[needlen] == ',')
4262 /* either , or EOS follows */
4266 * If not, search for the next comma and resume after that.
4267 * If no comma found, terminate.
4269 while (haylen > 0 && *haystack != ',')
4270 haylen--, haystack++;
4273 haylen--, haystack++; /* skip over comma itself */
4278 * SSH2 key creation method.
4280 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H,
4281 unsigned char *sessid, char chr,
4282 unsigned char *keyspace)
4285 /* First 20 bytes. */
4287 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
4289 SHA_Bytes(&s, H, 20);
4290 SHA_Bytes(&s, &chr, 1);
4291 SHA_Bytes(&s, sessid, 20);
4292 SHA_Final(&s, keyspace);
4293 /* Next 20 bytes. */
4295 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
4297 SHA_Bytes(&s, H, 20);
4298 SHA_Bytes(&s, keyspace, 20);
4299 SHA_Final(&s, keyspace + 20);
4303 * Handle the SSH2 transport layer.
4305 static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen,
4306 struct Packet *pktin)
4308 struct do_ssh2_transport_state {
4309 int nbits, pbits, warn;
4310 Bignum p, g, e, f, K;
4311 int kex_init_value, kex_reply_value;
4312 const struct ssh_mac **maclist;
4314 const struct ssh2_cipher *cscipher_tobe;
4315 const struct ssh2_cipher *sccipher_tobe;
4316 const struct ssh_mac *csmac_tobe;
4317 const struct ssh_mac *scmac_tobe;
4318 const struct ssh_compress *cscomp_tobe;
4319 const struct ssh_compress *sccomp_tobe;
4320 char *hostkeydata, *sigdata, *keystr, *fingerprint;
4321 int hostkeylen, siglen;
4322 void *hkey; /* actual host key */
4323 unsigned char exchange_hash[20];
4324 int n_preferred_ciphers;
4325 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
4326 const struct ssh_compress *preferred_comp;
4328 struct Packet *pktout;
4330 crState(do_ssh2_transport_state);
4332 crBegin(ssh->do_ssh2_transport_crstate);
4334 s->cscipher_tobe = s->sccipher_tobe = NULL;
4335 s->csmac_tobe = s->scmac_tobe = NULL;
4336 s->cscomp_tobe = s->sccomp_tobe = NULL;
4343 * Set up the preferred ciphers. (NULL => warn below here)
4345 s->n_preferred_ciphers = 0;
4346 for (i = 0; i < CIPHER_MAX; i++) {
4347 switch (ssh->cfg.ssh_cipherlist[i]) {
4348 case CIPHER_BLOWFISH:
4349 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
4352 if (ssh->cfg.ssh2_des_cbc) {
4353 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
4357 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
4360 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
4363 /* Flag for later. Don't bother if it's the last in
4365 if (i < CIPHER_MAX - 1) {
4366 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
4374 * Set up preferred compression.
4376 if (ssh->cfg.compression)
4377 s->preferred_comp = &ssh_zlib;
4379 s->preferred_comp = &ssh_comp_none;
4382 * Be prepared to work around the buggy MAC problem.
4384 if (ssh->remote_bugs & BUG_SSH2_HMAC)
4385 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
4387 s->maclist = macs, s->nmacs = lenof(macs);
4391 int i, j, cipherstr_started;
4394 * Enable queueing of outgoing auth- or connection-layer
4395 * packets while we are in the middle of a key exchange.
4397 ssh->queueing = TRUE;
4400 * Flag that KEX is in progress.
4402 ssh->kex_in_progress = TRUE;
4405 * Construct and send our key exchange packet.
4407 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
4408 for (i = 0; i < 16; i++)
4409 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
4410 /* List key exchange algorithms. */
4411 ssh2_pkt_addstring_start(s->pktout);
4412 for (i = 0; i < lenof(kex_algs); i++) {
4413 if (kex_algs[i] == &ssh_diffiehellman_gex &&
4414 (ssh->remote_bugs & BUG_SSH2_DH_GEX))
4416 ssh2_pkt_addstring_str(s->pktout, kex_algs[i]->name);
4417 if (i < lenof(kex_algs) - 1)
4418 ssh2_pkt_addstring_str(s->pktout, ",");
4420 /* List server host key algorithms. */
4421 ssh2_pkt_addstring_start(s->pktout);
4422 for (i = 0; i < lenof(hostkey_algs); i++) {
4423 ssh2_pkt_addstring_str(s->pktout, hostkey_algs[i]->name);
4424 if (i < lenof(hostkey_algs) - 1)
4425 ssh2_pkt_addstring_str(s->pktout, ",");
4427 /* List client->server encryption algorithms. */
4428 ssh2_pkt_addstring_start(s->pktout);
4429 cipherstr_started = 0;
4430 for (i = 0; i < s->n_preferred_ciphers; i++) {
4431 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
4432 if (!c) continue; /* warning flag */
4433 for (j = 0; j < c->nciphers; j++) {
4434 if (cipherstr_started)
4435 ssh2_pkt_addstring_str(s->pktout, ",");
4436 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
4437 cipherstr_started = 1;
4440 /* List server->client encryption algorithms. */
4441 ssh2_pkt_addstring_start(s->pktout);
4442 cipherstr_started = 0;
4443 for (i = 0; i < s->n_preferred_ciphers; i++) {
4444 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
4445 if (!c) continue; /* warning flag */
4446 for (j = 0; j < c->nciphers; j++) {
4447 if (cipherstr_started)
4448 ssh2_pkt_addstring_str(s->pktout, ",");
4449 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
4450 cipherstr_started = 1;
4453 /* List client->server MAC algorithms. */
4454 ssh2_pkt_addstring_start(s->pktout);
4455 for (i = 0; i < s->nmacs; i++) {
4456 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
4457 if (i < s->nmacs - 1)
4458 ssh2_pkt_addstring_str(s->pktout, ",");
4460 /* List server->client MAC algorithms. */
4461 ssh2_pkt_addstring_start(s->pktout);
4462 for (i = 0; i < s->nmacs; i++) {
4463 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
4464 if (i < s->nmacs - 1)
4465 ssh2_pkt_addstring_str(s->pktout, ",");
4467 /* List client->server compression algorithms. */
4468 ssh2_pkt_addstring_start(s->pktout);
4469 assert(lenof(compressions) > 1);
4470 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
4471 for (i = 0; i < lenof(compressions); i++) {
4472 const struct ssh_compress *c = compressions[i];
4473 if (c != s->preferred_comp) {
4474 ssh2_pkt_addstring_str(s->pktout, ",");
4475 ssh2_pkt_addstring_str(s->pktout, c->name);
4478 /* List server->client compression algorithms. */
4479 ssh2_pkt_addstring_start(s->pktout);
4480 assert(lenof(compressions) > 1);
4481 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
4482 for (i = 0; i < lenof(compressions); i++) {
4483 const struct ssh_compress *c = compressions[i];
4484 if (c != s->preferred_comp) {
4485 ssh2_pkt_addstring_str(s->pktout, ",");
4486 ssh2_pkt_addstring_str(s->pktout, c->name);
4489 /* List client->server languages. Empty list. */
4490 ssh2_pkt_addstring_start(s->pktout);
4491 /* List server->client languages. Empty list. */
4492 ssh2_pkt_addstring_start(s->pktout);
4493 /* First KEX packet does _not_ follow, because we're not that brave. */
4494 ssh2_pkt_addbool(s->pktout, FALSE);
4496 ssh2_pkt_adduint32(s->pktout, 0);
4499 ssh->exhash = ssh->exhashbase;
4500 sha_string(&ssh->exhash, s->pktout->data + 5, s->pktout->length - 5);
4502 ssh2_pkt_send_noqueue(ssh, s->pktout);
4506 if (pktin->length > 5)
4507 sha_string(&ssh->exhash, pktin->data + 5, pktin->length - 5);
4510 * Now examine the other side's KEXINIT to see what we're up
4517 if (pktin->type != SSH2_MSG_KEXINIT) {
4518 bombout(("expected key exchange packet from server"));
4522 ssh->hostkey = NULL;
4523 s->cscipher_tobe = NULL;
4524 s->sccipher_tobe = NULL;
4525 s->csmac_tobe = NULL;
4526 s->scmac_tobe = NULL;
4527 s->cscomp_tobe = NULL;
4528 s->sccomp_tobe = NULL;
4529 pktin->savedpos += 16; /* skip garbage cookie */
4530 ssh_pkt_getstring(pktin, &str, &len); /* key exchange algorithms */
4531 for (i = 0; i < lenof(kex_algs); i++) {
4532 if (kex_algs[i] == &ssh_diffiehellman_gex &&
4533 (ssh->remote_bugs & BUG_SSH2_DH_GEX))
4535 if (in_commasep_string(kex_algs[i]->name, str, len)) {
4536 ssh->kex = kex_algs[i];
4540 ssh_pkt_getstring(pktin, &str, &len); /* host key algorithms */
4541 for (i = 0; i < lenof(hostkey_algs); i++) {
4542 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
4543 ssh->hostkey = hostkey_algs[i];
4547 ssh_pkt_getstring(pktin, &str, &len); /* client->server cipher */
4549 for (i = 0; i < s->n_preferred_ciphers; i++) {
4550 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
4554 for (j = 0; j < c->nciphers; j++) {
4555 if (in_commasep_string(c->list[j]->name, str, len)) {
4556 s->cscipher_tobe = c->list[j];
4561 if (s->cscipher_tobe) {
4563 askcipher(ssh->frontend, s->cscipher_tobe->name, 1);
4567 if (!s->cscipher_tobe) {
4568 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
4569 str ? str : "(null)"));
4573 ssh_pkt_getstring(pktin, &str, &len); /* server->client cipher */
4575 for (i = 0; i < s->n_preferred_ciphers; i++) {
4576 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
4580 for (j = 0; j < c->nciphers; j++) {
4581 if (in_commasep_string(c->list[j]->name, str, len)) {
4582 s->sccipher_tobe = c->list[j];
4587 if (s->sccipher_tobe) {
4589 askcipher(ssh->frontend, s->sccipher_tobe->name, 2);
4593 if (!s->sccipher_tobe) {
4594 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
4595 str ? str : "(null)"));
4599 ssh_pkt_getstring(pktin, &str, &len); /* client->server mac */
4600 for (i = 0; i < s->nmacs; i++) {
4601 if (in_commasep_string(s->maclist[i]->name, str, len)) {
4602 s->csmac_tobe = s->maclist[i];
4606 ssh_pkt_getstring(pktin, &str, &len); /* server->client mac */
4607 for (i = 0; i < s->nmacs; i++) {
4608 if (in_commasep_string(s->maclist[i]->name, str, len)) {
4609 s->scmac_tobe = s->maclist[i];
4613 ssh_pkt_getstring(pktin, &str, &len); /* client->server compression */
4614 for (i = 0; i < lenof(compressions) + 1; i++) {
4615 const struct ssh_compress *c =
4616 i == 0 ? s->preferred_comp : compressions[i - 1];
4617 if (in_commasep_string(c->name, str, len)) {
4622 ssh_pkt_getstring(pktin, &str, &len); /* server->client compression */
4623 for (i = 0; i < lenof(compressions) + 1; i++) {
4624 const struct ssh_compress *c =
4625 i == 0 ? s->preferred_comp : compressions[i - 1];
4626 if (in_commasep_string(c->name, str, len)) {
4634 * Work out the number of bits of key we will need from the key
4635 * exchange. We start with the maximum key length of either
4641 csbits = s->cscipher_tobe->keylen;
4642 scbits = s->sccipher_tobe->keylen;
4643 s->nbits = (csbits > scbits ? csbits : scbits);
4645 /* The keys only have 160-bit entropy, since they're based on
4646 * a SHA-1 hash. So cap the key size at 160 bits. */
4651 * If we're doing Diffie-Hellman group exchange, start by
4652 * requesting a group.
4654 if (!ssh->kex->pdata) {
4655 logevent("Doing Diffie-Hellman group exchange");
4656 ssh->pkt_ctx |= SSH2_PKTCTX_DHGEX;
4658 * Work out how big a DH group we will need to allow that
4661 s->pbits = 512 << ((s->nbits - 1) / 64);
4662 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
4663 ssh2_pkt_adduint32(s->pktout, s->pbits);
4664 ssh2_pkt_send_noqueue(ssh, s->pktout);
4667 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
4668 bombout(("expected key exchange group packet from server"));
4671 s->p = ssh2_pkt_getmp(pktin);
4672 s->g = ssh2_pkt_getmp(pktin);
4673 if (!s->p || !s->g) {
4674 bombout(("unable to read mp-ints from incoming group packet"));
4677 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
4678 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
4679 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
4681 ssh->pkt_ctx |= SSH2_PKTCTX_DHGROUP;
4682 ssh->kex_ctx = dh_setup_group(ssh->kex);
4683 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
4684 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
4685 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
4686 ssh->kex->groupname);
4689 logevent("Doing Diffie-Hellman key exchange");
4691 * Now generate and send e for Diffie-Hellman.
4693 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
4694 s->pktout = ssh2_pkt_init(s->kex_init_value);
4695 ssh2_pkt_addmp(s->pktout, s->e);
4696 ssh2_pkt_send_noqueue(ssh, s->pktout);
4699 if (pktin->type != s->kex_reply_value) {
4700 bombout(("expected key exchange reply packet from server"));
4703 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
4704 s->f = ssh2_pkt_getmp(pktin);
4706 bombout(("unable to parse key exchange reply packet"));
4709 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
4711 s->K = dh_find_K(ssh->kex_ctx, s->f);
4713 sha_string(&ssh->exhash, s->hostkeydata, s->hostkeylen);
4714 if (ssh->kex == &ssh_diffiehellman_gex) {
4715 sha_uint32(&ssh->exhash, s->pbits);
4716 sha_mpint(&ssh->exhash, s->p);
4717 sha_mpint(&ssh->exhash, s->g);
4719 sha_mpint(&ssh->exhash, s->e);
4720 sha_mpint(&ssh->exhash, s->f);
4721 sha_mpint(&ssh->exhash, s->K);
4722 SHA_Final(&ssh->exhash, s->exchange_hash);
4724 dh_cleanup(ssh->kex_ctx);
4725 ssh->kex_ctx = NULL;
4728 debug(("Exchange hash is:\n"));
4729 dmemdump(s->exchange_hash, 20);
4732 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
4734 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
4735 (char *)s->exchange_hash, 20)) {
4736 bombout(("Server's host key did not match the signature supplied"));
4741 * Authenticate remote host: verify host key. (We've already
4742 * checked the signature of the exchange hash.)
4744 s->keystr = ssh->hostkey->fmtkey(s->hkey);
4745 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
4746 verify_ssh_host_key(ssh->frontend,
4747 ssh->savedhost, ssh->savedport, ssh->hostkey->keytype,
4748 s->keystr, s->fingerprint);
4749 if (s->first_kex) { /* don't bother logging this in rekeys */
4750 logevent("Host key fingerprint is:");
4751 logevent(s->fingerprint);
4753 sfree(s->fingerprint);
4755 ssh->hostkey->freekey(s->hkey);
4758 * The exchange hash from the very first key exchange is also
4759 * the session id, used in session key construction and
4763 memcpy(ssh->v2_session_id, s->exchange_hash,
4764 sizeof(s->exchange_hash));
4767 * Send SSH2_MSG_NEWKEYS.
4769 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
4770 ssh2_pkt_send_noqueue(ssh, s->pktout);
4771 ssh->outgoing_data_size = 0; /* start counting from here */
4774 * We've sent client NEWKEYS, so create and initialise
4775 * client-to-server session keys.
4777 if (ssh->cs_cipher_ctx)
4778 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
4779 ssh->cscipher = s->cscipher_tobe;
4780 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
4782 if (ssh->cs_mac_ctx)
4783 ssh->csmac->free_context(ssh->cs_mac_ctx);
4784 ssh->csmac = s->csmac_tobe;
4785 ssh->cs_mac_ctx = ssh->csmac->make_context();
4787 if (ssh->cs_comp_ctx)
4788 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
4789 ssh->cscomp = s->cscomp_tobe;
4790 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
4793 * Set IVs on client-to-server keys. Here we use the exchange
4794 * hash from the _first_ key exchange.
4797 unsigned char keyspace[40];
4798 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'C',keyspace);
4799 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
4800 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'A',keyspace);
4801 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
4802 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'E',keyspace);
4803 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
4806 logeventf(ssh, "Initialised %.200s client->server encryption",
4807 ssh->cscipher->text_name);
4808 logeventf(ssh, "Initialised %.200s client->server MAC algorithm",
4809 ssh->csmac->text_name);
4810 if (ssh->cscomp->text_name)
4811 logeventf(ssh, "Initialised %s compression",
4812 ssh->cscomp->text_name);
4815 * Now our end of the key exchange is complete, we can send all
4816 * our queued higher-layer packets.
4818 ssh->queueing = FALSE;
4819 ssh2_pkt_queuesend(ssh);
4822 * Expect SSH2_MSG_NEWKEYS from server.
4825 if (pktin->type != SSH2_MSG_NEWKEYS) {
4826 bombout(("expected new-keys packet from server"));
4829 ssh->incoming_data_size = 0; /* start counting from here */
4832 * We've seen server NEWKEYS, so create and initialise
4833 * server-to-client session keys.
4835 if (ssh->sc_cipher_ctx)
4836 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
4837 ssh->sccipher = s->sccipher_tobe;
4838 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
4840 if (ssh->sc_mac_ctx)
4841 ssh->scmac->free_context(ssh->sc_mac_ctx);
4842 ssh->scmac = s->scmac_tobe;
4843 ssh->sc_mac_ctx = ssh->scmac->make_context();
4845 if (ssh->sc_comp_ctx)
4846 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
4847 ssh->sccomp = s->sccomp_tobe;
4848 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
4851 * Set IVs on server-to-client keys. Here we use the exchange
4852 * hash from the _first_ key exchange.
4855 unsigned char keyspace[40];
4856 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'D',keyspace);
4857 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
4858 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'B',keyspace);
4859 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
4860 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'F',keyspace);
4861 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
4863 logeventf(ssh, "Initialised %.200s server->client encryption",
4864 ssh->sccipher->text_name);
4865 logeventf(ssh, "Initialised %.200s server->client MAC algorithm",
4866 ssh->scmac->text_name);
4867 if (ssh->sccomp->text_name)
4868 logeventf(ssh, "Initialised %s decompression",
4869 ssh->sccomp->text_name);
4872 * Free key exchange data.
4876 if (ssh->kex == &ssh_diffiehellman_gex) {
4882 * Key exchange is over. Schedule a timer for our next rekey.
4884 ssh->kex_in_progress = FALSE;
4885 ssh->next_rekey = schedule_timer(REKEY_TIMEOUT, ssh2_timer, ssh);
4888 * If this is the first key exchange phase, we must pass the
4889 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
4890 * wants to see it but because it will need time to initialise
4891 * itself before it sees an actual packet. In subsequent key
4892 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
4893 * it would only confuse the layer above.
4895 if (!s->first_kex) {
4901 * Now we're encrypting. Begin returning 1 to the protocol main
4902 * function so that other things can run on top of the
4903 * transport. If we ever see a KEXINIT, we must go back to the
4906 * We _also_ go back to the start if we see pktin==NULL and
4907 * inlen==-1, because this is a special signal meaning
4908 * `initiate client-driven rekey', and `in' contains a message
4909 * giving the reason for the rekey.
4911 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
4912 (!pktin && inlen == -1))) {
4916 logevent("Server initiated key re-exchange");
4918 logevent((char *)in);
4920 goto begin_key_exchange;
4926 * Add data to an SSH2 channel output buffer.
4928 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
4931 bufchain_add(&c->v.v2.outbuffer, buf, len);
4935 * Attempt to send data on an SSH2 channel.
4937 static int ssh2_try_send(struct ssh_channel *c)
4940 struct Packet *pktout;
4942 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
4945 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
4946 if ((unsigned)len > c->v.v2.remwindow)
4947 len = c->v.v2.remwindow;
4948 if ((unsigned)len > c->v.v2.remmaxpkt)
4949 len = c->v.v2.remmaxpkt;
4950 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
4951 ssh2_pkt_adduint32(pktout, c->remoteid);
4952 dont_log_data(ssh, pktout, PKTLOG_OMIT);
4953 ssh2_pkt_addstring_start(pktout);
4954 ssh2_pkt_addstring_data(pktout, data, len);
4955 end_log_omission(ssh, pktout);
4956 ssh2_pkt_send(ssh, pktout);
4957 bufchain_consume(&c->v.v2.outbuffer, len);
4958 c->v.v2.remwindow -= len;
4962 * After having sent as much data as we can, return the amount
4965 return bufchain_size(&c->v.v2.outbuffer);
4969 * Potentially enlarge the window on an SSH2 channel.
4971 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin)
4976 * Never send WINDOW_ADJUST for a channel that the remote side
4977 * already thinks it's closed; there's no point, since it won't
4978 * be sending any more data anyway.
4983 if (newwin > c->v.v2.locwindow) {
4984 struct Packet *pktout;
4986 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4987 ssh2_pkt_adduint32(pktout, c->remoteid);
4988 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
4989 ssh2_pkt_send(ssh, pktout);
4990 c->v.v2.locwindow = newwin;
4994 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
4996 unsigned i = ssh_pkt_getuint32(pktin);
4997 struct ssh_channel *c;
4998 c = find234(ssh->channels, &i, ssh_channelfind);
4999 if (c && !c->closes)
5000 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
5003 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
5007 unsigned i = ssh_pkt_getuint32(pktin);
5008 struct ssh_channel *c;
5009 c = find234(ssh->channels, &i, ssh_channelfind);
5011 return; /* nonexistent channel */
5012 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
5013 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
5014 return; /* extended but not stderr */
5015 ssh_pkt_getstring(pktin, &data, &length);
5018 c->v.v2.locwindow -= length;
5020 case CHAN_MAINSESSION:
5022 from_backend(ssh->frontend, pktin->type ==
5023 SSH2_MSG_CHANNEL_EXTENDED_DATA,
5027 bufsize = x11_send(c->u.x11.s, data, length);
5030 bufsize = pfd_send(c->u.pfd.s, data, length);
5033 while (length > 0) {
5034 if (c->u.a.lensofar < 4) {
5035 int l = min(4 - c->u.a.lensofar, length);
5036 memcpy(c->u.a.msglen + c->u.a.lensofar,
5040 c->u.a.lensofar += l;
5042 if (c->u.a.lensofar == 4) {
5044 4 + GET_32BIT(c->u.a.msglen);
5045 c->u.a.message = snewn(c->u.a.totallen,
5047 memcpy(c->u.a.message, c->u.a.msglen, 4);
5049 if (c->u.a.lensofar >= 4 && length > 0) {
5051 min(c->u.a.totallen - c->u.a.lensofar,
5053 memcpy(c->u.a.message + c->u.a.lensofar,
5057 c->u.a.lensofar += l;
5059 if (c->u.a.lensofar == c->u.a.totallen) {
5062 if (agent_query(c->u.a.message,
5065 ssh_agentf_callback, c))
5066 ssh_agentf_callback(c, reply, replylen);
5067 sfree(c->u.a.message);
5068 c->u.a.lensofar = 0;
5075 * If we are not buffering too much data,
5076 * enlarge the window again at the remote side.
5078 if (bufsize < OUR_V2_WINSIZE)
5079 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
5083 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
5085 unsigned i = ssh_pkt_getuint32(pktin);
5086 struct ssh_channel *c;
5088 c = find234(ssh->channels, &i, ssh_channelfind);
5090 return; /* nonexistent channel */
5092 if (c->type == CHAN_X11) {
5094 * Remote EOF on an X11 channel means we should
5095 * wrap up and close the channel ourselves.
5097 x11_close(c->u.x11.s);
5099 } else if (c->type == CHAN_AGENT) {
5101 } else if (c->type == CHAN_SOCKDATA) {
5102 pfd_close(c->u.pfd.s);
5107 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
5109 unsigned i = ssh_pkt_getuint32(pktin);
5110 struct ssh_channel *c;
5111 struct Packet *pktout;
5113 c = find234(ssh->channels, &i, ssh_channelfind);
5114 if (!c || ((int)c->remoteid) == -1) {
5115 bombout(("Received CHANNEL_CLOSE for %s channel %d\n",
5116 c ? "half-open" : "nonexistent", i));
5119 /* Do pre-close processing on the channel. */
5121 case CHAN_MAINSESSION:
5122 ssh->mainchan = NULL;
5123 update_specials_menu(ssh->frontend);
5126 if (c->u.x11.s != NULL)
5127 x11_close(c->u.x11.s);
5134 if (c->u.pfd.s != NULL)
5135 pfd_close(c->u.pfd.s);
5139 if (c->closes == 0) {
5140 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
5141 ssh2_pkt_adduint32(pktout, c->remoteid);
5142 ssh2_pkt_send(ssh, pktout);
5144 del234(ssh->channels, c);
5145 bufchain_clear(&c->v.v2.outbuffer);
5149 * See if that was the last channel left open.
5150 * (This is only our termination condition if we're
5151 * not running in -N mode.)
5153 if (!ssh->cfg.ssh_no_shell && count234(ssh->channels) == 0) {
5154 logevent("All channels closed. Disconnecting");
5157 * We used to send SSH_MSG_DISCONNECT here,
5158 * because I'd believed that _every_ conforming
5159 * SSH2 connection had to end with a disconnect
5160 * being sent by at least one side; apparently
5161 * I was wrong and it's perfectly OK to
5162 * unceremoniously slam the connection shut
5163 * when you're done, and indeed OpenSSH feels
5164 * this is more polite than sending a
5165 * DISCONNECT. So now we don't.
5167 s->pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
5168 ssh2_pkt_adduint32(s->pktout, SSH2_DISCONNECT_BY_APPLICATION);
5169 ssh2_pkt_addstring(s->pktout, "All open channels closed");
5170 ssh2_pkt_addstring(s->pktout, "en"); /* language tag */
5171 ssh2_pkt_send_noqueue(ssh, s->pktout);
5173 ssh_closing((Plug)ssh, NULL, 0, 0);
5177 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
5179 unsigned i = ssh_pkt_getuint32(pktin);
5180 struct ssh_channel *c;
5181 struct Packet *pktout;
5183 c = find234(ssh->channels, &i, ssh_channelfind);
5185 return; /* nonexistent channel */
5186 if (c->type != CHAN_SOCKDATA_DORMANT)
5187 return; /* dunno why they're confirming this */
5188 c->remoteid = ssh_pkt_getuint32(pktin);
5189 c->type = CHAN_SOCKDATA;
5190 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
5191 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
5193 pfd_confirm(c->u.pfd.s);
5196 * We have a pending close on this channel,
5197 * which we decided on before the server acked
5198 * the channel open. So now we know the
5199 * remoteid, we can close it again.
5201 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
5202 ssh2_pkt_adduint32(pktout, c->remoteid);
5203 ssh2_pkt_send(ssh, pktout);
5207 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
5209 static const char *const reasons[] = {
5210 "<unknown reason code>",
5211 "Administratively prohibited",
5213 "Unknown channel type",
5214 "Resource shortage",
5216 unsigned i = ssh_pkt_getuint32(pktin);
5217 unsigned reason_code;
5218 char *reason_string;
5221 struct ssh_channel *c;
5222 c = find234(ssh->channels, &i, ssh_channelfind);
5224 return; /* nonexistent channel */
5225 if (c->type != CHAN_SOCKDATA_DORMANT)
5226 return; /* dunno why they're failing this */
5228 reason_code = ssh_pkt_getuint32(pktin);
5229 if (reason_code >= lenof(reasons))
5230 reason_code = 0; /* ensure reasons[reason_code] in range */
5231 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
5232 message = dupprintf("Forwarded connection refused by"
5233 " server: %s [%.*s]", reasons[reason_code],
5234 reason_length, reason_string);
5238 pfd_close(c->u.pfd.s);
5240 del234(ssh->channels, c);
5244 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
5248 int typelen, want_reply;
5249 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
5250 struct ssh_channel *c;
5251 struct Packet *pktout;
5253 localid = ssh_pkt_getuint32(pktin);
5254 ssh_pkt_getstring(pktin, &type, &typelen);
5255 want_reply = ssh2_pkt_getbool(pktin);
5258 * First, check that the channel exists. Otherwise,
5259 * we can instantly disconnect with a rude message.
5261 c = find234(ssh->channels, &localid, ssh_channelfind);
5264 sprintf(buf, "Received channel request for nonexistent"
5265 " channel %d", localid);
5267 pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
5268 ssh2_pkt_adduint32(pktout, SSH2_DISCONNECT_BY_APPLICATION);
5269 ssh2_pkt_addstring(pktout, buf);
5270 ssh2_pkt_addstring(pktout, "en"); /* language tag */
5271 ssh2_pkt_send_noqueue(ssh, pktout);
5272 connection_fatal(ssh->frontend, "%s", buf);
5273 ssh_closing((Plug)ssh, NULL, 0, 0);
5278 * Having got the channel number, we now look at
5279 * the request type string to see if it's something
5282 if (c == ssh->mainchan) {
5284 * We recognise "exit-status" and "exit-signal" on
5285 * the primary channel.
5287 if (typelen == 11 &&
5288 !memcmp(type, "exit-status", 11)) {
5290 ssh->exitcode = ssh_pkt_getuint32(pktin);
5291 logeventf(ssh, "Server sent command exit status %d",
5293 reply = SSH2_MSG_CHANNEL_SUCCESS;
5295 } else if (typelen == 11 &&
5296 !memcmp(type, "exit-signal", 11)) {
5298 int is_plausible = TRUE, is_int = FALSE;
5299 char *fmt_sig = "", *fmt_msg = "";
5301 int msglen = 0, core = FALSE;
5302 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
5303 * provide an `int' for the signal, despite its
5304 * having been a `string' in the drafts since at
5305 * least 2001. (Fixed in session.c 1.147.) Try to
5306 * infer which we can safely parse it as. */
5308 unsigned char *p = pktin->body +
5310 long len = pktin->length - pktin->savedpos;
5311 unsigned long num = GET_32BIT(p); /* what is it? */
5312 /* If it's 0, it hardly matters; assume string */
5316 int maybe_int = FALSE, maybe_str = FALSE;
5317 #define CHECK_HYPOTHESIS(offset, result) \
5320 if (q >= 0 && q+4 <= len) { \
5321 q = q + 4 + GET_32BIT(p+q); \
5322 if (q >= 0 && q+4 <= len && \
5323 (q = q + 4 + GET_32BIT(p+q)) && q == len) \
5327 CHECK_HYPOTHESIS(4+1, maybe_int);
5328 CHECK_HYPOTHESIS(4+num+1, maybe_str);
5329 #undef CHECK_HYPOTHESIS
5330 if (maybe_int && !maybe_str)
5332 else if (!maybe_int && maybe_str)
5335 /* Crikey. Either or neither. Panic. */
5336 is_plausible = FALSE;
5341 /* Old non-standard OpenSSH. */
5342 int signum = ssh_pkt_getuint32(pktin);
5343 fmt_sig = dupprintf(" %d", signum);
5345 /* As per the drafts. */
5348 ssh_pkt_getstring(pktin, &sig, &siglen);
5349 /* Signal name isn't supposed to be blank, but
5350 * let's cope gracefully if it is. */
5352 fmt_sig = dupprintf(" \"%.*s\"",
5356 core = ssh2_pkt_getbool(pktin);
5357 ssh_pkt_getstring(pktin, &msg, &msglen);
5359 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
5361 /* ignore lang tag */
5362 } /* else don't attempt to parse */
5363 logeventf(ssh, "Server exited on signal%s%s%s",
5364 fmt_sig, core ? " (core dumped)" : "",
5366 if (*fmt_sig) sfree(fmt_sig);
5367 if (*fmt_msg) sfree(fmt_msg);
5368 reply = SSH2_MSG_CHANNEL_SUCCESS;
5373 * This is a channel request we don't know
5374 * about, so we now either ignore the request
5375 * or respond with CHANNEL_FAILURE, depending
5378 reply = SSH2_MSG_CHANNEL_FAILURE;
5381 pktout = ssh2_pkt_init(reply);
5382 ssh2_pkt_adduint32(pktout, c->remoteid);
5383 ssh2_pkt_send(ssh, pktout);
5387 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
5390 int typelen, want_reply;
5391 struct Packet *pktout;
5393 ssh_pkt_getstring(pktin, &type, &typelen);
5394 want_reply = ssh2_pkt_getbool(pktin);
5397 * We currently don't support any global requests
5398 * at all, so we either ignore the request or
5399 * respond with REQUEST_FAILURE, depending on
5403 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
5404 ssh2_pkt_send(ssh, pktout);
5408 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
5416 struct ssh_channel *c;
5417 unsigned remid, winsize, pktsize;
5418 struct Packet *pktout;
5420 ssh_pkt_getstring(pktin, &type, &typelen);
5421 c = snew(struct ssh_channel);
5424 remid = ssh_pkt_getuint32(pktin);
5425 winsize = ssh_pkt_getuint32(pktin);
5426 pktsize = ssh_pkt_getuint32(pktin);
5428 if (typelen == 3 && !memcmp(type, "x11", 3)) {
5431 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
5432 addrstr = snewn(peeraddrlen+1, char);
5433 memcpy(addrstr, peeraddr, peeraddrlen);
5434 addrstr[peeraddrlen] = '\0';
5435 peerport = ssh_pkt_getuint32(pktin);
5437 logeventf(ssh, "Received X11 connect request from %s:%d",
5440 if (!ssh->X11_fwd_enabled)
5441 error = "X11 forwarding is not enabled";
5442 else if (x11_init(&c->u.x11.s, ssh->cfg.x11_display, c,
5443 ssh->x11auth, addrstr, peerport,
5444 &ssh->cfg) != NULL) {
5445 error = "Unable to open an X11 connection";
5447 logevent("Opening X11 forward connection succeeded");
5452 } else if (typelen == 15 &&
5453 !memcmp(type, "forwarded-tcpip", 15)) {
5454 struct ssh_rportfwd pf, *realpf;
5457 ssh_pkt_getstring(pktin, &dummy, &dummylen);/* skip address */
5458 pf.sport = ssh_pkt_getuint32(pktin);
5459 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
5460 peerport = ssh_pkt_getuint32(pktin);
5461 realpf = find234(ssh->rportfwds, &pf, NULL);
5462 logeventf(ssh, "Received remote port %d open request "
5463 "from %s:%d", pf.sport, peeraddr, peerport);
5464 if (realpf == NULL) {
5465 error = "Remote port is not recognised";
5467 const char *e = pfd_newconnect(&c->u.pfd.s,
5471 logeventf(ssh, "Attempting to forward remote port to "
5472 "%s:%d", realpf->dhost, realpf->dport);
5474 logeventf(ssh, "Port open failed: %s", e);
5475 error = "Port open failed";
5477 logevent("Forwarded port opened successfully");
5478 c->type = CHAN_SOCKDATA;
5481 } else if (typelen == 22 &&
5482 !memcmp(type, "auth-agent@openssh.com", 3)) {
5483 if (!ssh->agentfwd_enabled)
5484 error = "Agent forwarding is not enabled";
5486 c->type = CHAN_AGENT; /* identify channel type */
5487 c->u.a.lensofar = 0;
5490 error = "Unsupported channel type requested";
5493 c->remoteid = remid;
5495 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
5496 ssh2_pkt_adduint32(pktout, c->remoteid);
5497 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
5498 ssh2_pkt_addstring(pktout, error);
5499 ssh2_pkt_addstring(pktout, "en"); /* language tag */
5500 ssh2_pkt_send(ssh, pktout);
5501 logeventf(ssh, "Rejected channel open: %s", error);
5504 c->localid = alloc_channel_id(ssh);
5506 c->v.v2.locwindow = OUR_V2_WINSIZE;
5507 c->v.v2.remwindow = winsize;
5508 c->v.v2.remmaxpkt = pktsize;
5509 bufchain_init(&c->v.v2.outbuffer);
5510 add234(ssh->channels, c);
5511 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
5512 ssh2_pkt_adduint32(pktout, c->remoteid);
5513 ssh2_pkt_adduint32(pktout, c->localid);
5514 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
5515 ssh2_pkt_adduint32(pktout, 0x4000UL); /* our max pkt size */
5516 ssh2_pkt_send(ssh, pktout);
5521 * Handle the SSH2 userauth and connection layers.
5523 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
5524 struct Packet *pktin)
5526 struct do_ssh2_authconn_state {
5528 AUTH_INVALID, AUTH_PUBLICKEY_AGENT, AUTH_PUBLICKEY_FILE,
5530 AUTH_KEYBOARD_INTERACTIVE
5534 AUTH_TYPE_PUBLICKEY,
5535 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
5536 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
5538 AUTH_TYPE_KEYBOARD_INTERACTIVE,
5539 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
5541 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
5542 int tried_pubkey_config, tried_agent, tried_keyb_inter;
5543 int kbd_inter_running;
5545 int num_prompts, curr_prompt, echo;
5550 void *publickey_blob;
5551 int publickey_bloblen;
5552 unsigned char request[5], *response, *p;
5556 char *pkblob, *alg, *commentp;
5557 int pklen, alglen, commentlen;
5558 int siglen, retlen, len;
5559 char *q, *agentreq, *ret;
5561 int num_env, env_left, env_ok;
5562 struct Packet *pktout;
5564 crState(do_ssh2_authconn_state);
5566 crBegin(ssh->do_ssh2_authconn_crstate);
5569 * Request userauth protocol, and await a response to it.
5571 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
5572 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
5573 ssh2_pkt_send(ssh, s->pktout);
5574 crWaitUntilV(pktin);
5575 if (pktin->type != SSH2_MSG_SERVICE_ACCEPT) {
5576 bombout(("Server refused user authentication protocol"));
5581 * We repeat this whole loop, including the username prompt,
5582 * until we manage a successful authentication. If the user
5583 * types the wrong _password_, they can be sent back to the
5584 * beginning to try another username, if this is configured on.
5585 * (If they specify a username in the config, they are never
5586 * asked, even if they do give a wrong password.)
5588 * I think this best serves the needs of
5590 * - the people who have no configuration, no keys, and just
5591 * want to try repeated (username,password) pairs until they
5592 * type both correctly
5594 * - people who have keys and configuration but occasionally
5595 * need to fall back to passwords
5597 * - people with a key held in Pageant, who might not have
5598 * logged in to a particular machine before; so they want to
5599 * type a username, and then _either_ their key will be
5600 * accepted, _or_ they will type a password. If they mistype
5601 * the username they will want to be able to get back and
5604 s->username[0] = '\0';
5605 s->got_username = FALSE;
5610 if (s->got_username && !ssh->cfg.change_username) {
5612 * We got a username last time round this loop, and
5613 * with change_username turned off we don't try to get
5616 } else if (!*ssh->cfg.username) {
5617 if (ssh_get_line && !ssh_getline_pw_only) {
5618 if (!ssh_get_line("login as: ",
5619 s->username, sizeof(s->username), FALSE)) {
5621 * get_line failed to get a username.
5624 logevent("No username provided. Abandoning session.");
5625 ssh_closing((Plug)ssh, NULL, 0, 0);
5629 int ret; /* need not be saved across crReturn */
5630 c_write_str(ssh, "login as: ");
5632 setup_userpass_input(ssh, s->username, sizeof(s->username), 1);
5634 crWaitUntilV(!pktin);
5635 ret = process_userpass_input(ssh, in, inlen);
5639 c_write_str(ssh, "\r\n");
5641 s->username[strcspn(s->username, "\n\r")] = '\0';
5644 strncpy(s->username, ssh->cfg.username, sizeof(s->username));
5645 s->username[sizeof(s->username)-1] = '\0';
5646 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
5647 stuff = dupprintf("Using username \"%s\".\r\n", s->username);
5648 c_write_str(ssh, stuff);
5652 s->got_username = TRUE;
5655 * Send an authentication request using method "none": (a)
5656 * just in case it succeeds, and (b) so that we know what
5657 * authentication methods we can usefully try next.
5659 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
5661 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
5662 ssh2_pkt_addstring(s->pktout, s->username);
5663 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
5664 ssh2_pkt_addstring(s->pktout, "none"); /* method */
5665 ssh2_pkt_send(ssh, s->pktout);
5666 s->type = AUTH_TYPE_NONE;
5668 s->we_are_in = FALSE;
5670 s->tried_pubkey_config = FALSE;
5671 s->tried_agent = FALSE;
5672 s->tried_keyb_inter = FALSE;
5673 s->kbd_inter_running = FALSE;
5674 /* Load the pub half of ssh->cfg.keyfile so we notice if it's in Pageant */
5675 if (!filename_is_null(ssh->cfg.keyfile)) {
5677 logeventf(ssh, "Reading private key file \"%.150s\"",
5678 filename_to_str(&ssh->cfg.keyfile));
5679 keytype = key_type(&ssh->cfg.keyfile);
5680 if (keytype == SSH_KEYTYPE_SSH2) {
5682 ssh2_userkey_loadpub(&ssh->cfg.keyfile, NULL,
5683 &s->publickey_bloblen, NULL);
5686 logeventf(ssh, "Unable to use this key file (%s)",
5687 key_type_to_str(keytype));
5688 msgbuf = dupprintf("Unable to use key file \"%.150s\""
5690 filename_to_str(&ssh->cfg.keyfile),
5691 key_type_to_str(keytype));
5692 c_write_str(ssh, msgbuf);
5694 s->publickey_blob = NULL;
5697 s->publickey_blob = NULL;
5701 * Wait for the result of the last authentication request.
5704 crWaitUntilV(pktin);
5705 while (pktin->type == SSH2_MSG_USERAUTH_BANNER) {
5709 * Don't show the banner if we're operating in
5710 * non-verbose non-interactive mode. (It's probably
5711 * a script, which means nobody will read the
5712 * banner _anyway_, and moreover the printing of
5713 * the banner will screw up processing on the
5714 * output of (say) plink.)
5716 if (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE)) {
5717 ssh_pkt_getstring(pktin, &banner, &size);
5719 c_write_untrusted(ssh, banner, size);
5721 crWaitUntilV(pktin);
5723 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
5724 logevent("Access granted");
5725 s->we_are_in = TRUE;
5729 if (s->kbd_inter_running &&
5730 pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
5732 * This is either a further set-of-prompts packet
5733 * in keyboard-interactive authentication, or it's
5734 * the same one and we came back here with `gotit'
5735 * set. In the former case, we must reset the
5736 * curr_prompt variable.
5740 } else if (pktin->type != SSH2_MSG_USERAUTH_FAILURE) {
5741 bombout(("Strange packet received during authentication: type %d",
5749 * OK, we're now sitting on a USERAUTH_FAILURE message, so
5750 * we can look at the string in it and know what we can
5751 * helpfully try next.
5753 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
5756 ssh_pkt_getstring(pktin, &methods, &methlen);
5757 s->kbd_inter_running = FALSE;
5758 if (!ssh2_pkt_getbool(pktin)) {
5760 * We have received an unequivocal Access
5761 * Denied. This can translate to a variety of
5764 * - if we'd just tried "none" authentication,
5765 * it's not worth printing anything at all
5767 * - if we'd just tried a public key _offer_,
5768 * the message should be "Server refused our
5769 * key" (or no message at all if the key
5770 * came from Pageant)
5772 * - if we'd just tried anything else, the
5773 * message really should be "Access denied".
5775 * Additionally, if we'd just tried password
5776 * authentication, we should break out of this
5777 * whole loop so as to go back to the username
5778 * prompt (iff we're configured to allow
5779 * username change attempts).
5781 if (s->type == AUTH_TYPE_NONE) {
5783 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
5784 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
5785 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
5786 c_write_str(ssh, "Server refused our key\r\n");
5787 logevent("Server refused public key");
5788 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
5789 /* server declined keyboard-interactive; ignore */
5791 c_write_str(ssh, "Access denied\r\n");
5792 logevent("Access denied");
5793 if (s->type == AUTH_TYPE_PASSWORD &&
5794 ssh->cfg.change_username) {
5795 /* XXX perhaps we should allow
5796 * keyboard-interactive to do this too? */
5797 s->we_are_in = FALSE;
5802 c_write_str(ssh, "Further authentication required\r\n");
5803 logevent("Further authentication required");
5807 in_commasep_string("publickey", methods, methlen);
5809 in_commasep_string("password", methods, methlen);
5810 s->can_keyb_inter = ssh->cfg.try_ki_auth &&
5811 in_commasep_string("keyboard-interactive", methods, methlen);
5815 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
5819 * Most password/passphrase prompts will be
5820 * non-echoing, so we set this to 0 by default.
5821 * Exception is that some keyboard-interactive prompts
5822 * can be echoing, in which case we'll set this to 1.
5826 if (!s->method && s->can_pubkey &&
5827 agent_exists() && !s->tried_agent) {
5829 * Attempt public-key authentication using Pageant.
5834 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
5835 ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
5837 s->tried_agent = TRUE;
5839 logevent("Pageant is running. Requesting keys.");
5841 /* Request the keys held by the agent. */
5842 PUT_32BIT(s->request, 1);
5843 s->request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
5844 if (!agent_query(s->request, 5, &r, &s->responselen,
5845 ssh_agent_callback, ssh)) {
5849 bombout(("Unexpected data from server while"
5850 " waiting for agent response"));
5853 } while (pktin || inlen > 0);
5854 r = ssh->agent_response;
5855 s->responselen = ssh->agent_response_len;
5857 s->response = (unsigned char *) r;
5858 if (s->response && s->responselen >= 5 &&
5859 s->response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
5860 s->p = s->response + 5;
5861 s->nkeys = GET_32BIT(s->p);
5865 sprintf(buf, "Pageant has %d SSH2 keys", s->nkeys);
5868 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
5873 sprintf(buf, "Trying Pageant key #%d", s->keyi);
5876 s->pklen = GET_32BIT(s->p);
5878 if (s->publickey_blob &&
5879 s->pklen == s->publickey_bloblen &&
5880 !memcmp(s->p, s->publickey_blob,
5881 s->publickey_bloblen)) {
5882 logevent("This key matches configured key file");
5883 s->tried_pubkey_config = 1;
5885 s->pkblob = (char *)s->p;
5887 s->alglen = GET_32BIT(s->pkblob);
5888 s->alg = s->pkblob + 4;
5889 s->commentlen = GET_32BIT(s->p);
5891 s->commentp = (char *)s->p;
5892 s->p += s->commentlen;
5893 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
5894 ssh2_pkt_addstring(s->pktout, s->username);
5895 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
5896 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
5897 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
5898 ssh2_pkt_addstring_start(s->pktout);
5899 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
5900 ssh2_pkt_addstring_start(s->pktout);
5901 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
5902 ssh2_pkt_send(ssh, s->pktout);
5904 crWaitUntilV(pktin);
5905 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
5906 logevent("Key refused");
5910 if (flags & FLAG_VERBOSE) {
5911 c_write_str(ssh, "Authenticating with "
5913 c_write(ssh, s->commentp, s->commentlen);
5914 c_write_str(ssh, "\" from agent\r\n");
5918 * Server is willing to accept the key.
5919 * Construct a SIGN_REQUEST.
5921 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
5922 ssh2_pkt_addstring(s->pktout, s->username);
5923 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
5924 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
5925 ssh2_pkt_addbool(s->pktout, TRUE);
5926 ssh2_pkt_addstring_start(s->pktout);
5927 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
5928 ssh2_pkt_addstring_start(s->pktout);
5929 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
5931 s->siglen = s->pktout->length - 5 + 4 + 20;
5932 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
5934 s->len = 1; /* message type */
5935 s->len += 4 + s->pklen; /* key blob */
5936 s->len += 4 + s->siglen; /* data to sign */
5937 s->len += 4; /* flags */
5938 s->agentreq = snewn(4 + s->len, char);
5939 PUT_32BIT(s->agentreq, s->len);
5940 s->q = s->agentreq + 4;
5941 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
5942 PUT_32BIT(s->q, s->pklen);
5944 memcpy(s->q, s->pkblob, s->pklen);
5946 PUT_32BIT(s->q, s->siglen);
5948 /* Now the data to be signed... */
5949 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
5950 PUT_32BIT(s->q, 20);
5953 memcpy(s->q, ssh->v2_session_id, 20);
5955 memcpy(s->q, s->pktout->data + 5,
5956 s->pktout->length - 5);
5957 s->q += s->pktout->length - 5;
5958 /* And finally the (zero) flags word. */
5960 if (!agent_query(s->agentreq, s->len + 4,
5962 ssh_agent_callback, ssh)) {
5966 bombout(("Unexpected data from server"
5967 " while waiting for agent"
5971 } while (pktin || inlen > 0);
5972 vret = ssh->agent_response;
5973 s->retlen = ssh->agent_response_len;
5978 if (s->ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
5979 logevent("Sending Pageant's response");
5980 ssh2_add_sigblob(ssh, s->pktout,
5981 s->pkblob, s->pklen,
5983 GET_32BIT(s->ret + 5));
5984 ssh2_pkt_send(ssh, s->pktout);
5989 ("Pageant failed to answer challenge");
6000 if (!s->method && s->can_pubkey && s->publickey_blob
6001 && !s->tried_pubkey_config) {
6002 unsigned char *pub_blob;
6003 char *algorithm, *comment;
6006 s->tried_pubkey_config = TRUE;
6008 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6009 ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
6012 * Try the public key supplied in the configuration.
6014 * First, offer the public blob to see if the server is
6015 * willing to accept it.
6018 (unsigned char *)ssh2_userkey_loadpub(&ssh->cfg.keyfile,
6023 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6024 ssh2_pkt_addstring(s->pktout, s->username);
6025 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
6026 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
6027 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
6028 ssh2_pkt_addstring(s->pktout, algorithm);
6029 ssh2_pkt_addstring_start(s->pktout);
6030 ssh2_pkt_addstring_data(s->pktout, (char *)pub_blob,
6032 ssh2_pkt_send(ssh, s->pktout);
6033 logevent("Offered public key");
6035 crWaitUntilV(pktin);
6036 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
6038 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
6039 continue; /* key refused; give up on it */
6042 logevent("Offer of public key accepted");
6044 * Actually attempt a serious authentication using
6047 if (ssh2_userkey_encrypted(&ssh->cfg.keyfile, &comment)) {
6048 sprintf(s->pwprompt,
6049 "Passphrase for key \"%.100s\": ",
6055 if (flags & FLAG_VERBOSE) {
6056 c_write_str(ssh, "Authenticating with public key \"");
6057 c_write_str(ssh, comment);
6058 c_write_str(ssh, "\"\r\n");
6060 s->method = AUTH_PUBLICKEY_FILE;
6064 if (!s->method && s->can_keyb_inter && !s->tried_keyb_inter) {
6065 s->method = AUTH_KEYBOARD_INTERACTIVE;
6066 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
6067 s->tried_keyb_inter = TRUE;
6069 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6070 ssh->pkt_ctx |= SSH2_PKTCTX_KBDINTER;
6072 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6073 ssh2_pkt_addstring(s->pktout, s->username);
6074 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
6075 ssh2_pkt_addstring(s->pktout, "keyboard-interactive"); /* method */
6076 ssh2_pkt_addstring(s->pktout, ""); /* lang */
6077 ssh2_pkt_addstring(s->pktout, "");
6078 ssh2_pkt_send(ssh, s->pktout);
6080 crWaitUntilV(pktin);
6081 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
6082 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE)
6084 logevent("Keyboard-interactive authentication refused");
6085 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
6089 s->kbd_inter_running = TRUE;
6093 if (s->kbd_inter_running) {
6094 s->method = AUTH_KEYBOARD_INTERACTIVE;
6095 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
6096 s->tried_keyb_inter = TRUE;
6098 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6099 ssh->pkt_ctx |= SSH2_PKTCTX_KBDINTER;
6101 if (s->curr_prompt == 0) {
6103 * We've got a fresh USERAUTH_INFO_REQUEST.
6104 * Display header data, and start going through
6107 char *name, *inst, *lang;
6108 int name_len, inst_len, lang_len;
6110 ssh_pkt_getstring(pktin, &name, &name_len);
6111 ssh_pkt_getstring(pktin, &inst, &inst_len);
6112 ssh_pkt_getstring(pktin, &lang, &lang_len);
6114 c_write_untrusted(ssh, name, name_len);
6115 c_write_str(ssh, "\r\n");
6118 c_write_untrusted(ssh, inst, inst_len);
6119 c_write_str(ssh, "\r\n");
6121 s->num_prompts = ssh_pkt_getuint32(pktin);
6125 * If there are prompts remaining in the packet,
6126 * display one and get a response.
6128 if (s->curr_prompt < s->num_prompts) {
6132 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
6133 if (prompt_len > 0) {
6134 static const char trunc[] = "<prompt truncated>: ";
6135 static const int prlen = sizeof(s->pwprompt) -
6137 if (prompt_len > prlen) {
6138 memcpy(s->pwprompt, prompt, prlen);
6139 strcpy(s->pwprompt + prlen, trunc);
6141 memcpy(s->pwprompt, prompt, prompt_len);
6142 s->pwprompt[prompt_len] = '\0';
6146 "<server failed to send prompt>: ");
6148 s->echo = ssh2_pkt_getbool(pktin);
6154 if (!s->method && s->can_passwd) {
6155 s->method = AUTH_PASSWORD;
6156 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6157 ssh->pkt_ctx |= SSH2_PKTCTX_PASSWORD;
6158 sprintf(s->pwprompt, "%.90s@%.90s's password: ", s->username,
6165 if (!ssh_get_line(s->pwprompt, s->password,
6166 sizeof(s->password), TRUE)) {
6168 * get_line failed to get a password (for
6169 * example because one was supplied on the
6170 * command line which has already failed to
6173 s->pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
6174 ssh2_pkt_adduint32(s->pktout,SSH2_DISCONNECT_BY_APPLICATION);
6175 ssh2_pkt_addstring(s->pktout, "No more passwords available"
6177 ssh2_pkt_addstring(s->pktout, "en"); /* language tag */
6178 ssh2_pkt_send_noqueue(ssh, s->pktout);
6179 logevent("Unable to authenticate");
6180 connection_fatal(ssh->frontend,
6181 "Unable to authenticate");
6182 ssh_closing((Plug)ssh, NULL, 0, 0);
6186 int ret; /* need not be saved across crReturn */
6187 c_write_untrusted(ssh, s->pwprompt, strlen(s->pwprompt));
6190 setup_userpass_input(ssh, s->password,
6191 sizeof(s->password), s->echo);
6193 crWaitUntilV(!pktin);
6194 ret = process_userpass_input(ssh, in, inlen);
6198 c_write_str(ssh, "\r\n");
6202 if (s->method == AUTH_PUBLICKEY_FILE) {
6204 * We have our passphrase. Now try the actual authentication.
6206 struct ssh2_userkey *key;
6207 const char *error = NULL;
6209 key = ssh2_load_userkey(&ssh->cfg.keyfile, s->password,
6211 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
6212 if (key == SSH2_WRONG_PASSPHRASE) {
6213 c_write_str(ssh, "Wrong passphrase\r\n");
6214 s->tried_pubkey_config = FALSE;
6216 c_write_str(ssh, "Unable to load private key (");
6217 c_write_str(ssh, error);
6218 c_write_str(ssh, ")\r\n");
6219 s->tried_pubkey_config = TRUE;
6221 /* Send a spurious AUTH_NONE to return to the top. */
6222 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6223 ssh2_pkt_addstring(s->pktout, s->username);
6224 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
6225 ssh2_pkt_addstring(s->pktout, "none"); /* method */
6226 ssh2_pkt_send(ssh, s->pktout);
6227 s->type = AUTH_TYPE_NONE;
6229 unsigned char *pkblob, *sigblob, *sigdata;
6230 int pkblob_len, sigblob_len, sigdata_len;
6234 * We have loaded the private key and the server
6235 * has announced that it's willing to accept it.
6236 * Hallelujah. Generate a signature and send it.
6238 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6239 ssh2_pkt_addstring(s->pktout, s->username);
6240 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
6241 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
6242 ssh2_pkt_addbool(s->pktout, TRUE);
6243 ssh2_pkt_addstring(s->pktout, key->alg->name);
6244 pkblob = key->alg->public_blob(key->data, &pkblob_len);
6245 ssh2_pkt_addstring_start(s->pktout);
6246 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob, pkblob_len);
6249 * The data to be signed is:
6253 * followed by everything so far placed in the
6256 sigdata_len = s->pktout->length - 5 + 4 + 20;
6257 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
6259 sigdata = snewn(sigdata_len, unsigned char);
6261 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
6262 PUT_32BIT(sigdata+p, 20);
6265 memcpy(sigdata+p, ssh->v2_session_id, 20); p += 20;
6266 memcpy(sigdata+p, s->pktout->data + 5,
6267 s->pktout->length - 5);
6268 p += s->pktout->length - 5;
6269 assert(p == sigdata_len);
6270 sigblob = key->alg->sign(key->data, (char *)sigdata,
6271 sigdata_len, &sigblob_len);
6272 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
6273 sigblob, sigblob_len);
6278 ssh2_pkt_send(ssh, s->pktout);
6279 s->type = AUTH_TYPE_PUBLICKEY;
6280 key->alg->freekey(key->data);
6282 } else if (s->method == AUTH_PASSWORD) {
6284 * We send the password packet lumped tightly together with
6285 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
6286 * string long enough to make the total length of the two
6287 * packets constant. This should ensure that a passive
6288 * listener doing traffic analyis can't work out the length
6291 * For this to work, we need an assumption about the
6292 * maximum length of the password packet. I think 256 is
6293 * pretty conservative. Anyone using a password longer than
6294 * that probably doesn't have much to worry about from
6295 * people who find out how long their password is!
6297 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6298 ssh2_pkt_addstring(s->pktout, s->username);
6299 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
6300 ssh2_pkt_addstring(s->pktout, "password");
6301 ssh2_pkt_addbool(s->pktout, FALSE);
6302 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
6303 ssh2_pkt_addstring(s->pktout, s->password);
6304 memset(s->password, 0, sizeof(s->password));
6305 end_log_omission(ssh, s->pktout);
6306 ssh2_pkt_defer(ssh, s->pktout);
6308 * We'll include a string that's an exact multiple of the
6309 * cipher block size. If the cipher is NULL for some
6310 * reason, we don't do this trick at all because we gain
6313 if (ssh->cscipher) {
6316 stringlen = (256 - ssh->deferred_len);
6317 stringlen += ssh->cscipher->blksize - 1;
6318 stringlen -= (stringlen % ssh->cscipher->blksize);
6321 * Temporarily disable actual compression,
6322 * so we can guarantee to get this string
6323 * exactly the length we want it. The
6324 * compression-disabling routine should
6325 * return an integer indicating how many
6326 * bytes we should adjust our string length
6330 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
6332 s->pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
6333 ssh2_pkt_addstring_start(s->pktout);
6334 for (i = 0; i < stringlen; i++) {
6335 char c = (char) random_byte();
6336 ssh2_pkt_addstring_data(s->pktout, &c, 1);
6338 ssh2_pkt_defer(ssh, s->pktout);
6340 ssh_pkt_defersend(ssh);
6341 logevent("Sent password");
6342 s->type = AUTH_TYPE_PASSWORD;
6343 } else if (s->method == AUTH_KEYBOARD_INTERACTIVE) {
6344 if (s->curr_prompt == 0) {
6345 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
6346 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
6348 if (s->need_pw) { /* only add pw if we just got one! */
6349 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
6350 ssh2_pkt_addstring(s->pktout, s->password);
6351 memset(s->password, 0, sizeof(s->password));
6352 end_log_omission(ssh, s->pktout);
6355 if (s->curr_prompt >= s->num_prompts) {
6356 ssh2_pkt_send(ssh, s->pktout);
6359 * If there are prompts remaining, we set
6360 * `gotit' so that we won't attempt to get
6361 * another packet. Then we go back round the
6362 * loop and will end up retrieving another
6363 * prompt out of the existing packet. Funky or
6368 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
6370 c_write_str(ssh, "No supported authentication methods"
6371 " left to try!\r\n");
6372 logevent("No supported authentications offered."
6374 s->pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
6375 ssh2_pkt_adduint32(s->pktout, SSH2_DISCONNECT_BY_APPLICATION);
6376 ssh2_pkt_addstring(s->pktout, "No supported authentication"
6377 " methods available");
6378 ssh2_pkt_addstring(s->pktout, "en"); /* language tag */
6379 ssh2_pkt_send_noqueue(ssh, s->pktout);
6380 ssh_closing((Plug)ssh, NULL, 0, 0);
6384 } while (!s->we_are_in);
6387 * Now we're authenticated for the connection protocol. The
6388 * connection protocol will automatically have started at this
6389 * point; there's no need to send SERVICE_REQUEST.
6392 ssh->channels = newtree234(ssh_channelcmp);
6395 * Set up handlers for some connection protocol messages, so we
6396 * don't have to handle them repeatedly in this coroutine.
6398 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
6399 ssh2_msg_channel_window_adjust;
6400 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
6401 ssh2_msg_global_request;
6404 * Create the main session channel.
6406 if (!ssh->cfg.ssh_no_shell) {
6407 ssh->mainchan = snew(struct ssh_channel);
6408 ssh->mainchan->ssh = ssh;
6409 ssh->mainchan->localid = alloc_channel_id(ssh);
6410 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
6411 ssh2_pkt_addstring(s->pktout, "session");
6412 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
6413 ssh->mainchan->v.v2.locwindow = OUR_V2_WINSIZE;
6414 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
6415 ssh2_pkt_adduint32(s->pktout, 0x4000UL); /* our max pkt size */
6416 ssh2_pkt_send(ssh, s->pktout);
6417 crWaitUntilV(pktin);
6418 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
6419 bombout(("Server refused to open a session"));
6421 /* FIXME: error data comes back in FAILURE packet */
6423 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
6424 bombout(("Server's channel confirmation cited wrong channel"));
6427 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
6428 ssh->mainchan->type = CHAN_MAINSESSION;
6429 ssh->mainchan->closes = 0;
6430 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
6431 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
6432 bufchain_init(&ssh->mainchan->v.v2.outbuffer);
6433 add234(ssh->channels, ssh->mainchan);
6434 update_specials_menu(ssh->frontend);
6435 logevent("Opened channel for session");
6437 ssh->mainchan = NULL;
6440 * Now we have a channel, make dispatch table entries for
6441 * general channel-based messages.
6443 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
6444 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
6445 ssh2_msg_channel_data;
6446 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
6447 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
6448 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
6449 ssh2_msg_channel_open_confirmation;
6450 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
6451 ssh2_msg_channel_open_failure;
6452 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
6453 ssh2_msg_channel_request;
6454 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
6455 ssh2_msg_channel_open;
6458 * Potentially enable X11 forwarding.
6460 if (ssh->mainchan && ssh->cfg.x11_forward) {
6461 char proto[20], data[64];
6462 logevent("Requesting X11 forwarding");
6463 ssh->x11auth = x11_invent_auth(proto, sizeof(proto),
6464 data, sizeof(data), ssh->cfg.x11_auth);
6465 x11_get_real_auth(ssh->x11auth, ssh->cfg.x11_display);
6466 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6467 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
6468 ssh2_pkt_addstring(s->pktout, "x11-req");
6469 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
6470 ssh2_pkt_addbool(s->pktout, 0); /* many connections */
6471 ssh2_pkt_addstring(s->pktout, proto);
6472 ssh2_pkt_addstring(s->pktout, data);
6473 ssh2_pkt_adduint32(s->pktout, x11_get_screen_number(ssh->cfg.x11_display));
6474 ssh2_pkt_send(ssh, s->pktout);
6476 crWaitUntilV(pktin);
6478 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
6479 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
6480 bombout(("Unexpected response to X11 forwarding request:"
6481 " packet type %d", pktin->type));
6484 logevent("X11 forwarding refused");
6486 logevent("X11 forwarding enabled");
6487 ssh->X11_fwd_enabled = TRUE;
6492 * Enable port forwardings.
6497 int sport,dport,sserv,dserv;
6498 char sports[256], dports[256], saddr[256], host[256];
6500 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
6501 /* Add port forwardings. */
6502 ssh->portfwd_strptr = ssh->cfg.portfwd;
6503 while (*ssh->portfwd_strptr) {
6504 type = *ssh->portfwd_strptr++;
6507 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != '\t') {
6508 if (*ssh->portfwd_strptr == ':') {
6510 * We've seen a colon in the middle of the
6511 * source port number. This means that
6512 * everything we've seen until now is the
6513 * source _address_, so we'll move it into
6514 * saddr and start sports from the beginning
6517 ssh->portfwd_strptr++;
6519 strcpy(saddr, sports);
6522 if (n < 255) sports[n++] = *ssh->portfwd_strptr++;
6526 if (*ssh->portfwd_strptr == '\t')
6527 ssh->portfwd_strptr++;
6529 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != ':') {
6530 if (n < 255) host[n++] = *ssh->portfwd_strptr++;
6533 if (*ssh->portfwd_strptr == ':')
6534 ssh->portfwd_strptr++;
6536 while (*ssh->portfwd_strptr) {
6537 if (n < 255) dports[n++] = *ssh->portfwd_strptr++;
6540 ssh->portfwd_strptr++;
6541 dport = atoi(dports);
6545 dport = net_service_lookup(dports);
6547 logeventf(ssh, "Service lookup failed for destination"
6548 " port \"%s\"", dports);
6552 while (*ssh->portfwd_strptr) ssh->portfwd_strptr++;
6554 ssh->portfwd_strptr++; /* eat the NUL and move to next one */
6556 sport = atoi(sports);
6560 sport = net_service_lookup(sports);
6562 logeventf(ssh, "Service lookup failed for source"
6563 " port \"%s\"", sports);
6566 if (sport && dport) {
6567 /* Set up a description of the source port. */
6568 static char *sportdesc;
6569 sportdesc = dupprintf("%.*s%.*s%.*s%.*s%d%.*s",
6570 (int)(*saddr?strlen(saddr):0), *saddr?saddr:NULL,
6571 (int)(*saddr?1:0), ":",
6572 (int)(sserv ? strlen(sports) : 0), sports,
6573 sserv, "(", sport, sserv, ")");
6575 /* Verbose description of the destination port */
6576 char *dportdesc = dupprintf("%s:%.*s%.*s%d%.*s",
6578 (int)(dserv ? strlen(dports) : 0), dports,
6579 dserv, "(", dport, dserv, ")");
6580 const char *err = pfd_addforward(host, dport,
6581 *saddr ? saddr : NULL,
6582 sport, ssh, &ssh->cfg);
6584 logeventf(ssh, "Local port %s forward to %s"
6585 " failed: %s", sportdesc, dportdesc, err);
6587 logeventf(ssh, "Local port %s forwarding to %s",
6588 sportdesc, dportdesc);
6591 } else if (type == 'D') {
6592 const char *err = pfd_addforward(NULL, -1,
6593 *saddr ? saddr : NULL,
6594 sport, ssh, &ssh->cfg);
6596 logeventf(ssh, "Local port %s SOCKS dynamic forward"
6597 " setup failed: %s", sportdesc, err);
6599 logeventf(ssh, "Local port %s doing SOCKS"
6600 " dynamic forwarding", sportdesc);
6603 struct ssh_rportfwd *pf;
6604 pf = snew(struct ssh_rportfwd);
6605 strcpy(pf->dhost, host);
6608 if (add234(ssh->rportfwds, pf) != pf) {
6609 logeventf(ssh, "Duplicate remote port forwarding"
6610 " to %s:%d", host, dport);
6613 logeventf(ssh, "Requesting remote port %s"
6614 " forward to %s:%.*s%.*s%d%.*s",
6617 (int)(dserv ? strlen(dports) : 0), dports,
6618 dserv, "(", dport, dserv, ")");
6619 s->pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
6620 ssh2_pkt_addstring(s->pktout, "tcpip-forward");
6621 ssh2_pkt_addbool(s->pktout, 1);/* want reply */
6623 ssh2_pkt_addstring(s->pktout, saddr);
6624 } else if (ssh->cfg.rport_acceptall) {
6625 ssh2_pkt_addstring(s->pktout, "0.0.0.0");
6627 ssh2_pkt_addstring(s->pktout, "127.0.0.1");
6629 ssh2_pkt_adduint32(s->pktout, sport);
6630 ssh2_pkt_send(ssh, s->pktout);
6632 crWaitUntilV(pktin);
6634 if (pktin->type != SSH2_MSG_REQUEST_SUCCESS) {
6635 if (pktin->type != SSH2_MSG_REQUEST_FAILURE) {
6636 bombout(("Unexpected response to port "
6637 "forwarding request: packet type %d",
6641 logevent("Server refused this port forwarding");
6643 logevent("Remote port forwarding enabled");
6653 * Potentially enable agent forwarding.
6655 if (ssh->mainchan && ssh->cfg.agentfwd && agent_exists()) {
6656 logevent("Requesting OpenSSH-style agent forwarding");
6657 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6658 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
6659 ssh2_pkt_addstring(s->pktout, "auth-agent-req@openssh.com");
6660 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
6661 ssh2_pkt_send(ssh, s->pktout);
6663 crWaitUntilV(pktin);
6665 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
6666 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
6667 bombout(("Unexpected response to agent forwarding request:"
6668 " packet type %d", pktin->type));
6671 logevent("Agent forwarding refused");
6673 logevent("Agent forwarding enabled");
6674 ssh->agentfwd_enabled = TRUE;
6679 * Now allocate a pty for the session.
6681 if (ssh->mainchan && !ssh->cfg.nopty) {
6682 /* Unpick the terminal-speed string. */
6683 /* XXX perhaps we should allow no speeds to be sent. */
6684 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
6685 sscanf(ssh->cfg.termspeed, "%d,%d", &ssh->ospeed, &ssh->ispeed);
6686 /* Build the pty request. */
6687 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6688 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
6689 ssh2_pkt_addstring(s->pktout, "pty-req");
6690 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
6691 ssh2_pkt_addstring(s->pktout, ssh->cfg.termtype);
6692 ssh2_pkt_adduint32(s->pktout, ssh->term_width);
6693 ssh2_pkt_adduint32(s->pktout, ssh->term_height);
6694 ssh2_pkt_adduint32(s->pktout, 0); /* pixel width */
6695 ssh2_pkt_adduint32(s->pktout, 0); /* pixel height */
6696 ssh2_pkt_addstring_start(s->pktout);
6697 ssh2_pkt_addbyte(s->pktout, 128); /* TTY_OP_ISPEED */
6698 ssh2_pkt_adduint32(s->pktout, ssh->ispeed);
6699 ssh2_pkt_addbyte(s->pktout, 129); /* TTY_OP_OSPEED */
6700 ssh2_pkt_adduint32(s->pktout, ssh->ospeed);
6701 ssh2_pkt_addstring_data(s->pktout, "\0", 1); /* TTY_OP_END */
6702 ssh2_pkt_send(ssh, s->pktout);
6703 ssh->state = SSH_STATE_INTERMED;
6705 crWaitUntilV(pktin);
6707 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
6708 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
6709 bombout(("Unexpected response to pty request:"
6710 " packet type %d", pktin->type));
6713 c_write_str(ssh, "Server refused to allocate pty\r\n");
6714 ssh->editing = ssh->echoing = 1;
6716 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
6717 ssh->ospeed, ssh->ispeed);
6720 ssh->editing = ssh->echoing = 1;
6724 * Send environment variables.
6726 * Simplest thing here is to send all the requests at once, and
6727 * then wait for a whole bunch of successes or failures.
6729 if (ssh->mainchan && *ssh->cfg.environmt) {
6730 char *e = ssh->cfg.environmt;
6731 char *var, *varend, *val;
6737 while (*e && *e != '\t') e++;
6739 if (*e == '\t') e++;
6744 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6745 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
6746 ssh2_pkt_addstring(s->pktout, "env");
6747 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
6748 ssh2_pkt_addstring_start(s->pktout);
6749 ssh2_pkt_addstring_data(s->pktout, var, varend-var);
6750 ssh2_pkt_addstring(s->pktout, val);
6751 ssh2_pkt_send(ssh, s->pktout);
6756 logeventf(ssh, "Sent %d environment variables", s->num_env);
6759 s->env_left = s->num_env;
6761 while (s->env_left > 0) {
6762 crWaitUntilV(pktin);
6764 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
6765 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
6766 bombout(("Unexpected response to environment request:"
6767 " packet type %d", pktin->type));
6777 if (s->env_ok == s->num_env) {
6778 logevent("All environment variables successfully set");
6779 } else if (s->env_ok == 0) {
6780 logevent("All environment variables refused");
6781 c_write_str(ssh, "Server refused to set environment variables\r\n");
6783 logeventf(ssh, "%d environment variables refused",
6784 s->num_env - s->env_ok);
6785 c_write_str(ssh, "Server refused to set all environment variables\r\n");
6790 * Start a shell or a remote command. We may have to attempt
6791 * this twice if the config data has provided a second choice
6794 if (ssh->mainchan) while (1) {
6798 if (ssh->fallback_cmd) {
6799 subsys = ssh->cfg.ssh_subsys2;
6800 cmd = ssh->cfg.remote_cmd_ptr2;
6802 subsys = ssh->cfg.ssh_subsys;
6803 cmd = ssh->cfg.remote_cmd_ptr;
6806 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6807 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
6809 ssh2_pkt_addstring(s->pktout, "subsystem");
6810 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
6811 ssh2_pkt_addstring(s->pktout, cmd);
6813 ssh2_pkt_addstring(s->pktout, "exec");
6814 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
6815 ssh2_pkt_addstring(s->pktout, cmd);
6817 ssh2_pkt_addstring(s->pktout, "shell");
6818 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
6820 ssh2_pkt_send(ssh, s->pktout);
6822 crWaitUntilV(pktin);
6824 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
6825 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
6826 bombout(("Unexpected response to shell/command request:"
6827 " packet type %d", pktin->type));
6831 * We failed to start the command. If this is the
6832 * fallback command, we really are finished; if it's
6833 * not, and if the fallback command exists, try falling
6834 * back to it before complaining.
6836 if (!ssh->fallback_cmd && ssh->cfg.remote_cmd_ptr2 != NULL) {
6837 logevent("Primary command failed; attempting fallback");
6838 ssh->fallback_cmd = TRUE;
6841 bombout(("Server refused to start a shell/command"));
6844 logevent("Started a shell/command");
6849 ssh->state = SSH_STATE_SESSION;
6850 if (ssh->size_needed)
6851 ssh_size(ssh, ssh->term_width, ssh->term_height);
6852 if (ssh->eof_needed)
6853 ssh_special(ssh, TS_EOF);
6859 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
6864 s->try_send = FALSE;
6868 * _All_ the connection-layer packets we expect to
6869 * receive are now handled by the dispatch table.
6870 * Anything that reaches here must be bogus.
6873 bombout(("Strange packet received: type %d", pktin->type));
6875 } else if (ssh->mainchan) {
6877 * We have spare data. Add it to the channel buffer.
6879 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
6884 struct ssh_channel *c;
6886 * Try to send data on all channels if we can.
6888 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
6891 continue; /* don't send on closing channels */
6892 bufsize = ssh2_try_send(c);
6895 case CHAN_MAINSESSION:
6896 /* stdin need not receive an unthrottle
6897 * notification since it will be polled */
6900 x11_unthrottle(c->u.x11.s);
6903 /* agent sockets are request/response and need no
6904 * buffer management */
6907 pfd_unthrottle(c->u.pfd.s);
6919 * Handlers for SSH2 messages that might arrive at any moment.
6921 void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
6923 /* log reason code in disconnect message */
6925 int nowlen, reason, msglen;
6927 reason = ssh_pkt_getuint32(pktin);
6928 ssh_pkt_getstring(pktin, &msg, &msglen);
6930 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
6931 buf = dupprintf("Received disconnect message (%s)",
6932 ssh2_disconnect_reasons[reason]);
6934 buf = dupprintf("Received disconnect message (unknown"
6935 " type %d)", reason);
6939 buf = dupprintf("Disconnection message text: %n%.*s",
6940 &nowlen, msglen, msg);
6942 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
6944 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
6945 ssh2_disconnect_reasons[reason] : "unknown",
6950 void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
6952 /* log the debug message */
6957 /* XXX maybe we should actually take notice of this */
6958 always_display = ssh2_pkt_getbool(pktin);
6959 ssh_pkt_getstring(pktin, &msg, &msglen);
6961 buf = dupprintf("Remote debug message: %.*s", msglen, msg);
6966 void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
6968 struct Packet *pktout;
6969 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
6970 ssh2_pkt_adduint32(pktout, pktin->sequence);
6972 * UNIMPLEMENTED messages MUST appear in the same order as the
6973 * messages they respond to. Hence, never queue them.
6975 ssh2_pkt_send_noqueue(ssh, pktout);
6979 * Handle the top-level SSH2 protocol.
6981 static void ssh2_protocol_setup(Ssh ssh)
6986 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
6988 for (i = 0; i < 256; i++)
6989 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
6992 * Any message we actually understand, we set to NULL so that
6993 * the coroutines will get it.
6995 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = NULL;
6996 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = NULL;
6997 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = NULL;
6998 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = NULL;
6999 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = NULL;
7000 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = NULL;
7001 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = NULL;
7002 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = NULL; duplicate case value */
7003 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = NULL; duplicate case value */
7004 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = NULL;
7005 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = NULL;
7006 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = NULL;
7007 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = NULL;
7008 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = NULL;
7009 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
7010 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = NULL;
7011 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = NULL; duplicate case value */
7012 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = NULL; duplicate case value */
7013 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = NULL;
7014 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = NULL;
7015 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = NULL;
7016 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = NULL;
7017 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = NULL;
7018 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = NULL;
7019 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = NULL;
7020 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = NULL;
7021 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = NULL;
7022 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = NULL;
7023 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = NULL;
7024 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = NULL;
7025 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = NULL;
7026 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = NULL;
7027 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = NULL;
7030 * These special message types we install handlers for.
7032 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
7033 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with ssh1 */
7034 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
7037 static void ssh2_timer(void *ctx, long now)
7041 if (!ssh->kex_in_progress &&
7042 now - ssh->next_rekey >= 0) {
7043 do_ssh2_transport(ssh, "Initiating key re-exchange (timeout)",
7048 static void ssh2_protocol(Ssh ssh, unsigned char *in, int inlen,
7049 struct Packet *pktin)
7051 if (ssh->state == SSH_STATE_CLOSED)
7055 ssh->incoming_data_size += pktin->encrypted_len;
7056 if (!ssh->kex_in_progress &&
7057 ssh->incoming_data_size > MAX_DATA_BEFORE_REKEY)
7058 do_ssh2_transport(ssh, "Initiating key re-exchange "
7059 "(too much data received)", -1, NULL);
7062 if (pktin && ssh->packet_dispatch[pktin->type]) {
7063 ssh->packet_dispatch[pktin->type](ssh, pktin);
7067 if (!ssh->protocol_initial_phase_done ||
7068 (pktin && pktin->type >= 20 && pktin->type < 50)) {
7069 if (do_ssh2_transport(ssh, in, inlen, pktin) &&
7070 !ssh->protocol_initial_phase_done) {
7071 ssh->protocol_initial_phase_done = TRUE;
7073 * Allow authconn to initialise itself.
7075 do_ssh2_authconn(ssh, NULL, 0, NULL);
7078 do_ssh2_authconn(ssh, in, inlen, pktin);
7083 * Called to set up the connection.
7085 * Returns an error message, or NULL on success.
7087 static const char *ssh_init(void *frontend_handle, void **backend_handle,
7089 char *host, int port, char **realhost, int nodelay,
7095 ssh = snew(struct ssh_tag);
7096 ssh->cfg = *cfg; /* STRUCTURE COPY */
7097 ssh->version = 0; /* when not ready yet */
7100 ssh->v1_cipher_ctx = NULL;
7101 ssh->crcda_ctx = NULL;
7102 ssh->cscipher = NULL;
7103 ssh->cs_cipher_ctx = NULL;
7104 ssh->sccipher = NULL;
7105 ssh->sc_cipher_ctx = NULL;
7107 ssh->cs_mac_ctx = NULL;
7109 ssh->sc_mac_ctx = NULL;
7111 ssh->cs_comp_ctx = NULL;
7113 ssh->sc_comp_ctx = NULL;
7115 ssh->kex_ctx = NULL;
7116 ssh->hostkey = NULL;
7118 ssh->state = SSH_STATE_PREPACKET;
7119 ssh->size_needed = FALSE;
7120 ssh->eof_needed = FALSE;
7123 ssh->deferred_send_data = NULL;
7124 ssh->deferred_len = 0;
7125 ssh->deferred_size = 0;
7126 ssh->fallback_cmd = 0;
7128 ssh->x11auth = NULL;
7129 ssh->v1_compressing = FALSE;
7130 ssh->v2_outgoing_sequence = 0;
7131 ssh->ssh1_rdpkt_crstate = 0;
7132 ssh->ssh2_rdpkt_crstate = 0;
7133 ssh->do_ssh_init_crstate = 0;
7134 ssh->ssh_gotdata_crstate = 0;
7135 ssh->do_ssh1_connection_crstate = 0;
7136 ssh->do_ssh1_login_crstate = 0;
7137 ssh->do_ssh2_transport_crstate = 0;
7138 ssh->do_ssh2_authconn_crstate = 0;
7139 ssh->do_ssh_init_state = NULL;
7140 ssh->do_ssh1_login_state = NULL;
7141 ssh->do_ssh2_transport_state = NULL;
7142 ssh->do_ssh2_authconn_state = NULL;
7143 ssh->mainchan = NULL;
7144 ssh->throttled_all = 0;
7145 ssh->v1_stdout_throttling = 0;
7147 ssh->queuelen = ssh->queuesize = 0;
7148 ssh->queueing = FALSE;
7150 *backend_handle = ssh;
7153 if (crypto_startup() == 0)
7154 return "Microsoft high encryption pack not installed!";
7157 ssh->frontend = frontend_handle;
7158 ssh->term_width = ssh->cfg.width;
7159 ssh->term_height = ssh->cfg.height;
7161 ssh->channels = NULL;
7162 ssh->rportfwds = NULL;
7167 ssh->v1_throttle_count = 0;
7168 ssh->overall_bufsize = 0;
7169 ssh->fallback_cmd = 0;
7171 ssh->protocol = NULL;
7173 ssh->protocol_initial_phase_done = FALSE;
7177 ssh->incoming_data_size = ssh->outgoing_data_size =
7178 ssh->deferred_data_size = 0L;
7179 ssh->kex_in_progress = FALSE;
7181 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
7190 static void ssh_free(void *handle)
7192 Ssh ssh = (Ssh) handle;
7193 struct ssh_channel *c;
7194 struct ssh_rportfwd *pf;
7196 if (ssh->v1_cipher_ctx)
7197 ssh->cipher->free_context(ssh->v1_cipher_ctx);
7198 if (ssh->cs_cipher_ctx)
7199 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
7200 if (ssh->sc_cipher_ctx)
7201 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
7202 if (ssh->cs_mac_ctx)
7203 ssh->csmac->free_context(ssh->cs_mac_ctx);
7204 if (ssh->sc_mac_ctx)
7205 ssh->scmac->free_context(ssh->sc_mac_ctx);
7206 if (ssh->cs_comp_ctx) {
7208 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
7210 zlib_compress_cleanup(ssh->cs_comp_ctx);
7212 if (ssh->sc_comp_ctx) {
7214 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
7216 zlib_decompress_cleanup(ssh->sc_comp_ctx);
7219 dh_cleanup(ssh->kex_ctx);
7220 sfree(ssh->savedhost);
7222 while (ssh->queuelen-- > 0)
7223 ssh_free_packet(ssh->queue[ssh->queuelen]);
7226 if (ssh->channels) {
7227 while ((c = delpos234(ssh->channels, 0)) != NULL) {
7230 if (c->u.x11.s != NULL)
7231 x11_close(c->u.x11.s);
7234 if (c->u.pfd.s != NULL)
7235 pfd_close(c->u.pfd.s);
7240 freetree234(ssh->channels);
7241 ssh->channels = NULL;
7244 if (ssh->rportfwds) {
7245 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
7247 freetree234(ssh->rportfwds);
7248 ssh->rportfwds = NULL;
7250 sfree(ssh->deferred_send_data);
7252 x11_free_auth(ssh->x11auth);
7253 sfree(ssh->do_ssh_init_state);
7254 sfree(ssh->do_ssh1_login_state);
7255 sfree(ssh->do_ssh2_transport_state);
7256 sfree(ssh->do_ssh2_authconn_state);
7257 if (ssh->crcda_ctx) {
7258 crcda_free_context(ssh->crcda_ctx);
7259 ssh->crcda_ctx = NULL;
7263 expire_timer_context(ssh);
7265 pinger_free(ssh->pinger);
7272 * Reconfigure the SSH backend.
7274 * Currently, this function does nothing very useful. In future,
7275 * however, we could do some handy things with it. For example, we
7276 * could make the port forwarding configurer active in the Change
7277 * Settings box, and this routine could close down existing
7278 * forwardings and open up new ones in response to changes.
7280 static void ssh_reconfig(void *handle, Config *cfg)
7282 Ssh ssh = (Ssh) handle;
7283 pinger_reconfig(ssh->pinger, &ssh->cfg, cfg);
7284 ssh->cfg = *cfg; /* STRUCTURE COPY */
7288 * Called to send data down the Telnet connection.
7290 static int ssh_send(void *handle, char *buf, int len)
7292 Ssh ssh = (Ssh) handle;
7294 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
7297 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
7299 return ssh_sendbuffer(ssh);
7303 * Called to query the current amount of buffered stdin data.
7305 static int ssh_sendbuffer(void *handle)
7307 Ssh ssh = (Ssh) handle;
7310 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
7314 * If the SSH socket itself has backed up, add the total backup
7315 * size on that to any individual buffer on the stdin channel.
7318 if (ssh->throttled_all)
7319 override_value = ssh->overall_bufsize;
7321 if (ssh->version == 1) {
7322 return override_value;
7323 } else if (ssh->version == 2) {
7324 if (!ssh->mainchan || ssh->mainchan->closes > 0)
7325 return override_value;
7327 return (override_value +
7328 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
7335 * Called to set the size of the window from SSH's POV.
7337 static void ssh_size(void *handle, int width, int height)
7339 Ssh ssh = (Ssh) handle;
7340 struct Packet *pktout;
7342 ssh->term_width = width;
7343 ssh->term_height = height;
7345 switch (ssh->state) {
7346 case SSH_STATE_BEFORE_SIZE:
7347 case SSH_STATE_PREPACKET:
7348 case SSH_STATE_CLOSED:
7349 break; /* do nothing */
7350 case SSH_STATE_INTERMED:
7351 ssh->size_needed = TRUE; /* buffer for later */
7353 case SSH_STATE_SESSION:
7354 if (!ssh->cfg.nopty) {
7355 if (ssh->version == 1) {
7356 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
7357 PKT_INT, ssh->term_height,
7358 PKT_INT, ssh->term_width,
7359 PKT_INT, 0, PKT_INT, 0, PKT_END);
7360 } else if (ssh->mainchan) {
7361 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7362 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
7363 ssh2_pkt_addstring(pktout, "window-change");
7364 ssh2_pkt_addbool(pktout, 0);
7365 ssh2_pkt_adduint32(pktout, ssh->term_width);
7366 ssh2_pkt_adduint32(pktout, ssh->term_height);
7367 ssh2_pkt_adduint32(pktout, 0);
7368 ssh2_pkt_adduint32(pktout, 0);
7369 ssh2_pkt_send(ssh, pktout);
7377 * Return a list of the special codes that make sense in this
7380 static const struct telnet_special *ssh_get_specials(void *handle)
7382 static const struct telnet_special ignore_special[] = {
7383 {"IGNORE message", TS_NOP},
7384 {"Repeat key exchange", TS_REKEY},
7386 static const struct telnet_special ssh2_session_specials[] = {
7389 /* These are the signal names defined by draft-ietf-secsh-connect-19.
7390 * They include all the ISO C signals, but are a subset of the POSIX
7391 * required signals. */
7392 {"SIGINT (Interrupt)", TS_SIGINT},
7393 {"SIGTERM (Terminate)", TS_SIGTERM},
7394 {"SIGKILL (Kill)", TS_SIGKILL},
7395 {"SIGQUIT (Quit)", TS_SIGQUIT},
7396 {"SIGHUP (Hangup)", TS_SIGHUP},
7397 {"More signals", TS_SUBMENU},
7398 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
7399 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
7400 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
7401 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
7404 static const struct telnet_special specials_end[] = {
7407 static struct telnet_special ssh_specials[lenof(ignore_special) +
7408 lenof(ssh2_session_specials) +
7409 lenof(specials_end)];
7410 Ssh ssh = (Ssh) handle;
7412 #define ADD_SPECIALS(name) \
7414 assert((i + lenof(name)) <= lenof(ssh_specials)); \
7415 memcpy(&ssh_specials[i], name, sizeof name); \
7419 if (ssh->version == 1) {
7420 /* Don't bother offering IGNORE if we've decided the remote
7421 * won't cope with it, since we wouldn't bother sending it if
7423 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
7424 ADD_SPECIALS(ignore_special);
7425 } else if (ssh->version == 2) {
7426 ADD_SPECIALS(ignore_special);
7428 ADD_SPECIALS(ssh2_session_specials);
7429 } /* else we're not ready yet */
7432 ADD_SPECIALS(specials_end);
7433 return ssh_specials;
7441 * Send Telnet special codes. TS_EOF is useful for `plink', so you
7442 * can send an EOF and collect resulting output (e.g. `plink
7445 static void ssh_special(void *handle, Telnet_Special code)
7447 Ssh ssh = (Ssh) handle;
7448 struct Packet *pktout;
7450 if (code == TS_EOF) {
7451 if (ssh->state != SSH_STATE_SESSION) {
7453 * Buffer the EOF in case we are pre-SESSION, so we can
7454 * send it as soon as we reach SESSION.
7457 ssh->eof_needed = TRUE;
7460 if (ssh->version == 1) {
7461 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
7462 } else if (ssh->mainchan) {
7463 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
7464 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
7465 ssh2_pkt_send(ssh, pktout);
7467 logevent("Sent EOF message");
7468 } else if (code == TS_PING || code == TS_NOP) {
7469 if (ssh->state == SSH_STATE_CLOSED
7470 || ssh->state == SSH_STATE_PREPACKET) return;
7471 if (ssh->version == 1) {
7472 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
7473 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
7475 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
7476 ssh2_pkt_addstring_start(pktout);
7477 ssh2_pkt_send_noqueue(ssh, pktout);
7479 } else if (code == TS_REKEY) {
7480 if (!ssh->kex_in_progress && ssh->version == 2) {
7481 do_ssh2_transport(ssh, "Initiating key re-exchange at"
7482 " user request", -1, NULL);
7484 } else if (code == TS_BRK) {
7485 if (ssh->state == SSH_STATE_CLOSED
7486 || ssh->state == SSH_STATE_PREPACKET) return;
7487 if (ssh->version == 1) {
7488 logevent("Unable to send BREAK signal in SSH1");
7489 } else if (ssh->mainchan) {
7490 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7491 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
7492 ssh2_pkt_addstring(pktout, "break");
7493 ssh2_pkt_addbool(pktout, 0);
7494 ssh2_pkt_adduint32(pktout, 0); /* default break length */
7495 ssh2_pkt_send(ssh, pktout);
7498 /* Is is a POSIX signal? */
7499 char *signame = NULL;
7500 if (code == TS_SIGABRT) signame = "ABRT";
7501 if (code == TS_SIGALRM) signame = "ALRM";
7502 if (code == TS_SIGFPE) signame = "FPE";
7503 if (code == TS_SIGHUP) signame = "HUP";
7504 if (code == TS_SIGILL) signame = "ILL";
7505 if (code == TS_SIGINT) signame = "INT";
7506 if (code == TS_SIGKILL) signame = "KILL";
7507 if (code == TS_SIGPIPE) signame = "PIPE";
7508 if (code == TS_SIGQUIT) signame = "QUIT";
7509 if (code == TS_SIGSEGV) signame = "SEGV";
7510 if (code == TS_SIGTERM) signame = "TERM";
7511 if (code == TS_SIGUSR1) signame = "USR1";
7512 if (code == TS_SIGUSR2) signame = "USR2";
7513 /* The SSH-2 protocol does in principle support arbitrary named
7514 * signals, including signame@domain, but we don't support those. */
7516 /* It's a signal. */
7517 if (ssh->version == 2 && ssh->mainchan) {
7518 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7519 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
7520 ssh2_pkt_addstring(pktout, "signal");
7521 ssh2_pkt_addbool(pktout, 0);
7522 ssh2_pkt_addstring(pktout, signame);
7523 ssh2_pkt_send(ssh, pktout);
7524 logeventf(ssh, "Sent signal SIG%s", signame);
7527 /* Never heard of it. Do nothing */
7532 void *new_sock_channel(void *handle, Socket s)
7534 Ssh ssh = (Ssh) handle;
7535 struct ssh_channel *c;
7536 c = snew(struct ssh_channel);
7540 c->remoteid = -1; /* to be set when open confirmed */
7541 c->localid = alloc_channel_id(ssh);
7543 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
7545 bufchain_init(&c->v.v2.outbuffer);
7546 add234(ssh->channels, c);
7552 * This is called when stdout/stderr (the entity to which
7553 * from_backend sends data) manages to clear some backlog.
7555 static void ssh_unthrottle(void *handle, int bufsize)
7557 Ssh ssh = (Ssh) handle;
7558 if (ssh->version == 1) {
7559 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
7560 ssh->v1_stdout_throttling = 0;
7561 ssh1_throttle(ssh, -1);
7564 if (ssh->mainchan && ssh->mainchan->closes == 0)
7565 ssh2_set_window(ssh->mainchan, OUR_V2_WINSIZE - bufsize);
7569 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
7571 struct ssh_channel *c = (struct ssh_channel *)channel;
7573 struct Packet *pktout;
7575 logeventf(ssh, "Opening forwarded connection to %s:%d", hostname, port);
7577 if (ssh->version == 1) {
7578 send_packet(ssh, SSH1_MSG_PORT_OPEN,
7579 PKT_INT, c->localid,
7582 //PKT_STR, <org:orgport>,
7585 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7586 ssh2_pkt_addstring(pktout, "direct-tcpip");
7587 ssh2_pkt_adduint32(pktout, c->localid);
7588 c->v.v2.locwindow = OUR_V2_WINSIZE;
7589 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
7590 ssh2_pkt_adduint32(pktout, 0x4000UL); /* our max pkt size */
7591 ssh2_pkt_addstring(pktout, hostname);
7592 ssh2_pkt_adduint32(pktout, port);
7594 * We make up values for the originator data; partly it's
7595 * too much hassle to keep track, and partly I'm not
7596 * convinced the server should be told details like that
7597 * about my local network configuration.
7599 ssh2_pkt_addstring(pktout, "client-side-connection");
7600 ssh2_pkt_adduint32(pktout, 0);
7601 ssh2_pkt_send(ssh, pktout);
7605 static Socket ssh_socket(void *handle)
7607 Ssh ssh = (Ssh) handle;
7611 static int ssh_sendok(void *handle)
7613 Ssh ssh = (Ssh) handle;
7614 return ssh->send_ok;
7617 static int ssh_ldisc(void *handle, int option)
7619 Ssh ssh = (Ssh) handle;
7620 if (option == LD_ECHO)
7621 return ssh->echoing;
7622 if (option == LD_EDIT)
7623 return ssh->editing;
7627 static void ssh_provide_ldisc(void *handle, void *ldisc)
7629 Ssh ssh = (Ssh) handle;
7633 static void ssh_provide_logctx(void *handle, void *logctx)
7635 Ssh ssh = (Ssh) handle;
7636 ssh->logctx = logctx;
7639 static int ssh_return_exitcode(void *handle)
7641 Ssh ssh = (Ssh) handle;
7645 return (ssh->exitcode >= 0 ? ssh->exitcode : 0);
7649 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
7650 * that fails. This variable is the means by which scp.c can reach
7651 * into the SSH code and find out which one it got.
7653 extern int ssh_fallback_cmd(void *handle)
7655 Ssh ssh = (Ssh) handle;
7656 return ssh->fallback_cmd;
7659 Backend ssh_backend = {
7669 ssh_return_exitcode,