17 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
18 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
19 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
20 #define SSH1_CMSG_USER 4 /* 0x4 */
21 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
22 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
23 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
24 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
25 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
26 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
27 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
28 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
29 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
30 #define SSH1_SMSG_FAILURE 15 /* 0xf */
31 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
32 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
33 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
34 #define SSH1_CMSG_EOF 19 /* 0x13 */
35 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
36 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
37 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
38 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
39 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
40 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
41 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
42 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
43 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
44 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
45 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
46 #define SSH1_MSG_IGNORE 32 /* 0x20 */
47 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
48 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
49 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
50 #define SSH1_MSG_DEBUG 36 /* 0x24 */
51 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
52 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
53 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
54 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
55 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
56 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
57 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
59 #define SSH1_AUTH_TIS 5 /* 0x5 */
60 #define SSH1_AUTH_CCARD 16 /* 0x10 */
62 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
63 /* Mask for protoflags we will echo back to server if seen */
64 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
66 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
67 #define SSH2_MSG_IGNORE 2 /* 0x2 */
68 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
69 #define SSH2_MSG_DEBUG 4 /* 0x4 */
70 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
71 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
72 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
73 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
74 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
75 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
76 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
77 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
78 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
79 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
80 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
81 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
82 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
83 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
84 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
85 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
86 #define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */
87 #define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */
88 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
89 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
90 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
91 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
92 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
93 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
94 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
95 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
96 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
97 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
98 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
99 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
100 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
101 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
104 * Packet type contexts, so that ssh2_pkt_type can correctly decode
105 * the ambiguous type numbers back into the correct type strings.
107 #define SSH2_PKTCTX_DHGROUP1 0x0001
108 #define SSH2_PKTCTX_DHGEX 0x0002
109 #define SSH2_PKTCTX_PUBLICKEY 0x0010
110 #define SSH2_PKTCTX_PASSWORD 0x0020
111 #define SSH2_PKTCTX_KBDINTER 0x0040
112 #define SSH2_PKTCTX_AUTH_MASK 0x00F0
114 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
115 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
116 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
117 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
118 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
119 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
120 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
121 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
122 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
123 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
124 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
125 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
126 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
127 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
128 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
130 static const char *const ssh2_disconnect_reasons[] = {
132 "SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT",
133 "SSH_DISCONNECT_PROTOCOL_ERROR",
134 "SSH_DISCONNECT_KEY_EXCHANGE_FAILED",
135 "SSH_DISCONNECT_HOST_AUTHENTICATION_FAILED",
136 "SSH_DISCONNECT_MAC_ERROR",
137 "SSH_DISCONNECT_COMPRESSION_ERROR",
138 "SSH_DISCONNECT_SERVICE_NOT_AVAILABLE",
139 "SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED",
140 "SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE",
141 "SSH_DISCONNECT_CONNECTION_LOST",
142 "SSH_DISCONNECT_BY_APPLICATION",
143 "SSH_DISCONNECT_TOO_MANY_CONNECTIONS",
144 "SSH_DISCONNECT_AUTH_CANCELLED_BY_USER",
145 "SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE",
146 "SSH_DISCONNECT_ILLEGAL_USER_NAME",
149 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
150 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
151 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
152 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
154 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
157 * Various remote-bug flags.
159 #define BUG_CHOKES_ON_SSH1_IGNORE 1
160 #define BUG_SSH2_HMAC 2
161 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
162 #define BUG_CHOKES_ON_RSA 8
163 #define BUG_SSH2_RSA_PADDING 16
164 #define BUG_SSH2_DERIVEKEY 32
165 #define BUG_SSH2_DH_GEX 64
166 #define BUG_SSH2_PK_SESSIONID 128
168 #define translate(x) if (type == x) return #x
169 #define translatec(x,ctx) if (type == x && (pkt_ctx & ctx)) return #x
170 static char *ssh1_pkt_type(int type)
172 translate(SSH1_MSG_DISCONNECT);
173 translate(SSH1_SMSG_PUBLIC_KEY);
174 translate(SSH1_CMSG_SESSION_KEY);
175 translate(SSH1_CMSG_USER);
176 translate(SSH1_CMSG_AUTH_RSA);
177 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
178 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
179 translate(SSH1_CMSG_AUTH_PASSWORD);
180 translate(SSH1_CMSG_REQUEST_PTY);
181 translate(SSH1_CMSG_WINDOW_SIZE);
182 translate(SSH1_CMSG_EXEC_SHELL);
183 translate(SSH1_CMSG_EXEC_CMD);
184 translate(SSH1_SMSG_SUCCESS);
185 translate(SSH1_SMSG_FAILURE);
186 translate(SSH1_CMSG_STDIN_DATA);
187 translate(SSH1_SMSG_STDOUT_DATA);
188 translate(SSH1_SMSG_STDERR_DATA);
189 translate(SSH1_CMSG_EOF);
190 translate(SSH1_SMSG_EXIT_STATUS);
191 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
192 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
193 translate(SSH1_MSG_CHANNEL_DATA);
194 translate(SSH1_MSG_CHANNEL_CLOSE);
195 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
196 translate(SSH1_SMSG_X11_OPEN);
197 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
198 translate(SSH1_MSG_PORT_OPEN);
199 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
200 translate(SSH1_SMSG_AGENT_OPEN);
201 translate(SSH1_MSG_IGNORE);
202 translate(SSH1_CMSG_EXIT_CONFIRMATION);
203 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
204 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
205 translate(SSH1_MSG_DEBUG);
206 translate(SSH1_CMSG_REQUEST_COMPRESSION);
207 translate(SSH1_CMSG_AUTH_TIS);
208 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
209 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
210 translate(SSH1_CMSG_AUTH_CCARD);
211 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
212 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
215 static char *ssh2_pkt_type(int pkt_ctx, int type)
217 translate(SSH2_MSG_DISCONNECT);
218 translate(SSH2_MSG_IGNORE);
219 translate(SSH2_MSG_UNIMPLEMENTED);
220 translate(SSH2_MSG_DEBUG);
221 translate(SSH2_MSG_SERVICE_REQUEST);
222 translate(SSH2_MSG_SERVICE_ACCEPT);
223 translate(SSH2_MSG_KEXINIT);
224 translate(SSH2_MSG_NEWKEYS);
225 translatec(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP1);
226 translatec(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP1);
227 translatec(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
228 translatec(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
229 translatec(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
230 translatec(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
231 translate(SSH2_MSG_USERAUTH_REQUEST);
232 translate(SSH2_MSG_USERAUTH_FAILURE);
233 translate(SSH2_MSG_USERAUTH_SUCCESS);
234 translate(SSH2_MSG_USERAUTH_BANNER);
235 translatec(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
236 translatec(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
237 translatec(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
238 translatec(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
239 translate(SSH2_MSG_GLOBAL_REQUEST);
240 translate(SSH2_MSG_REQUEST_SUCCESS);
241 translate(SSH2_MSG_REQUEST_FAILURE);
242 translate(SSH2_MSG_CHANNEL_OPEN);
243 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
244 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
245 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
246 translate(SSH2_MSG_CHANNEL_DATA);
247 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
248 translate(SSH2_MSG_CHANNEL_EOF);
249 translate(SSH2_MSG_CHANNEL_CLOSE);
250 translate(SSH2_MSG_CHANNEL_REQUEST);
251 translate(SSH2_MSG_CHANNEL_SUCCESS);
252 translate(SSH2_MSG_CHANNEL_FAILURE);
258 #define GET_32BIT(cp) \
259 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
260 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
261 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
262 ((unsigned long)(unsigned char)(cp)[3]))
264 #define PUT_32BIT(cp, value) { \
265 (cp)[0] = (unsigned char)((value) >> 24); \
266 (cp)[1] = (unsigned char)((value) >> 16); \
267 (cp)[2] = (unsigned char)((value) >> 8); \
268 (cp)[3] = (unsigned char)(value); }
270 /* Enumeration values for fields in SSH-1 packets */
272 PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
273 /* These values are for communicating relevant semantics of
274 * fields to the packet logging code. */
275 PKTT_OTHER, PKTT_PASSWORD, PKTT_DATA
279 * Coroutine mechanics for the sillier bits of the code. If these
280 * macros look impenetrable to you, you might find it helpful to
283 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
285 * which explains the theory behind these macros.
287 * In particular, if you are getting `case expression not constant'
288 * errors when building with MS Visual Studio, this is because MS's
289 * Edit and Continue debugging feature causes their compiler to
290 * violate ANSI C. To disable Edit and Continue debugging:
292 * - right-click ssh.c in the FileView
294 * - select the C/C++ tab and the General category
295 * - under `Debug info:', select anything _other_ than `Program
296 * Database for Edit and Continue'.
298 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
301 if (!ssh->t) ssh->t = snew(struct t); \
303 #define crFinish(z) } *crLine = 0; return (z); }
304 #define crFinishV } *crLine = 0; return; }
305 #define crReturn(z) \
307 *crLine =__LINE__; return (z); case __LINE__:;\
311 *crLine=__LINE__; return; case __LINE__:;\
313 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
314 #define crStopV do{ *crLine = 0; return; }while(0)
315 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
316 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
318 typedef struct ssh_tag *Ssh;
321 static struct Packet *ssh2_pkt_init(int pkt_type);
322 static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
323 static void ssh2_pkt_adduint32(struct Packet *, unsigned long value);
324 static void ssh2_pkt_addstring_start(struct Packet *);
325 static void ssh2_pkt_addstring_str(struct Packet *, char *data);
326 static void ssh2_pkt_addstring_data(struct Packet *, char *data, int len);
327 static void ssh2_pkt_addstring(struct Packet *, char *data);
328 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
329 static void ssh2_pkt_addmp(struct Packet *, Bignum b);
330 static int ssh2_pkt_construct(Ssh, struct Packet *);
331 static void ssh2_pkt_send(Ssh, struct Packet *);
332 static 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,
368 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
370 static void *nullmac_make_context(void)
374 static void nullmac_free_context(void *handle)
377 static void nullmac_key(void *handle, unsigned char *key)
380 static void nullmac_generate(void *handle, unsigned char *blk, int len,
384 static int nullmac_verify(void *handle, unsigned char *blk, int len,
389 const static struct ssh_mac ssh_mac_none = {
390 nullmac_make_context, nullmac_free_context, nullmac_key,
391 nullmac_generate, nullmac_verify, "none", 0
393 const static struct ssh_mac *macs[] = {
394 &ssh_sha1, &ssh_md5, &ssh_mac_none
396 const static struct ssh_mac *buggymacs[] = {
397 &ssh_sha1_buggy, &ssh_md5, &ssh_mac_none
400 static void *ssh_comp_none_init(void)
404 static void ssh_comp_none_cleanup(void *handle)
407 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
408 unsigned char **outblock, int *outlen)
412 static int ssh_comp_none_disable(void *handle)
416 const static struct ssh_compress ssh_comp_none = {
418 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
419 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
420 ssh_comp_none_disable, NULL
422 extern const struct ssh_compress ssh_zlib;
423 const static struct ssh_compress *compressions[] = {
424 &ssh_zlib, &ssh_comp_none
427 enum { /* channel types */
432 CHAN_SOCKDATA_DORMANT /* one the remote hasn't confirmed */
436 * 2-3-4 tree storing channels.
439 Ssh ssh; /* pointer back to main context */
440 unsigned remoteid, localid;
443 * In SSH1, this value contains four bits:
445 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
446 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
447 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
448 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
450 * A channel is completely finished with when all four bits are set.
454 struct ssh1_data_channel {
457 struct ssh2_data_channel {
459 unsigned remwindow, remmaxpkt;
464 struct ssh_agent_channel {
465 unsigned char *message;
466 unsigned char msglen[4];
467 unsigned lensofar, totallen;
469 struct ssh_x11_channel {
472 struct ssh_pfd_channel {
479 * 2-3-4 tree storing remote->local port forwardings. SSH 1 and SSH
480 * 2 use this structure in different ways, reflecting SSH 2's
481 * altogether saner approach to port forwarding.
483 * In SSH 1, you arrange a remote forwarding by sending the server
484 * the remote port number, and the local destination host:port.
485 * When a connection comes in, the server sends you back that
486 * host:port pair, and you connect to it. This is a ready-made
487 * security hole if you're not on the ball: a malicious server
488 * could send you back _any_ host:port pair, so if you trustingly
489 * connect to the address it gives you then you've just opened the
490 * entire inside of your corporate network just by connecting
491 * through it to a dodgy SSH server. Hence, we must store a list of
492 * host:port pairs we _are_ trying to forward to, and reject a
493 * connection request from the server if it's not in the list.
495 * In SSH 2, each side of the connection minds its own business and
496 * doesn't send unnecessary information to the other. You arrange a
497 * remote forwarding by sending the server just the remote port
498 * number. When a connection comes in, the server tells you which
499 * of its ports was connected to; and _you_ have to remember what
500 * local host:port pair went with that port number.
502 * Hence: in SSH 1 this structure stores host:port pairs we intend
503 * to allow connections to, and is indexed by those host:port
504 * pairs. In SSH 2 it stores a mapping from source port to
505 * destination host:port pair, and is indexed by source port.
507 struct ssh_rportfwd {
508 unsigned sport, dport;
515 unsigned long sequence;
520 long encrypted_len; /* for SSH2 total-size counting */
523 * State associated with packet logging
527 struct logblank_t *blanks;
530 static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen,
531 struct Packet *pktin);
532 static void ssh2_protocol(Ssh ssh, unsigned char *in, int inlen,
533 struct Packet *pktin);
534 static void ssh1_protocol_setup(Ssh ssh);
535 static void ssh2_protocol_setup(Ssh ssh);
536 static void ssh_size(void *handle, int width, int height);
537 static void ssh_special(void *handle, Telnet_Special);
538 static int ssh2_try_send(struct ssh_channel *c);
539 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
540 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
541 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin);
542 static int ssh_sendbuffer(void *handle);
543 static void ssh_do_close(Ssh ssh);
544 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
545 static int ssh2_pkt_getbool(struct Packet *pkt);
546 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
547 static void ssh2_timer(void *ctx, long now);
548 static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen,
549 struct Packet *pktin);
551 struct rdpkt1_state_tag {
552 long len, pad, biglen, to_read;
553 unsigned long realcrc, gotcrc;
557 struct Packet *pktin;
560 struct rdpkt2_state_tag {
561 long len, pad, payload, packetlen, maclen;
564 unsigned long incoming_sequence;
565 struct Packet *pktin;
568 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
571 const struct plug_function_table *fn;
572 /* the above field _must_ be first in the structure */
574 SHA_State exhash, exhashbase;
581 unsigned char session_key[32];
583 int v1_remote_protoflags;
584 int v1_local_protoflags;
585 int agentfwd_enabled;
588 const struct ssh_cipher *cipher;
591 const struct ssh2_cipher *cscipher, *sccipher;
592 void *cs_cipher_ctx, *sc_cipher_ctx;
593 const struct ssh_mac *csmac, *scmac;
594 void *cs_mac_ctx, *sc_mac_ctx;
595 const struct ssh_compress *cscomp, *sccomp;
596 void *cs_comp_ctx, *sc_comp_ctx;
597 const struct ssh_kex *kex;
598 const struct ssh_signkey *hostkey;
599 unsigned char v2_session_id[20];
605 int echoing, editing;
609 int ospeed, ispeed; /* temporaries */
610 int term_width, term_height;
612 tree234 *channels; /* indexed by local id */
613 struct ssh_channel *mainchan; /* primary session channel */
620 SSH_STATE_BEFORE_SIZE,
626 int size_needed, eof_needed;
628 struct Packet **queue;
629 int queuelen, queuesize;
631 unsigned char *deferred_send_data;
632 int deferred_len, deferred_size;
635 * Gross hack: pscp will try to start SFTP but fall back to
636 * scp1 if that fails. This variable is the means by which
637 * scp.c can reach into the SSH code and find out which one it
643 * Used for username and password input.
645 char *userpass_input_buffer;
646 int userpass_input_buflen;
647 int userpass_input_bufpos;
648 int userpass_input_echo;
650 char *portfwd_strptr;
656 int v1_throttle_count;
659 int v1_stdout_throttling;
660 int v2_outgoing_sequence;
662 int ssh1_rdpkt_crstate;
663 int ssh2_rdpkt_crstate;
664 int do_ssh_init_crstate;
665 int ssh_gotdata_crstate;
666 int do_ssh1_login_crstate;
667 int do_ssh1_connection_crstate;
668 int do_ssh2_transport_crstate;
669 int do_ssh2_authconn_crstate;
671 void *do_ssh_init_state;
672 void *do_ssh1_login_state;
673 void *do_ssh2_transport_state;
674 void *do_ssh2_authconn_state;
676 struct rdpkt1_state_tag rdpkt1_state;
677 struct rdpkt2_state_tag rdpkt2_state;
679 /* ssh1 and ssh2 use this for different things, but both use it */
680 int protocol_initial_phase_done;
682 void (*protocol) (Ssh ssh, unsigned char *in, int inlen,
684 struct Packet *(*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
687 * We maintain a full _copy_ of a Config structure here, not
688 * merely a pointer to it. That way, when we're passed a new
689 * one for reconfiguration, we can check the differences and
690 * potentially reconfigure port forwardings etc in mid-session.
695 * Used to transfer data back from async agent callbacks.
697 void *agent_response;
698 int agent_response_len;
701 * Dispatch table for packet types that we may have to deal
704 handler_fn_t packet_dispatch[256];
707 * This module deals with sending keepalives.
712 * Track incoming and outgoing data sizes and time, for
715 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
720 #define MAX_DATA_BEFORE_REKEY (0x40000000UL)
721 #define REKEY_TIMEOUT (3600 * TICKSPERSEC)
723 #define logevent(s) logevent(ssh->frontend, s)
725 /* logevent, only printf-formatted. */
726 static void logeventf(Ssh ssh, const char *fmt, ...)
732 buf = dupvprintf(fmt, ap);
738 #define bombout(msg) \
740 char *text = dupprintf msg; \
743 connection_fatal(ssh->frontend, "%s", text); \
747 /* Functions to leave bits out of the SSH packet log file. */
749 static void dont_log_password(Ssh ssh, struct Packet *pkt, int blanktype)
751 if (ssh->cfg.logomitpass)
752 pkt->logmode = blanktype;
755 static void dont_log_data(Ssh ssh, struct Packet *pkt, int blanktype)
757 if (ssh->cfg.logomitdata)
758 pkt->logmode = blanktype;
761 static void end_log_omission(Ssh ssh, struct Packet *pkt)
763 pkt->logmode = PKTLOG_EMIT;
766 static int ssh_channelcmp(void *av, void *bv)
768 struct ssh_channel *a = (struct ssh_channel *) av;
769 struct ssh_channel *b = (struct ssh_channel *) bv;
770 if (a->localid < b->localid)
772 if (a->localid > b->localid)
776 static int ssh_channelfind(void *av, void *bv)
778 unsigned *a = (unsigned *) av;
779 struct ssh_channel *b = (struct ssh_channel *) bv;
787 static int ssh_rportcmp_ssh1(void *av, void *bv)
789 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
790 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
792 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
793 return i < 0 ? -1 : +1;
794 if (a->dport > b->dport)
796 if (a->dport < b->dport)
801 static int ssh_rportcmp_ssh2(void *av, void *bv)
803 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
804 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
806 if (a->sport > b->sport)
808 if (a->sport < b->sport)
813 static int alloc_channel_id(Ssh ssh)
815 const unsigned CHANNEL_NUMBER_OFFSET = 256;
816 unsigned low, high, mid;
818 struct ssh_channel *c;
821 * First-fit allocation of channel numbers: always pick the
822 * lowest unused one. To do this, binary-search using the
823 * counted B-tree to find the largest channel ID which is in a
824 * contiguous sequence from the beginning. (Precisely
825 * everything in that sequence must have ID equal to its tree
826 * index plus CHANNEL_NUMBER_OFFSET.)
828 tsize = count234(ssh->channels);
832 while (high - low > 1) {
833 mid = (high + low) / 2;
834 c = index234(ssh->channels, mid);
835 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
836 low = mid; /* this one is fine */
838 high = mid; /* this one is past it */
841 * Now low points to either -1, or the tree index of the
842 * largest ID in the initial sequence.
845 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
846 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
848 return low + 1 + CHANNEL_NUMBER_OFFSET;
851 static void c_write(Ssh ssh, const char *buf, int len)
853 if ((flags & FLAG_STDERR)) {
855 for (i = 0; i < len; i++)
857 fputc(buf[i], stderr);
860 from_backend(ssh->frontend, 1, buf, len);
863 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
866 for (i = 0; i < len; i++) {
868 c_write(ssh, "\r\n", 2);
869 else if ((buf[i] & 0x60) || (buf[i] == '\r'))
870 c_write(ssh, buf + i, 1);
874 static void c_write_str(Ssh ssh, const char *buf)
876 c_write(ssh, buf, strlen(buf));
879 static void ssh_free_packet(struct Packet *pkt)
884 static struct Packet *ssh_new_packet(void)
886 struct Packet *pkt = snew(struct Packet);
890 pkt->logmode = PKTLOG_EMIT;
898 * Collect incoming data in the incoming packet buffer.
899 * Decipher and verify the packet when it is completely read.
900 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
901 * Update the *data and *datalen variables.
902 * Return a Packet structure when a packet is completed.
904 static struct Packet *ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
906 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
908 crBegin(ssh->ssh1_rdpkt_crstate);
910 st->pktin = ssh_new_packet();
913 st->pktin->length = 0;
915 for (st->i = st->len = 0; st->i < 4; st->i++) {
916 while ((*datalen) == 0)
918 st->len = (st->len << 8) + **data;
919 (*data)++, (*datalen)--;
922 st->pad = 8 - (st->len % 8);
923 st->biglen = st->len + st->pad;
924 st->pktin->length = st->len - 5;
926 if (st->biglen < 0) {
927 bombout(("Extremely large packet length from server suggests"
928 " data stream corruption"));
929 ssh_free_packet(st->pktin);
933 st->pktin->maxlen = st->biglen;
934 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
936 st->to_read = st->biglen;
937 st->p = st->pktin->data;
938 while (st->to_read > 0) {
939 st->chunk = st->to_read;
940 while ((*datalen) == 0)
942 if (st->chunk > (*datalen))
943 st->chunk = (*datalen);
944 memcpy(st->p, *data, st->chunk);
946 *datalen -= st->chunk;
948 st->to_read -= st->chunk;
951 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
953 bombout(("Network attack (CRC compensation) detected!"));
954 ssh_free_packet(st->pktin);
959 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
961 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
962 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
963 if (st->gotcrc != st->realcrc) {
964 bombout(("Incorrect CRC received on packet"));
965 ssh_free_packet(st->pktin);
969 st->pktin->body = st->pktin->data + st->pad + 1;
970 st->pktin->savedpos = 0;
972 if (ssh->v1_compressing) {
973 unsigned char *decompblk;
975 if (!zlib_decompress_block(ssh->sc_comp_ctx,
976 st->pktin->body - 1, st->pktin->length + 1,
977 &decompblk, &decomplen)) {
978 bombout(("Zlib decompression encountered invalid data"));
979 ssh_free_packet(st->pktin);
983 if (st->pktin->maxlen < st->pad + decomplen) {
984 st->pktin->maxlen = st->pad + decomplen;
985 st->pktin->data = sresize(st->pktin->data,
986 st->pktin->maxlen + APIEXTRA,
988 st->pktin->body = st->pktin->data + st->pad + 1;
991 memcpy(st->pktin->body - 1, decompblk, decomplen);
993 st->pktin->length = decomplen - 1;
996 st->pktin->type = st->pktin->body[-1];
999 * Log incoming packet, possibly omitting sensitive fields.
1003 struct logblank_t blank;
1004 if (ssh->cfg.logomitdata) {
1005 int do_blank = FALSE, blank_prefix = 0;
1006 /* "Session data" packets - omit the data field */
1007 if ((st->pktin->type == SSH1_SMSG_STDOUT_DATA) ||
1008 (st->pktin->type == SSH1_SMSG_STDERR_DATA)) {
1009 do_blank = TRUE; blank_prefix = 0;
1010 } else if (st->pktin->type == SSH1_MSG_CHANNEL_DATA) {
1011 do_blank = TRUE; blank_prefix = 4;
1014 blank.offset = blank_prefix;
1015 blank.len = st->pktin->length;
1016 blank.type = PKTLOG_OMIT;
1020 log_packet(ssh->logctx,
1021 PKT_INCOMING, st->pktin->type,
1022 ssh1_pkt_type(st->pktin->type),
1023 st->pktin->body, st->pktin->length,
1027 crFinish(st->pktin);
1030 static struct Packet *ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1032 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1034 crBegin(ssh->ssh2_rdpkt_crstate);
1036 st->pktin = ssh_new_packet();
1038 st->pktin->type = 0;
1039 st->pktin->length = 0;
1041 st->cipherblk = ssh->sccipher->blksize;
1044 if (st->cipherblk < 8)
1047 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1050 * Acquire and decrypt the first block of the packet. This will
1051 * contain the length and padding details.
1053 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1054 while ((*datalen) == 0)
1056 st->pktin->data[st->i] = *(*data)++;
1061 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1062 st->pktin->data, st->cipherblk);
1065 * Now get the length and padding figures.
1067 st->len = GET_32BIT(st->pktin->data);
1068 st->pad = st->pktin->data[4];
1071 * _Completely_ silly lengths should be stomped on before they
1072 * do us any more damage.
1074 if (st->len < 0 || st->pad < 0 || st->len + st->pad < 0) {
1075 bombout(("Incoming packet was garbled on decryption"));
1076 ssh_free_packet(st->pktin);
1081 * This enables us to deduce the payload length.
1083 st->payload = st->len - st->pad - 1;
1085 st->pktin->length = st->payload + 5;
1088 * So now we can work out the total packet length.
1090 st->packetlen = st->len + 4;
1091 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1094 * Allocate memory for the rest of the packet.
1096 st->pktin->maxlen = st->packetlen + st->maclen;
1097 st->pktin->data = sresize(st->pktin->data,
1098 st->pktin->maxlen + APIEXTRA,
1102 * Read and decrypt the remainder of the packet.
1104 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1106 while ((*datalen) == 0)
1108 st->pktin->data[st->i] = *(*data)++;
1111 /* Decrypt everything _except_ the MAC. */
1113 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1114 st->pktin->data + st->cipherblk,
1115 st->packetlen - st->cipherblk);
1117 st->pktin->encrypted_len = st->packetlen;
1123 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data, st->len + 4,
1124 st->incoming_sequence)) {
1125 bombout(("Incorrect MAC received on packet"));
1126 ssh_free_packet(st->pktin);
1130 st->pktin->sequence = st->incoming_sequence++;
1133 * Decompress packet payload.
1136 unsigned char *newpayload;
1139 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1140 st->pktin->data + 5, st->pktin->length - 5,
1141 &newpayload, &newlen)) {
1142 if (st->pktin->maxlen < newlen + 5) {
1143 st->pktin->maxlen = newlen + 5;
1144 st->pktin->data = sresize(st->pktin->data,
1145 st->pktin->maxlen + APIEXTRA,
1148 st->pktin->length = 5 + newlen;
1149 memcpy(st->pktin->data + 5, newpayload, newlen);
1154 st->pktin->savedpos = 6;
1155 st->pktin->body = st->pktin->data;
1156 st->pktin->type = st->pktin->data[5];
1159 * Log incoming packet, possibly omitting sensitive fields.
1163 struct logblank_t blank;
1164 if (ssh->cfg.logomitdata) {
1165 int do_blank = FALSE, blank_prefix = 0;
1166 /* "Session data" packets - omit the data field */
1167 if (st->pktin->type == SSH2_MSG_CHANNEL_DATA) {
1168 do_blank = TRUE; blank_prefix = 4;
1169 } else if (st->pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
1170 do_blank = TRUE; blank_prefix = 8;
1173 blank.offset = blank_prefix;
1174 blank.len = (st->pktin->length-6) - blank_prefix;
1175 blank.type = PKTLOG_OMIT;
1179 log_packet(ssh->logctx, PKT_INCOMING, st->pktin->type,
1180 ssh2_pkt_type(ssh->pkt_ctx, st->pktin->type),
1181 st->pktin->data+6, st->pktin->length-6,
1185 crFinish(st->pktin);
1188 static void ssh1_pktout_size(struct Packet *pkt, int len)
1192 len += 5; /* type and CRC */
1193 pad = 8 - (len % 8);
1196 pkt->length = len - 5;
1197 if (pkt->maxlen < biglen) {
1198 pkt->maxlen = biglen;
1199 pkt->data = sresize(pkt->data, biglen + 4 + APIEXTRA, unsigned char);
1201 pkt->body = pkt->data + 4 + pad + 1;
1204 static struct Packet *s_wrpkt_start(int type, int len)
1206 struct Packet *pkt = ssh_new_packet();
1207 ssh1_pktout_size(pkt, len);
1209 /* Initialise log omission state */
1215 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt)
1221 * XXX various versions of SC (including 8.8.4) screw up the
1222 * register allocation in this function and use the same register
1223 * (D6) for len and as a temporary, with predictable results. The
1224 * following sledgehammer prevents this.
1230 pkt->body[-1] = pkt->type;
1233 log_packet(ssh->logctx, PKT_OUTGOING, pkt->type,
1234 ssh1_pkt_type(pkt->type),
1235 pkt->body, pkt->length,
1236 pkt->nblanks, pkt->blanks);
1237 sfree(pkt->blanks); pkt->blanks = NULL;
1240 if (ssh->v1_compressing) {
1241 unsigned char *compblk;
1243 zlib_compress_block(ssh->cs_comp_ctx,
1244 pkt->body - 1, pkt->length + 1,
1245 &compblk, &complen);
1246 ssh1_pktout_size(pkt, complen - 1);
1247 memcpy(pkt->body - 1, compblk, complen);
1251 len = pkt->length + 5; /* type and CRC */
1252 pad = 8 - (len % 8);
1255 for (i = 0; i < pad; i++)
1256 pkt->data[i + 4] = random_byte();
1257 crc = crc32_compute(pkt->data + 4, biglen - 4);
1258 PUT_32BIT(pkt->data + biglen, crc);
1259 PUT_32BIT(pkt->data, len);
1262 ssh->cipher->encrypt(ssh->v1_cipher_ctx, pkt->data + 4, biglen);
1267 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1270 len = s_wrpkt_prepare(ssh, pkt);
1271 backlog = sk_write(ssh->s, (char *)pkt->data, len);
1272 if (backlog > SSH_MAX_BACKLOG)
1273 ssh_throttle_all(ssh, 1, backlog);
1276 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1279 len = s_wrpkt_prepare(ssh, pkt);
1280 if (ssh->deferred_len + len > ssh->deferred_size) {
1281 ssh->deferred_size = ssh->deferred_len + len + 128;
1282 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1286 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->data, len);
1287 ssh->deferred_len += len;
1291 * Construct a packet with the specified contents.
1293 static struct Packet *construct_packet(Ssh ssh, int pkttype,
1294 va_list ap1, va_list ap2)
1296 unsigned char *p, *argp, argchar;
1297 unsigned long argint;
1298 int pktlen, argtype, arglen;
1303 while ((argtype = va_arg(ap1, int)) != PKT_END) {
1306 (void) va_arg(ap1, int);
1310 (void) va_arg(ap1, int);
1314 (void) va_arg(ap1, unsigned char *);
1315 arglen = va_arg(ap1, int);
1319 argp = va_arg(ap1, unsigned char *);
1320 arglen = strlen((char *)argp);
1321 pktlen += 4 + arglen;
1324 bn = va_arg(ap1, Bignum);
1325 pktlen += ssh1_bignum_length(bn);
1330 /* ignore this pass */
1337 pkt = s_wrpkt_start(pkttype, pktlen);
1340 while ((argtype = va_arg(ap2, int)) != PKT_END) {
1341 int offset = p - pkt->body, len = 0;
1343 /* Actual fields in the packet */
1345 argint = va_arg(ap2, int);
1346 PUT_32BIT(p, argint);
1350 argchar = (unsigned char) va_arg(ap2, int);
1355 argp = va_arg(ap2, unsigned char *);
1356 arglen = va_arg(ap2, int);
1357 memcpy(p, argp, arglen);
1361 argp = va_arg(ap2, unsigned char *);
1362 arglen = strlen((char *)argp);
1363 PUT_32BIT(p, arglen);
1364 memcpy(p + 4, argp, arglen);
1368 bn = va_arg(ap2, Bignum);
1369 len = ssh1_write_bignum(p, bn);
1371 /* Tokens for modifications to packet logging */
1373 dont_log_password(ssh, pkt, PKTLOG_BLANK);
1376 dont_log_data(ssh, pkt, PKTLOG_OMIT);
1379 end_log_omission(ssh, pkt);
1383 /* Deal with logfile omission, if required. */
1384 if (len && (pkt->logmode != PKTLOG_EMIT)) {
1386 pkt->blanks = sresize(pkt->blanks, pkt->nblanks,
1388 pkt->blanks[pkt->nblanks-1].offset = offset;
1389 pkt->blanks[pkt->nblanks-1].len = len;
1390 pkt->blanks[pkt->nblanks-1].type = pkt->logmode;
1397 static void send_packet(Ssh ssh, int pkttype, ...)
1401 va_start(ap1, pkttype);
1402 va_start(ap2, pkttype);
1403 pkt = construct_packet(ssh, pkttype, ap1, ap2);
1407 ssh_free_packet(pkt);
1410 static void defer_packet(Ssh ssh, int pkttype, ...)
1414 va_start(ap1, pkttype);
1415 va_start(ap2, pkttype);
1416 pkt = construct_packet(ssh, pkttype, ap1, ap2);
1419 s_wrpkt_defer(ssh, pkt);
1420 ssh_free_packet(pkt);
1423 static int ssh_versioncmp(char *a, char *b)
1426 unsigned long av, bv;
1428 av = strtoul(a, &ae, 10);
1429 bv = strtoul(b, &be, 10);
1431 return (av < bv ? -1 : +1);
1436 av = strtoul(ae, &ae, 10);
1437 bv = strtoul(be, &be, 10);
1439 return (av < bv ? -1 : +1);
1444 * Utility routines for putting an SSH-protocol `string' and
1445 * `uint32' into a SHA state.
1448 static void sha_string(SHA_State * s, void *str, int len)
1450 unsigned char lenblk[4];
1451 PUT_32BIT(lenblk, len);
1452 SHA_Bytes(s, lenblk, 4);
1453 SHA_Bytes(s, str, len);
1456 static void sha_uint32(SHA_State * s, unsigned i)
1458 unsigned char intblk[4];
1459 PUT_32BIT(intblk, i);
1460 SHA_Bytes(s, intblk, 4);
1464 * SSH2 packet construction functions.
1466 static void ssh2_pkt_ensure(struct Packet *pkt, int length)
1468 if (pkt->maxlen < length) {
1469 pkt->maxlen = length + 256;
1470 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
1473 static void ssh2_pkt_adddata(struct Packet *pkt, void *data, int len)
1475 if (pkt->logmode != PKTLOG_EMIT) {
1477 pkt->blanks = sresize(pkt->blanks, pkt->nblanks, struct logblank_t);
1478 pkt->blanks[pkt->nblanks-1].offset = pkt->length - 6;
1479 pkt->blanks[pkt->nblanks-1].len = len;
1480 pkt->blanks[pkt->nblanks-1].type = pkt->logmode;
1483 ssh2_pkt_ensure(pkt, pkt->length);
1484 memcpy(pkt->data + pkt->length - len, data, len);
1486 static void ssh2_pkt_addbyte(struct Packet *pkt, unsigned char byte)
1488 ssh2_pkt_adddata(pkt, &byte, 1);
1490 static struct Packet *ssh2_pkt_init(int pkt_type)
1492 struct Packet *pkt = ssh_new_packet();
1494 ssh2_pkt_addbyte(pkt, (unsigned char) pkt_type);
1497 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
1499 ssh2_pkt_adddata(pkt, &value, 1);
1501 static void ssh2_pkt_adduint32(struct Packet *pkt, unsigned long value)
1504 PUT_32BIT(x, value);
1505 ssh2_pkt_adddata(pkt, x, 4);
1507 static void ssh2_pkt_addstring_start(struct Packet *pkt)
1509 ssh2_pkt_adduint32(pkt, 0);
1510 pkt->savedpos = pkt->length;
1512 static void ssh2_pkt_addstring_str(struct Packet *pkt, char *data)
1514 ssh2_pkt_adddata(pkt, data, strlen(data));
1515 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1517 static void ssh2_pkt_addstring_data(struct Packet *pkt, char *data, int len)
1519 ssh2_pkt_adddata(pkt, data, len);
1520 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1522 static void ssh2_pkt_addstring(struct Packet *pkt, char *data)
1524 ssh2_pkt_addstring_start(pkt);
1525 ssh2_pkt_addstring_str(pkt, data);
1527 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
1530 int i, n = (bignum_bitcount(b) + 7) / 8;
1531 p = snewn(n + 1, unsigned char);
1533 fatalbox("out of memory");
1535 for (i = 1; i <= n; i++)
1536 p[i] = bignum_byte(b, n - i);
1538 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1540 memmove(p, p + i, n + 1 - i);
1544 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
1548 p = ssh2_mpint_fmt(b, &len);
1549 ssh2_pkt_addstring_start(pkt);
1550 ssh2_pkt_addstring_data(pkt, (char *)p, len);
1555 * Construct an SSH2 final-form packet: compress it, encrypt it,
1556 * put the MAC on it. Final packet, ready to be sent, is stored in
1557 * pkt->data. Total length is returned.
1559 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
1561 int cipherblk, maclen, padding, i;
1564 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1565 ssh2_pkt_type(ssh->pkt_ctx, pkt->data[5]),
1566 pkt->data + 6, pkt->length - 6,
1567 pkt->nblanks, pkt->blanks);
1568 sfree(pkt->blanks); pkt->blanks = NULL;
1572 * Compress packet payload.
1575 unsigned char *newpayload;
1578 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
1580 &newpayload, &newlen)) {
1582 ssh2_pkt_adddata(pkt, newpayload, newlen);
1588 * Add padding. At least four bytes, and must also bring total
1589 * length (minus MAC) up to a multiple of the block size.
1591 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
1592 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1595 (cipherblk - (pkt->length + padding) % cipherblk) % cipherblk;
1596 maclen = ssh->csmac ? ssh->csmac->len : 0;
1597 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
1598 pkt->data[4] = padding;
1599 for (i = 0; i < padding; i++)
1600 pkt->data[pkt->length + i] = random_byte();
1601 PUT_32BIT(pkt->data, pkt->length + padding - 4);
1603 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
1604 pkt->length + padding,
1605 ssh->v2_outgoing_sequence);
1606 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
1609 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
1610 pkt->data, pkt->length + padding);
1612 pkt->encrypted_len = pkt->length + padding;
1614 /* Ready-to-send packet starts at pkt->data. We return length. */
1615 return pkt->length + padding + maclen;
1619 * Routines called from the main SSH code to send packets. There
1620 * are quite a few of these, because we have two separate
1621 * mechanisms for delaying the sending of packets:
1623 * - In order to send an IGNORE message and a password message in
1624 * a single fixed-length blob, we require the ability to
1625 * concatenate the encrypted forms of those two packets _into_ a
1626 * single blob and then pass it to our <network.h> transport
1627 * layer in one go. Hence, there's a deferment mechanism which
1628 * works after packet encryption.
1630 * - In order to avoid sending any connection-layer messages
1631 * during repeat key exchange, we have to queue up any such
1632 * outgoing messages _before_ they are encrypted (and in
1633 * particular before they're allocated sequence numbers), and
1634 * then send them once we've finished.
1636 * I call these mechanisms `defer' and `queue' respectively, so as
1637 * to distinguish them reasonably easily.
1639 * The functions send_noqueue() and defer_noqueue() free the packet
1640 * structure they are passed. Every outgoing packet goes through
1641 * precisely one of these functions in its life; packets passed to
1642 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
1643 * these or get queued, and then when the queue is later emptied
1644 * the packets are all passed to defer_noqueue().
1648 * Send an SSH2 packet immediately, without queuing or deferring.
1650 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
1654 len = ssh2_pkt_construct(ssh, pkt);
1655 backlog = sk_write(ssh->s, (char *)pkt->data, len);
1656 if (backlog > SSH_MAX_BACKLOG)
1657 ssh_throttle_all(ssh, 1, backlog);
1659 ssh->outgoing_data_size += pkt->encrypted_len;
1660 if (!ssh->kex_in_progress &&
1661 ssh->outgoing_data_size > MAX_DATA_BEFORE_REKEY)
1662 do_ssh2_transport(ssh, "Initiating key re-exchange "
1663 "(too much data sent)", -1, NULL);
1665 ssh_free_packet(pkt);
1669 * Defer an SSH2 packet.
1671 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt)
1673 int len = ssh2_pkt_construct(ssh, pkt);
1674 if (ssh->deferred_len + len > ssh->deferred_size) {
1675 ssh->deferred_size = ssh->deferred_len + len + 128;
1676 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1680 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->data, len);
1681 ssh->deferred_len += len;
1682 ssh->deferred_data_size += pkt->encrypted_len;
1683 ssh_free_packet(pkt);
1687 * Queue an SSH2 packet.
1689 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
1691 assert(ssh->queueing);
1693 if (ssh->queuelen >= ssh->queuesize) {
1694 ssh->queuesize = ssh->queuelen + 32;
1695 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
1698 ssh->queue[ssh->queuelen++] = pkt;
1702 * Either queue or send a packet, depending on whether queueing is
1705 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
1708 ssh2_pkt_queue(ssh, pkt);
1710 ssh2_pkt_send_noqueue(ssh, pkt);
1714 * Either queue or defer a packet, depending on whether queueing is
1717 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
1720 ssh2_pkt_queue(ssh, pkt);
1722 ssh2_pkt_defer_noqueue(ssh, pkt);
1726 * Send the whole deferred data block constructed by
1727 * ssh2_pkt_defer() or SSH1's defer_packet().
1729 * The expected use of the defer mechanism is that you call
1730 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
1731 * not currently queueing, this simply sets up deferred_send_data
1732 * and then sends it. If we _are_ currently queueing, the calls to
1733 * ssh2_pkt_defer() put the deferred packets on to the queue
1734 * instead, and therefore ssh_pkt_defersend() has no deferred data
1735 * to send. Hence, there's no need to make it conditional on
1738 static void ssh_pkt_defersend(Ssh ssh)
1741 backlog = sk_write(ssh->s, (char *)ssh->deferred_send_data,
1743 ssh->deferred_len = ssh->deferred_size = 0;
1744 sfree(ssh->deferred_send_data);
1745 ssh->deferred_send_data = NULL;
1746 if (backlog > SSH_MAX_BACKLOG)
1747 ssh_throttle_all(ssh, 1, backlog);
1749 ssh->outgoing_data_size += ssh->deferred_data_size;
1750 if (!ssh->kex_in_progress &&
1751 ssh->outgoing_data_size > MAX_DATA_BEFORE_REKEY)
1752 do_ssh2_transport(ssh, "Initiating key re-exchange "
1753 "(too much data sent)", -1, NULL);
1754 ssh->deferred_data_size = 0;
1758 * Send all queued SSH2 packets. We send them by means of
1759 * ssh2_pkt_defer_noqueue(), in case they included a pair of
1760 * packets that needed to be lumped together.
1762 static void ssh2_pkt_queuesend(Ssh ssh)
1766 assert(!ssh->queueing);
1768 for (i = 0; i < ssh->queuelen; i++)
1769 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i]);
1772 ssh_pkt_defersend(ssh);
1776 void bndebug(char *string, Bignum b)
1780 p = ssh2_mpint_fmt(b, &len);
1781 debug(("%s", string));
1782 for (i = 0; i < len; i++)
1783 debug((" %02x", p[i]));
1789 static void sha_mpint(SHA_State * s, Bignum b)
1793 p = ssh2_mpint_fmt(b, &len);
1794 sha_string(s, p, len);
1799 * Packet decode functions for both SSH1 and SSH2.
1801 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
1803 unsigned long value;
1804 if (pkt->length - pkt->savedpos < 4)
1805 return 0; /* arrgh, no way to decline (FIXME?) */
1806 value = GET_32BIT(pkt->body + pkt->savedpos);
1810 static int ssh2_pkt_getbool(struct Packet *pkt)
1812 unsigned long value;
1813 if (pkt->length - pkt->savedpos < 1)
1814 return 0; /* arrgh, no way to decline (FIXME?) */
1815 value = pkt->body[pkt->savedpos] != 0;
1819 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
1824 if (pkt->length - pkt->savedpos < 4)
1826 len = GET_32BIT(pkt->body + pkt->savedpos);
1831 if (pkt->length - pkt->savedpos < *length)
1833 *p = (char *)(pkt->body + pkt->savedpos);
1834 pkt->savedpos += *length;
1836 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
1838 if (pkt->length - pkt->savedpos < length)
1840 pkt->savedpos += length;
1841 return pkt->body + (pkt->savedpos - length);
1843 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
1844 unsigned char **keystr)
1848 j = makekey(pkt->body + pkt->savedpos,
1849 pkt->length - pkt->savedpos,
1856 assert(pkt->savedpos < pkt->length);
1860 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
1865 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
1866 pkt->length - pkt->savedpos, &b);
1874 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
1880 ssh_pkt_getstring(pkt, &p, &length);
1885 b = bignum_from_bytes((unsigned char *)p, length);
1890 * Helper function to add an SSH2 signature blob to a packet.
1891 * Expects to be shown the public key blob as well as the signature
1892 * blob. Normally works just like ssh2_pkt_addstring, but will
1893 * fiddle with the signature packet if necessary for
1894 * BUG_SSH2_RSA_PADDING.
1896 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
1897 void *pkblob_v, int pkblob_len,
1898 void *sigblob_v, int sigblob_len)
1900 unsigned char *pkblob = (unsigned char *)pkblob_v;
1901 unsigned char *sigblob = (unsigned char *)sigblob_v;
1903 /* dmemdump(pkblob, pkblob_len); */
1904 /* dmemdump(sigblob, sigblob_len); */
1907 * See if this is in fact an ssh-rsa signature and a buggy
1908 * server; otherwise we can just do this the easy way.
1910 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) &&
1911 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
1912 int pos, len, siglen;
1915 * Find the byte length of the modulus.
1918 pos = 4+7; /* skip over "ssh-rsa" */
1919 pos += 4 + GET_32BIT(pkblob+pos); /* skip over exponent */
1920 len = GET_32BIT(pkblob+pos); /* find length of modulus */
1921 pos += 4; /* find modulus itself */
1922 while (len > 0 && pkblob[pos] == 0)
1924 /* debug(("modulus length is %d\n", len)); */
1927 * Now find the signature integer.
1929 pos = 4+7; /* skip over "ssh-rsa" */
1930 siglen = GET_32BIT(sigblob+pos);
1931 /* debug(("signature length is %d\n", siglen)); */
1933 if (len != siglen) {
1934 unsigned char newlen[4];
1935 ssh2_pkt_addstring_start(pkt);
1936 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
1937 /* dmemdump(sigblob, pos); */
1938 pos += 4; /* point to start of actual sig */
1939 PUT_32BIT(newlen, len);
1940 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
1941 /* dmemdump(newlen, 4); */
1943 while (len-- > siglen) {
1944 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
1945 /* dmemdump(newlen, 1); */
1947 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
1948 /* dmemdump(sigblob+pos, siglen); */
1952 /* Otherwise fall through and do it the easy way. */
1955 ssh2_pkt_addstring_start(pkt);
1956 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
1960 * Examine the remote side's version string and compare it against
1961 * a list of known buggy implementations.
1963 static void ssh_detect_bugs(Ssh ssh, char *vstring)
1965 char *imp; /* pointer to implementation part */
1967 imp += strcspn(imp, "-");
1969 imp += strcspn(imp, "-");
1972 ssh->remote_bugs = 0;
1974 if (ssh->cfg.sshbug_ignore1 == FORCE_ON ||
1975 (ssh->cfg.sshbug_ignore1 == AUTO &&
1976 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
1977 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
1978 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
1979 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
1981 * These versions don't support SSH1_MSG_IGNORE, so we have
1982 * to use a different defence against password length
1985 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
1986 logevent("We believe remote version has SSH1 ignore bug");
1989 if (ssh->cfg.sshbug_plainpw1 == FORCE_ON ||
1990 (ssh->cfg.sshbug_plainpw1 == AUTO &&
1991 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
1993 * These versions need a plain password sent; they can't
1994 * handle having a null and a random length of data after
1997 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
1998 logevent("We believe remote version needs a plain SSH1 password");
2001 if (ssh->cfg.sshbug_rsa1 == FORCE_ON ||
2002 (ssh->cfg.sshbug_rsa1 == AUTO &&
2003 (!strcmp(imp, "Cisco-1.25")))) {
2005 * These versions apparently have no clue whatever about
2006 * RSA authentication and will panic and die if they see
2007 * an AUTH_RSA message.
2009 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2010 logevent("We believe remote version can't handle RSA authentication");
2013 if (ssh->cfg.sshbug_hmac2 == FORCE_ON ||
2014 (ssh->cfg.sshbug_hmac2 == AUTO &&
2015 !wc_match("* VShell", imp) &&
2016 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2017 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2018 wc_match("2.1 *", imp)))) {
2020 * These versions have the HMAC bug.
2022 ssh->remote_bugs |= BUG_SSH2_HMAC;
2023 logevent("We believe remote version has SSH2 HMAC bug");
2026 if (ssh->cfg.sshbug_derivekey2 == FORCE_ON ||
2027 (ssh->cfg.sshbug_derivekey2 == AUTO &&
2028 !wc_match("* VShell", imp) &&
2029 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2031 * These versions have the key-derivation bug (failing to
2032 * include the literal shared secret in the hashes that
2033 * generate the keys).
2035 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2036 logevent("We believe remote version has SSH2 key-derivation bug");
2039 if (ssh->cfg.sshbug_rsapad2 == FORCE_ON ||
2040 (ssh->cfg.sshbug_rsapad2 == AUTO &&
2041 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2042 wc_match("OpenSSH_3.[0-2]*", imp)))) {
2044 * These versions have the SSH2 RSA padding bug.
2046 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2047 logevent("We believe remote version has SSH2 RSA padding bug");
2050 if (ssh->cfg.sshbug_pksessid2 == FORCE_ON ||
2051 (ssh->cfg.sshbug_pksessid2 == AUTO &&
2052 wc_match("OpenSSH_2.[0-2]*", imp))) {
2054 * These versions have the SSH2 session-ID bug in
2055 * public-key authentication.
2057 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2058 logevent("We believe remote version has SSH2 public-key-session-ID bug");
2061 if (ssh->cfg.sshbug_dhgex2 == FORCE_ON) {
2063 * User specified the SSH2 DH GEX bug.
2065 ssh->remote_bugs |= BUG_SSH2_DH_GEX;
2066 logevent("We believe remote version has SSH2 DH group exchange bug");
2070 static int do_ssh_init(Ssh ssh, unsigned char c)
2072 struct do_ssh_init_state {
2080 crState(do_ssh_init_state);
2082 crBegin(ssh->do_ssh_init_crstate);
2084 /* Search for the string "SSH-" in the input. */
2087 static const int transS[] = { 1, 2, 2, 1 };
2088 static const int transH[] = { 0, 0, 3, 0 };
2089 static const int transminus[] = { 0, 0, 0, -1 };
2091 s->i = transS[s->i];
2093 s->i = transH[s->i];
2095 s->i = transminus[s->i];
2100 crReturn(1); /* get another character */
2104 s->vstring = snewn(s->vstrsize, char);
2105 strcpy(s->vstring, "SSH-");
2109 crReturn(1); /* get another char */
2110 if (s->vslen >= s->vstrsize - 1) {
2112 s->vstring = sresize(s->vstring, s->vstrsize, char);
2114 s->vstring[s->vslen++] = c;
2117 s->version[s->i] = '\0';
2119 } else if (s->i < sizeof(s->version) - 1)
2120 s->version[s->i++] = c;
2121 } else if (c == '\012')
2125 ssh->agentfwd_enabled = FALSE;
2126 ssh->rdpkt2_state.incoming_sequence = 0;
2128 s->vstring[s->vslen] = 0;
2129 s->vstring[strcspn(s->vstring, "\r\n")] = '\0';/* remove EOL chars */
2132 vlog = snewn(20 + s->vslen, char);
2133 sprintf(vlog, "Server version: %s", s->vstring);
2137 ssh_detect_bugs(ssh, s->vstring);
2140 * Decide which SSH protocol version to support.
2143 /* Anything strictly below "2.0" means protocol 1 is supported. */
2144 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
2145 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2146 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
2148 if (ssh->cfg.sshprot == 0 && !s->proto1) {
2149 bombout(("SSH protocol version 1 required by user but not provided by server"));
2152 if (ssh->cfg.sshprot == 3 && !s->proto2) {
2153 bombout(("SSH protocol version 2 required by user but not provided by server"));
2157 if (s->proto2 && (ssh->cfg.sshprot >= 2 || !s->proto1)) {
2161 char verstring[80], vlog[100];
2162 sprintf(verstring, "SSH-2.0-%s", sshver);
2163 SHA_Init(&ssh->exhashbase);
2165 * Hash our version string and their version string.
2167 sha_string(&ssh->exhashbase, verstring, strlen(verstring));
2168 sha_string(&ssh->exhashbase, s->vstring, strcspn(s->vstring, "\r\n"));
2169 sprintf(vlog, "We claim version: %s", verstring);
2171 strcat(verstring, "\012");
2172 logevent("Using SSH protocol version 2");
2173 sk_write(ssh->s, verstring, strlen(verstring));
2174 ssh->protocol = ssh2_protocol;
2175 ssh2_protocol_setup(ssh);
2177 ssh->s_rdpkt = ssh2_rdpkt;
2182 char verstring[80], vlog[100];
2183 sprintf(verstring, "SSH-%s-%s",
2184 (ssh_versioncmp(s->version, "1.5") <= 0 ? s->version : "1.5"),
2186 sprintf(vlog, "We claim version: %s", verstring);
2188 strcat(verstring, "\012");
2190 logevent("Using SSH protocol version 1");
2191 sk_write(ssh->s, verstring, strlen(verstring));
2192 ssh->protocol = ssh1_protocol;
2193 ssh1_protocol_setup(ssh);
2195 ssh->s_rdpkt = ssh1_rdpkt;
2197 update_specials_menu(ssh->frontend);
2198 ssh->state = SSH_STATE_BEFORE_SIZE;
2199 ssh->pinger = pinger_new(&ssh->cfg, &ssh_backend, ssh);
2206 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
2208 crBegin(ssh->ssh_gotdata_crstate);
2211 * To begin with, feed the characters one by one to the
2212 * protocol initialisation / selection function do_ssh_init().
2213 * When that returns 0, we're done with the initial greeting
2214 * exchange and can move on to packet discipline.
2217 int ret; /* need not be kept across crReturn */
2219 crReturnV; /* more data please */
2220 ret = do_ssh_init(ssh, *data);
2228 * We emerge from that loop when the initial negotiation is
2229 * over and we have selected an s_rdpkt function. Now pass
2230 * everything to s_rdpkt, and then pass the resulting packets
2231 * to the proper protocol handler.
2236 while (datalen > 0) {
2237 struct Packet *pktin = ssh->s_rdpkt(ssh, &data, &datalen);
2239 ssh->protocol(ssh, NULL, 0, pktin);
2240 ssh_free_packet(pktin);
2242 if (ssh->state == SSH_STATE_CLOSED)
2250 static void ssh_do_close(Ssh ssh)
2253 struct ssh_channel *c;
2255 ssh->state = SSH_STATE_CLOSED;
2259 notify_remote_exit(ssh->frontend);
2262 * Now we must shut down any port and X forwardings going
2263 * through this connection.
2265 if (ssh->channels) {
2266 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
2269 x11_close(c->u.x11.s);
2272 pfd_close(c->u.pfd.s);
2275 del234(ssh->channels, c);
2276 if (ssh->version == 2)
2277 bufchain_clear(&c->v.v2.outbuffer);
2283 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
2286 Ssh ssh = (Ssh) plug;
2289 /* A socket error has occurred. */
2290 logevent(error_msg);
2291 connection_fatal(ssh->frontend, "%s", error_msg);
2293 /* Otherwise, the remote side closed the connection normally. */
2298 static int ssh_receive(Plug plug, int urgent, char *data, int len)
2300 Ssh ssh = (Ssh) plug;
2301 ssh_gotdata(ssh, (unsigned char *)data, len);
2302 if (ssh->state == SSH_STATE_CLOSED) {
2309 static void ssh_sent(Plug plug, int bufsize)
2311 Ssh ssh = (Ssh) plug;
2313 * If the send backlog on the SSH socket itself clears, we
2314 * should unthrottle the whole world if it was throttled.
2316 if (bufsize < SSH_MAX_BACKLOG)
2317 ssh_throttle_all(ssh, 0, bufsize);
2321 * Connect to specified host and port.
2322 * Returns an error message, or NULL on success.
2323 * Also places the canonical host name into `realhost'. It must be
2324 * freed by the caller.
2326 static const char *connect_to_host(Ssh ssh, char *host, int port,
2327 char **realhost, int nodelay, int keepalive)
2329 static const struct plug_function_table fn_table = {
2339 ssh->savedhost = snewn(1 + strlen(host), char);
2340 if (!ssh->savedhost)
2341 fatalbox("Out of memory");
2342 strcpy(ssh->savedhost, host);
2345 port = 22; /* default ssh port */
2346 ssh->savedport = port;
2351 logeventf(ssh, "Looking up host \"%s\"", host);
2352 addr = name_lookup(host, port, realhost, &ssh->cfg);
2353 if ((err = sk_addr_error(addr)) != NULL) {
2363 sk_getaddr(addr, addrbuf, 100);
2364 logeventf(ssh, "Connecting to %s port %d", addrbuf, port);
2366 ssh->fn = &fn_table;
2367 ssh->s = new_connection(addr, *realhost, port,
2368 0, 1, nodelay, keepalive, (Plug) ssh, &ssh->cfg);
2369 if ((err = sk_socket_error(ssh->s)) != NULL) {
2371 notify_remote_exit(ssh->frontend);
2379 * Throttle or unthrottle the SSH connection.
2381 static void ssh1_throttle(Ssh ssh, int adjust)
2383 int old_count = ssh->v1_throttle_count;
2384 ssh->v1_throttle_count += adjust;
2385 assert(ssh->v1_throttle_count >= 0);
2386 if (ssh->v1_throttle_count && !old_count) {
2387 sk_set_frozen(ssh->s, 1);
2388 } else if (!ssh->v1_throttle_count && old_count) {
2389 sk_set_frozen(ssh->s, 0);
2394 * Throttle or unthrottle _all_ local data streams (for when sends
2395 * on the SSH connection itself back up).
2397 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
2400 struct ssh_channel *c;
2402 if (enable == ssh->throttled_all)
2404 ssh->throttled_all = enable;
2405 ssh->overall_bufsize = bufsize;
2408 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
2410 case CHAN_MAINSESSION:
2412 * This is treated separately, outside the switch.
2416 x11_override_throttle(c->u.x11.s, enable);
2419 /* Agent channels require no buffer management. */
2422 pfd_override_throttle(c->u.pfd.s, enable);
2429 * Username and password input, abstracted off into routines
2430 * reusable in several places - even between SSH1 and SSH2.
2433 /* Set up a username or password input loop on a given buffer. */
2434 static void setup_userpass_input(Ssh ssh, char *buffer, int buflen, int echo)
2436 ssh->userpass_input_buffer = buffer;
2437 ssh->userpass_input_buflen = buflen;
2438 ssh->userpass_input_bufpos = 0;
2439 ssh->userpass_input_echo = echo;
2443 * Process some terminal data in the course of username/password
2444 * input. Returns >0 for success (line of input returned in
2445 * buffer), <0 for failure (user hit ^C/^D, bomb out and exit), 0
2446 * for inconclusive (keep waiting for more input please).
2448 static int process_userpass_input(Ssh ssh, unsigned char *in, int inlen)
2453 switch (c = *in++) {
2456 ssh->userpass_input_buffer[ssh->userpass_input_bufpos] = 0;
2457 ssh->userpass_input_buffer[ssh->userpass_input_buflen-1] = 0;
2462 if (ssh->userpass_input_bufpos > 0) {
2463 if (ssh->userpass_input_echo)
2464 c_write_str(ssh, "\b \b");
2465 ssh->userpass_input_bufpos--;
2470 while (ssh->userpass_input_bufpos > 0) {
2471 if (ssh->userpass_input_echo)
2472 c_write_str(ssh, "\b \b");
2473 ssh->userpass_input_bufpos--;
2482 * This simplistic check for printability is disabled
2483 * when we're doing password input, because some people
2484 * have control characters in their passwords.o
2486 if ((!ssh->userpass_input_echo ||
2487 (c >= ' ' && c <= '~') ||
2488 ((unsigned char) c >= 160))
2489 && ssh->userpass_input_bufpos < ssh->userpass_input_buflen-1) {
2490 ssh->userpass_input_buffer[ssh->userpass_input_bufpos++] = c;
2491 if (ssh->userpass_input_echo)
2492 c_write(ssh, &c, 1);
2500 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
2502 Ssh ssh = (Ssh) sshv;
2504 ssh->agent_response = reply;
2505 ssh->agent_response_len = replylen;
2507 if (ssh->version == 1)
2508 do_ssh1_login(ssh, NULL, -1, NULL);
2510 do_ssh2_authconn(ssh, NULL, -1, NULL);
2513 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
2515 struct ssh_channel *c = (struct ssh_channel *)cv;
2517 void *sentreply = reply;
2520 /* Fake SSH_AGENT_FAILURE. */
2521 sentreply = "\0\0\0\1\5";
2524 if (ssh->version == 2) {
2525 ssh2_add_channel_data(c, sentreply, replylen);
2528 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
2529 PKT_INT, c->remoteid,
2532 PKT_DATA, sentreply, replylen,
2541 * Handle the key exchange and user authentication phases.
2543 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
2544 struct Packet *pktin)
2547 unsigned char cookie[8], *ptr;
2548 struct RSAKey servkey, hostkey;
2549 struct MD5Context md5c;
2550 struct do_ssh1_login_state {
2552 unsigned char *rsabuf, *keystr1, *keystr2;
2553 unsigned long supported_ciphers_mask, supported_auths_mask;
2554 int tried_publickey, tried_agent;
2555 int tis_auth_refused, ccard_auth_refused;
2556 unsigned char session_id[16];
2559 void *publickey_blob;
2560 int publickey_bloblen;
2566 unsigned char request[5], *response, *p;
2575 crState(do_ssh1_login_state);
2577 crBegin(ssh->do_ssh1_login_crstate);
2584 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
2585 bombout(("Public key packet not received"));
2589 logevent("Received public keys");
2591 ptr = ssh_pkt_getdata(pktin, 8);
2593 bombout(("SSH1 public key packet stopped before random cookie"));
2596 memcpy(cookie, ptr, 8);
2598 if (!ssh1_pkt_getrsakey(pktin, &servkey, &s->keystr1) ||
2599 !ssh1_pkt_getrsakey(pktin, &hostkey, &s->keystr2)) {
2600 bombout(("Failed to read SSH1 public keys from public key packet"));
2605 * Log the host key fingerprint.
2609 logevent("Host key fingerprint is:");
2610 strcpy(logmsg, " ");
2611 hostkey.comment = NULL;
2612 rsa_fingerprint(logmsg + strlen(logmsg),
2613 sizeof(logmsg) - strlen(logmsg), &hostkey);
2617 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
2618 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
2619 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
2621 ssh->v1_local_protoflags =
2622 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
2623 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
2626 MD5Update(&md5c, s->keystr2, hostkey.bytes);
2627 MD5Update(&md5c, s->keystr1, servkey.bytes);
2628 MD5Update(&md5c, cookie, 8);
2629 MD5Final(s->session_id, &md5c);
2631 for (i = 0; i < 32; i++)
2632 ssh->session_key[i] = random_byte();
2635 * Verify that the `bits' and `bytes' parameters match.
2637 if (hostkey.bits > hostkey.bytes * 8 ||
2638 servkey.bits > servkey.bytes * 8) {
2639 bombout(("SSH1 public keys were badly formatted"));
2643 s->len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
2645 s->rsabuf = snewn(s->len, unsigned char);
2647 fatalbox("Out of memory");
2650 * Verify the host key.
2654 * First format the key into a string.
2656 int len = rsastr_len(&hostkey);
2657 char fingerprint[100];
2658 char *keystr = snewn(len, char);
2660 fatalbox("Out of memory");
2661 rsastr_fmt(keystr, &hostkey);
2662 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
2663 verify_ssh_host_key(ssh->frontend,
2664 ssh->savedhost, ssh->savedport, "rsa", keystr,
2669 for (i = 0; i < 32; i++) {
2670 s->rsabuf[i] = ssh->session_key[i];
2672 s->rsabuf[i] ^= s->session_id[i];
2675 if (hostkey.bytes > servkey.bytes) {
2676 ret = rsaencrypt(s->rsabuf, 32, &servkey);
2678 ret = rsaencrypt(s->rsabuf, servkey.bytes, &hostkey);
2680 ret = rsaencrypt(s->rsabuf, 32, &hostkey);
2682 ret = rsaencrypt(s->rsabuf, hostkey.bytes, &servkey);
2685 bombout(("SSH1 public key encryptions failed due to bad formatting"));
2689 logevent("Encrypted session key");
2692 int cipher_chosen = 0, warn = 0;
2693 char *cipher_string = NULL;
2695 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
2696 int next_cipher = ssh->cfg.ssh_cipherlist[i];
2697 if (next_cipher == CIPHER_WARN) {
2698 /* If/when we choose a cipher, warn about it */
2700 } else if (next_cipher == CIPHER_AES) {
2701 /* XXX Probably don't need to mention this. */
2702 logevent("AES not supported in SSH1, skipping");
2704 switch (next_cipher) {
2705 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
2706 cipher_string = "3DES"; break;
2707 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
2708 cipher_string = "Blowfish"; break;
2709 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
2710 cipher_string = "single-DES"; break;
2712 if (s->supported_ciphers_mask & (1 << s->cipher_type))
2716 if (!cipher_chosen) {
2717 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
2718 bombout(("Server violates SSH 1 protocol by not "
2719 "supporting 3DES encryption"));
2721 /* shouldn't happen */
2722 bombout(("No supported ciphers found"));
2726 /* Warn about chosen cipher if necessary. */
2728 askcipher(ssh->frontend, cipher_string, 0);
2731 switch (s->cipher_type) {
2732 case SSH_CIPHER_3DES:
2733 logevent("Using 3DES encryption");
2735 case SSH_CIPHER_DES:
2736 logevent("Using single-DES encryption");
2738 case SSH_CIPHER_BLOWFISH:
2739 logevent("Using Blowfish encryption");
2743 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
2744 PKT_CHAR, s->cipher_type,
2745 PKT_DATA, cookie, 8,
2746 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
2747 PKT_DATA, s->rsabuf, s->len,
2748 PKT_INT, ssh->v1_local_protoflags, PKT_END);
2750 logevent("Trying to enable encryption...");
2754 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
2755 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
2757 ssh->v1_cipher_ctx = ssh->cipher->make_context();
2758 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
2759 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
2761 ssh->crcda_ctx = crcda_make_context();
2762 logevent("Installing CRC compensation attack detector");
2764 if (servkey.modulus) {
2765 sfree(servkey.modulus);
2766 servkey.modulus = NULL;
2768 if (servkey.exponent) {
2769 sfree(servkey.exponent);
2770 servkey.exponent = NULL;
2772 if (hostkey.modulus) {
2773 sfree(hostkey.modulus);
2774 hostkey.modulus = NULL;
2776 if (hostkey.exponent) {
2777 sfree(hostkey.exponent);
2778 hostkey.exponent = NULL;
2782 if (pktin->type != SSH1_SMSG_SUCCESS) {
2783 bombout(("Encryption not successfully enabled"));
2787 logevent("Successfully started encryption");
2791 if (!*ssh->cfg.username) {
2792 if (ssh_get_line && !ssh_getline_pw_only) {
2793 if (!ssh_get_line("login as: ",
2794 s->username, sizeof(s->username), FALSE)) {
2796 * get_line failed to get a username.
2799 logevent("No username provided. Abandoning session.");
2800 ssh_closing((Plug)ssh, NULL, 0, 0);
2804 int ret; /* need not be kept over crReturn */
2805 c_write_str(ssh, "login as: ");
2808 setup_userpass_input(ssh, s->username, sizeof(s->username), 1);
2810 crWaitUntil(!pktin);
2811 ret = process_userpass_input(ssh, in, inlen);
2815 c_write_str(ssh, "\r\n");
2818 strncpy(s->username, ssh->cfg.username, sizeof(s->username));
2819 s->username[sizeof(s->username)-1] = '\0';
2822 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, s->username, PKT_END);
2824 char userlog[22 + sizeof(s->username)];
2825 sprintf(userlog, "Sent username \"%s\"", s->username);
2827 if (flags & FLAG_INTERACTIVE &&
2828 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
2829 strcat(userlog, "\r\n");
2830 c_write_str(ssh, userlog);
2837 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA)) {
2838 /* We must not attempt PK auth. Pretend we've already tried it. */
2839 s->tried_publickey = s->tried_agent = 1;
2841 s->tried_publickey = s->tried_agent = 0;
2843 s->tis_auth_refused = s->ccard_auth_refused = 0;
2844 /* Load the public half of ssh->cfg.keyfile so we notice if it's in Pageant */
2845 if (!filename_is_null(ssh->cfg.keyfile)) {
2846 if (!rsakey_pubblob(&ssh->cfg.keyfile,
2847 &s->publickey_blob, &s->publickey_bloblen, NULL))
2848 s->publickey_blob = NULL;
2850 s->publickey_blob = NULL;
2852 while (pktin->type == SSH1_SMSG_FAILURE) {
2853 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
2855 if (agent_exists() && !s->tried_agent) {
2857 * Attempt RSA authentication using Pageant.
2863 logevent("Pageant is running. Requesting keys.");
2865 /* Request the keys held by the agent. */
2866 PUT_32BIT(s->request, 1);
2867 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
2868 if (!agent_query(s->request, 5, &r, &s->responselen,
2869 ssh_agent_callback, ssh)) {
2873 bombout(("Unexpected data from server while waiting"
2874 " for agent response"));
2877 } while (pktin || inlen > 0);
2878 r = ssh->agent_response;
2879 s->responselen = ssh->agent_response_len;
2881 s->response = (unsigned char *) r;
2882 if (s->response && s->responselen >= 5 &&
2883 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
2884 s->p = s->response + 5;
2885 s->nkeys = GET_32BIT(s->p);
2889 sprintf(buf, "Pageant has %d SSH1 keys", s->nkeys);
2892 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
2895 sprintf(buf, "Trying Pageant key #%d", s->keyi);
2898 if (s->publickey_blob &&
2899 !memcmp(s->p, s->publickey_blob,
2900 s->publickey_bloblen)) {
2901 logevent("This key matches configured key file");
2902 s->tried_publickey = 1;
2907 do { /* do while (0) to make breaking easy */
2908 n = ssh1_read_bignum
2909 (s->p, s->responselen-(s->p-s->response),
2914 n = ssh1_read_bignum
2915 (s->p, s->responselen-(s->p-s->response),
2920 if (s->responselen - (s->p-s->response) < 4)
2922 s->commentlen = GET_32BIT(s->p);
2924 if (s->responselen - (s->p-s->response) <
2927 s->commentp = (char *)s->p;
2928 s->p += s->commentlen;
2932 logevent("Pageant key list packet was truncated");
2936 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
2937 PKT_BIGNUM, s->key.modulus, PKT_END);
2939 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
2940 logevent("Key refused");
2943 logevent("Received RSA challenge");
2944 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
2945 bombout(("Server's RSA challenge was badly formatted"));
2950 char *agentreq, *q, *ret;
2953 len = 1 + 4; /* message type, bit count */
2954 len += ssh1_bignum_length(s->key.exponent);
2955 len += ssh1_bignum_length(s->key.modulus);
2956 len += ssh1_bignum_length(s->challenge);
2957 len += 16; /* session id */
2958 len += 4; /* response format */
2959 agentreq = snewn(4 + len, char);
2960 PUT_32BIT(agentreq, len);
2962 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
2963 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
2965 q += ssh1_write_bignum(q, s->key.exponent);
2966 q += ssh1_write_bignum(q, s->key.modulus);
2967 q += ssh1_write_bignum(q, s->challenge);
2968 memcpy(q, s->session_id, 16);
2970 PUT_32BIT(q, 1); /* response format */
2971 if (!agent_query(agentreq, len + 4, &vret, &retlen,
2972 ssh_agent_callback, ssh)) {
2977 bombout(("Unexpected data from server"
2978 " while waiting for agent"
2982 } while (pktin || inlen > 0);
2983 vret = ssh->agent_response;
2984 retlen = ssh->agent_response_len;
2989 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
2990 logevent("Sending Pageant's response");
2991 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
2992 PKT_DATA, ret + 5, 16,
2996 if (pktin->type == SSH1_SMSG_SUCCESS) {
2998 ("Pageant's response accepted");
2999 if (flags & FLAG_VERBOSE) {
3000 c_write_str(ssh, "Authenticated using"
3002 c_write(ssh, s->commentp,
3004 c_write_str(ssh, "\" from agent\r\n");
3009 ("Pageant's response not accepted");
3012 ("Pageant failed to answer challenge");
3016 logevent("No reply received from Pageant");
3019 freebn(s->key.exponent);
3020 freebn(s->key.modulus);
3021 freebn(s->challenge);
3030 if (!filename_is_null(ssh->cfg.keyfile) && !s->tried_publickey)
3031 s->pwpkt_type = SSH1_CMSG_AUTH_RSA;
3033 if (ssh->cfg.try_tis_auth &&
3034 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
3035 !s->tis_auth_refused) {
3036 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
3037 logevent("Requested TIS authentication");
3038 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
3040 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
3041 logevent("TIS authentication declined");
3042 if (flags & FLAG_INTERACTIVE)
3043 c_write_str(ssh, "TIS authentication refused.\r\n");
3044 s->tis_auth_refused = 1;
3050 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3052 bombout(("TIS challenge packet was badly formed"));
3055 logevent("Received TIS challenge");
3056 if (challengelen > sizeof(s->prompt) - 1)
3057 challengelen = sizeof(s->prompt) - 1;/* prevent overrun */
3058 memcpy(s->prompt, challenge, challengelen);
3059 /* Prompt heuristic comes from OpenSSH */
3060 strncpy(s->prompt + challengelen,
3061 memchr(s->prompt, '\n', challengelen) ?
3062 "": "\r\nResponse: ",
3063 (sizeof s->prompt) - challengelen);
3064 s->prompt[(sizeof s->prompt) - 1] = '\0';
3067 if (ssh->cfg.try_tis_auth &&
3068 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
3069 !s->ccard_auth_refused) {
3070 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
3071 logevent("Requested CryptoCard authentication");
3072 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
3074 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
3075 logevent("CryptoCard authentication declined");
3076 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
3077 s->ccard_auth_refused = 1;
3083 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3085 bombout(("CryptoCard challenge packet was badly formed"));
3088 logevent("Received CryptoCard challenge");
3089 if (challengelen > sizeof(s->prompt) - 1)
3090 challengelen = sizeof(s->prompt) - 1;/* prevent overrun */
3091 memcpy(s->prompt, challenge, challengelen);
3092 strncpy(s->prompt + challengelen,
3093 memchr(s->prompt, '\n', challengelen) ?
3094 "" : "\r\nResponse: ",
3095 sizeof(s->prompt) - challengelen);
3096 s->prompt[sizeof(s->prompt) - 1] = '\0';
3099 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
3100 sprintf(s->prompt, "%.90s@%.90s's password: ",
3101 s->username, ssh->savedhost);
3103 if (s->pwpkt_type == SSH1_CMSG_AUTH_RSA) {
3104 char *comment = NULL;
3107 if (flags & FLAG_VERBOSE)
3108 c_write_str(ssh, "Trying public key authentication.\r\n");
3109 logeventf(ssh, "Trying public key \"%s\"",
3110 filename_to_str(&ssh->cfg.keyfile));
3111 type = key_type(&ssh->cfg.keyfile);
3112 if (type != SSH_KEYTYPE_SSH1) {
3113 sprintf(msgbuf, "Key is of wrong type (%s)",
3114 key_type_to_str(type));
3116 c_write_str(ssh, msgbuf);
3117 c_write_str(ssh, "\r\n");
3118 s->tried_publickey = 1;
3121 if (!rsakey_encrypted(&ssh->cfg.keyfile, &comment)) {
3122 if (flags & FLAG_VERBOSE)
3123 c_write_str(ssh, "No passphrase required.\r\n");
3126 sprintf(s->prompt, "Passphrase for key \"%.100s\": ", comment);
3131 * Show password prompt, having first obtained it via a TIS
3132 * or CryptoCard exchange if we're doing TIS or CryptoCard
3136 if (!ssh_get_line(s->prompt, s->password,
3137 sizeof(s->password), TRUE)) {
3139 * get_line failed to get a password (for example
3140 * because one was supplied on the command line
3141 * which has already failed to work). Terminate.
3143 send_packet(ssh, SSH1_MSG_DISCONNECT,
3144 PKT_STR, "No more passwords available to try",
3146 logevent("Unable to authenticate");
3147 connection_fatal(ssh->frontend, "Unable to authenticate");
3148 ssh_closing((Plug)ssh, NULL, 0, 0);
3152 /* Prompt may have come from server. We've munged it a bit, so
3153 * we know it to be zero-terminated at least once. */
3154 int ret; /* need not be saved over crReturn */
3155 c_write_untrusted(ssh, s->prompt, strlen(s->prompt));
3158 setup_userpass_input(ssh, s->password, sizeof(s->password), 0);
3160 crWaitUntil(!pktin);
3161 ret = process_userpass_input(ssh, in, inlen);
3165 c_write_str(ssh, "\r\n");
3169 if (s->pwpkt_type == SSH1_CMSG_AUTH_RSA) {
3171 * Try public key authentication with the specified
3174 s->tried_publickey = 1;
3177 const char *error = NULL;
3178 int ret = loadrsakey(&ssh->cfg.keyfile, &s->key, s->password,
3181 c_write_str(ssh, "Couldn't load private key from ");
3182 c_write_str(ssh, filename_to_str(&ssh->cfg.keyfile));
3183 c_write_str(ssh, " (");
3184 c_write_str(ssh, error);
3185 c_write_str(ssh, ").\r\n");
3186 continue; /* go and try password */
3189 c_write_str(ssh, "Wrong passphrase.\r\n");
3190 s->tried_publickey = 0;
3191 continue; /* try again */
3196 * Send a public key attempt.
3198 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3199 PKT_BIGNUM, s->key.modulus, PKT_END);
3202 if (pktin->type == SSH1_SMSG_FAILURE) {
3203 c_write_str(ssh, "Server refused our public key.\r\n");
3204 continue; /* go and try password */
3206 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3207 bombout(("Bizarre response to offer of public key"));
3213 unsigned char buffer[32];
3214 Bignum challenge, response;
3216 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3217 bombout(("Server's RSA challenge was badly formatted"));
3220 response = rsadecrypt(challenge, &s->key);
3221 freebn(s->key.private_exponent);/* burn the evidence */
3223 for (i = 0; i < 32; i++) {
3224 buffer[i] = bignum_byte(response, 31 - i);
3228 MD5Update(&md5c, buffer, 32);
3229 MD5Update(&md5c, s->session_id, 16);
3230 MD5Final(buffer, &md5c);
3232 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3233 PKT_DATA, buffer, 16, PKT_END);
3240 if (pktin->type == SSH1_SMSG_FAILURE) {
3241 if (flags & FLAG_VERBOSE)
3242 c_write_str(ssh, "Failed to authenticate with"
3243 " our public key.\r\n");
3244 continue; /* go and try password */
3245 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
3246 bombout(("Bizarre response to RSA authentication response"));
3250 break; /* we're through! */
3252 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
3254 * Defence against traffic analysis: we send a
3255 * whole bunch of packets containing strings of
3256 * different lengths. One of these strings is the
3257 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
3258 * The others are all random data in
3259 * SSH1_MSG_IGNORE packets. This way a passive
3260 * listener can't tell which is the password, and
3261 * hence can't deduce the password length.
3263 * Anybody with a password length greater than 16
3264 * bytes is going to have enough entropy in their
3265 * password that a listener won't find it _that_
3266 * much help to know how long it is. So what we'll
3269 * - if password length < 16, we send 15 packets
3270 * containing string lengths 1 through 15
3272 * - otherwise, we let N be the nearest multiple
3273 * of 8 below the password length, and send 8
3274 * packets containing string lengths N through
3275 * N+7. This won't obscure the order of
3276 * magnitude of the password length, but it will
3277 * introduce a bit of extra uncertainty.
3279 * A few servers (the old 1.2.18 through 1.2.22)
3280 * can't deal with SSH1_MSG_IGNORE. For these
3281 * servers, we need an alternative defence. We make
3282 * use of the fact that the password is interpreted
3283 * as a C string: so we can append a NUL, then some
3286 * One server (a Cisco one) can deal with neither
3287 * SSH1_MSG_IGNORE _nor_ a padded password string.
3288 * For this server we are left with no defences
3289 * against password length sniffing.
3291 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE)) {
3293 * The server can deal with SSH1_MSG_IGNORE, so
3294 * we can use the primary defence.
3296 int bottom, top, pwlen, i;
3299 pwlen = strlen(s->password);
3301 bottom = 0; /* zero length passwords are OK! :-) */
3304 bottom = pwlen & ~7;
3308 assert(pwlen >= bottom && pwlen <= top);
3310 randomstr = snewn(top + 1, char);
3312 for (i = bottom; i <= top; i++) {
3314 defer_packet(ssh, s->pwpkt_type,
3315 PKTT_PASSWORD, PKT_STR, s->password,
3316 PKTT_OTHER, PKT_END);
3318 for (j = 0; j < i; j++) {
3320 randomstr[j] = random_byte();
3321 } while (randomstr[j] == '\0');
3323 randomstr[i] = '\0';
3324 defer_packet(ssh, SSH1_MSG_IGNORE,
3325 PKT_STR, randomstr, PKT_END);
3328 logevent("Sending password with camouflage packets");
3329 ssh_pkt_defersend(ssh);
3332 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
3334 * The server can't deal with SSH1_MSG_IGNORE
3335 * but can deal with padded passwords, so we
3336 * can use the secondary defence.
3342 len = strlen(s->password);
3343 if (len < sizeof(string)) {
3345 strcpy(string, s->password);
3346 len++; /* cover the zero byte */
3347 while (len < sizeof(string)) {
3348 string[len++] = (char) random_byte();
3353 logevent("Sending length-padded password");
3354 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
3355 PKT_INT, len, PKT_DATA, ss, len,
3356 PKTT_OTHER, PKT_END);
3359 * The server has _both_
3360 * BUG_CHOKES_ON_SSH1_IGNORE and
3361 * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
3362 * therefore nothing we can do.
3365 len = strlen(s->password);
3366 logevent("Sending unpadded password");
3367 send_packet(ssh, s->pwpkt_type,
3368 PKTT_PASSWORD, PKT_INT, len,
3369 PKT_DATA, s->password, len,
3370 PKTT_OTHER, PKT_END);
3373 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
3374 PKT_STR, s->password, PKTT_OTHER, PKT_END);
3377 logevent("Sent password");
3378 memset(s->password, 0, strlen(s->password));
3380 if (pktin->type == SSH1_SMSG_FAILURE) {
3381 if (flags & FLAG_VERBOSE)
3382 c_write_str(ssh, "Access denied\r\n");
3383 logevent("Authentication refused");
3384 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
3385 bombout(("Strange packet received, type %d", pktin->type));
3390 logevent("Authentication successful");
3395 void sshfwd_close(struct ssh_channel *c)
3399 if (ssh->state != SSH_STATE_SESSION) {
3400 assert(ssh->state == SSH_STATE_CLOSED);
3404 if (c && !c->closes) {
3406 * If the channel's remoteid is -1, we have sent
3407 * CHANNEL_OPEN for this channel, but it hasn't even been
3408 * acknowledged by the server. So we must set a close flag
3409 * on it now, and then when the server acks the channel
3410 * open, we can close it then.
3412 if (((int)c->remoteid) != -1) {
3413 if (ssh->version == 1) {
3414 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
3417 struct Packet *pktout;
3418 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
3419 ssh2_pkt_adduint32(pktout, c->remoteid);
3420 ssh2_pkt_send(ssh, pktout);
3423 c->closes = 1; /* sent MSG_CLOSE */
3424 if (c->type == CHAN_X11) {
3426 logevent("Forwarded X11 connection terminated");
3427 } else if (c->type == CHAN_SOCKDATA ||
3428 c->type == CHAN_SOCKDATA_DORMANT) {
3430 logevent("Forwarded port closed");
3435 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
3439 if (ssh->state != SSH_STATE_SESSION) {
3440 assert(ssh->state == SSH_STATE_CLOSED);
3444 if (ssh->version == 1) {
3445 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3446 PKT_INT, c->remoteid,
3448 PKT_INT, len, PKT_DATA, buf, len,
3449 PKTT_OTHER, PKT_END);
3451 * In SSH1 we can return 0 here - implying that forwarded
3452 * connections are never individually throttled - because
3453 * the only circumstance that can cause throttling will be
3454 * the whole SSH connection backing up, in which case
3455 * _everything_ will be throttled as a whole.
3459 ssh2_add_channel_data(c, buf, len);
3460 return ssh2_try_send(c);
3464 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
3468 if (ssh->state != SSH_STATE_SESSION) {
3469 assert(ssh->state == SSH_STATE_CLOSED);
3473 if (ssh->version == 1) {
3474 if (c->v.v1.throttling && bufsize < SSH1_BUFFER_LIMIT) {
3475 c->v.v1.throttling = 0;
3476 ssh1_throttle(ssh, -1);
3479 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
3483 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
3486 int stringlen, bufsize;
3488 ssh_pkt_getstring(pktin, &string, &stringlen);
3489 if (string == NULL) {
3490 bombout(("Incoming terminal data packet was badly formed"));
3494 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
3496 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
3497 ssh->v1_stdout_throttling = 1;
3498 ssh1_throttle(ssh, +1);
3502 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
3504 /* Remote side is trying to open a channel to talk to our
3505 * X-Server. Give them back a local channel number. */
3506 struct ssh_channel *c;
3507 int remoteid = ssh_pkt_getuint32(pktin);
3509 logevent("Received X11 connect request");
3510 /* Refuse if X11 forwarding is disabled. */
3511 if (!ssh->X11_fwd_enabled) {
3512 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3513 PKT_INT, remoteid, PKT_END);
3514 logevent("Rejected X11 connect request");
3516 c = snew(struct ssh_channel);
3519 if (x11_init(&c->u.x11.s, ssh->cfg.x11_display, c,
3520 ssh->x11auth, NULL, -1, &ssh->cfg) != NULL) {
3521 logevent("Opening X11 forward connection failed");
3523 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3524 PKT_INT, remoteid, PKT_END);
3527 ("Opening X11 forward connection succeeded");
3528 c->remoteid = remoteid;
3529 c->localid = alloc_channel_id(ssh);
3531 c->v.v1.throttling = 0;
3532 c->type = CHAN_X11; /* identify channel type */
3533 add234(ssh->channels, c);
3534 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3535 PKT_INT, c->remoteid, PKT_INT,
3536 c->localid, PKT_END);
3537 logevent("Opened X11 forward channel");
3542 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
3544 /* Remote side is trying to open a channel to talk to our
3545 * agent. Give them back a local channel number. */
3546 struct ssh_channel *c;
3547 int remoteid = ssh_pkt_getuint32(pktin);
3549 /* Refuse if agent forwarding is disabled. */
3550 if (!ssh->agentfwd_enabled) {
3551 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3552 PKT_INT, remoteid, PKT_END);
3554 c = snew(struct ssh_channel);
3556 c->remoteid = remoteid;
3557 c->localid = alloc_channel_id(ssh);
3559 c->v.v1.throttling = 0;
3560 c->type = CHAN_AGENT; /* identify channel type */
3561 c->u.a.lensofar = 0;
3562 add234(ssh->channels, c);
3563 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3564 PKT_INT, c->remoteid, PKT_INT, c->localid,
3569 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
3571 /* Remote side is trying to open a channel to talk to a
3572 * forwarded port. Give them back a local channel number. */
3573 struct ssh_channel *c;
3574 struct ssh_rportfwd pf;
3577 char *host, buf[1024];
3579 c = snew(struct ssh_channel);
3582 remoteid = ssh_pkt_getuint32(pktin);
3583 ssh_pkt_getstring(pktin, &host, &hostsize);
3584 port = ssh_pkt_getuint32(pktin);
3586 if (hostsize >= lenof(pf.dhost))
3587 hostsize = lenof(pf.dhost)-1;
3588 memcpy(pf.dhost, host, hostsize);
3589 pf.dhost[hostsize] = '\0';
3592 if (find234(ssh->rportfwds, &pf, NULL) == NULL) {
3593 sprintf(buf, "Rejected remote port open request for %s:%d",
3596 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3597 PKT_INT, remoteid, PKT_END);
3599 sprintf(buf, "Received remote port open request for %s:%d",
3602 e = pfd_newconnect(&c->u.pfd.s, pf.dhost, port,
3606 sprintf(buf, "Port open failed: %s", e);
3609 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3610 PKT_INT, remoteid, PKT_END);
3612 c->remoteid = remoteid;
3613 c->localid = alloc_channel_id(ssh);
3615 c->v.v1.throttling = 0;
3616 c->type = CHAN_SOCKDATA; /* identify channel type */
3617 add234(ssh->channels, c);
3618 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3619 PKT_INT, c->remoteid, PKT_INT,
3620 c->localid, PKT_END);
3621 logevent("Forwarded port opened successfully");
3626 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
3628 unsigned int remoteid = ssh_pkt_getuint32(pktin);
3629 unsigned int localid = ssh_pkt_getuint32(pktin);
3630 struct ssh_channel *c;
3632 c = find234(ssh->channels, &remoteid, ssh_channelfind);
3633 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
3634 c->remoteid = localid;
3635 c->type = CHAN_SOCKDATA;
3636 c->v.v1.throttling = 0;
3637 pfd_confirm(c->u.pfd.s);
3640 if (c && c->closes) {
3642 * We have a pending close on this channel,
3643 * which we decided on before the server acked
3644 * the channel open. So now we know the
3645 * remoteid, we can close it again.
3647 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE,
3648 PKT_INT, c->remoteid, PKT_END);
3652 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
3654 unsigned int remoteid = ssh_pkt_getuint32(pktin);
3655 struct ssh_channel *c;
3657 c = find234(ssh->channels, &remoteid, ssh_channelfind);
3658 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
3659 logevent("Forwarded connection refused by server");
3660 pfd_close(c->u.pfd.s);
3661 del234(ssh->channels, c);
3666 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
3668 /* Remote side closes a channel. */
3669 unsigned i = ssh_pkt_getuint32(pktin);
3670 struct ssh_channel *c;
3671 c = find234(ssh->channels, &i, ssh_channelfind);
3672 if (c && ((int)c->remoteid) != -1) {
3675 (pktin->type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
3677 if ((c->closes == 0) && (c->type == CHAN_X11)) {
3678 logevent("Forwarded X11 connection terminated");
3679 assert(c->u.x11.s != NULL);
3680 x11_close(c->u.x11.s);
3683 if ((c->closes == 0) && (c->type == CHAN_SOCKDATA)) {
3684 logevent("Forwarded port closed");
3685 assert(c->u.pfd.s != NULL);
3686 pfd_close(c->u.pfd.s);
3690 c->closes |= (closetype << 2); /* seen this message */
3691 if (!(c->closes & closetype)) {
3692 send_packet(ssh, pktin->type, PKT_INT, c->remoteid,
3694 c->closes |= closetype; /* sent it too */
3697 if (c->closes == 15) {
3698 del234(ssh->channels, c);
3702 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
3703 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
3704 "_CONFIRMATION", c ? "half-open" : "nonexistent",
3709 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
3711 /* Data sent down one of our channels. */
3712 int i = ssh_pkt_getuint32(pktin);
3715 struct ssh_channel *c;
3717 ssh_pkt_getstring(pktin, &p, &len);
3719 c = find234(ssh->channels, &i, ssh_channelfind);
3724 bufsize = x11_send(c->u.x11.s, p, len);
3727 bufsize = pfd_send(c->u.pfd.s, p, len);
3730 /* Data for an agent message. Buffer it. */
3732 if (c->u.a.lensofar < 4) {
3733 int l = min(4 - c->u.a.lensofar, len);
3734 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
3738 c->u.a.lensofar += l;
3740 if (c->u.a.lensofar == 4) {
3742 4 + GET_32BIT(c->u.a.msglen);
3743 c->u.a.message = snewn(c->u.a.totallen,
3745 memcpy(c->u.a.message, c->u.a.msglen, 4);
3747 if (c->u.a.lensofar >= 4 && len > 0) {
3749 min(c->u.a.totallen - c->u.a.lensofar,
3751 memcpy(c->u.a.message + c->u.a.lensofar, p,
3755 c->u.a.lensofar += l;
3757 if (c->u.a.lensofar == c->u.a.totallen) {
3760 if (agent_query(c->u.a.message,
3763 ssh_agentf_callback, c))
3764 ssh_agentf_callback(c, reply, replylen);
3765 sfree(c->u.a.message);
3766 c->u.a.lensofar = 0;
3769 bufsize = 0; /* agent channels never back up */
3772 if (!c->v.v1.throttling && bufsize > SSH1_BUFFER_LIMIT) {
3773 c->v.v1.throttling = 1;
3774 ssh1_throttle(ssh, +1);
3779 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
3782 ssh->exitcode = ssh_pkt_getuint32(pktin);
3783 sprintf(buf, "Server sent command exit status %d",
3786 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
3788 * In case `helpful' firewalls or proxies tack
3789 * extra human-readable text on the end of the
3790 * session which we might mistake for another
3791 * encrypted packet, we close the session once
3792 * we've sent EXIT_CONFIRMATION.
3794 ssh_closing((Plug)ssh, NULL, 0, 0);
3797 static void do_ssh1_connection(Ssh ssh, unsigned char *in, int inlen,
3798 struct Packet *pktin)
3800 crBegin(ssh->do_ssh1_connection_crstate);
3802 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
3803 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
3804 ssh1_smsg_stdout_stderr_data;
3806 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
3807 ssh1_msg_channel_open_confirmation;
3808 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
3809 ssh1_msg_channel_open_failure;
3810 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
3811 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
3812 ssh1_msg_channel_close;
3813 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
3814 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
3816 if (ssh->cfg.agentfwd && agent_exists()) {
3817 logevent("Requesting agent forwarding");
3818 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
3822 if (pktin->type != SSH1_SMSG_SUCCESS
3823 && pktin->type != SSH1_SMSG_FAILURE) {
3824 bombout(("Protocol confusion"));
3826 } else if (pktin->type == SSH1_SMSG_FAILURE) {
3827 logevent("Agent forwarding refused");
3829 logevent("Agent forwarding enabled");
3830 ssh->agentfwd_enabled = TRUE;
3831 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
3835 if (ssh->cfg.x11_forward) {
3836 char proto[20], data[64];
3837 logevent("Requesting X11 forwarding");
3838 ssh->x11auth = x11_invent_auth(proto, sizeof(proto),
3839 data, sizeof(data), ssh->cfg.x11_auth);
3840 x11_get_real_auth(ssh->x11auth, ssh->cfg.x11_display);
3841 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
3842 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
3843 PKT_STR, proto, PKT_STR, data,
3844 PKT_INT, x11_get_screen_number(ssh->cfg.x11_display),
3847 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
3848 PKT_STR, proto, PKT_STR, data, PKT_END);
3853 if (pktin->type != SSH1_SMSG_SUCCESS
3854 && pktin->type != SSH1_SMSG_FAILURE) {
3855 bombout(("Protocol confusion"));
3857 } else if (pktin->type == SSH1_SMSG_FAILURE) {
3858 logevent("X11 forwarding refused");
3860 logevent("X11 forwarding enabled");
3861 ssh->X11_fwd_enabled = TRUE;
3862 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
3869 int sport,dport,sserv,dserv;
3870 char sports[256], dports[256], saddr[256], host[256];
3872 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
3873 /* Add port forwardings. */
3874 ssh->portfwd_strptr = ssh->cfg.portfwd;
3875 while (*ssh->portfwd_strptr) {
3876 type = *ssh->portfwd_strptr++;
3879 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != '\t') {
3880 if (*ssh->portfwd_strptr == ':') {
3882 * We've seen a colon in the middle of the
3883 * source port number. This means that
3884 * everything we've seen until now is the
3885 * source _address_, so we'll move it into
3886 * saddr and start sports from the beginning
3889 ssh->portfwd_strptr++;
3891 strcpy(saddr, sports);
3894 if (n < 255) sports[n++] = *ssh->portfwd_strptr++;
3898 if (*ssh->portfwd_strptr == '\t')
3899 ssh->portfwd_strptr++;
3901 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != ':') {
3902 if (n < 255) host[n++] = *ssh->portfwd_strptr++;
3905 if (*ssh->portfwd_strptr == ':')
3906 ssh->portfwd_strptr++;
3908 while (*ssh->portfwd_strptr) {
3909 if (n < 255) dports[n++] = *ssh->portfwd_strptr++;
3912 ssh->portfwd_strptr++;
3913 dport = atoi(dports);
3917 dport = net_service_lookup(dports);
3919 logeventf(ssh, "Service lookup failed for"
3920 " destination port \"%s\"", dports);
3924 while (*ssh->portfwd_strptr) ssh->portfwd_strptr++;
3926 ssh->portfwd_strptr++; /* eat the NUL and move to next one */
3928 sport = atoi(sports);
3932 sport = net_service_lookup(sports);
3934 logeventf(ssh, "Service lookup failed for source"
3935 " port \"%s\"", sports);
3938 if (sport && dport) {
3939 /* Set up a description of the source port. */
3940 static char *sportdesc;
3941 sportdesc = dupprintf("%.*s%.*s%.*s%.*s%d%.*s",
3942 (int)(*saddr?strlen(saddr):0), *saddr?saddr:NULL,
3943 (int)(*saddr?1:0), ":",
3944 (int)(sserv ? strlen(sports) : 0), sports,
3945 sserv, "(", sport, sserv, ")");
3947 /* Verbose description of the destination port */
3948 char *dportdesc = dupprintf("%s:%.*s%.*s%d%.*s",
3950 (int)(dserv ? strlen(dports) : 0), dports,
3951 dserv, "(", dport, dserv, ")");
3952 const char *err = pfd_addforward(host, dport,
3953 *saddr ? saddr : NULL,
3954 sport, ssh, &ssh->cfg);
3956 logeventf(ssh, "Local port %s forward to %s"
3957 " failed: %s", sportdesc, dportdesc, err);
3959 logeventf(ssh, "Local port %s forwarding to %s",
3960 sportdesc, dportdesc);
3963 } else if (type == 'D') {
3964 const char *err = pfd_addforward(NULL, -1,
3965 *saddr ? saddr : NULL,
3966 sport, ssh, &ssh->cfg);
3968 logeventf(ssh, "Local port %s SOCKS dynamic forward"
3969 " setup failed: %s", sportdesc, err);
3971 logeventf(ssh, "Local port %s doing SOCKS"
3972 " dynamic forwarding", sportdesc);
3975 struct ssh_rportfwd *pf;
3976 pf = snew(struct ssh_rportfwd);
3977 strcpy(pf->dhost, host);
3981 "SSH1 cannot handle source address spec \"%s:%d\"; ignoring",
3984 if (add234(ssh->rportfwds, pf) != pf) {
3986 "Duplicate remote port forwarding to %s:%d",
3990 logeventf(ssh, "Requesting remote port %.*s%.*s%d%.*s"
3991 " forward to %s:%.*s%.*s%d%.*s",
3992 (int)(sserv ? strlen(sports) : 0), sports,
3993 sserv, "(", sport, sserv, ")",
3995 (int)(dserv ? strlen(dports) : 0), dports,
3996 dserv, "(", dport, dserv, ")");
3997 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
4005 if (pktin->type != SSH1_SMSG_SUCCESS
4006 && pktin->type != SSH1_SMSG_FAILURE) {
4007 bombout(("Protocol confusion"));
4009 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4010 c_write_str(ssh, "Server refused port"
4012 logevent("Server refused this port forwarding");
4014 logevent("Remote port forwarding enabled");
4015 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] =
4025 if (!ssh->cfg.nopty) {
4026 /* Unpick the terminal-speed string. */
4027 /* XXX perhaps we should allow no speeds to be sent. */
4028 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
4029 sscanf(ssh->cfg.termspeed, "%d,%d", &ssh->ospeed, &ssh->ispeed);
4030 /* Send the pty request. */
4031 send_packet(ssh, SSH1_CMSG_REQUEST_PTY,
4032 PKT_STR, ssh->cfg.termtype,
4033 PKT_INT, ssh->term_height,
4034 PKT_INT, ssh->term_width,
4035 PKT_INT, 0, PKT_INT, 0, /* width,height in pixels */
4036 PKT_CHAR, 192, PKT_INT, ssh->ispeed, /* TTY_OP_ISPEED */
4037 PKT_CHAR, 193, PKT_INT, ssh->ospeed, /* TTY_OP_OSPEED */
4038 PKT_CHAR, 0, PKT_END);
4039 ssh->state = SSH_STATE_INTERMED;
4043 if (pktin->type != SSH1_SMSG_SUCCESS
4044 && pktin->type != SSH1_SMSG_FAILURE) {
4045 bombout(("Protocol confusion"));
4047 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4048 c_write_str(ssh, "Server refused to allocate pty\r\n");
4049 ssh->editing = ssh->echoing = 1;
4051 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
4052 ssh->ospeed, ssh->ispeed);
4054 ssh->editing = ssh->echoing = 1;
4057 if (ssh->cfg.compression) {
4058 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
4062 if (pktin->type != SSH1_SMSG_SUCCESS
4063 && pktin->type != SSH1_SMSG_FAILURE) {
4064 bombout(("Protocol confusion"));
4066 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4067 c_write_str(ssh, "Server refused to compress\r\n");
4069 logevent("Started compression");
4070 ssh->v1_compressing = TRUE;
4071 ssh->cs_comp_ctx = zlib_compress_init();
4072 logevent("Initialised zlib (RFC1950) compression");
4073 ssh->sc_comp_ctx = zlib_decompress_init();
4074 logevent("Initialised zlib (RFC1950) decompression");
4078 * Start the shell or command.
4080 * Special case: if the first-choice command is an SSH2
4081 * subsystem (hence not usable here) and the second choice
4082 * exists, we fall straight back to that.
4085 char *cmd = ssh->cfg.remote_cmd_ptr;
4087 if (ssh->cfg.ssh_subsys && ssh->cfg.remote_cmd_ptr2) {
4088 cmd = ssh->cfg.remote_cmd_ptr2;
4089 ssh->fallback_cmd = TRUE;
4092 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
4094 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
4095 logevent("Started session");
4098 ssh->state = SSH_STATE_SESSION;
4099 if (ssh->size_needed)
4100 ssh_size(ssh, ssh->term_width, ssh->term_height);
4101 if (ssh->eof_needed)
4102 ssh_special(ssh, TS_EOF);
4105 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
4107 ssh->channels = newtree234(ssh_channelcmp);
4111 * By this point, most incoming packets are already being
4112 * handled by the dispatch table, and we need only pay
4113 * attention to the unusual ones.
4118 if (pktin->type == SSH1_SMSG_SUCCESS) {
4119 /* may be from EXEC_SHELL on some servers */
4120 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4121 /* may be from EXEC_SHELL on some servers
4122 * if no pty is available or in other odd cases. Ignore */
4124 bombout(("Strange packet received: type %d", pktin->type));
4129 int len = min(inlen, 512);
4130 send_packet(ssh, SSH1_CMSG_STDIN_DATA, PKTT_DATA,
4131 PKT_INT, len, PKT_DATA, in, len,
4132 PKTT_OTHER, PKT_END);
4143 * Handle the top-level SSH2 protocol.
4145 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
4150 ssh_pkt_getstring(pktin, &msg, &msglen);
4151 buf = dupprintf("Remote debug message: %.*s", msglen, msg);
4156 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
4158 /* log reason code in disconnect message */
4162 ssh_pkt_getstring(pktin, &msg, &msglen);
4163 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
4166 void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
4168 /* Do nothing, because we're ignoring it! Duhh. */
4171 static void ssh1_protocol_setup(Ssh ssh)
4176 * Most messages are handled by the coroutines.
4178 for (i = 0; i < 256; i++)
4179 ssh->packet_dispatch[i] = NULL;
4182 * These special message types we install handlers for.
4184 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
4185 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
4186 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
4189 static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen,
4190 struct Packet *pktin)
4192 if (ssh->state == SSH_STATE_CLOSED)
4195 if (pktin && ssh->packet_dispatch[pktin->type]) {
4196 ssh->packet_dispatch[pktin->type](ssh, pktin);
4200 if (!ssh->protocol_initial_phase_done) {
4201 if (do_ssh1_login(ssh, in, inlen, pktin))
4202 ssh->protocol_initial_phase_done = TRUE;
4207 do_ssh1_connection(ssh, in, inlen, pktin);
4211 * Utility routine for decoding comma-separated strings in KEXINIT.
4213 static int in_commasep_string(char *needle, char *haystack, int haylen)
4216 if (!needle || !haystack) /* protect against null pointers */
4218 needlen = strlen(needle);
4221 * Is it at the start of the string?
4223 if (haylen >= needlen && /* haystack is long enough */
4224 !memcmp(needle, haystack, needlen) && /* initial match */
4225 (haylen == needlen || haystack[needlen] == ',')
4226 /* either , or EOS follows */
4230 * If not, search for the next comma and resume after that.
4231 * If no comma found, terminate.
4233 while (haylen > 0 && *haystack != ',')
4234 haylen--, haystack++;
4237 haylen--, haystack++; /* skip over comma itself */
4242 * SSH2 key creation method.
4244 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H,
4245 unsigned char *sessid, char chr,
4246 unsigned char *keyspace)
4249 /* First 20 bytes. */
4251 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
4253 SHA_Bytes(&s, H, 20);
4254 SHA_Bytes(&s, &chr, 1);
4255 SHA_Bytes(&s, sessid, 20);
4256 SHA_Final(&s, keyspace);
4257 /* Next 20 bytes. */
4259 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
4261 SHA_Bytes(&s, H, 20);
4262 SHA_Bytes(&s, keyspace, 20);
4263 SHA_Final(&s, keyspace + 20);
4267 * Handle the SSH2 transport layer.
4269 static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen,
4270 struct Packet *pktin)
4272 struct do_ssh2_transport_state {
4273 int nbits, pbits, warn;
4274 Bignum p, g, e, f, K;
4275 int kex_init_value, kex_reply_value;
4276 const struct ssh_mac **maclist;
4278 const struct ssh2_cipher *cscipher_tobe;
4279 const struct ssh2_cipher *sccipher_tobe;
4280 const struct ssh_mac *csmac_tobe;
4281 const struct ssh_mac *scmac_tobe;
4282 const struct ssh_compress *cscomp_tobe;
4283 const struct ssh_compress *sccomp_tobe;
4284 char *hostkeydata, *sigdata, *keystr, *fingerprint;
4285 int hostkeylen, siglen;
4286 void *hkey; /* actual host key */
4287 unsigned char exchange_hash[20];
4288 int n_preferred_ciphers;
4289 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
4290 const struct ssh_compress *preferred_comp;
4292 struct Packet *pktout;
4294 crState(do_ssh2_transport_state);
4296 crBegin(ssh->do_ssh2_transport_crstate);
4298 s->cscipher_tobe = s->sccipher_tobe = NULL;
4299 s->csmac_tobe = s->scmac_tobe = NULL;
4300 s->cscomp_tobe = s->sccomp_tobe = NULL;
4308 * Set up the preferred ciphers. (NULL => warn below here)
4310 s->n_preferred_ciphers = 0;
4311 for (i = 0; i < CIPHER_MAX; i++) {
4312 switch (ssh->cfg.ssh_cipherlist[i]) {
4313 case CIPHER_BLOWFISH:
4314 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
4317 if (ssh->cfg.ssh2_des_cbc) {
4318 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
4322 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
4325 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
4328 /* Flag for later. Don't bother if it's the last in
4330 if (i < CIPHER_MAX - 1) {
4331 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
4339 * Set up preferred compression.
4341 if (ssh->cfg.compression)
4342 s->preferred_comp = &ssh_zlib;
4344 s->preferred_comp = &ssh_comp_none;
4347 * Be prepared to work around the buggy MAC problem.
4349 if (ssh->remote_bugs & BUG_SSH2_HMAC)
4350 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
4352 s->maclist = macs, s->nmacs = lenof(macs);
4356 int i, j, cipherstr_started;
4359 * Enable queueing of outgoing auth- or connection-layer
4360 * packets while we are in the middle of a key exchange.
4362 ssh->queueing = TRUE;
4365 * Flag that KEX is in progress.
4367 ssh->kex_in_progress = TRUE;
4370 * Construct and send our key exchange packet.
4372 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
4373 for (i = 0; i < 16; i++)
4374 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
4375 /* List key exchange algorithms. */
4376 ssh2_pkt_addstring_start(s->pktout);
4377 for (i = 0; i < lenof(kex_algs); i++) {
4378 if (kex_algs[i] == &ssh_diffiehellman_gex &&
4379 (ssh->remote_bugs & BUG_SSH2_DH_GEX))
4381 ssh2_pkt_addstring_str(s->pktout, kex_algs[i]->name);
4382 if (i < lenof(kex_algs) - 1)
4383 ssh2_pkt_addstring_str(s->pktout, ",");
4385 /* List server host key algorithms. */
4386 ssh2_pkt_addstring_start(s->pktout);
4387 for (i = 0; i < lenof(hostkey_algs); i++) {
4388 ssh2_pkt_addstring_str(s->pktout, hostkey_algs[i]->name);
4389 if (i < lenof(hostkey_algs) - 1)
4390 ssh2_pkt_addstring_str(s->pktout, ",");
4392 /* List client->server encryption algorithms. */
4393 ssh2_pkt_addstring_start(s->pktout);
4394 cipherstr_started = 0;
4395 for (i = 0; i < s->n_preferred_ciphers; i++) {
4396 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
4397 if (!c) continue; /* warning flag */
4398 for (j = 0; j < c->nciphers; j++) {
4399 if (cipherstr_started)
4400 ssh2_pkt_addstring_str(s->pktout, ",");
4401 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
4402 cipherstr_started = 1;
4405 /* List server->client encryption algorithms. */
4406 ssh2_pkt_addstring_start(s->pktout);
4407 cipherstr_started = 0;
4408 for (i = 0; i < s->n_preferred_ciphers; i++) {
4409 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
4410 if (!c) continue; /* warning flag */
4411 for (j = 0; j < c->nciphers; j++) {
4412 if (cipherstr_started)
4413 ssh2_pkt_addstring_str(s->pktout, ",");
4414 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
4415 cipherstr_started = 1;
4418 /* List client->server MAC algorithms. */
4419 ssh2_pkt_addstring_start(s->pktout);
4420 for (i = 0; i < s->nmacs; i++) {
4421 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
4422 if (i < s->nmacs - 1)
4423 ssh2_pkt_addstring_str(s->pktout, ",");
4425 /* List server->client MAC algorithms. */
4426 ssh2_pkt_addstring_start(s->pktout);
4427 for (i = 0; i < s->nmacs; i++) {
4428 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
4429 if (i < s->nmacs - 1)
4430 ssh2_pkt_addstring_str(s->pktout, ",");
4432 /* List client->server compression algorithms. */
4433 ssh2_pkt_addstring_start(s->pktout);
4434 assert(lenof(compressions) > 1);
4435 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
4436 for (i = 0; i < lenof(compressions); i++) {
4437 const struct ssh_compress *c = compressions[i];
4438 if (c != s->preferred_comp) {
4439 ssh2_pkt_addstring_str(s->pktout, ",");
4440 ssh2_pkt_addstring_str(s->pktout, c->name);
4443 /* List server->client compression algorithms. */
4444 ssh2_pkt_addstring_start(s->pktout);
4445 assert(lenof(compressions) > 1);
4446 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
4447 for (i = 0; i < lenof(compressions); i++) {
4448 const struct ssh_compress *c = compressions[i];
4449 if (c != s->preferred_comp) {
4450 ssh2_pkt_addstring_str(s->pktout, ",");
4451 ssh2_pkt_addstring_str(s->pktout, c->name);
4454 /* List client->server languages. Empty list. */
4455 ssh2_pkt_addstring_start(s->pktout);
4456 /* List server->client languages. Empty list. */
4457 ssh2_pkt_addstring_start(s->pktout);
4458 /* First KEX packet does _not_ follow, because we're not that brave. */
4459 ssh2_pkt_addbool(s->pktout, FALSE);
4461 ssh2_pkt_adduint32(s->pktout, 0);
4464 ssh->exhash = ssh->exhashbase;
4465 sha_string(&ssh->exhash, s->pktout->data + 5, s->pktout->length - 5);
4467 ssh2_pkt_send_noqueue(ssh, s->pktout);
4471 if (pktin->length > 5)
4472 sha_string(&ssh->exhash, pktin->data + 5, pktin->length - 5);
4475 * Now examine the other side's KEXINIT to see what we're up
4482 if (pktin->type != SSH2_MSG_KEXINIT) {
4483 bombout(("expected key exchange packet from server"));
4487 ssh->hostkey = NULL;
4488 s->cscipher_tobe = NULL;
4489 s->sccipher_tobe = NULL;
4490 s->csmac_tobe = NULL;
4491 s->scmac_tobe = NULL;
4492 s->cscomp_tobe = NULL;
4493 s->sccomp_tobe = NULL;
4494 pktin->savedpos += 16; /* skip garbage cookie */
4495 ssh_pkt_getstring(pktin, &str, &len); /* key exchange algorithms */
4496 for (i = 0; i < lenof(kex_algs); i++) {
4497 if (kex_algs[i] == &ssh_diffiehellman_gex &&
4498 (ssh->remote_bugs & BUG_SSH2_DH_GEX))
4500 if (in_commasep_string(kex_algs[i]->name, str, len)) {
4501 ssh->kex = kex_algs[i];
4505 ssh_pkt_getstring(pktin, &str, &len); /* host key algorithms */
4506 for (i = 0; i < lenof(hostkey_algs); i++) {
4507 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
4508 ssh->hostkey = hostkey_algs[i];
4512 ssh_pkt_getstring(pktin, &str, &len); /* client->server cipher */
4514 for (i = 0; i < s->n_preferred_ciphers; i++) {
4515 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
4519 for (j = 0; j < c->nciphers; j++) {
4520 if (in_commasep_string(c->list[j]->name, str, len)) {
4521 s->cscipher_tobe = c->list[j];
4526 if (s->cscipher_tobe) {
4528 askcipher(ssh->frontend, s->cscipher_tobe->name, 1);
4532 if (!s->cscipher_tobe) {
4533 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
4534 str ? str : "(null)"));
4538 ssh_pkt_getstring(pktin, &str, &len); /* server->client cipher */
4540 for (i = 0; i < s->n_preferred_ciphers; i++) {
4541 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
4545 for (j = 0; j < c->nciphers; j++) {
4546 if (in_commasep_string(c->list[j]->name, str, len)) {
4547 s->sccipher_tobe = c->list[j];
4552 if (s->sccipher_tobe) {
4554 askcipher(ssh->frontend, s->sccipher_tobe->name, 2);
4558 if (!s->sccipher_tobe) {
4559 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
4560 str ? str : "(null)"));
4564 ssh_pkt_getstring(pktin, &str, &len); /* client->server mac */
4565 for (i = 0; i < s->nmacs; i++) {
4566 if (in_commasep_string(s->maclist[i]->name, str, len)) {
4567 s->csmac_tobe = s->maclist[i];
4571 ssh_pkt_getstring(pktin, &str, &len); /* server->client mac */
4572 for (i = 0; i < s->nmacs; i++) {
4573 if (in_commasep_string(s->maclist[i]->name, str, len)) {
4574 s->scmac_tobe = s->maclist[i];
4578 ssh_pkt_getstring(pktin, &str, &len); /* client->server compression */
4579 for (i = 0; i < lenof(compressions) + 1; i++) {
4580 const struct ssh_compress *c =
4581 i == 0 ? s->preferred_comp : compressions[i - 1];
4582 if (in_commasep_string(c->name, str, len)) {
4587 ssh_pkt_getstring(pktin, &str, &len); /* server->client compression */
4588 for (i = 0; i < lenof(compressions) + 1; i++) {
4589 const struct ssh_compress *c =
4590 i == 0 ? s->preferred_comp : compressions[i - 1];
4591 if (in_commasep_string(c->name, str, len)) {
4599 * Work out the number of bits of key we will need from the key
4600 * exchange. We start with the maximum key length of either
4606 csbits = s->cscipher_tobe->keylen;
4607 scbits = s->sccipher_tobe->keylen;
4608 s->nbits = (csbits > scbits ? csbits : scbits);
4610 /* The keys only have 160-bit entropy, since they're based on
4611 * a SHA-1 hash. So cap the key size at 160 bits. */
4616 * If we're doing Diffie-Hellman group exchange, start by
4617 * requesting a group.
4619 if (ssh->kex == &ssh_diffiehellman_gex) {
4620 logevent("Doing Diffie-Hellman group exchange");
4621 ssh->pkt_ctx |= SSH2_PKTCTX_DHGEX;
4623 * Work out how big a DH group we will need to allow that
4626 s->pbits = 512 << ((s->nbits - 1) / 64);
4627 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
4628 ssh2_pkt_adduint32(s->pktout, s->pbits);
4629 ssh2_pkt_send_noqueue(ssh, s->pktout);
4632 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
4633 bombout(("expected key exchange group packet from server"));
4636 s->p = ssh2_pkt_getmp(pktin);
4637 s->g = ssh2_pkt_getmp(pktin);
4638 if (!s->p || !s->g) {
4639 bombout(("unable to read mp-ints from incoming group packet"));
4642 ssh->kex_ctx = dh_setup_group(s->p, s->g);
4643 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
4644 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
4646 ssh->pkt_ctx |= SSH2_PKTCTX_DHGROUP1;
4647 ssh->kex_ctx = dh_setup_group1();
4648 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
4649 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
4652 logevent("Doing Diffie-Hellman key exchange");
4654 * Now generate and send e for Diffie-Hellman.
4656 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
4657 s->pktout = ssh2_pkt_init(s->kex_init_value);
4658 ssh2_pkt_addmp(s->pktout, s->e);
4659 ssh2_pkt_send_noqueue(ssh, s->pktout);
4662 if (pktin->type != s->kex_reply_value) {
4663 bombout(("expected key exchange reply packet from server"));
4666 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
4667 s->f = ssh2_pkt_getmp(pktin);
4669 bombout(("unable to parse key exchange reply packet"));
4672 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
4674 s->K = dh_find_K(ssh->kex_ctx, s->f);
4676 sha_string(&ssh->exhash, s->hostkeydata, s->hostkeylen);
4677 if (ssh->kex == &ssh_diffiehellman_gex) {
4678 sha_uint32(&ssh->exhash, s->pbits);
4679 sha_mpint(&ssh->exhash, s->p);
4680 sha_mpint(&ssh->exhash, s->g);
4682 sha_mpint(&ssh->exhash, s->e);
4683 sha_mpint(&ssh->exhash, s->f);
4684 sha_mpint(&ssh->exhash, s->K);
4685 SHA_Final(&ssh->exhash, s->exchange_hash);
4687 dh_cleanup(ssh->kex_ctx);
4688 ssh->kex_ctx = NULL;
4691 debug(("Exchange hash is:\n"));
4692 dmemdump(s->exchange_hash, 20);
4695 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
4697 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
4698 (char *)s->exchange_hash, 20)) {
4699 bombout(("Server's host key did not match the signature supplied"));
4704 * Authenticate remote host: verify host key. (We've already
4705 * checked the signature of the exchange hash.)
4707 s->keystr = ssh->hostkey->fmtkey(s->hkey);
4708 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
4709 verify_ssh_host_key(ssh->frontend,
4710 ssh->savedhost, ssh->savedport, ssh->hostkey->keytype,
4711 s->keystr, s->fingerprint);
4712 if (s->first_kex) { /* don't bother logging this in rekeys */
4713 logevent("Host key fingerprint is:");
4714 logevent(s->fingerprint);
4716 sfree(s->fingerprint);
4718 ssh->hostkey->freekey(s->hkey);
4721 * The exchange hash from the very first key exchange is also
4722 * the session id, used in session key construction and
4726 memcpy(ssh->v2_session_id, s->exchange_hash,
4727 sizeof(s->exchange_hash));
4730 * Send SSH2_MSG_NEWKEYS.
4732 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
4733 ssh2_pkt_send_noqueue(ssh, s->pktout);
4734 ssh->outgoing_data_size = 0; /* start counting from here */
4737 * We've sent client NEWKEYS, so create and initialise
4738 * client-to-servere session keys.
4740 if (ssh->cs_cipher_ctx)
4741 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
4742 ssh->cscipher = s->cscipher_tobe;
4743 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
4745 if (ssh->cs_mac_ctx)
4746 ssh->csmac->free_context(ssh->cs_mac_ctx);
4747 ssh->csmac = s->csmac_tobe;
4748 ssh->cs_mac_ctx = ssh->csmac->make_context();
4750 if (ssh->cs_comp_ctx)
4751 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
4752 ssh->cscomp = s->cscomp_tobe;
4753 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
4756 * Set IVs on client-to-server keys. Here we use the exchange
4757 * hash from the _first_ key exchange.
4760 unsigned char keyspace[40];
4761 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'C',keyspace);
4762 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
4763 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'A',keyspace);
4764 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
4765 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'E',keyspace);
4766 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
4769 logeventf(ssh, "Initialised %.200s client->server encryption",
4770 ssh->cscipher->text_name);
4771 logeventf(ssh, "Initialised %.200s client->server MAC algorithm",
4772 ssh->csmac->text_name);
4773 if (ssh->cscomp->text_name)
4774 logeventf(ssh, "Initialised %s compression",
4775 ssh->cscomp->text_name);
4778 * Now our end of the key exchange is complete, we can send all
4779 * our queued higher-layer packets.
4781 ssh->queueing = FALSE;
4782 ssh2_pkt_queuesend(ssh);
4785 * Expect SSH2_MSG_NEWKEYS from server.
4788 if (pktin->type != SSH2_MSG_NEWKEYS) {
4789 bombout(("expected new-keys packet from server"));
4792 ssh->incoming_data_size = 0; /* start counting from here */
4795 * We've seen server NEWKEYS, so create and initialise
4796 * server-to-client session keys.
4798 if (ssh->sc_cipher_ctx)
4799 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
4800 ssh->sccipher = s->sccipher_tobe;
4801 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
4803 if (ssh->sc_mac_ctx)
4804 ssh->scmac->free_context(ssh->sc_mac_ctx);
4805 ssh->scmac = s->scmac_tobe;
4806 ssh->sc_mac_ctx = ssh->scmac->make_context();
4808 if (ssh->sc_comp_ctx)
4809 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
4810 ssh->sccomp = s->sccomp_tobe;
4811 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
4814 * Set IVs on server-to-client keys. Here we use the exchange
4815 * hash from the _first_ key exchange.
4818 unsigned char keyspace[40];
4819 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'D',keyspace);
4820 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
4821 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'B',keyspace);
4822 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
4823 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'F',keyspace);
4824 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
4826 logeventf(ssh, "Initialised %.200s server->client encryption",
4827 ssh->sccipher->text_name);
4828 logeventf(ssh, "Initialised %.200s server->client MAC algorithm",
4829 ssh->scmac->text_name);
4830 if (ssh->sccomp->text_name)
4831 logeventf(ssh, "Initialised %s decompression",
4832 ssh->sccomp->text_name);
4835 * Free key exchange data.
4839 if (ssh->kex == &ssh_diffiehellman_gex) {
4845 * Key exchange is over. Schedule a timer for our next rekey.
4847 ssh->kex_in_progress = FALSE;
4848 ssh->next_rekey = schedule_timer(REKEY_TIMEOUT, ssh2_timer, ssh);
4851 * If this is the first key exchange phase, we must pass the
4852 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
4853 * wants to see it but because it will need time to initialise
4854 * itself before it sees an actual packet. In subsequent key
4855 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
4856 * it would only confuse the layer above.
4858 if (!s->first_kex) {
4864 * Now we're encrypting. Begin returning 1 to the protocol main
4865 * function so that other things can run on top of the
4866 * transport. If we ever see a KEXINIT, we must go back to the
4869 * We _also_ go back to the start if we see pktin==NULL and
4870 * inlen==-1, because this is a special signal meaning
4871 * `initiate client-driven rekey', and `in' contains a message
4872 * giving the reason for the rekey.
4874 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
4875 (!pktin && inlen == -1))) {
4879 logevent("Server initiated key re-exchange");
4881 logevent((char *)in);
4883 goto begin_key_exchange;
4889 * Add data to an SSH2 channel output buffer.
4891 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
4894 bufchain_add(&c->v.v2.outbuffer, buf, len);
4898 * Attempt to send data on an SSH2 channel.
4900 static int ssh2_try_send(struct ssh_channel *c)
4903 struct Packet *pktout;
4905 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
4908 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
4909 if ((unsigned)len > c->v.v2.remwindow)
4910 len = c->v.v2.remwindow;
4911 if ((unsigned)len > c->v.v2.remmaxpkt)
4912 len = c->v.v2.remmaxpkt;
4913 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
4914 ssh2_pkt_adduint32(pktout, c->remoteid);
4915 dont_log_data(ssh, pktout, PKTLOG_OMIT);
4916 ssh2_pkt_addstring_start(pktout);
4917 ssh2_pkt_addstring_data(pktout, data, len);
4918 end_log_omission(ssh, pktout);
4919 ssh2_pkt_send(ssh, pktout);
4920 bufchain_consume(&c->v.v2.outbuffer, len);
4921 c->v.v2.remwindow -= len;
4925 * After having sent as much data as we can, return the amount
4928 return bufchain_size(&c->v.v2.outbuffer);
4932 * Potentially enlarge the window on an SSH2 channel.
4934 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin)
4939 * Never send WINDOW_ADJUST for a channel that the remote side
4940 * already thinks it's closed; there's no point, since it won't
4941 * be sending any more data anyway.
4946 if (newwin > c->v.v2.locwindow) {
4947 struct Packet *pktout;
4949 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4950 ssh2_pkt_adduint32(pktout, c->remoteid);
4951 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
4952 ssh2_pkt_send(ssh, pktout);
4953 c->v.v2.locwindow = newwin;
4957 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
4959 unsigned i = ssh_pkt_getuint32(pktin);
4960 struct ssh_channel *c;
4961 c = find234(ssh->channels, &i, ssh_channelfind);
4962 if (c && !c->closes)
4963 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
4966 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
4970 unsigned i = ssh_pkt_getuint32(pktin);
4971 struct ssh_channel *c;
4972 c = find234(ssh->channels, &i, ssh_channelfind);
4974 return; /* nonexistent channel */
4975 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
4976 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
4977 return; /* extended but not stderr */
4978 ssh_pkt_getstring(pktin, &data, &length);
4981 c->v.v2.locwindow -= length;
4983 case CHAN_MAINSESSION:
4985 from_backend(ssh->frontend, pktin->type ==
4986 SSH2_MSG_CHANNEL_EXTENDED_DATA,
4990 bufsize = x11_send(c->u.x11.s, data, length);
4993 bufsize = pfd_send(c->u.pfd.s, data, length);
4996 while (length > 0) {
4997 if (c->u.a.lensofar < 4) {
4998 int l = min(4 - c->u.a.lensofar, length);
4999 memcpy(c->u.a.msglen + c->u.a.lensofar,
5003 c->u.a.lensofar += l;
5005 if (c->u.a.lensofar == 4) {
5007 4 + GET_32BIT(c->u.a.msglen);
5008 c->u.a.message = snewn(c->u.a.totallen,
5010 memcpy(c->u.a.message, c->u.a.msglen, 4);
5012 if (c->u.a.lensofar >= 4 && length > 0) {
5014 min(c->u.a.totallen - c->u.a.lensofar,
5016 memcpy(c->u.a.message + c->u.a.lensofar,
5020 c->u.a.lensofar += l;
5022 if (c->u.a.lensofar == c->u.a.totallen) {
5025 if (agent_query(c->u.a.message,
5028 ssh_agentf_callback, c))
5029 ssh_agentf_callback(c, reply, replylen);
5030 sfree(c->u.a.message);
5031 c->u.a.lensofar = 0;
5038 * If we are not buffering too much data,
5039 * enlarge the window again at the remote side.
5041 if (bufsize < OUR_V2_WINSIZE)
5042 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
5046 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
5048 unsigned i = ssh_pkt_getuint32(pktin);
5049 struct ssh_channel *c;
5051 c = find234(ssh->channels, &i, ssh_channelfind);
5053 return; /* nonexistent channel */
5055 if (c->type == CHAN_X11) {
5057 * Remote EOF on an X11 channel means we should
5058 * wrap up and close the channel ourselves.
5060 x11_close(c->u.x11.s);
5062 } else if (c->type == CHAN_AGENT) {
5064 } else if (c->type == CHAN_SOCKDATA) {
5065 pfd_close(c->u.pfd.s);
5070 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
5072 unsigned i = ssh_pkt_getuint32(pktin);
5073 struct ssh_channel *c;
5074 struct Packet *pktout;
5076 c = find234(ssh->channels, &i, ssh_channelfind);
5077 if (!c || ((int)c->remoteid) == -1) {
5078 bombout(("Received CHANNEL_CLOSE for %s channel %d\n",
5079 c ? "half-open" : "nonexistent", i));
5082 /* Do pre-close processing on the channel. */
5084 case CHAN_MAINSESSION:
5085 ssh->mainchan = NULL;
5086 update_specials_menu(ssh->frontend);
5089 if (c->u.x11.s != NULL)
5090 x11_close(c->u.x11.s);
5097 if (c->u.pfd.s != NULL)
5098 pfd_close(c->u.pfd.s);
5102 if (c->closes == 0) {
5103 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
5104 ssh2_pkt_adduint32(pktout, c->remoteid);
5105 ssh2_pkt_send(ssh, pktout);
5107 del234(ssh->channels, c);
5108 bufchain_clear(&c->v.v2.outbuffer);
5112 * See if that was the last channel left open.
5113 * (This is only our termination condition if we're
5114 * not running in -N mode.)
5116 if (!ssh->cfg.ssh_no_shell && count234(ssh->channels) == 0) {
5117 logevent("All channels closed. Disconnecting");
5120 * We used to send SSH_MSG_DISCONNECT here,
5121 * because I'd believed that _every_ conforming
5122 * SSH2 connection had to end with a disconnect
5123 * being sent by at least one side; apparently
5124 * I was wrong and it's perfectly OK to
5125 * unceremoniously slam the connection shut
5126 * when you're done, and indeed OpenSSH feels
5127 * this is more polite than sending a
5128 * DISCONNECT. So now we don't.
5130 s->pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
5131 ssh2_pkt_adduint32(s->pktout, SSH2_DISCONNECT_BY_APPLICATION);
5132 ssh2_pkt_addstring(s->pktout, "All open channels closed");
5133 ssh2_pkt_addstring(s->pktout, "en"); /* language tag */
5134 ssh2_pkt_send_noqueue(ssh, s->pktout);
5136 ssh_closing((Plug)ssh, NULL, 0, 0);
5140 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
5142 unsigned i = ssh_pkt_getuint32(pktin);
5143 struct ssh_channel *c;
5144 struct Packet *pktout;
5146 c = find234(ssh->channels, &i, ssh_channelfind);
5148 return; /* nonexistent channel */
5149 if (c->type != CHAN_SOCKDATA_DORMANT)
5150 return; /* dunno why they're confirming this */
5151 c->remoteid = ssh_pkt_getuint32(pktin);
5152 c->type = CHAN_SOCKDATA;
5153 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
5154 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
5156 pfd_confirm(c->u.pfd.s);
5159 * We have a pending close on this channel,
5160 * which we decided on before the server acked
5161 * the channel open. So now we know the
5162 * remoteid, we can close it again.
5164 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
5165 ssh2_pkt_adduint32(pktout, c->remoteid);
5166 ssh2_pkt_send(ssh, pktout);
5170 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
5172 static const char *const reasons[] = {
5173 "<unknown reason code>",
5174 "Administratively prohibited",
5176 "Unknown channel type",
5177 "Resource shortage",
5179 unsigned i = ssh_pkt_getuint32(pktin);
5180 unsigned reason_code;
5181 char *reason_string;
5184 struct ssh_channel *c;
5185 c = find234(ssh->channels, &i, ssh_channelfind);
5187 return; /* nonexistent channel */
5188 if (c->type != CHAN_SOCKDATA_DORMANT)
5189 return; /* dunno why they're failing this */
5191 reason_code = ssh_pkt_getuint32(pktin);
5192 if (reason_code >= lenof(reasons))
5193 reason_code = 0; /* ensure reasons[reason_code] in range */
5194 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
5195 message = dupprintf("Forwarded connection refused by"
5196 " server: %s [%.*s]", reasons[reason_code],
5197 reason_length, reason_string);
5201 pfd_close(c->u.pfd.s);
5203 del234(ssh->channels, c);
5207 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
5211 int typelen, want_reply;
5212 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
5213 struct ssh_channel *c;
5214 struct Packet *pktout;
5216 localid = ssh_pkt_getuint32(pktin);
5217 ssh_pkt_getstring(pktin, &type, &typelen);
5218 want_reply = ssh2_pkt_getbool(pktin);
5221 * First, check that the channel exists. Otherwise,
5222 * we can instantly disconnect with a rude message.
5224 c = find234(ssh->channels, &localid, ssh_channelfind);
5227 sprintf(buf, "Received channel request for nonexistent"
5228 " channel %d", localid);
5230 pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
5231 ssh2_pkt_adduint32(pktout, SSH2_DISCONNECT_BY_APPLICATION);
5232 ssh2_pkt_addstring(pktout, buf);
5233 ssh2_pkt_addstring(pktout, "en"); /* language tag */
5234 ssh2_pkt_send_noqueue(ssh, pktout);
5235 connection_fatal(ssh->frontend, "%s", buf);
5236 ssh_closing((Plug)ssh, NULL, 0, 0);
5241 * Having got the channel number, we now look at
5242 * the request type string to see if it's something
5245 if (c == ssh->mainchan) {
5247 * We recognise "exit-status" and "exit-signal" on
5248 * the primary channel.
5250 if (typelen == 11 &&
5251 !memcmp(type, "exit-status", 11)) {
5253 ssh->exitcode = ssh_pkt_getuint32(pktin);
5254 logeventf(ssh, "Server sent command exit status %d",
5256 reply = SSH2_MSG_CHANNEL_SUCCESS;
5258 } else if (typelen == 11 &&
5259 !memcmp(type, "exit-signal", 11)) {
5261 int is_plausible = TRUE, is_int = FALSE;
5262 char *fmt_sig = "", *fmt_msg = "";
5264 int msglen = 0, core = FALSE;
5265 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
5266 * provide an `int' for the signal, despite its
5267 * having been a `string' in the drafts since at
5268 * least 2001. (Fixed in session.c 1.147.) Try to
5269 * infer which we can safely parse it as. */
5271 unsigned char *p = pktin->body +
5273 long len = pktin->length - pktin->savedpos;
5274 unsigned long num = GET_32BIT(p); /* what is it? */
5275 /* If it's 0, it hardly matters; assume string */
5279 int maybe_int = FALSE, maybe_str = FALSE;
5280 #define CHECK_HYPOTHESIS(offset, result) \
5283 if (q >= 0 && q+4 <= len) { \
5284 q = q + 4 + GET_32BIT(p+q); \
5285 if (q >= 0 && q+4 <= len && \
5286 (q = q + 4 + GET_32BIT(p+q)) && q == len) \
5290 CHECK_HYPOTHESIS(4+1, maybe_int);
5291 CHECK_HYPOTHESIS(4+num+1, maybe_str);
5292 #undef CHECK_HYPOTHESIS
5293 if (maybe_int && !maybe_str)
5295 else if (!maybe_int && maybe_str)
5298 /* Crikey. Either or neither. Panic. */
5299 is_plausible = FALSE;
5304 /* Old non-standard OpenSSH. */
5305 int signum = ssh_pkt_getuint32(pktin);
5306 fmt_sig = dupprintf(" %d", signum);
5308 /* As per the drafts. */
5311 ssh_pkt_getstring(pktin, &sig, &siglen);
5312 /* Signal name isn't supposed to be blank, but
5313 * let's cope gracefully if it is. */
5315 fmt_sig = dupprintf(" \"%.*s\"",
5319 core = ssh2_pkt_getbool(pktin);
5320 ssh_pkt_getstring(pktin, &msg, &msglen);
5322 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
5324 /* ignore lang tag */
5325 } /* else don't attempt to parse */
5326 logeventf(ssh, "Server exited on signal%s%s%s",
5327 fmt_sig, core ? " (core dumped)" : "",
5329 if (*fmt_sig) sfree(fmt_sig);
5330 if (*fmt_msg) sfree(fmt_msg);
5331 reply = SSH2_MSG_CHANNEL_SUCCESS;
5336 * This is a channel request we don't know
5337 * about, so we now either ignore the request
5338 * or respond with CHANNEL_FAILURE, depending
5341 reply = SSH2_MSG_CHANNEL_FAILURE;
5344 pktout = ssh2_pkt_init(reply);
5345 ssh2_pkt_adduint32(pktout, c->remoteid);
5346 ssh2_pkt_send(ssh, pktout);
5350 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
5353 int typelen, want_reply;
5354 struct Packet *pktout;
5356 ssh_pkt_getstring(pktin, &type, &typelen);
5357 want_reply = ssh2_pkt_getbool(pktin);
5360 * We currently don't support any global requests
5361 * at all, so we either ignore the request or
5362 * respond with REQUEST_FAILURE, depending on
5366 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
5367 ssh2_pkt_send(ssh, pktout);
5371 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
5379 struct ssh_channel *c;
5380 unsigned remid, winsize, pktsize;
5381 struct Packet *pktout;
5383 ssh_pkt_getstring(pktin, &type, &typelen);
5384 c = snew(struct ssh_channel);
5387 remid = ssh_pkt_getuint32(pktin);
5388 winsize = ssh_pkt_getuint32(pktin);
5389 pktsize = ssh_pkt_getuint32(pktin);
5391 if (typelen == 3 && !memcmp(type, "x11", 3)) {
5394 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
5395 addrstr = snewn(peeraddrlen+1, char);
5396 memcpy(addrstr, peeraddr, peeraddrlen);
5397 addrstr[peeraddrlen] = '\0';
5398 peerport = ssh_pkt_getuint32(pktin);
5400 logeventf(ssh, "Received X11 connect request from %s:%d",
5403 if (!ssh->X11_fwd_enabled)
5404 error = "X11 forwarding is not enabled";
5405 else if (x11_init(&c->u.x11.s, ssh->cfg.x11_display, c,
5406 ssh->x11auth, addrstr, peerport,
5407 &ssh->cfg) != NULL) {
5408 error = "Unable to open an X11 connection";
5410 logevent("Opening X11 forward connection succeeded");
5415 } else if (typelen == 15 &&
5416 !memcmp(type, "forwarded-tcpip", 15)) {
5417 struct ssh_rportfwd pf, *realpf;
5420 ssh_pkt_getstring(pktin, &dummy, &dummylen);/* skip address */
5421 pf.sport = ssh_pkt_getuint32(pktin);
5422 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
5423 peerport = ssh_pkt_getuint32(pktin);
5424 realpf = find234(ssh->rportfwds, &pf, NULL);
5425 logeventf(ssh, "Received remote port %d open request "
5426 "from %s:%d", pf.sport, peeraddr, peerport);
5427 if (realpf == NULL) {
5428 error = "Remote port is not recognised";
5430 const char *e = pfd_newconnect(&c->u.pfd.s,
5434 logeventf(ssh, "Attempting to forward remote port to "
5435 "%s:%d", realpf->dhost, realpf->dport);
5437 logeventf(ssh, "Port open failed: %s", e);
5438 error = "Port open failed";
5440 logevent("Forwarded port opened successfully");
5441 c->type = CHAN_SOCKDATA;
5444 } else if (typelen == 22 &&
5445 !memcmp(type, "auth-agent@openssh.com", 3)) {
5446 if (!ssh->agentfwd_enabled)
5447 error = "Agent forwarding is not enabled";
5449 c->type = CHAN_AGENT; /* identify channel type */
5450 c->u.a.lensofar = 0;
5453 error = "Unsupported channel type requested";
5456 c->remoteid = remid;
5458 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
5459 ssh2_pkt_adduint32(pktout, c->remoteid);
5460 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
5461 ssh2_pkt_addstring(pktout, error);
5462 ssh2_pkt_addstring(pktout, "en"); /* language tag */
5463 ssh2_pkt_send(ssh, pktout);
5464 logeventf(ssh, "Rejected channel open: %s", error);
5467 c->localid = alloc_channel_id(ssh);
5469 c->v.v2.locwindow = OUR_V2_WINSIZE;
5470 c->v.v2.remwindow = winsize;
5471 c->v.v2.remmaxpkt = pktsize;
5472 bufchain_init(&c->v.v2.outbuffer);
5473 add234(ssh->channels, c);
5474 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
5475 ssh2_pkt_adduint32(pktout, c->remoteid);
5476 ssh2_pkt_adduint32(pktout, c->localid);
5477 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
5478 ssh2_pkt_adduint32(pktout, 0x4000UL); /* our max pkt size */
5479 ssh2_pkt_send(ssh, pktout);
5484 * Handle the SSH2 userauth and connection layers.
5486 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
5487 struct Packet *pktin)
5489 struct do_ssh2_authconn_state {
5491 AUTH_INVALID, AUTH_PUBLICKEY_AGENT, AUTH_PUBLICKEY_FILE,
5493 AUTH_KEYBOARD_INTERACTIVE
5497 AUTH_TYPE_PUBLICKEY,
5498 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
5499 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
5501 AUTH_TYPE_KEYBOARD_INTERACTIVE,
5502 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
5504 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
5505 int tried_pubkey_config, tried_agent, tried_keyb_inter;
5506 int kbd_inter_running;
5508 int num_prompts, curr_prompt, echo;
5513 void *publickey_blob;
5514 int publickey_bloblen;
5515 unsigned char request[5], *response, *p;
5519 char *pkblob, *alg, *commentp;
5520 int pklen, alglen, commentlen;
5521 int siglen, retlen, len;
5522 char *q, *agentreq, *ret;
5524 int num_env, env_left, env_ok;
5525 struct Packet *pktout;
5527 crState(do_ssh2_authconn_state);
5529 crBegin(ssh->do_ssh2_authconn_crstate);
5532 * Request userauth protocol, and await a response to it.
5534 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
5535 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
5536 ssh2_pkt_send(ssh, s->pktout);
5537 crWaitUntilV(pktin);
5538 if (pktin->type != SSH2_MSG_SERVICE_ACCEPT) {
5539 bombout(("Server refused user authentication protocol"));
5544 * We repeat this whole loop, including the username prompt,
5545 * until we manage a successful authentication. If the user
5546 * types the wrong _password_, they can be sent back to the
5547 * beginning to try another username, if this is configured on.
5548 * (If they specify a username in the config, they are never
5549 * asked, even if they do give a wrong password.)
5551 * I think this best serves the needs of
5553 * - the people who have no configuration, no keys, and just
5554 * want to try repeated (username,password) pairs until they
5555 * type both correctly
5557 * - people who have keys and configuration but occasionally
5558 * need to fall back to passwords
5560 * - people with a key held in Pageant, who might not have
5561 * logged in to a particular machine before; so they want to
5562 * type a username, and then _either_ their key will be
5563 * accepted, _or_ they will type a password. If they mistype
5564 * the username they will want to be able to get back and
5567 s->username[0] = '\0';
5568 s->got_username = FALSE;
5573 if (s->got_username && !ssh->cfg.change_username) {
5575 * We got a username last time round this loop, and
5576 * with change_username turned off we don't try to get
5579 } else if (!*ssh->cfg.username) {
5580 if (ssh_get_line && !ssh_getline_pw_only) {
5581 if (!ssh_get_line("login as: ",
5582 s->username, sizeof(s->username), FALSE)) {
5584 * get_line failed to get a username.
5587 logevent("No username provided. Abandoning session.");
5588 ssh_closing((Plug)ssh, NULL, 0, 0);
5592 int ret; /* need not be saved across crReturn */
5593 c_write_str(ssh, "login as: ");
5595 setup_userpass_input(ssh, s->username, sizeof(s->username), 1);
5597 crWaitUntilV(!pktin);
5598 ret = process_userpass_input(ssh, in, inlen);
5602 c_write_str(ssh, "\r\n");
5604 s->username[strcspn(s->username, "\n\r")] = '\0';
5607 strncpy(s->username, ssh->cfg.username, sizeof(s->username));
5608 s->username[sizeof(s->username)-1] = '\0';
5609 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
5610 stuff = dupprintf("Using username \"%s\".\r\n", s->username);
5611 c_write_str(ssh, stuff);
5615 s->got_username = TRUE;
5618 * Send an authentication request using method "none": (a)
5619 * just in case it succeeds, and (b) so that we know what
5620 * authentication methods we can usefully try next.
5622 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
5624 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
5625 ssh2_pkt_addstring(s->pktout, s->username);
5626 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
5627 ssh2_pkt_addstring(s->pktout, "none"); /* method */
5628 ssh2_pkt_send(ssh, s->pktout);
5629 s->type = AUTH_TYPE_NONE;
5631 s->we_are_in = FALSE;
5633 s->tried_pubkey_config = FALSE;
5634 s->tried_agent = FALSE;
5635 s->tried_keyb_inter = FALSE;
5636 s->kbd_inter_running = FALSE;
5637 /* Load the pub half of ssh->cfg.keyfile so we notice if it's in Pageant */
5638 if (!filename_is_null(ssh->cfg.keyfile)) {
5640 logeventf(ssh, "Reading private key file \"%.150s\"",
5641 filename_to_str(&ssh->cfg.keyfile));
5642 keytype = key_type(&ssh->cfg.keyfile);
5643 if (keytype == SSH_KEYTYPE_SSH2) {
5645 ssh2_userkey_loadpub(&ssh->cfg.keyfile, NULL,
5646 &s->publickey_bloblen, NULL);
5649 logeventf(ssh, "Unable to use this key file (%s)",
5650 key_type_to_str(keytype));
5651 msgbuf = dupprintf("Unable to use key file \"%.150s\""
5653 filename_to_str(&ssh->cfg.keyfile),
5654 key_type_to_str(keytype));
5655 c_write_str(ssh, msgbuf);
5657 s->publickey_blob = NULL;
5660 s->publickey_blob = NULL;
5664 * Wait for the result of the last authentication request.
5667 crWaitUntilV(pktin);
5668 while (pktin->type == SSH2_MSG_USERAUTH_BANNER) {
5672 * Don't show the banner if we're operating in
5673 * non-verbose non-interactive mode. (It's probably
5674 * a script, which means nobody will read the
5675 * banner _anyway_, and moreover the printing of
5676 * the banner will screw up processing on the
5677 * output of (say) plink.)
5679 if (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE)) {
5680 ssh_pkt_getstring(pktin, &banner, &size);
5682 c_write_untrusted(ssh, banner, size);
5684 crWaitUntilV(pktin);
5686 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
5687 logevent("Access granted");
5688 s->we_are_in = TRUE;
5692 if (s->kbd_inter_running &&
5693 pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
5695 * This is either a further set-of-prompts packet
5696 * in keyboard-interactive authentication, or it's
5697 * the same one and we came back here with `gotit'
5698 * set. In the former case, we must reset the
5699 * curr_prompt variable.
5703 } else if (pktin->type != SSH2_MSG_USERAUTH_FAILURE) {
5704 bombout(("Strange packet received during authentication: type %d",
5712 * OK, we're now sitting on a USERAUTH_FAILURE message, so
5713 * we can look at the string in it and know what we can
5714 * helpfully try next.
5716 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
5719 ssh_pkt_getstring(pktin, &methods, &methlen);
5720 s->kbd_inter_running = FALSE;
5721 if (!ssh2_pkt_getbool(pktin)) {
5723 * We have received an unequivocal Access
5724 * Denied. This can translate to a variety of
5727 * - if we'd just tried "none" authentication,
5728 * it's not worth printing anything at all
5730 * - if we'd just tried a public key _offer_,
5731 * the message should be "Server refused our
5732 * key" (or no message at all if the key
5733 * came from Pageant)
5735 * - if we'd just tried anything else, the
5736 * message really should be "Access denied".
5738 * Additionally, if we'd just tried password
5739 * authentication, we should break out of this
5740 * whole loop so as to go back to the username
5741 * prompt (iff we're configured to allow
5742 * username change attempts).
5744 if (s->type == AUTH_TYPE_NONE) {
5746 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
5747 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
5748 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
5749 c_write_str(ssh, "Server refused our key\r\n");
5750 logevent("Server refused public key");
5751 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
5752 /* server declined keyboard-interactive; ignore */
5754 c_write_str(ssh, "Access denied\r\n");
5755 logevent("Access denied");
5756 if (s->type == AUTH_TYPE_PASSWORD &&
5757 ssh->cfg.change_username) {
5758 /* XXX perhaps we should allow
5759 * keyboard-interactive to do this too? */
5760 s->we_are_in = FALSE;
5765 c_write_str(ssh, "Further authentication required\r\n");
5766 logevent("Further authentication required");
5770 in_commasep_string("publickey", methods, methlen);
5772 in_commasep_string("password", methods, methlen);
5773 s->can_keyb_inter = ssh->cfg.try_ki_auth &&
5774 in_commasep_string("keyboard-interactive", methods, methlen);
5778 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
5782 * Most password/passphrase prompts will be
5783 * non-echoing, so we set this to 0 by default.
5784 * Exception is that some keyboard-interactive prompts
5785 * can be echoing, in which case we'll set this to 1.
5789 if (!s->method && s->can_pubkey &&
5790 agent_exists() && !s->tried_agent) {
5792 * Attempt public-key authentication using Pageant.
5797 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
5798 ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
5800 s->tried_agent = TRUE;
5802 logevent("Pageant is running. Requesting keys.");
5804 /* Request the keys held by the agent. */
5805 PUT_32BIT(s->request, 1);
5806 s->request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
5807 if (!agent_query(s->request, 5, &r, &s->responselen,
5808 ssh_agent_callback, ssh)) {
5812 bombout(("Unexpected data from server while"
5813 " waiting for agent response"));
5816 } while (pktin || inlen > 0);
5817 r = ssh->agent_response;
5818 s->responselen = ssh->agent_response_len;
5820 s->response = (unsigned char *) r;
5821 if (s->response && s->responselen >= 5 &&
5822 s->response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
5823 s->p = s->response + 5;
5824 s->nkeys = GET_32BIT(s->p);
5828 sprintf(buf, "Pageant has %d SSH2 keys", s->nkeys);
5831 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
5836 sprintf(buf, "Trying Pageant key #%d", s->keyi);
5839 s->pklen = GET_32BIT(s->p);
5841 if (s->publickey_blob &&
5842 s->pklen == s->publickey_bloblen &&
5843 !memcmp(s->p, s->publickey_blob,
5844 s->publickey_bloblen)) {
5845 logevent("This key matches configured key file");
5846 s->tried_pubkey_config = 1;
5848 s->pkblob = (char *)s->p;
5850 s->alglen = GET_32BIT(s->pkblob);
5851 s->alg = s->pkblob + 4;
5852 s->commentlen = GET_32BIT(s->p);
5854 s->commentp = (char *)s->p;
5855 s->p += s->commentlen;
5856 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
5857 ssh2_pkt_addstring(s->pktout, s->username);
5858 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
5859 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
5860 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
5861 ssh2_pkt_addstring_start(s->pktout);
5862 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
5863 ssh2_pkt_addstring_start(s->pktout);
5864 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
5865 ssh2_pkt_send(ssh, s->pktout);
5867 crWaitUntilV(pktin);
5868 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
5869 logevent("Key refused");
5873 if (flags & FLAG_VERBOSE) {
5874 c_write_str(ssh, "Authenticating with "
5876 c_write(ssh, s->commentp, s->commentlen);
5877 c_write_str(ssh, "\" from agent\r\n");
5881 * Server is willing to accept the key.
5882 * Construct a SIGN_REQUEST.
5884 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
5885 ssh2_pkt_addstring(s->pktout, s->username);
5886 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
5887 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
5888 ssh2_pkt_addbool(s->pktout, TRUE);
5889 ssh2_pkt_addstring_start(s->pktout);
5890 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
5891 ssh2_pkt_addstring_start(s->pktout);
5892 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
5894 s->siglen = s->pktout->length - 5 + 4 + 20;
5895 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
5897 s->len = 1; /* message type */
5898 s->len += 4 + s->pklen; /* key blob */
5899 s->len += 4 + s->siglen; /* data to sign */
5900 s->len += 4; /* flags */
5901 s->agentreq = snewn(4 + s->len, char);
5902 PUT_32BIT(s->agentreq, s->len);
5903 s->q = s->agentreq + 4;
5904 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
5905 PUT_32BIT(s->q, s->pklen);
5907 memcpy(s->q, s->pkblob, s->pklen);
5909 PUT_32BIT(s->q, s->siglen);
5911 /* Now the data to be signed... */
5912 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
5913 PUT_32BIT(s->q, 20);
5916 memcpy(s->q, ssh->v2_session_id, 20);
5918 memcpy(s->q, s->pktout->data + 5,
5919 s->pktout->length - 5);
5920 s->q += s->pktout->length - 5;
5921 /* And finally the (zero) flags word. */
5923 if (!agent_query(s->agentreq, s->len + 4,
5925 ssh_agent_callback, ssh)) {
5929 bombout(("Unexpected data from server"
5930 " while waiting for agent"
5934 } while (pktin || inlen > 0);
5935 vret = ssh->agent_response;
5936 s->retlen = ssh->agent_response_len;
5941 if (s->ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
5942 logevent("Sending Pageant's response");
5943 ssh2_add_sigblob(ssh, s->pktout,
5944 s->pkblob, s->pklen,
5946 GET_32BIT(s->ret + 5));
5947 ssh2_pkt_send(ssh, s->pktout);
5952 ("Pageant failed to answer challenge");
5963 if (!s->method && s->can_pubkey && s->publickey_blob
5964 && !s->tried_pubkey_config) {
5965 unsigned char *pub_blob;
5966 char *algorithm, *comment;
5969 s->tried_pubkey_config = TRUE;
5971 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
5972 ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
5975 * Try the public key supplied in the configuration.
5977 * First, offer the public blob to see if the server is
5978 * willing to accept it.
5981 (unsigned char *)ssh2_userkey_loadpub(&ssh->cfg.keyfile,
5986 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
5987 ssh2_pkt_addstring(s->pktout, s->username);
5988 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
5989 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
5990 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
5991 ssh2_pkt_addstring(s->pktout, algorithm);
5992 ssh2_pkt_addstring_start(s->pktout);
5993 ssh2_pkt_addstring_data(s->pktout, (char *)pub_blob,
5995 ssh2_pkt_send(ssh, s->pktout);
5996 logevent("Offered public key");
5998 crWaitUntilV(pktin);
5999 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
6001 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
6002 continue; /* key refused; give up on it */
6005 logevent("Offer of public key accepted");
6007 * Actually attempt a serious authentication using
6010 if (ssh2_userkey_encrypted(&ssh->cfg.keyfile, &comment)) {
6011 sprintf(s->pwprompt,
6012 "Passphrase for key \"%.100s\": ",
6018 if (flags & FLAG_VERBOSE) {
6019 c_write_str(ssh, "Authenticating with public key \"");
6020 c_write_str(ssh, comment);
6021 c_write_str(ssh, "\"\r\n");
6023 s->method = AUTH_PUBLICKEY_FILE;
6027 if (!s->method && s->can_keyb_inter && !s->tried_keyb_inter) {
6028 s->method = AUTH_KEYBOARD_INTERACTIVE;
6029 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
6030 s->tried_keyb_inter = TRUE;
6032 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6033 ssh->pkt_ctx |= SSH2_PKTCTX_KBDINTER;
6035 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6036 ssh2_pkt_addstring(s->pktout, s->username);
6037 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
6038 ssh2_pkt_addstring(s->pktout, "keyboard-interactive"); /* method */
6039 ssh2_pkt_addstring(s->pktout, ""); /* lang */
6040 ssh2_pkt_addstring(s->pktout, "");
6041 ssh2_pkt_send(ssh, s->pktout);
6043 crWaitUntilV(pktin);
6044 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
6045 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE)
6047 logevent("Keyboard-interactive authentication refused");
6048 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
6052 s->kbd_inter_running = TRUE;
6056 if (s->kbd_inter_running) {
6057 s->method = AUTH_KEYBOARD_INTERACTIVE;
6058 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
6059 s->tried_keyb_inter = TRUE;
6061 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6062 ssh->pkt_ctx |= SSH2_PKTCTX_KBDINTER;
6064 if (s->curr_prompt == 0) {
6066 * We've got a fresh USERAUTH_INFO_REQUEST.
6067 * Display header data, and start going through
6070 char *name, *inst, *lang;
6071 int name_len, inst_len, lang_len;
6073 ssh_pkt_getstring(pktin, &name, &name_len);
6074 ssh_pkt_getstring(pktin, &inst, &inst_len);
6075 ssh_pkt_getstring(pktin, &lang, &lang_len);
6077 c_write_untrusted(ssh, name, name_len);
6078 c_write_str(ssh, "\r\n");
6081 c_write_untrusted(ssh, inst, inst_len);
6082 c_write_str(ssh, "\r\n");
6084 s->num_prompts = ssh_pkt_getuint32(pktin);
6088 * If there are prompts remaining in the packet,
6089 * display one and get a response.
6091 if (s->curr_prompt < s->num_prompts) {
6095 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
6096 if (prompt_len > 0) {
6097 static const char trunc[] = "<prompt truncated>: ";
6098 static const int prlen = sizeof(s->pwprompt) -
6100 if (prompt_len > prlen) {
6101 memcpy(s->pwprompt, prompt, prlen);
6102 strcpy(s->pwprompt + prlen, trunc);
6104 memcpy(s->pwprompt, prompt, prompt_len);
6105 s->pwprompt[prompt_len] = '\0';
6109 "<server failed to send prompt>: ");
6111 s->echo = ssh2_pkt_getbool(pktin);
6117 if (!s->method && s->can_passwd) {
6118 s->method = AUTH_PASSWORD;
6119 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6120 ssh->pkt_ctx |= SSH2_PKTCTX_PASSWORD;
6121 sprintf(s->pwprompt, "%.90s@%.90s's password: ", s->username,
6128 if (!ssh_get_line(s->pwprompt, s->password,
6129 sizeof(s->password), TRUE)) {
6131 * get_line failed to get a password (for
6132 * example because one was supplied on the
6133 * command line which has already failed to
6136 s->pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
6137 ssh2_pkt_adduint32(s->pktout,SSH2_DISCONNECT_BY_APPLICATION);
6138 ssh2_pkt_addstring(s->pktout, "No more passwords available"
6140 ssh2_pkt_addstring(s->pktout, "en"); /* language tag */
6141 ssh2_pkt_send_noqueue(ssh, s->pktout);
6142 logevent("Unable to authenticate");
6143 connection_fatal(ssh->frontend,
6144 "Unable to authenticate");
6145 ssh_closing((Plug)ssh, NULL, 0, 0);
6149 int ret; /* need not be saved across crReturn */
6150 c_write_untrusted(ssh, s->pwprompt, strlen(s->pwprompt));
6153 setup_userpass_input(ssh, s->password,
6154 sizeof(s->password), s->echo);
6156 crWaitUntilV(!pktin);
6157 ret = process_userpass_input(ssh, in, inlen);
6161 c_write_str(ssh, "\r\n");
6165 if (s->method == AUTH_PUBLICKEY_FILE) {
6167 * We have our passphrase. Now try the actual authentication.
6169 struct ssh2_userkey *key;
6170 const char *error = NULL;
6172 key = ssh2_load_userkey(&ssh->cfg.keyfile, s->password,
6174 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
6175 if (key == SSH2_WRONG_PASSPHRASE) {
6176 c_write_str(ssh, "Wrong passphrase\r\n");
6177 s->tried_pubkey_config = FALSE;
6179 c_write_str(ssh, "Unable to load private key (");
6180 c_write_str(ssh, error);
6181 c_write_str(ssh, ")\r\n");
6182 s->tried_pubkey_config = TRUE;
6184 /* Send a spurious AUTH_NONE to return to the top. */
6185 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6186 ssh2_pkt_addstring(s->pktout, s->username);
6187 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
6188 ssh2_pkt_addstring(s->pktout, "none"); /* method */
6189 ssh2_pkt_send(ssh, s->pktout);
6190 s->type = AUTH_TYPE_NONE;
6192 unsigned char *pkblob, *sigblob, *sigdata;
6193 int pkblob_len, sigblob_len, sigdata_len;
6197 * We have loaded the private key and the server
6198 * has announced that it's willing to accept it.
6199 * Hallelujah. Generate a signature and send it.
6201 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6202 ssh2_pkt_addstring(s->pktout, s->username);
6203 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
6204 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
6205 ssh2_pkt_addbool(s->pktout, TRUE);
6206 ssh2_pkt_addstring(s->pktout, key->alg->name);
6207 pkblob = key->alg->public_blob(key->data, &pkblob_len);
6208 ssh2_pkt_addstring_start(s->pktout);
6209 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob, pkblob_len);
6212 * The data to be signed is:
6216 * followed by everything so far placed in the
6219 sigdata_len = s->pktout->length - 5 + 4 + 20;
6220 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
6222 sigdata = snewn(sigdata_len, unsigned char);
6224 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
6225 PUT_32BIT(sigdata+p, 20);
6228 memcpy(sigdata+p, ssh->v2_session_id, 20); p += 20;
6229 memcpy(sigdata+p, s->pktout->data + 5,
6230 s->pktout->length - 5);
6231 p += s->pktout->length - 5;
6232 assert(p == sigdata_len);
6233 sigblob = key->alg->sign(key->data, (char *)sigdata,
6234 sigdata_len, &sigblob_len);
6235 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
6236 sigblob, sigblob_len);
6241 ssh2_pkt_send(ssh, s->pktout);
6242 s->type = AUTH_TYPE_PUBLICKEY;
6243 key->alg->freekey(key->data);
6245 } else if (s->method == AUTH_PASSWORD) {
6247 * We send the password packet lumped tightly together with
6248 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
6249 * string long enough to make the total length of the two
6250 * packets constant. This should ensure that a passive
6251 * listener doing traffic analyis can't work out the length
6254 * For this to work, we need an assumption about the
6255 * maximum length of the password packet. I think 256 is
6256 * pretty conservative. Anyone using a password longer than
6257 * that probably doesn't have much to worry about from
6258 * people who find out how long their password is!
6260 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6261 ssh2_pkt_addstring(s->pktout, s->username);
6262 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
6263 ssh2_pkt_addstring(s->pktout, "password");
6264 ssh2_pkt_addbool(s->pktout, FALSE);
6265 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
6266 ssh2_pkt_addstring(s->pktout, s->password);
6267 memset(s->password, 0, sizeof(s->password));
6268 end_log_omission(ssh, s->pktout);
6269 ssh2_pkt_defer(ssh, s->pktout);
6271 * We'll include a string that's an exact multiple of the
6272 * cipher block size. If the cipher is NULL for some
6273 * reason, we don't do this trick at all because we gain
6276 if (ssh->cscipher) {
6279 stringlen = (256 - ssh->deferred_len);
6280 stringlen += ssh->cscipher->blksize - 1;
6281 stringlen -= (stringlen % ssh->cscipher->blksize);
6284 * Temporarily disable actual compression,
6285 * so we can guarantee to get this string
6286 * exactly the length we want it. The
6287 * compression-disabling routine should
6288 * return an integer indicating how many
6289 * bytes we should adjust our string length
6293 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
6295 s->pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
6296 ssh2_pkt_addstring_start(s->pktout);
6297 for (i = 0; i < stringlen; i++) {
6298 char c = (char) random_byte();
6299 ssh2_pkt_addstring_data(s->pktout, &c, 1);
6301 ssh2_pkt_defer(ssh, s->pktout);
6303 ssh_pkt_defersend(ssh);
6304 logevent("Sent password");
6305 s->type = AUTH_TYPE_PASSWORD;
6306 } else if (s->method == AUTH_KEYBOARD_INTERACTIVE) {
6307 if (s->curr_prompt == 0) {
6308 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
6309 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
6311 if (s->need_pw) { /* only add pw if we just got one! */
6312 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
6313 ssh2_pkt_addstring(s->pktout, s->password);
6314 memset(s->password, 0, sizeof(s->password));
6315 end_log_omission(ssh, s->pktout);
6318 if (s->curr_prompt >= s->num_prompts) {
6319 ssh2_pkt_send(ssh, s->pktout);
6322 * If there are prompts remaining, we set
6323 * `gotit' so that we won't attempt to get
6324 * another packet. Then we go back round the
6325 * loop and will end up retrieving another
6326 * prompt out of the existing packet. Funky or
6331 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
6333 c_write_str(ssh, "No supported authentication methods"
6334 " left to try!\r\n");
6335 logevent("No supported authentications offered."
6337 s->pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
6338 ssh2_pkt_adduint32(s->pktout, SSH2_DISCONNECT_BY_APPLICATION);
6339 ssh2_pkt_addstring(s->pktout, "No supported authentication"
6340 " methods available");
6341 ssh2_pkt_addstring(s->pktout, "en"); /* language tag */
6342 ssh2_pkt_send_noqueue(ssh, s->pktout);
6343 ssh_closing((Plug)ssh, NULL, 0, 0);
6347 } while (!s->we_are_in);
6350 * Now we're authenticated for the connection protocol. The
6351 * connection protocol will automatically have started at this
6352 * point; there's no need to send SERVICE_REQUEST.
6355 ssh->channels = newtree234(ssh_channelcmp);
6358 * Set up handlers for some connection protocol messages, so we
6359 * don't have to handle them repeatedly in this coroutine.
6361 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
6362 ssh2_msg_channel_window_adjust;
6363 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
6364 ssh2_msg_global_request;
6367 * Create the main session channel.
6369 if (!ssh->cfg.ssh_no_shell) {
6370 ssh->mainchan = snew(struct ssh_channel);
6371 ssh->mainchan->ssh = ssh;
6372 ssh->mainchan->localid = alloc_channel_id(ssh);
6373 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
6374 ssh2_pkt_addstring(s->pktout, "session");
6375 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
6376 ssh->mainchan->v.v2.locwindow = OUR_V2_WINSIZE;
6377 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
6378 ssh2_pkt_adduint32(s->pktout, 0x4000UL); /* our max pkt size */
6379 ssh2_pkt_send(ssh, s->pktout);
6380 crWaitUntilV(pktin);
6381 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
6382 bombout(("Server refused to open a session"));
6384 /* FIXME: error data comes back in FAILURE packet */
6386 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
6387 bombout(("Server's channel confirmation cited wrong channel"));
6390 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
6391 ssh->mainchan->type = CHAN_MAINSESSION;
6392 ssh->mainchan->closes = 0;
6393 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
6394 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
6395 bufchain_init(&ssh->mainchan->v.v2.outbuffer);
6396 add234(ssh->channels, ssh->mainchan);
6397 update_specials_menu(ssh->frontend);
6398 logevent("Opened channel for session");
6400 ssh->mainchan = NULL;
6403 * Now we have a channel, make dispatch table entries for
6404 * general channel-based messages.
6406 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
6407 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
6408 ssh2_msg_channel_data;
6409 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
6410 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
6411 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
6412 ssh2_msg_channel_open_confirmation;
6413 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
6414 ssh2_msg_channel_open_failure;
6415 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
6416 ssh2_msg_channel_request;
6417 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
6418 ssh2_msg_channel_open;
6421 * Potentially enable X11 forwarding.
6423 if (ssh->mainchan && ssh->cfg.x11_forward) {
6424 char proto[20], data[64];
6425 logevent("Requesting X11 forwarding");
6426 ssh->x11auth = x11_invent_auth(proto, sizeof(proto),
6427 data, sizeof(data), ssh->cfg.x11_auth);
6428 x11_get_real_auth(ssh->x11auth, ssh->cfg.x11_display);
6429 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6430 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
6431 ssh2_pkt_addstring(s->pktout, "x11-req");
6432 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
6433 ssh2_pkt_addbool(s->pktout, 0); /* many connections */
6434 ssh2_pkt_addstring(s->pktout, proto);
6435 ssh2_pkt_addstring(s->pktout, data);
6436 ssh2_pkt_adduint32(s->pktout, x11_get_screen_number(ssh->cfg.x11_display));
6437 ssh2_pkt_send(ssh, s->pktout);
6439 crWaitUntilV(pktin);
6441 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
6442 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
6443 bombout(("Unexpected response to X11 forwarding request:"
6444 " packet type %d", pktin->type));
6447 logevent("X11 forwarding refused");
6449 logevent("X11 forwarding enabled");
6450 ssh->X11_fwd_enabled = TRUE;
6455 * Enable port forwardings.
6460 int sport,dport,sserv,dserv;
6461 char sports[256], dports[256], saddr[256], host[256];
6463 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
6464 /* Add port forwardings. */
6465 ssh->portfwd_strptr = ssh->cfg.portfwd;
6466 while (*ssh->portfwd_strptr) {
6467 type = *ssh->portfwd_strptr++;
6470 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != '\t') {
6471 if (*ssh->portfwd_strptr == ':') {
6473 * We've seen a colon in the middle of the
6474 * source port number. This means that
6475 * everything we've seen until now is the
6476 * source _address_, so we'll move it into
6477 * saddr and start sports from the beginning
6480 ssh->portfwd_strptr++;
6482 strcpy(saddr, sports);
6485 if (n < 255) sports[n++] = *ssh->portfwd_strptr++;
6489 if (*ssh->portfwd_strptr == '\t')
6490 ssh->portfwd_strptr++;
6492 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != ':') {
6493 if (n < 255) host[n++] = *ssh->portfwd_strptr++;
6496 if (*ssh->portfwd_strptr == ':')
6497 ssh->portfwd_strptr++;
6499 while (*ssh->portfwd_strptr) {
6500 if (n < 255) dports[n++] = *ssh->portfwd_strptr++;
6503 ssh->portfwd_strptr++;
6504 dport = atoi(dports);
6508 dport = net_service_lookup(dports);
6510 logeventf(ssh, "Service lookup failed for destination"
6511 " port \"%s\"", dports);
6515 while (*ssh->portfwd_strptr) ssh->portfwd_strptr++;
6517 ssh->portfwd_strptr++; /* eat the NUL and move to next one */
6519 sport = atoi(sports);
6523 sport = net_service_lookup(sports);
6525 logeventf(ssh, "Service lookup failed for source"
6526 " port \"%s\"", sports);
6529 if (sport && dport) {
6530 /* Set up a description of the source port. */
6531 static char *sportdesc;
6532 sportdesc = dupprintf("%.*s%.*s%.*s%.*s%d%.*s",
6533 (int)(*saddr?strlen(saddr):0), *saddr?saddr:NULL,
6534 (int)(*saddr?1:0), ":",
6535 (int)(sserv ? strlen(sports) : 0), sports,
6536 sserv, "(", sport, sserv, ")");
6538 /* Verbose description of the destination port */
6539 char *dportdesc = dupprintf("%s:%.*s%.*s%d%.*s",
6541 (int)(dserv ? strlen(dports) : 0), dports,
6542 dserv, "(", dport, dserv, ")");
6543 const char *err = pfd_addforward(host, dport,
6544 *saddr ? saddr : NULL,
6545 sport, ssh, &ssh->cfg);
6547 logeventf(ssh, "Local port %s forward to %s"
6548 " failed: %s", sportdesc, dportdesc, err);
6550 logeventf(ssh, "Local port %s forwarding to %s",
6551 sportdesc, dportdesc);
6554 } else if (type == 'D') {
6555 const char *err = pfd_addforward(NULL, -1,
6556 *saddr ? saddr : NULL,
6557 sport, ssh, &ssh->cfg);
6559 logeventf(ssh, "Local port %s SOCKS dynamic forward"
6560 " setup failed: %s", sportdesc, err);
6562 logeventf(ssh, "Local port %s doing SOCKS"
6563 " dynamic forwarding", sportdesc);
6566 struct ssh_rportfwd *pf;
6567 pf = snew(struct ssh_rportfwd);
6568 strcpy(pf->dhost, host);
6571 if (add234(ssh->rportfwds, pf) != pf) {
6572 logeventf(ssh, "Duplicate remote port forwarding"
6573 " to %s:%d", host, dport);
6576 logeventf(ssh, "Requesting remote port %s"
6577 " forward to %s:%.*s%.*s%d%.*s",
6580 (int)(dserv ? strlen(dports) : 0), dports,
6581 dserv, "(", dport, dserv, ")");
6582 s->pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
6583 ssh2_pkt_addstring(s->pktout, "tcpip-forward");
6584 ssh2_pkt_addbool(s->pktout, 1);/* want reply */
6586 ssh2_pkt_addstring(s->pktout, saddr);
6587 } else if (ssh->cfg.rport_acceptall) {
6588 ssh2_pkt_addstring(s->pktout, "0.0.0.0");
6590 ssh2_pkt_addstring(s->pktout, "127.0.0.1");
6592 ssh2_pkt_adduint32(s->pktout, sport);
6593 ssh2_pkt_send(ssh, s->pktout);
6595 crWaitUntilV(pktin);
6597 if (pktin->type != SSH2_MSG_REQUEST_SUCCESS) {
6598 if (pktin->type != SSH2_MSG_REQUEST_FAILURE) {
6599 bombout(("Unexpected response to port "
6600 "forwarding request: packet type %d",
6604 logevent("Server refused this port forwarding");
6606 logevent("Remote port forwarding enabled");
6616 * Potentially enable agent forwarding.
6618 if (ssh->mainchan && ssh->cfg.agentfwd && agent_exists()) {
6619 logevent("Requesting OpenSSH-style agent forwarding");
6620 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6621 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
6622 ssh2_pkt_addstring(s->pktout, "auth-agent-req@openssh.com");
6623 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
6624 ssh2_pkt_send(ssh, s->pktout);
6626 crWaitUntilV(pktin);
6628 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
6629 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
6630 bombout(("Unexpected response to agent forwarding request:"
6631 " packet type %d", pktin->type));
6634 logevent("Agent forwarding refused");
6636 logevent("Agent forwarding enabled");
6637 ssh->agentfwd_enabled = TRUE;
6642 * Now allocate a pty for the session.
6644 if (ssh->mainchan && !ssh->cfg.nopty) {
6645 /* Unpick the terminal-speed string. */
6646 /* XXX perhaps we should allow no speeds to be sent. */
6647 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
6648 sscanf(ssh->cfg.termspeed, "%d,%d", &ssh->ospeed, &ssh->ispeed);
6649 /* Build the pty request. */
6650 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6651 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
6652 ssh2_pkt_addstring(s->pktout, "pty-req");
6653 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
6654 ssh2_pkt_addstring(s->pktout, ssh->cfg.termtype);
6655 ssh2_pkt_adduint32(s->pktout, ssh->term_width);
6656 ssh2_pkt_adduint32(s->pktout, ssh->term_height);
6657 ssh2_pkt_adduint32(s->pktout, 0); /* pixel width */
6658 ssh2_pkt_adduint32(s->pktout, 0); /* pixel height */
6659 ssh2_pkt_addstring_start(s->pktout);
6660 ssh2_pkt_addbyte(s->pktout, 128); /* TTY_OP_ISPEED */
6661 ssh2_pkt_adduint32(s->pktout, ssh->ispeed);
6662 ssh2_pkt_addbyte(s->pktout, 129); /* TTY_OP_OSPEED */
6663 ssh2_pkt_adduint32(s->pktout, ssh->ospeed);
6664 ssh2_pkt_addstring_data(s->pktout, "\0", 1); /* TTY_OP_END */
6665 ssh2_pkt_send(ssh, s->pktout);
6666 ssh->state = SSH_STATE_INTERMED;
6668 crWaitUntilV(pktin);
6670 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
6671 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
6672 bombout(("Unexpected response to pty request:"
6673 " packet type %d", pktin->type));
6676 c_write_str(ssh, "Server refused to allocate pty\r\n");
6677 ssh->editing = ssh->echoing = 1;
6679 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
6680 ssh->ospeed, ssh->ispeed);
6683 ssh->editing = ssh->echoing = 1;
6687 * Send environment variables.
6689 * Simplest thing here is to send all the requests at once, and
6690 * then wait for a whole bunch of successes or failures.
6692 if (ssh->mainchan && *ssh->cfg.environmt) {
6693 char *e = ssh->cfg.environmt;
6694 char *var, *varend, *val;
6700 while (*e && *e != '\t') e++;
6702 if (*e == '\t') e++;
6707 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6708 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
6709 ssh2_pkt_addstring(s->pktout, "env");
6710 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
6711 ssh2_pkt_addstring_start(s->pktout);
6712 ssh2_pkt_addstring_data(s->pktout, var, varend-var);
6713 ssh2_pkt_addstring(s->pktout, val);
6714 ssh2_pkt_send(ssh, s->pktout);
6719 logeventf(ssh, "Sent %d environment variables", s->num_env);
6722 s->env_left = s->num_env;
6724 while (s->env_left > 0) {
6725 crWaitUntilV(pktin);
6727 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
6728 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
6729 bombout(("Unexpected response to environment request:"
6730 " packet type %d", pktin->type));
6740 if (s->env_ok == s->num_env) {
6741 logevent("All environment variables successfully set");
6742 } else if (s->env_ok == 0) {
6743 logevent("All environment variables refused");
6744 c_write_str(ssh, "Server refused to set environment variables\r\n");
6746 logeventf(ssh, "%d environment variables refused",
6747 s->num_env - s->env_ok);
6748 c_write_str(ssh, "Server refused to set all environment variables\r\n");
6753 * Start a shell or a remote command. We may have to attempt
6754 * this twice if the config data has provided a second choice
6757 if (ssh->mainchan) while (1) {
6761 if (ssh->fallback_cmd) {
6762 subsys = ssh->cfg.ssh_subsys2;
6763 cmd = ssh->cfg.remote_cmd_ptr2;
6765 subsys = ssh->cfg.ssh_subsys;
6766 cmd = ssh->cfg.remote_cmd_ptr;
6769 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6770 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
6772 ssh2_pkt_addstring(s->pktout, "subsystem");
6773 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
6774 ssh2_pkt_addstring(s->pktout, cmd);
6776 ssh2_pkt_addstring(s->pktout, "exec");
6777 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
6778 ssh2_pkt_addstring(s->pktout, cmd);
6780 ssh2_pkt_addstring(s->pktout, "shell");
6781 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
6783 ssh2_pkt_send(ssh, s->pktout);
6785 crWaitUntilV(pktin);
6787 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
6788 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
6789 bombout(("Unexpected response to shell/command request:"
6790 " packet type %d", pktin->type));
6794 * We failed to start the command. If this is the
6795 * fallback command, we really are finished; if it's
6796 * not, and if the fallback command exists, try falling
6797 * back to it before complaining.
6799 if (!ssh->fallback_cmd && ssh->cfg.remote_cmd_ptr2 != NULL) {
6800 logevent("Primary command failed; attempting fallback");
6801 ssh->fallback_cmd = TRUE;
6804 bombout(("Server refused to start a shell/command"));
6807 logevent("Started a shell/command");
6812 ssh->state = SSH_STATE_SESSION;
6813 if (ssh->size_needed)
6814 ssh_size(ssh, ssh->term_width, ssh->term_height);
6815 if (ssh->eof_needed)
6816 ssh_special(ssh, TS_EOF);
6822 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
6827 s->try_send = FALSE;
6831 * _All_ the connection-layer packets we expect to
6832 * receive are now handled by the dispatch table.
6833 * Anything that reaches here must be bogus.
6836 bombout(("Strange packet received: type %d", pktin->type));
6838 } else if (ssh->mainchan) {
6840 * We have spare data. Add it to the channel buffer.
6842 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
6847 struct ssh_channel *c;
6849 * Try to send data on all channels if we can.
6851 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
6854 continue; /* don't send on closing channels */
6855 bufsize = ssh2_try_send(c);
6858 case CHAN_MAINSESSION:
6859 /* stdin need not receive an unthrottle
6860 * notification since it will be polled */
6863 x11_unthrottle(c->u.x11.s);
6866 /* agent sockets are request/response and need no
6867 * buffer management */
6870 pfd_unthrottle(c->u.pfd.s);
6882 * Handlers for SSH2 messages that might arrive at any moment.
6884 void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
6886 /* log reason code in disconnect message */
6888 int nowlen, reason, msglen;
6890 reason = ssh_pkt_getuint32(pktin);
6891 ssh_pkt_getstring(pktin, &msg, &msglen);
6893 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
6894 buf = dupprintf("Received disconnect message (%s)",
6895 ssh2_disconnect_reasons[reason]);
6897 buf = dupprintf("Received disconnect message (unknown"
6898 " type %d)", reason);
6902 buf = dupprintf("Disconnection message text: %n%.*s",
6903 &nowlen, msglen, msg);
6905 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
6907 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
6908 ssh2_disconnect_reasons[reason] : "unknown",
6913 void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
6915 /* log the debug message */
6920 /* XXX maybe we should actually take notice of this */
6921 always_display = ssh2_pkt_getbool(pktin);
6922 ssh_pkt_getstring(pktin, &msg, &msglen);
6924 buf = dupprintf("Remote debug message: %.*s", msglen, msg);
6929 void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
6931 struct Packet *pktout;
6932 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
6933 ssh2_pkt_adduint32(pktout, pktin->sequence);
6935 * UNIMPLEMENTED messages MUST appear in the same order as the
6936 * messages they respond to. Hence, never queue them.
6938 ssh2_pkt_send_noqueue(ssh, pktout);
6942 * Handle the top-level SSH2 protocol.
6944 static void ssh2_protocol_setup(Ssh ssh)
6949 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
6951 for (i = 0; i < 256; i++)
6952 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
6955 * Any message we actually understand, we set to NULL so that
6956 * the coroutines will get it.
6958 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = NULL;
6959 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = NULL;
6960 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = NULL;
6961 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = NULL;
6962 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = NULL;
6963 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = NULL;
6964 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = NULL;
6965 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = NULL; duplicate case value */
6966 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = NULL; duplicate case value */
6967 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = NULL;
6968 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = NULL;
6969 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = NULL;
6970 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = NULL;
6971 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = NULL;
6972 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
6973 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = NULL;
6974 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = NULL; duplicate case value */
6975 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = NULL; duplicate case value */
6976 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = NULL;
6977 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = NULL;
6978 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = NULL;
6979 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = NULL;
6980 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = NULL;
6981 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = NULL;
6982 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = NULL;
6983 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = NULL;
6984 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = NULL;
6985 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = NULL;
6986 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = NULL;
6987 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = NULL;
6988 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = NULL;
6989 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = NULL;
6990 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = NULL;
6993 * These special message types we install handlers for.
6995 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
6996 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with ssh1 */
6997 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
7000 static void ssh2_timer(void *ctx, long now)
7004 if (!ssh->kex_in_progress &&
7005 now - ssh->next_rekey >= 0) {
7006 do_ssh2_transport(ssh, "Initiating key re-exchange (timeout)",
7011 static void ssh2_protocol(Ssh ssh, unsigned char *in, int inlen,
7012 struct Packet *pktin)
7014 if (ssh->state == SSH_STATE_CLOSED)
7018 ssh->incoming_data_size += pktin->encrypted_len;
7019 if (!ssh->kex_in_progress &&
7020 ssh->incoming_data_size > MAX_DATA_BEFORE_REKEY)
7021 do_ssh2_transport(ssh, "Initiating key re-exchange "
7022 "(too much data received)", -1, NULL);
7025 if (pktin && ssh->packet_dispatch[pktin->type]) {
7026 ssh->packet_dispatch[pktin->type](ssh, pktin);
7030 if (!ssh->protocol_initial_phase_done ||
7031 (pktin && pktin->type >= 20 && pktin->type < 50)) {
7032 if (do_ssh2_transport(ssh, in, inlen, pktin) &&
7033 !ssh->protocol_initial_phase_done) {
7034 ssh->protocol_initial_phase_done = TRUE;
7036 * Allow authconn to initialise itself.
7038 do_ssh2_authconn(ssh, NULL, 0, NULL);
7041 do_ssh2_authconn(ssh, in, inlen, pktin);
7046 * Called to set up the connection.
7048 * Returns an error message, or NULL on success.
7050 static const char *ssh_init(void *frontend_handle, void **backend_handle,
7052 char *host, int port, char **realhost, int nodelay,
7058 ssh = snew(struct ssh_tag);
7059 ssh->cfg = *cfg; /* STRUCTURE COPY */
7060 ssh->version = 0; /* when not ready yet */
7063 ssh->v1_cipher_ctx = NULL;
7064 ssh->crcda_ctx = NULL;
7065 ssh->cscipher = NULL;
7066 ssh->cs_cipher_ctx = NULL;
7067 ssh->sccipher = NULL;
7068 ssh->sc_cipher_ctx = NULL;
7070 ssh->cs_mac_ctx = NULL;
7072 ssh->sc_mac_ctx = NULL;
7074 ssh->cs_comp_ctx = NULL;
7076 ssh->sc_comp_ctx = NULL;
7078 ssh->kex_ctx = NULL;
7079 ssh->hostkey = NULL;
7081 ssh->state = SSH_STATE_PREPACKET;
7082 ssh->size_needed = FALSE;
7083 ssh->eof_needed = FALSE;
7086 ssh->deferred_send_data = NULL;
7087 ssh->deferred_len = 0;
7088 ssh->deferred_size = 0;
7089 ssh->fallback_cmd = 0;
7091 ssh->x11auth = NULL;
7092 ssh->v1_compressing = FALSE;
7093 ssh->v2_outgoing_sequence = 0;
7094 ssh->ssh1_rdpkt_crstate = 0;
7095 ssh->ssh2_rdpkt_crstate = 0;
7096 ssh->do_ssh_init_crstate = 0;
7097 ssh->ssh_gotdata_crstate = 0;
7098 ssh->do_ssh1_connection_crstate = 0;
7099 ssh->do_ssh1_login_crstate = 0;
7100 ssh->do_ssh2_transport_crstate = 0;
7101 ssh->do_ssh2_authconn_crstate = 0;
7102 ssh->do_ssh_init_state = NULL;
7103 ssh->do_ssh1_login_state = NULL;
7104 ssh->do_ssh2_transport_state = NULL;
7105 ssh->do_ssh2_authconn_state = NULL;
7106 ssh->mainchan = NULL;
7107 ssh->throttled_all = 0;
7108 ssh->v1_stdout_throttling = 0;
7110 ssh->queuelen = ssh->queuesize = 0;
7111 ssh->queueing = FALSE;
7113 *backend_handle = ssh;
7116 if (crypto_startup() == 0)
7117 return "Microsoft high encryption pack not installed!";
7120 ssh->frontend = frontend_handle;
7121 ssh->term_width = ssh->cfg.width;
7122 ssh->term_height = ssh->cfg.height;
7124 ssh->channels = NULL;
7125 ssh->rportfwds = NULL;
7130 ssh->v1_throttle_count = 0;
7131 ssh->overall_bufsize = 0;
7132 ssh->fallback_cmd = 0;
7134 ssh->protocol = NULL;
7136 ssh->protocol_initial_phase_done = FALSE;
7140 ssh->incoming_data_size = ssh->outgoing_data_size =
7141 ssh->deferred_data_size = 0L;
7142 ssh->kex_in_progress = FALSE;
7144 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
7151 static void ssh_free(void *handle)
7153 Ssh ssh = (Ssh) handle;
7154 struct ssh_channel *c;
7155 struct ssh_rportfwd *pf;
7157 if (ssh->v1_cipher_ctx)
7158 ssh->cipher->free_context(ssh->v1_cipher_ctx);
7159 if (ssh->cs_cipher_ctx)
7160 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
7161 if (ssh->sc_cipher_ctx)
7162 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
7163 if (ssh->cs_mac_ctx)
7164 ssh->csmac->free_context(ssh->cs_mac_ctx);
7165 if (ssh->sc_mac_ctx)
7166 ssh->scmac->free_context(ssh->sc_mac_ctx);
7167 if (ssh->cs_comp_ctx) {
7169 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
7171 zlib_compress_cleanup(ssh->cs_comp_ctx);
7173 if (ssh->sc_comp_ctx) {
7175 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
7177 zlib_decompress_cleanup(ssh->sc_comp_ctx);
7180 dh_cleanup(ssh->kex_ctx);
7181 sfree(ssh->savedhost);
7183 while (ssh->queuelen-- > 0)
7184 ssh_free_packet(ssh->queue[ssh->queuelen]);
7187 if (ssh->channels) {
7188 while ((c = delpos234(ssh->channels, 0)) != NULL) {
7191 if (c->u.x11.s != NULL)
7192 x11_close(c->u.x11.s);
7195 if (c->u.pfd.s != NULL)
7196 pfd_close(c->u.pfd.s);
7201 freetree234(ssh->channels);
7204 if (ssh->rportfwds) {
7205 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
7207 freetree234(ssh->rportfwds);
7209 sfree(ssh->deferred_send_data);
7211 x11_free_auth(ssh->x11auth);
7212 sfree(ssh->do_ssh_init_state);
7213 sfree(ssh->do_ssh1_login_state);
7214 sfree(ssh->do_ssh2_transport_state);
7215 sfree(ssh->do_ssh2_authconn_state);
7216 if (ssh->crcda_ctx) {
7217 crcda_free_context(ssh->crcda_ctx);
7218 ssh->crcda_ctx = NULL;
7222 expire_timer_context(ssh);
7225 pinger_free(ssh->pinger);
7229 * Reconfigure the SSH backend.
7231 * Currently, this function does nothing very useful. In future,
7232 * however, we could do some handy things with it. For example, we
7233 * could make the port forwarding configurer active in the Change
7234 * Settings box, and this routine could close down existing
7235 * forwardings and open up new ones in response to changes.
7237 static void ssh_reconfig(void *handle, Config *cfg)
7239 Ssh ssh = (Ssh) handle;
7240 pinger_reconfig(ssh->pinger, &ssh->cfg, cfg);
7241 ssh->cfg = *cfg; /* STRUCTURE COPY */
7245 * Called to send data down the Telnet connection.
7247 static int ssh_send(void *handle, char *buf, int len)
7249 Ssh ssh = (Ssh) handle;
7251 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
7254 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
7256 return ssh_sendbuffer(ssh);
7260 * Called to query the current amount of buffered stdin data.
7262 static int ssh_sendbuffer(void *handle)
7264 Ssh ssh = (Ssh) handle;
7267 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
7271 * If the SSH socket itself has backed up, add the total backup
7272 * size on that to any individual buffer on the stdin channel.
7275 if (ssh->throttled_all)
7276 override_value = ssh->overall_bufsize;
7278 if (ssh->version == 1) {
7279 return override_value;
7280 } else if (ssh->version == 2) {
7281 if (!ssh->mainchan || ssh->mainchan->closes > 0)
7282 return override_value;
7284 return (override_value +
7285 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
7292 * Called to set the size of the window from SSH's POV.
7294 static void ssh_size(void *handle, int width, int height)
7296 Ssh ssh = (Ssh) handle;
7297 struct Packet *pktout;
7299 ssh->term_width = width;
7300 ssh->term_height = height;
7302 switch (ssh->state) {
7303 case SSH_STATE_BEFORE_SIZE:
7304 case SSH_STATE_PREPACKET:
7305 case SSH_STATE_CLOSED:
7306 break; /* do nothing */
7307 case SSH_STATE_INTERMED:
7308 ssh->size_needed = TRUE; /* buffer for later */
7310 case SSH_STATE_SESSION:
7311 if (!ssh->cfg.nopty) {
7312 if (ssh->version == 1) {
7313 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
7314 PKT_INT, ssh->term_height,
7315 PKT_INT, ssh->term_width,
7316 PKT_INT, 0, PKT_INT, 0, PKT_END);
7317 } else if (ssh->mainchan) {
7318 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7319 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
7320 ssh2_pkt_addstring(pktout, "window-change");
7321 ssh2_pkt_addbool(pktout, 0);
7322 ssh2_pkt_adduint32(pktout, ssh->term_width);
7323 ssh2_pkt_adduint32(pktout, ssh->term_height);
7324 ssh2_pkt_adduint32(pktout, 0);
7325 ssh2_pkt_adduint32(pktout, 0);
7326 ssh2_pkt_send(ssh, pktout);
7334 * Return a list of the special codes that make sense in this
7337 static const struct telnet_special *ssh_get_specials(void *handle)
7339 static const struct telnet_special ignore_special[] = {
7340 {"IGNORE message", TS_NOP},
7341 {"Repeat key exchange", TS_REKEY},
7343 static const struct telnet_special ssh2_session_specials[] = {
7346 /* These are the signal names defined by draft-ietf-secsh-connect-19.
7347 * They include all the ISO C signals, but are a subset of the POSIX
7348 * required signals. */
7349 {"SIGINT (Interrupt)", TS_SIGINT},
7350 {"SIGTERM (Terminate)", TS_SIGTERM},
7351 {"SIGKILL (Kill)", TS_SIGKILL},
7352 {"SIGQUIT (Quit)", TS_SIGQUIT},
7353 {"SIGHUP (Hangup)", TS_SIGHUP},
7354 {"More signals", TS_SUBMENU},
7355 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
7356 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
7357 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
7358 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
7361 static const struct telnet_special specials_end[] = {
7364 static struct telnet_special ssh_specials[lenof(ignore_special) +
7365 lenof(ssh2_session_specials) +
7366 lenof(specials_end)];
7367 Ssh ssh = (Ssh) handle;
7369 #define ADD_SPECIALS(name) \
7371 assert((i + lenof(name)) <= lenof(ssh_specials)); \
7372 memcpy(&ssh_specials[i], name, sizeof name); \
7376 if (ssh->version == 1) {
7377 /* Don't bother offering IGNORE if we've decided the remote
7378 * won't cope with it, since we wouldn't bother sending it if
7380 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
7381 ADD_SPECIALS(ignore_special);
7382 } else if (ssh->version == 2) {
7383 ADD_SPECIALS(ignore_special);
7385 ADD_SPECIALS(ssh2_session_specials);
7386 } /* else we're not ready yet */
7389 ADD_SPECIALS(specials_end);
7390 return ssh_specials;
7398 * Send Telnet special codes. TS_EOF is useful for `plink', so you
7399 * can send an EOF and collect resulting output (e.g. `plink
7402 static void ssh_special(void *handle, Telnet_Special code)
7404 Ssh ssh = (Ssh) handle;
7405 struct Packet *pktout;
7407 if (code == TS_EOF) {
7408 if (ssh->state != SSH_STATE_SESSION) {
7410 * Buffer the EOF in case we are pre-SESSION, so we can
7411 * send it as soon as we reach SESSION.
7414 ssh->eof_needed = TRUE;
7417 if (ssh->version == 1) {
7418 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
7419 } else if (ssh->mainchan) {
7420 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
7421 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
7422 ssh2_pkt_send(ssh, pktout);
7424 logevent("Sent EOF message");
7425 } else if (code == TS_PING || code == TS_NOP) {
7426 if (ssh->state == SSH_STATE_CLOSED
7427 || ssh->state == SSH_STATE_PREPACKET) return;
7428 if (ssh->version == 1) {
7429 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
7430 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
7432 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
7433 ssh2_pkt_addstring_start(pktout);
7434 ssh2_pkt_send_noqueue(ssh, pktout);
7436 } else if (code == TS_REKEY) {
7437 if (!ssh->kex_in_progress && ssh->version == 2) {
7438 do_ssh2_transport(ssh, "Initiating key re-exchange at"
7439 " user request", -1, NULL);
7441 } else if (code == TS_BRK) {
7442 if (ssh->state == SSH_STATE_CLOSED
7443 || ssh->state == SSH_STATE_PREPACKET) return;
7444 if (ssh->version == 1) {
7445 logevent("Unable to send BREAK signal in SSH1");
7446 } else if (ssh->mainchan) {
7447 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7448 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
7449 ssh2_pkt_addstring(pktout, "break");
7450 ssh2_pkt_addbool(pktout, 0);
7451 ssh2_pkt_adduint32(pktout, 0); /* default break length */
7452 ssh2_pkt_send(ssh, pktout);
7455 /* Is is a POSIX signal? */
7456 char *signame = NULL;
7457 if (code == TS_SIGABRT) signame = "ABRT";
7458 if (code == TS_SIGALRM) signame = "ALRM";
7459 if (code == TS_SIGFPE) signame = "FPE";
7460 if (code == TS_SIGHUP) signame = "HUP";
7461 if (code == TS_SIGILL) signame = "ILL";
7462 if (code == TS_SIGINT) signame = "INT";
7463 if (code == TS_SIGKILL) signame = "KILL";
7464 if (code == TS_SIGPIPE) signame = "PIPE";
7465 if (code == TS_SIGQUIT) signame = "QUIT";
7466 if (code == TS_SIGSEGV) signame = "SEGV";
7467 if (code == TS_SIGTERM) signame = "TERM";
7468 if (code == TS_SIGUSR1) signame = "USR1";
7469 if (code == TS_SIGUSR2) signame = "USR2";
7470 /* The SSH-2 protocol does in principle support arbitrary named
7471 * signals, including signame@domain, but we don't support those. */
7473 /* It's a signal. */
7474 if (ssh->version == 2 && ssh->mainchan) {
7475 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7476 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
7477 ssh2_pkt_addstring(pktout, "signal");
7478 ssh2_pkt_addbool(pktout, 0);
7479 ssh2_pkt_addstring(pktout, signame);
7480 ssh2_pkt_send(ssh, pktout);
7481 logeventf(ssh, "Sent signal SIG%s", signame);
7484 /* Never heard of it. Do nothing */
7489 void *new_sock_channel(void *handle, Socket s)
7491 Ssh ssh = (Ssh) handle;
7492 struct ssh_channel *c;
7493 c = snew(struct ssh_channel);
7497 c->remoteid = -1; /* to be set when open confirmed */
7498 c->localid = alloc_channel_id(ssh);
7500 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
7502 bufchain_init(&c->v.v2.outbuffer);
7503 add234(ssh->channels, c);
7509 * This is called when stdout/stderr (the entity to which
7510 * from_backend sends data) manages to clear some backlog.
7512 static void ssh_unthrottle(void *handle, int bufsize)
7514 Ssh ssh = (Ssh) handle;
7515 if (ssh->version == 1) {
7516 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
7517 ssh->v1_stdout_throttling = 0;
7518 ssh1_throttle(ssh, -1);
7521 if (ssh->mainchan && ssh->mainchan->closes == 0)
7522 ssh2_set_window(ssh->mainchan, OUR_V2_WINSIZE - bufsize);
7526 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
7528 struct ssh_channel *c = (struct ssh_channel *)channel;
7530 struct Packet *pktout;
7532 logeventf(ssh, "Opening forwarded connection to %s:%d", hostname, port);
7534 if (ssh->version == 1) {
7535 send_packet(ssh, SSH1_MSG_PORT_OPEN,
7536 PKT_INT, c->localid,
7539 //PKT_STR, <org:orgport>,
7542 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7543 ssh2_pkt_addstring(pktout, "direct-tcpip");
7544 ssh2_pkt_adduint32(pktout, c->localid);
7545 c->v.v2.locwindow = OUR_V2_WINSIZE;
7546 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
7547 ssh2_pkt_adduint32(pktout, 0x4000UL); /* our max pkt size */
7548 ssh2_pkt_addstring(pktout, hostname);
7549 ssh2_pkt_adduint32(pktout, port);
7551 * We make up values for the originator data; partly it's
7552 * too much hassle to keep track, and partly I'm not
7553 * convinced the server should be told details like that
7554 * about my local network configuration.
7556 ssh2_pkt_addstring(pktout, "client-side-connection");
7557 ssh2_pkt_adduint32(pktout, 0);
7558 ssh2_pkt_send(ssh, pktout);
7562 static Socket ssh_socket(void *handle)
7564 Ssh ssh = (Ssh) handle;
7568 static int ssh_sendok(void *handle)
7570 Ssh ssh = (Ssh) handle;
7571 return ssh->send_ok;
7574 static int ssh_ldisc(void *handle, int option)
7576 Ssh ssh = (Ssh) handle;
7577 if (option == LD_ECHO)
7578 return ssh->echoing;
7579 if (option == LD_EDIT)
7580 return ssh->editing;
7584 static void ssh_provide_ldisc(void *handle, void *ldisc)
7586 Ssh ssh = (Ssh) handle;
7590 static void ssh_provide_logctx(void *handle, void *logctx)
7592 Ssh ssh = (Ssh) handle;
7593 ssh->logctx = logctx;
7596 static int ssh_return_exitcode(void *handle)
7598 Ssh ssh = (Ssh) handle;
7602 return (ssh->exitcode >= 0 ? ssh->exitcode : 0);
7606 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
7607 * that fails. This variable is the means by which scp.c can reach
7608 * into the SSH code and find out which one it got.
7610 extern int ssh_fallback_cmd(void *handle)
7612 Ssh ssh = (Ssh) handle;
7613 return ssh->fallback_cmd;
7616 Backend ssh_backend = {
7626 ssh_return_exitcode,