17 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
18 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
19 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
20 #define SSH1_CMSG_USER 4 /* 0x4 */
21 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
22 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
23 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
24 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
25 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
26 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
27 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
28 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
29 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
30 #define SSH1_SMSG_FAILURE 15 /* 0xf */
31 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
32 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
33 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
34 #define SSH1_CMSG_EOF 19 /* 0x13 */
35 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
36 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
37 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
38 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
39 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
40 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
41 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
42 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
43 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
44 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
45 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
46 #define SSH1_MSG_IGNORE 32 /* 0x20 */
47 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
48 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
49 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
50 #define SSH1_MSG_DEBUG 36 /* 0x24 */
51 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
52 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
53 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
54 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
55 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
56 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
57 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
59 #define SSH1_AUTH_TIS 5 /* 0x5 */
60 #define SSH1_AUTH_CCARD 16 /* 0x10 */
62 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
63 /* Mask for protoflags we will echo back to server if seen */
64 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
66 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
67 #define SSH2_MSG_IGNORE 2 /* 0x2 */
68 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
69 #define SSH2_MSG_DEBUG 4 /* 0x4 */
70 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
71 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
72 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
73 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
74 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
75 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
76 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
77 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
78 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
79 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
80 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
81 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
82 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
83 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
84 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
85 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
86 #define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */
87 #define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */
88 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
89 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
90 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
91 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
92 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
93 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
94 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
95 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
96 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
97 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
98 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
99 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
100 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
101 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
104 * Packet type contexts, so that ssh2_pkt_type can correctly decode
105 * the ambiguous type numbers back into the correct type strings.
107 #define SSH2_PKTCTX_DHGROUP 0x0001
108 #define SSH2_PKTCTX_DHGEX 0x0002
109 #define SSH2_PKTCTX_KEX_MASK 0x000F
110 #define SSH2_PKTCTX_PUBLICKEY 0x0010
111 #define SSH2_PKTCTX_PASSWORD 0x0020
112 #define SSH2_PKTCTX_KBDINTER 0x0040
113 #define SSH2_PKTCTX_AUTH_MASK 0x00F0
115 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
116 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
117 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
118 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
119 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
120 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
121 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
122 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
123 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
124 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
125 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
126 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
127 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
128 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
129 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
131 static const char *const ssh2_disconnect_reasons[] = {
133 "SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT",
134 "SSH_DISCONNECT_PROTOCOL_ERROR",
135 "SSH_DISCONNECT_KEY_EXCHANGE_FAILED",
136 "SSH_DISCONNECT_HOST_AUTHENTICATION_FAILED",
137 "SSH_DISCONNECT_MAC_ERROR",
138 "SSH_DISCONNECT_COMPRESSION_ERROR",
139 "SSH_DISCONNECT_SERVICE_NOT_AVAILABLE",
140 "SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED",
141 "SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE",
142 "SSH_DISCONNECT_CONNECTION_LOST",
143 "SSH_DISCONNECT_BY_APPLICATION",
144 "SSH_DISCONNECT_TOO_MANY_CONNECTIONS",
145 "SSH_DISCONNECT_AUTH_CANCELLED_BY_USER",
146 "SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE",
147 "SSH_DISCONNECT_ILLEGAL_USER_NAME",
150 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
151 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
152 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
153 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
155 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
158 * Various remote-bug flags.
160 #define BUG_CHOKES_ON_SSH1_IGNORE 1
161 #define BUG_SSH2_HMAC 2
162 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
163 #define BUG_CHOKES_ON_RSA 8
164 #define BUG_SSH2_RSA_PADDING 16
165 #define BUG_SSH2_DERIVEKEY 32
166 #define BUG_SSH2_REKEY 64
167 #define BUG_SSH2_PK_SESSIONID 128
169 #define translate(x) if (type == x) return #x
170 #define translatec(x,ctx) if (type == x && (pkt_ctx & ctx)) return #x
171 static char *ssh1_pkt_type(int type)
173 translate(SSH1_MSG_DISCONNECT);
174 translate(SSH1_SMSG_PUBLIC_KEY);
175 translate(SSH1_CMSG_SESSION_KEY);
176 translate(SSH1_CMSG_USER);
177 translate(SSH1_CMSG_AUTH_RSA);
178 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
179 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
180 translate(SSH1_CMSG_AUTH_PASSWORD);
181 translate(SSH1_CMSG_REQUEST_PTY);
182 translate(SSH1_CMSG_WINDOW_SIZE);
183 translate(SSH1_CMSG_EXEC_SHELL);
184 translate(SSH1_CMSG_EXEC_CMD);
185 translate(SSH1_SMSG_SUCCESS);
186 translate(SSH1_SMSG_FAILURE);
187 translate(SSH1_CMSG_STDIN_DATA);
188 translate(SSH1_SMSG_STDOUT_DATA);
189 translate(SSH1_SMSG_STDERR_DATA);
190 translate(SSH1_CMSG_EOF);
191 translate(SSH1_SMSG_EXIT_STATUS);
192 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
193 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
194 translate(SSH1_MSG_CHANNEL_DATA);
195 translate(SSH1_MSG_CHANNEL_CLOSE);
196 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
197 translate(SSH1_SMSG_X11_OPEN);
198 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
199 translate(SSH1_MSG_PORT_OPEN);
200 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
201 translate(SSH1_SMSG_AGENT_OPEN);
202 translate(SSH1_MSG_IGNORE);
203 translate(SSH1_CMSG_EXIT_CONFIRMATION);
204 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
205 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
206 translate(SSH1_MSG_DEBUG);
207 translate(SSH1_CMSG_REQUEST_COMPRESSION);
208 translate(SSH1_CMSG_AUTH_TIS);
209 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
210 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
211 translate(SSH1_CMSG_AUTH_CCARD);
212 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
213 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
216 static char *ssh2_pkt_type(int pkt_ctx, int type)
218 translate(SSH2_MSG_DISCONNECT);
219 translate(SSH2_MSG_IGNORE);
220 translate(SSH2_MSG_UNIMPLEMENTED);
221 translate(SSH2_MSG_DEBUG);
222 translate(SSH2_MSG_SERVICE_REQUEST);
223 translate(SSH2_MSG_SERVICE_ACCEPT);
224 translate(SSH2_MSG_KEXINIT);
225 translate(SSH2_MSG_NEWKEYS);
226 translatec(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP);
227 translatec(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP);
228 translatec(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
229 translatec(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
230 translatec(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
231 translatec(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
232 translate(SSH2_MSG_USERAUTH_REQUEST);
233 translate(SSH2_MSG_USERAUTH_FAILURE);
234 translate(SSH2_MSG_USERAUTH_SUCCESS);
235 translate(SSH2_MSG_USERAUTH_BANNER);
236 translatec(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
237 translatec(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
238 translatec(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
239 translatec(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
240 translate(SSH2_MSG_GLOBAL_REQUEST);
241 translate(SSH2_MSG_REQUEST_SUCCESS);
242 translate(SSH2_MSG_REQUEST_FAILURE);
243 translate(SSH2_MSG_CHANNEL_OPEN);
244 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
245 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
246 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
247 translate(SSH2_MSG_CHANNEL_DATA);
248 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
249 translate(SSH2_MSG_CHANNEL_EOF);
250 translate(SSH2_MSG_CHANNEL_CLOSE);
251 translate(SSH2_MSG_CHANNEL_REQUEST);
252 translate(SSH2_MSG_CHANNEL_SUCCESS);
253 translate(SSH2_MSG_CHANNEL_FAILURE);
259 /* Enumeration values for fields in SSH-1 packets */
261 PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
262 /* These values are for communicating relevant semantics of
263 * fields to the packet logging code. */
264 PKTT_OTHER, PKTT_PASSWORD, PKTT_DATA
268 * Coroutine mechanics for the sillier bits of the code. If these
269 * macros look impenetrable to you, you might find it helpful to
272 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
274 * which explains the theory behind these macros.
276 * In particular, if you are getting `case expression not constant'
277 * errors when building with MS Visual Studio, this is because MS's
278 * Edit and Continue debugging feature causes their compiler to
279 * violate ANSI C. To disable Edit and Continue debugging:
281 * - right-click ssh.c in the FileView
283 * - select the C/C++ tab and the General category
284 * - under `Debug info:', select anything _other_ than `Program
285 * Database for Edit and Continue'.
287 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
290 if (!ssh->t) ssh->t = snew(struct t); \
292 #define crFinish(z) } *crLine = 0; return (z); }
293 #define crFinishV } *crLine = 0; return; }
294 #define crReturn(z) \
296 *crLine =__LINE__; return (z); case __LINE__:;\
300 *crLine=__LINE__; return; case __LINE__:;\
302 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
303 #define crStopV do{ *crLine = 0; return; }while(0)
304 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
305 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
307 typedef struct ssh_tag *Ssh;
310 static struct Packet *ssh1_pkt_init(int pkt_type);
311 static struct Packet *ssh2_pkt_init(int pkt_type);
312 static void ssh_pkt_ensure(struct Packet *, int length);
313 static void ssh_pkt_adddata(struct Packet *, void *data, int len);
314 static void ssh_pkt_addbyte(struct Packet *, unsigned char value);
315 static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
316 static void ssh_pkt_adduint32(struct Packet *, unsigned long value);
317 static void ssh_pkt_addstring_start(struct Packet *);
318 static void ssh_pkt_addstring_str(struct Packet *, char *data);
319 static void ssh_pkt_addstring_data(struct Packet *, char *data, int len);
320 static void ssh_pkt_addstring(struct Packet *, char *data);
321 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
322 static void ssh1_pkt_addmp(struct Packet *, Bignum b);
323 static void ssh2_pkt_addmp(struct Packet *, Bignum b);
324 static int ssh2_pkt_construct(Ssh, struct Packet *);
325 static void ssh2_pkt_send(Ssh, struct Packet *);
326 static void ssh2_pkt_send_noqueue(Ssh, struct Packet *);
327 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
328 struct Packet *pktin);
329 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
330 struct Packet *pktin);
333 * Buffer management constants. There are several of these for
334 * various different purposes:
336 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
337 * on a local data stream before we throttle the whole SSH
338 * connection (in SSH-1 only). Throttling the whole connection is
339 * pretty drastic so we set this high in the hope it won't
342 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
343 * on the SSH connection itself before we defensively throttle
344 * _all_ local data streams. This is pretty drastic too (though
345 * thankfully unlikely in SSH-2 since the window mechanism should
346 * ensure that the server never has any need to throttle its end
347 * of the connection), so we set this high as well.
349 * - OUR_V2_WINSIZE is the maximum window size we present on SSH-2
353 #define SSH1_BUFFER_LIMIT 32768
354 #define SSH_MAX_BACKLOG 32768
355 #define OUR_V2_WINSIZE 16384
356 #define OUR_V2_MAXPKT 0x4000UL
358 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
360 const static struct ssh_mac *macs[] = {
363 const static struct ssh_mac *buggymacs[] = {
364 &ssh_sha1_buggy, &ssh_md5
367 static void *ssh_comp_none_init(void)
371 static void ssh_comp_none_cleanup(void *handle)
374 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
375 unsigned char **outblock, int *outlen)
379 static int ssh_comp_none_disable(void *handle)
383 const static struct ssh_compress ssh_comp_none = {
385 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
386 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
387 ssh_comp_none_disable, NULL
389 extern const struct ssh_compress ssh_zlib;
390 const static struct ssh_compress *compressions[] = {
391 &ssh_zlib, &ssh_comp_none
394 enum { /* channel types */
399 CHAN_SOCKDATA_DORMANT /* one the remote hasn't confirmed */
403 * 2-3-4 tree storing channels.
406 Ssh ssh; /* pointer back to main context */
407 unsigned remoteid, localid;
409 /* True if we opened this channel but server hasn't confirmed. */
412 * In SSH-1, this value contains four bits:
414 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
415 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
416 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
417 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
419 * A channel is completely finished with when all four bits are set.
423 struct ssh1_data_channel {
426 struct ssh2_data_channel {
428 unsigned remwindow, remmaxpkt;
433 struct ssh_agent_channel {
434 unsigned char *message;
435 unsigned char msglen[4];
436 unsigned lensofar, totallen;
438 struct ssh_x11_channel {
441 struct ssh_pfd_channel {
448 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
449 * use this structure in different ways, reflecting SSH-2's
450 * altogether saner approach to port forwarding.
452 * In SSH-1, you arrange a remote forwarding by sending the server
453 * the remote port number, and the local destination host:port.
454 * When a connection comes in, the server sends you back that
455 * host:port pair, and you connect to it. This is a ready-made
456 * security hole if you're not on the ball: a malicious server
457 * could send you back _any_ host:port pair, so if you trustingly
458 * connect to the address it gives you then you've just opened the
459 * entire inside of your corporate network just by connecting
460 * through it to a dodgy SSH server. Hence, we must store a list of
461 * host:port pairs we _are_ trying to forward to, and reject a
462 * connection request from the server if it's not in the list.
464 * In SSH-2, each side of the connection minds its own business and
465 * doesn't send unnecessary information to the other. You arrange a
466 * remote forwarding by sending the server just the remote port
467 * number. When a connection comes in, the server tells you which
468 * of its ports was connected to; and _you_ have to remember what
469 * local host:port pair went with that port number.
471 * Hence, in SSH-1 this structure is indexed by destination
472 * host:port pair, whereas in SSH-2 it is indexed by source port.
474 struct ssh_portfwd; /* forward declaration */
476 struct ssh_rportfwd {
477 unsigned sport, dport;
480 struct ssh_portfwd *pfrec;
482 #define free_rportfwd(pf) ( \
483 ((pf) ? (sfree((pf)->sportdesc)) : (void)0 ), sfree(pf) )
486 * Separately to the rportfwd tree (which is for looking up port
487 * open requests from the server), a tree of _these_ structures is
488 * used to keep track of all the currently open port forwardings,
489 * so that we can reconfigure in mid-session if the user requests
493 enum { DESTROY, KEEP, CREATE } status;
495 unsigned sport, dport;
498 struct ssh_rportfwd *remote;
502 #define free_portfwd(pf) ( \
503 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
504 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
507 long length; /* length of `data' actually used */
508 long forcepad; /* SSH-2: force padding to at least this length */
509 int type; /* only used for incoming packets */
510 unsigned long sequence; /* SSH-2 incoming sequence number */
511 unsigned char *data; /* allocated storage */
512 unsigned char *body; /* offset of payload within `data' */
513 long savedpos; /* temporary index into `data' (for strings) */
514 long maxlen; /* amount of storage allocated for `data' */
515 long encrypted_len; /* for SSH-2 total-size counting */
518 * State associated with packet logging
522 struct logblank_t *blanks;
525 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
526 struct Packet *pktin);
527 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
528 struct Packet *pktin);
529 static void ssh1_protocol_setup(Ssh ssh);
530 static void ssh2_protocol_setup(Ssh ssh);
531 static void ssh_size(void *handle, int width, int height);
532 static void ssh_special(void *handle, Telnet_Special);
533 static int ssh2_try_send(struct ssh_channel *c);
534 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
535 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
536 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin);
537 static int ssh_sendbuffer(void *handle);
538 static int ssh_do_close(Ssh ssh, int notify_exit);
539 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
540 static int ssh2_pkt_getbool(struct Packet *pkt);
541 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
542 static void ssh2_timer(void *ctx, long now);
543 static int do_ssh2_transport(Ssh ssh, void *vin, int inlen,
544 struct Packet *pktin);
546 struct rdpkt1_state_tag {
547 long len, pad, biglen, to_read;
548 unsigned long realcrc, gotcrc;
552 struct Packet *pktin;
555 struct rdpkt2_state_tag {
556 long len, pad, payload, packetlen, maclen;
559 unsigned long incoming_sequence;
560 struct Packet *pktin;
563 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
564 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
566 struct queued_handler;
567 struct queued_handler {
569 chandler_fn_t handler;
571 struct queued_handler *next;
575 const struct plug_function_table *fn;
576 /* the above field _must_ be first in the structure */
578 SHA_State exhash, exhashbase;
585 unsigned char session_key[32];
587 int v1_remote_protoflags;
588 int v1_local_protoflags;
589 int agentfwd_enabled;
592 const struct ssh_cipher *cipher;
595 const struct ssh2_cipher *cscipher, *sccipher;
596 void *cs_cipher_ctx, *sc_cipher_ctx;
597 const struct ssh_mac *csmac, *scmac;
598 void *cs_mac_ctx, *sc_mac_ctx;
599 const struct ssh_compress *cscomp, *sccomp;
600 void *cs_comp_ctx, *sc_comp_ctx;
601 const struct ssh_kex *kex;
602 const struct ssh_signkey *hostkey;
603 unsigned char v2_session_id[20];
609 int echoing, editing;
613 int ospeed, ispeed; /* temporaries */
614 int term_width, term_height;
616 tree234 *channels; /* indexed by local id */
617 struct ssh_channel *mainchan; /* primary session channel */
621 tree234 *rportfwds, *portfwds;
625 SSH_STATE_BEFORE_SIZE,
631 int size_needed, eof_needed;
633 struct Packet **queue;
634 int queuelen, queuesize;
636 unsigned char *deferred_send_data;
637 int deferred_len, deferred_size;
640 * Gross hack: pscp will try to start SFTP but fall back to
641 * scp1 if that fails. This variable is the means by which
642 * scp.c can reach into the SSH code and find out which one it
648 * Used for username and password input.
650 char *userpass_input_buffer;
651 int userpass_input_buflen;
652 int userpass_input_bufpos;
653 int userpass_input_echo;
660 int v1_throttle_count;
663 int v1_stdout_throttling;
664 unsigned long v2_outgoing_sequence;
666 int ssh1_rdpkt_crstate;
667 int ssh2_rdpkt_crstate;
668 int do_ssh_init_crstate;
669 int ssh_gotdata_crstate;
670 int do_ssh1_login_crstate;
671 int do_ssh1_connection_crstate;
672 int do_ssh2_transport_crstate;
673 int do_ssh2_authconn_crstate;
675 void *do_ssh_init_state;
676 void *do_ssh1_login_state;
677 void *do_ssh2_transport_state;
678 void *do_ssh2_authconn_state;
680 struct rdpkt1_state_tag rdpkt1_state;
681 struct rdpkt2_state_tag rdpkt2_state;
683 /* SSH-1 and SSH-2 use this for different things, but both use it */
684 int protocol_initial_phase_done;
686 void (*protocol) (Ssh ssh, void *vin, int inlen,
688 struct Packet *(*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
691 * We maintain a full _copy_ of a Config structure here, not
692 * merely a pointer to it. That way, when we're passed a new
693 * one for reconfiguration, we can check the differences and
694 * potentially reconfigure port forwardings etc in mid-session.
699 * Used to transfer data back from async callbacks.
701 void *agent_response;
702 int agent_response_len;
706 * The SSH connection can be set as `frozen', meaning we are
707 * not currently accepting incoming data from the network. This
708 * is slightly more serious than setting the _socket_ as
709 * frozen, because we may already have had data passed to us
710 * from the network which we need to delay processing until
711 * after the freeze is lifted, so we also need a bufchain to
715 bufchain queued_incoming_data;
718 * Dispatch table for packet types that we may have to deal
721 handler_fn_t packet_dispatch[256];
724 * Queues of one-off handler functions for success/failure
725 * indications from a request.
727 struct queued_handler *qhead, *qtail;
730 * This module deals with sending keepalives.
735 * Track incoming and outgoing data sizes and time, for
738 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
739 unsigned long max_data_size;
741 long next_rekey, last_rekey;
742 char *deferred_rekey_reason; /* points to STATIC string; don't free */
745 #define logevent(s) logevent(ssh->frontend, s)
747 /* logevent, only printf-formatted. */
748 static void logeventf(Ssh ssh, const char *fmt, ...)
754 buf = dupvprintf(fmt, ap);
760 #define bombout(msg) \
762 char *text = dupprintf msg; \
763 ssh_do_close(ssh, FALSE); \
765 connection_fatal(ssh->frontend, "%s", text); \
769 /* Functions to leave bits out of the SSH packet log file. */
771 static void dont_log_password(Ssh ssh, struct Packet *pkt, int blanktype)
773 if (ssh->cfg.logomitpass)
774 pkt->logmode = blanktype;
777 static void dont_log_data(Ssh ssh, struct Packet *pkt, int blanktype)
779 if (ssh->cfg.logomitdata)
780 pkt->logmode = blanktype;
783 static void end_log_omission(Ssh ssh, struct Packet *pkt)
785 pkt->logmode = PKTLOG_EMIT;
788 static int ssh_channelcmp(void *av, void *bv)
790 struct ssh_channel *a = (struct ssh_channel *) av;
791 struct ssh_channel *b = (struct ssh_channel *) bv;
792 if (a->localid < b->localid)
794 if (a->localid > b->localid)
798 static int ssh_channelfind(void *av, void *bv)
800 unsigned *a = (unsigned *) av;
801 struct ssh_channel *b = (struct ssh_channel *) bv;
809 static int ssh_rportcmp_ssh1(void *av, void *bv)
811 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
812 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
814 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
815 return i < 0 ? -1 : +1;
816 if (a->dport > b->dport)
818 if (a->dport < b->dport)
823 static int ssh_rportcmp_ssh2(void *av, void *bv)
825 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
826 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
828 if (a->sport > b->sport)
830 if (a->sport < b->sport)
836 * Special form of strcmp which can cope with NULL inputs. NULL is
837 * defined to sort before even the empty string.
839 static int nullstrcmp(const char *a, const char *b)
841 if (a == NULL && b == NULL)
850 static int ssh_portcmp(void *av, void *bv)
852 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
853 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
855 if (a->type > b->type)
857 if (a->type < b->type)
859 if (a->addressfamily > b->addressfamily)
861 if (a->addressfamily < b->addressfamily)
863 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
864 return i < 0 ? -1 : +1;
865 if (a->sport > b->sport)
867 if (a->sport < b->sport)
869 if (a->type != 'D') {
870 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
871 return i < 0 ? -1 : +1;
872 if (a->dport > b->dport)
874 if (a->dport < b->dport)
880 static int alloc_channel_id(Ssh ssh)
882 const unsigned CHANNEL_NUMBER_OFFSET = 256;
883 unsigned low, high, mid;
885 struct ssh_channel *c;
888 * First-fit allocation of channel numbers: always pick the
889 * lowest unused one. To do this, binary-search using the
890 * counted B-tree to find the largest channel ID which is in a
891 * contiguous sequence from the beginning. (Precisely
892 * everything in that sequence must have ID equal to its tree
893 * index plus CHANNEL_NUMBER_OFFSET.)
895 tsize = count234(ssh->channels);
899 while (high - low > 1) {
900 mid = (high + low) / 2;
901 c = index234(ssh->channels, mid);
902 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
903 low = mid; /* this one is fine */
905 high = mid; /* this one is past it */
908 * Now low points to either -1, or the tree index of the
909 * largest ID in the initial sequence.
912 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
913 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
915 return low + 1 + CHANNEL_NUMBER_OFFSET;
918 static void c_write(Ssh ssh, const char *buf, int len)
920 if ((flags & FLAG_STDERR)) {
922 for (i = 0; i < len; i++)
924 fputc(buf[i], stderr);
927 from_backend(ssh->frontend, 1, buf, len);
930 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
933 for (i = 0; i < len; i++) {
935 c_write(ssh, "\r\n", 2);
936 else if ((buf[i] & 0x60) || (buf[i] == '\r'))
937 c_write(ssh, buf + i, 1);
941 static void c_write_str(Ssh ssh, const char *buf)
943 c_write(ssh, buf, strlen(buf));
946 static void ssh_free_packet(struct Packet *pkt)
951 static struct Packet *ssh_new_packet(void)
953 struct Packet *pkt = snew(struct Packet);
955 pkt->body = pkt->data = NULL;
957 pkt->logmode = PKTLOG_EMIT;
965 * Collect incoming data in the incoming packet buffer.
966 * Decipher and verify the packet when it is completely read.
967 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
968 * Update the *data and *datalen variables.
969 * Return a Packet structure when a packet is completed.
971 static struct Packet *ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
973 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
975 crBegin(ssh->ssh1_rdpkt_crstate);
977 st->pktin = ssh_new_packet();
980 st->pktin->length = 0;
982 for (st->i = st->len = 0; st->i < 4; st->i++) {
983 while ((*datalen) == 0)
985 st->len = (st->len << 8) + **data;
986 (*data)++, (*datalen)--;
989 st->pad = 8 - (st->len % 8);
990 st->biglen = st->len + st->pad;
991 st->pktin->length = st->len - 5;
993 if (st->biglen < 0) {
994 bombout(("Extremely large packet length from server suggests"
995 " data stream corruption"));
996 ssh_free_packet(st->pktin);
1000 st->pktin->maxlen = st->biglen;
1001 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1003 st->to_read = st->biglen;
1004 st->p = st->pktin->data;
1005 while (st->to_read > 0) {
1006 st->chunk = st->to_read;
1007 while ((*datalen) == 0)
1009 if (st->chunk > (*datalen))
1010 st->chunk = (*datalen);
1011 memcpy(st->p, *data, st->chunk);
1013 *datalen -= st->chunk;
1015 st->to_read -= st->chunk;
1018 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1019 st->biglen, NULL)) {
1020 bombout(("Network attack (CRC compensation) detected!"));
1021 ssh_free_packet(st->pktin);
1026 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1028 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1029 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1030 if (st->gotcrc != st->realcrc) {
1031 bombout(("Incorrect CRC received on packet"));
1032 ssh_free_packet(st->pktin);
1036 st->pktin->body = st->pktin->data + st->pad + 1;
1037 st->pktin->savedpos = 0;
1039 if (ssh->v1_compressing) {
1040 unsigned char *decompblk;
1042 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1043 st->pktin->body - 1, st->pktin->length + 1,
1044 &decompblk, &decomplen)) {
1045 bombout(("Zlib decompression encountered invalid data"));
1046 ssh_free_packet(st->pktin);
1050 if (st->pktin->maxlen < st->pad + decomplen) {
1051 st->pktin->maxlen = st->pad + decomplen;
1052 st->pktin->data = sresize(st->pktin->data,
1053 st->pktin->maxlen + APIEXTRA,
1055 st->pktin->body = st->pktin->data + st->pad + 1;
1058 memcpy(st->pktin->body - 1, decompblk, decomplen);
1060 st->pktin->length = decomplen - 1;
1063 st->pktin->type = st->pktin->body[-1];
1066 * Log incoming packet, possibly omitting sensitive fields.
1070 struct logblank_t blank;
1071 if (ssh->cfg.logomitdata) {
1072 int do_blank = FALSE, blank_prefix = 0;
1073 /* "Session data" packets - omit the data field */
1074 if ((st->pktin->type == SSH1_SMSG_STDOUT_DATA) ||
1075 (st->pktin->type == SSH1_SMSG_STDERR_DATA)) {
1076 do_blank = TRUE; blank_prefix = 0;
1077 } else if (st->pktin->type == SSH1_MSG_CHANNEL_DATA) {
1078 do_blank = TRUE; blank_prefix = 4;
1081 blank.offset = blank_prefix;
1082 blank.len = st->pktin->length;
1083 blank.type = PKTLOG_OMIT;
1087 log_packet(ssh->logctx,
1088 PKT_INCOMING, st->pktin->type,
1089 ssh1_pkt_type(st->pktin->type),
1090 st->pktin->body, st->pktin->length,
1094 crFinish(st->pktin);
1097 static struct Packet *ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1099 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1101 crBegin(ssh->ssh2_rdpkt_crstate);
1103 st->pktin = ssh_new_packet();
1105 st->pktin->type = 0;
1106 st->pktin->length = 0;
1108 st->cipherblk = ssh->sccipher->blksize;
1111 if (st->cipherblk < 8)
1114 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1117 * Acquire and decrypt the first block of the packet. This will
1118 * contain the length and padding details.
1120 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1121 while ((*datalen) == 0)
1123 st->pktin->data[st->i] = *(*data)++;
1128 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1129 st->pktin->data, st->cipherblk);
1132 * Now get the length and padding figures.
1134 st->len = GET_32BIT(st->pktin->data);
1135 st->pad = st->pktin->data[4];
1138 * _Completely_ silly lengths should be stomped on before they
1139 * do us any more damage.
1141 if (st->len < 0 || st->pad < 0 || st->len + st->pad < 0) {
1142 bombout(("Incoming packet was garbled on decryption"));
1143 ssh_free_packet(st->pktin);
1148 * This enables us to deduce the payload length.
1150 st->payload = st->len - st->pad - 1;
1152 st->pktin->length = st->payload + 5;
1155 * So now we can work out the total packet length.
1157 st->packetlen = st->len + 4;
1158 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1161 * Allocate memory for the rest of the packet.
1163 st->pktin->maxlen = st->packetlen + st->maclen;
1164 st->pktin->data = sresize(st->pktin->data,
1165 st->pktin->maxlen + APIEXTRA,
1169 * Read and decrypt the remainder of the packet.
1171 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1173 while ((*datalen) == 0)
1175 st->pktin->data[st->i] = *(*data)++;
1178 /* Decrypt everything _except_ the MAC. */
1180 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1181 st->pktin->data + st->cipherblk,
1182 st->packetlen - st->cipherblk);
1184 st->pktin->encrypted_len = st->packetlen;
1190 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data, st->len + 4,
1191 st->incoming_sequence)) {
1192 bombout(("Incorrect MAC received on packet"));
1193 ssh_free_packet(st->pktin);
1197 st->pktin->sequence = st->incoming_sequence++;
1200 * Decompress packet payload.
1203 unsigned char *newpayload;
1206 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1207 st->pktin->data + 5, st->pktin->length - 5,
1208 &newpayload, &newlen)) {
1209 if (st->pktin->maxlen < newlen + 5) {
1210 st->pktin->maxlen = newlen + 5;
1211 st->pktin->data = sresize(st->pktin->data,
1212 st->pktin->maxlen + APIEXTRA,
1215 st->pktin->length = 5 + newlen;
1216 memcpy(st->pktin->data + 5, newpayload, newlen);
1221 st->pktin->savedpos = 6;
1222 st->pktin->body = st->pktin->data;
1223 st->pktin->type = st->pktin->data[5];
1226 * Log incoming packet, possibly omitting sensitive fields.
1230 struct logblank_t blank;
1231 if (ssh->cfg.logomitdata) {
1232 int do_blank = FALSE, blank_prefix = 0;
1233 /* "Session data" packets - omit the data field */
1234 if (st->pktin->type == SSH2_MSG_CHANNEL_DATA) {
1235 do_blank = TRUE; blank_prefix = 4;
1236 } else if (st->pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
1237 do_blank = TRUE; blank_prefix = 8;
1240 blank.offset = blank_prefix;
1241 blank.len = (st->pktin->length-6) - blank_prefix;
1242 blank.type = PKTLOG_OMIT;
1246 log_packet(ssh->logctx, PKT_INCOMING, st->pktin->type,
1247 ssh2_pkt_type(ssh->pkt_ctx, st->pktin->type),
1248 st->pktin->data+6, st->pktin->length-6,
1252 crFinish(st->pktin);
1255 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1257 int pad, biglen, i, pktoffs;
1261 * XXX various versions of SC (including 8.8.4) screw up the
1262 * register allocation in this function and use the same register
1263 * (D6) for len and as a temporary, with predictable results. The
1264 * following sledgehammer prevents this.
1271 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1272 ssh1_pkt_type(pkt->data[12]),
1273 pkt->body, pkt->length - (pkt->body - pkt->data),
1274 pkt->nblanks, pkt->blanks);
1275 sfree(pkt->blanks); pkt->blanks = NULL;
1278 if (ssh->v1_compressing) {
1279 unsigned char *compblk;
1281 zlib_compress_block(ssh->cs_comp_ctx,
1282 pkt->data + 12, pkt->length - 12,
1283 &compblk, &complen);
1284 memcpy(pkt->data + 12, compblk, complen);
1286 pkt->length = complen + 12;
1289 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1291 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1292 pad = 8 - (len % 8);
1294 biglen = len + pad; /* len(padding+type+data+CRC) */
1296 for (i = pktoffs; i < 4+8; i++)
1297 pkt->data[i] = random_byte();
1298 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
1299 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
1300 PUT_32BIT(pkt->data + pktoffs, len);
1303 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
1304 pkt->data + pktoffs + 4, biglen);
1306 if (offset_p) *offset_p = pktoffs;
1307 return biglen + 4; /* len(length+padding+type+data+CRC) */
1310 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1312 int len, backlog, offset;
1313 len = s_wrpkt_prepare(ssh, pkt, &offset);
1314 backlog = sk_write(ssh->s, (char *)pkt->data + offset, len);
1315 if (backlog > SSH_MAX_BACKLOG)
1316 ssh_throttle_all(ssh, 1, backlog);
1317 ssh_free_packet(pkt);
1320 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1323 len = s_wrpkt_prepare(ssh, pkt, &offset);
1324 if (ssh->deferred_len + len > ssh->deferred_size) {
1325 ssh->deferred_size = ssh->deferred_len + len + 128;
1326 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1330 memcpy(ssh->deferred_send_data + ssh->deferred_len,
1331 pkt->data + offset, len);
1332 ssh->deferred_len += len;
1333 ssh_free_packet(pkt);
1337 * Construct a SSH-1 packet with the specified contents.
1338 * (This all-at-once interface used to be the only one, but now SSH-1
1339 * packets can also be constructed incrementally.)
1341 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
1347 pkt = ssh1_pkt_init(pkttype);
1349 while ((argtype = va_arg(ap, int)) != PKT_END) {
1350 unsigned char *argp, argchar;
1351 unsigned long argint;
1354 /* Actual fields in the packet */
1356 argint = va_arg(ap, int);
1357 ssh_pkt_adduint32(pkt, argint);
1360 argchar = (unsigned char) va_arg(ap, int);
1361 ssh_pkt_addbyte(pkt, argchar);
1364 argp = va_arg(ap, unsigned char *);
1365 arglen = va_arg(ap, int);
1366 ssh_pkt_adddata(pkt, argp, arglen);
1369 argp = va_arg(ap, unsigned char *);
1370 ssh_pkt_addstring(pkt, argp);
1373 bn = va_arg(ap, Bignum);
1374 ssh1_pkt_addmp(pkt, bn);
1376 /* Tokens for modifications to packet logging */
1378 dont_log_password(ssh, pkt, PKTLOG_BLANK);
1381 dont_log_data(ssh, pkt, PKTLOG_OMIT);
1384 end_log_omission(ssh, pkt);
1392 static void send_packet(Ssh ssh, int pkttype, ...)
1396 va_start(ap, pkttype);
1397 pkt = construct_packet(ssh, pkttype, ap);
1402 static void defer_packet(Ssh ssh, int pkttype, ...)
1406 va_start(ap, pkttype);
1407 pkt = construct_packet(ssh, pkttype, ap);
1409 s_wrpkt_defer(ssh, pkt);
1412 static int ssh_versioncmp(char *a, char *b)
1415 unsigned long av, bv;
1417 av = strtoul(a, &ae, 10);
1418 bv = strtoul(b, &be, 10);
1420 return (av < bv ? -1 : +1);
1425 av = strtoul(ae, &ae, 10);
1426 bv = strtoul(be, &be, 10);
1428 return (av < bv ? -1 : +1);
1433 * Utility routines for putting an SSH-protocol `string' and
1434 * `uint32' into a SHA state.
1436 static void sha_string(SHA_State * s, void *str, int len)
1438 unsigned char lenblk[4];
1439 PUT_32BIT(lenblk, len);
1440 SHA_Bytes(s, lenblk, 4);
1441 SHA_Bytes(s, str, len);
1444 static void sha_uint32(SHA_State * s, unsigned i)
1446 unsigned char intblk[4];
1447 PUT_32BIT(intblk, i);
1448 SHA_Bytes(s, intblk, 4);
1452 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
1454 static void ssh_pkt_ensure(struct Packet *pkt, int length)
1456 if (pkt->maxlen < length) {
1457 unsigned char *body = pkt->body;
1458 int offset = body ? pkt->data - body : 0;
1459 pkt->maxlen = length + 256;
1460 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
1461 if (body) pkt->body = pkt->data + offset;
1464 static void ssh_pkt_adddata(struct Packet *pkt, void *data, int len)
1466 if (pkt->logmode != PKTLOG_EMIT) {
1468 pkt->blanks = sresize(pkt->blanks, pkt->nblanks, struct logblank_t);
1470 pkt->blanks[pkt->nblanks-1].offset = pkt->length -
1471 (pkt->body - pkt->data);
1472 pkt->blanks[pkt->nblanks-1].len = len;
1473 pkt->blanks[pkt->nblanks-1].type = pkt->logmode;
1476 ssh_pkt_ensure(pkt, pkt->length);
1477 memcpy(pkt->data + pkt->length - len, data, len);
1479 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
1481 ssh_pkt_adddata(pkt, &byte, 1);
1483 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
1485 ssh_pkt_adddata(pkt, &value, 1);
1487 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
1490 PUT_32BIT(x, value);
1491 ssh_pkt_adddata(pkt, x, 4);
1493 static void ssh_pkt_addstring_start(struct Packet *pkt)
1495 ssh_pkt_adduint32(pkt, 0);
1496 pkt->savedpos = pkt->length;
1498 static void ssh_pkt_addstring_str(struct Packet *pkt, char *data)
1500 ssh_pkt_adddata(pkt, data, strlen(data));
1501 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1503 static void ssh_pkt_addstring_data(struct Packet *pkt, char *data, int len)
1505 ssh_pkt_adddata(pkt, data, len);
1506 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1508 static void ssh_pkt_addstring(struct Packet *pkt, char *data)
1510 ssh_pkt_addstring_start(pkt);
1511 ssh_pkt_addstring_str(pkt, data);
1513 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
1515 int len = ssh1_bignum_length(b);
1516 unsigned char *data = snewn(len, char);
1517 (void) ssh1_write_bignum(data, b);
1518 ssh_pkt_adddata(pkt, data, len);
1521 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
1524 int i, n = (bignum_bitcount(b) + 7) / 8;
1525 p = snewn(n + 1, unsigned char);
1527 fatalbox("out of memory");
1529 for (i = 1; i <= n; i++)
1530 p[i] = bignum_byte(b, n - i);
1532 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1534 memmove(p, p + i, n + 1 - i);
1538 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
1542 p = ssh2_mpint_fmt(b, &len);
1543 ssh_pkt_addstring_start(pkt);
1544 ssh_pkt_addstring_data(pkt, (char *)p, len);
1548 static struct Packet *ssh1_pkt_init(int pkt_type)
1550 struct Packet *pkt = ssh_new_packet();
1551 pkt->length = 4 + 8; /* space for length + max padding */
1552 ssh_pkt_addbyte(pkt, pkt_type);
1553 pkt->body = pkt->data + pkt->length;
1557 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
1558 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
1559 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
1560 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
1561 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
1562 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
1563 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
1564 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
1565 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
1567 static struct Packet *ssh2_pkt_init(int pkt_type)
1569 struct Packet *pkt = ssh_new_packet();
1572 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
1573 pkt->body = pkt->data + pkt->length;
1578 * Construct an SSH-2 final-form packet: compress it, encrypt it,
1579 * put the MAC on it. Final packet, ready to be sent, is stored in
1580 * pkt->data. Total length is returned.
1582 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
1584 int cipherblk, maclen, padding, i;
1587 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1588 ssh2_pkt_type(ssh->pkt_ctx, pkt->data[5]),
1589 pkt->body, pkt->length - (pkt->body - pkt->data),
1590 pkt->nblanks, pkt->blanks);
1591 sfree(pkt->blanks); pkt->blanks = NULL;
1595 * Compress packet payload.
1598 unsigned char *newpayload;
1601 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
1603 &newpayload, &newlen)) {
1605 ssh2_pkt_adddata(pkt, newpayload, newlen);
1611 * Add padding. At least four bytes, and must also bring total
1612 * length (minus MAC) up to a multiple of the block size.
1613 * If pkt->forcepad is set, make sure the packet is at least that size
1616 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
1617 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1619 if (pkt->length + padding < pkt->forcepad)
1620 padding = pkt->forcepad - pkt->length;
1622 (cipherblk - (pkt->length + padding) % cipherblk) % cipherblk;
1623 assert(padding <= 255);
1624 maclen = ssh->csmac ? ssh->csmac->len : 0;
1625 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
1626 pkt->data[4] = padding;
1627 for (i = 0; i < padding; i++)
1628 pkt->data[pkt->length + i] = random_byte();
1629 PUT_32BIT(pkt->data, pkt->length + padding - 4);
1631 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
1632 pkt->length + padding,
1633 ssh->v2_outgoing_sequence);
1634 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
1637 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
1638 pkt->data, pkt->length + padding);
1640 pkt->encrypted_len = pkt->length + padding;
1642 /* Ready-to-send packet starts at pkt->data. We return length. */
1643 return pkt->length + padding + maclen;
1647 * Routines called from the main SSH code to send packets. There
1648 * are quite a few of these, because we have two separate
1649 * mechanisms for delaying the sending of packets:
1651 * - In order to send an IGNORE message and a password message in
1652 * a single fixed-length blob, we require the ability to
1653 * concatenate the encrypted forms of those two packets _into_ a
1654 * single blob and then pass it to our <network.h> transport
1655 * layer in one go. Hence, there's a deferment mechanism which
1656 * works after packet encryption.
1658 * - In order to avoid sending any connection-layer messages
1659 * during repeat key exchange, we have to queue up any such
1660 * outgoing messages _before_ they are encrypted (and in
1661 * particular before they're allocated sequence numbers), and
1662 * then send them once we've finished.
1664 * I call these mechanisms `defer' and `queue' respectively, so as
1665 * to distinguish them reasonably easily.
1667 * The functions send_noqueue() and defer_noqueue() free the packet
1668 * structure they are passed. Every outgoing packet goes through
1669 * precisely one of these functions in its life; packets passed to
1670 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
1671 * these or get queued, and then when the queue is later emptied
1672 * the packets are all passed to defer_noqueue().
1676 * Send an SSH-2 packet immediately, without queuing or deferring.
1678 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
1682 len = ssh2_pkt_construct(ssh, pkt);
1683 backlog = sk_write(ssh->s, (char *)pkt->data, len);
1684 if (backlog > SSH_MAX_BACKLOG)
1685 ssh_throttle_all(ssh, 1, backlog);
1687 ssh->outgoing_data_size += pkt->encrypted_len;
1688 if (!ssh->kex_in_progress &&
1689 ssh->max_data_size != 0 &&
1690 ssh->outgoing_data_size > ssh->max_data_size)
1691 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
1693 ssh_free_packet(pkt);
1697 * Defer an SSH-2 packet.
1699 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt)
1701 int len = ssh2_pkt_construct(ssh, pkt);
1702 if (ssh->deferred_len + len > ssh->deferred_size) {
1703 ssh->deferred_size = ssh->deferred_len + len + 128;
1704 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1708 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->data, len);
1709 ssh->deferred_len += len;
1710 ssh->deferred_data_size += pkt->encrypted_len;
1711 ssh_free_packet(pkt);
1715 * Queue an SSH-2 packet.
1717 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
1719 assert(ssh->queueing);
1721 if (ssh->queuelen >= ssh->queuesize) {
1722 ssh->queuesize = ssh->queuelen + 32;
1723 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
1726 ssh->queue[ssh->queuelen++] = pkt;
1730 * Either queue or send a packet, depending on whether queueing is
1733 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
1736 ssh2_pkt_queue(ssh, pkt);
1738 ssh2_pkt_send_noqueue(ssh, pkt);
1743 * Either queue or defer a packet, depending on whether queueing is
1746 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
1749 ssh2_pkt_queue(ssh, pkt);
1751 ssh2_pkt_defer_noqueue(ssh, pkt);
1756 * Send the whole deferred data block constructed by
1757 * ssh2_pkt_defer() or SSH-1's defer_packet().
1759 * The expected use of the defer mechanism is that you call
1760 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
1761 * not currently queueing, this simply sets up deferred_send_data
1762 * and then sends it. If we _are_ currently queueing, the calls to
1763 * ssh2_pkt_defer() put the deferred packets on to the queue
1764 * instead, and therefore ssh_pkt_defersend() has no deferred data
1765 * to send. Hence, there's no need to make it conditional on
1768 static void ssh_pkt_defersend(Ssh ssh)
1771 backlog = sk_write(ssh->s, (char *)ssh->deferred_send_data,
1773 ssh->deferred_len = ssh->deferred_size = 0;
1774 sfree(ssh->deferred_send_data);
1775 ssh->deferred_send_data = NULL;
1776 if (backlog > SSH_MAX_BACKLOG)
1777 ssh_throttle_all(ssh, 1, backlog);
1779 ssh->outgoing_data_size += ssh->deferred_data_size;
1780 if (!ssh->kex_in_progress &&
1781 ssh->max_data_size != 0 &&
1782 ssh->outgoing_data_size > ssh->max_data_size)
1783 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
1784 ssh->deferred_data_size = 0;
1788 * Send all queued SSH-2 packets. We send them by means of
1789 * ssh2_pkt_defer_noqueue(), in case they included a pair of
1790 * packets that needed to be lumped together.
1792 static void ssh2_pkt_queuesend(Ssh ssh)
1796 assert(!ssh->queueing);
1798 for (i = 0; i < ssh->queuelen; i++)
1799 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i]);
1802 ssh_pkt_defersend(ssh);
1806 void bndebug(char *string, Bignum b)
1810 p = ssh2_mpint_fmt(b, &len);
1811 debug(("%s", string));
1812 for (i = 0; i < len; i++)
1813 debug((" %02x", p[i]));
1819 static void sha_mpint(SHA_State * s, Bignum b)
1823 p = ssh2_mpint_fmt(b, &len);
1824 sha_string(s, p, len);
1829 * Packet decode functions for both SSH-1 and SSH-2.
1831 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
1833 unsigned long value;
1834 if (pkt->length - pkt->savedpos < 4)
1835 return 0; /* arrgh, no way to decline (FIXME?) */
1836 value = GET_32BIT(pkt->body + pkt->savedpos);
1840 static int ssh2_pkt_getbool(struct Packet *pkt)
1842 unsigned long value;
1843 if (pkt->length - pkt->savedpos < 1)
1844 return 0; /* arrgh, no way to decline (FIXME?) */
1845 value = pkt->body[pkt->savedpos] != 0;
1849 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
1854 if (pkt->length - pkt->savedpos < 4)
1856 len = GET_32BIT(pkt->body + pkt->savedpos);
1861 if (pkt->length - pkt->savedpos < *length)
1863 *p = (char *)(pkt->body + pkt->savedpos);
1864 pkt->savedpos += *length;
1866 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
1868 if (pkt->length - pkt->savedpos < length)
1870 pkt->savedpos += length;
1871 return pkt->body + (pkt->savedpos - length);
1873 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
1874 unsigned char **keystr)
1878 j = makekey(pkt->body + pkt->savedpos,
1879 pkt->length - pkt->savedpos,
1886 assert(pkt->savedpos < pkt->length);
1890 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
1895 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
1896 pkt->length - pkt->savedpos, &b);
1904 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
1910 ssh_pkt_getstring(pkt, &p, &length);
1915 b = bignum_from_bytes((unsigned char *)p, length);
1920 * Helper function to add an SSH-2 signature blob to a packet.
1921 * Expects to be shown the public key blob as well as the signature
1922 * blob. Normally works just like ssh2_pkt_addstring, but will
1923 * fiddle with the signature packet if necessary for
1924 * BUG_SSH2_RSA_PADDING.
1926 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
1927 void *pkblob_v, int pkblob_len,
1928 void *sigblob_v, int sigblob_len)
1930 unsigned char *pkblob = (unsigned char *)pkblob_v;
1931 unsigned char *sigblob = (unsigned char *)sigblob_v;
1933 /* dmemdump(pkblob, pkblob_len); */
1934 /* dmemdump(sigblob, sigblob_len); */
1937 * See if this is in fact an ssh-rsa signature and a buggy
1938 * server; otherwise we can just do this the easy way.
1940 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) &&
1941 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
1942 int pos, len, siglen;
1945 * Find the byte length of the modulus.
1948 pos = 4+7; /* skip over "ssh-rsa" */
1949 pos += 4 + GET_32BIT(pkblob+pos); /* skip over exponent */
1950 len = GET_32BIT(pkblob+pos); /* find length of modulus */
1951 pos += 4; /* find modulus itself */
1952 while (len > 0 && pkblob[pos] == 0)
1954 /* debug(("modulus length is %d\n", len)); */
1957 * Now find the signature integer.
1959 pos = 4+7; /* skip over "ssh-rsa" */
1960 siglen = GET_32BIT(sigblob+pos);
1961 /* debug(("signature length is %d\n", siglen)); */
1963 if (len != siglen) {
1964 unsigned char newlen[4];
1965 ssh2_pkt_addstring_start(pkt);
1966 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
1967 /* dmemdump(sigblob, pos); */
1968 pos += 4; /* point to start of actual sig */
1969 PUT_32BIT(newlen, len);
1970 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
1971 /* dmemdump(newlen, 4); */
1973 while (len-- > siglen) {
1974 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
1975 /* dmemdump(newlen, 1); */
1977 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
1978 /* dmemdump(sigblob+pos, siglen); */
1982 /* Otherwise fall through and do it the easy way. */
1985 ssh2_pkt_addstring_start(pkt);
1986 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
1990 * Examine the remote side's version string and compare it against
1991 * a list of known buggy implementations.
1993 static void ssh_detect_bugs(Ssh ssh, char *vstring)
1995 char *imp; /* pointer to implementation part */
1997 imp += strcspn(imp, "-");
1999 imp += strcspn(imp, "-");
2002 ssh->remote_bugs = 0;
2004 if (ssh->cfg.sshbug_ignore1 == FORCE_ON ||
2005 (ssh->cfg.sshbug_ignore1 == AUTO &&
2006 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2007 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2008 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2009 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2011 * These versions don't support SSH1_MSG_IGNORE, so we have
2012 * to use a different defence against password length
2015 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2016 logevent("We believe remote version has SSH-1 ignore bug");
2019 if (ssh->cfg.sshbug_plainpw1 == FORCE_ON ||
2020 (ssh->cfg.sshbug_plainpw1 == AUTO &&
2021 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2023 * These versions need a plain password sent; they can't
2024 * handle having a null and a random length of data after
2027 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2028 logevent("We believe remote version needs a plain SSH-1 password");
2031 if (ssh->cfg.sshbug_rsa1 == FORCE_ON ||
2032 (ssh->cfg.sshbug_rsa1 == AUTO &&
2033 (!strcmp(imp, "Cisco-1.25")))) {
2035 * These versions apparently have no clue whatever about
2036 * RSA authentication and will panic and die if they see
2037 * an AUTH_RSA message.
2039 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2040 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2043 if (ssh->cfg.sshbug_hmac2 == FORCE_ON ||
2044 (ssh->cfg.sshbug_hmac2 == AUTO &&
2045 !wc_match("* VShell", imp) &&
2046 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2047 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2048 wc_match("2.1 *", imp)))) {
2050 * These versions have the HMAC bug.
2052 ssh->remote_bugs |= BUG_SSH2_HMAC;
2053 logevent("We believe remote version has SSH-2 HMAC bug");
2056 if (ssh->cfg.sshbug_derivekey2 == FORCE_ON ||
2057 (ssh->cfg.sshbug_derivekey2 == AUTO &&
2058 !wc_match("* VShell", imp) &&
2059 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2061 * These versions have the key-derivation bug (failing to
2062 * include the literal shared secret in the hashes that
2063 * generate the keys).
2065 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2066 logevent("We believe remote version has SSH-2 key-derivation bug");
2069 if (ssh->cfg.sshbug_rsapad2 == FORCE_ON ||
2070 (ssh->cfg.sshbug_rsapad2 == AUTO &&
2071 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2072 wc_match("OpenSSH_3.[0-2]*", imp)))) {
2074 * These versions have the SSH-2 RSA padding bug.
2076 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2077 logevent("We believe remote version has SSH-2 RSA padding bug");
2080 if (ssh->cfg.sshbug_pksessid2 == FORCE_ON ||
2081 (ssh->cfg.sshbug_pksessid2 == AUTO &&
2082 wc_match("OpenSSH_2.[0-2]*", imp))) {
2084 * These versions have the SSH-2 session-ID bug in
2085 * public-key authentication.
2087 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2088 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2091 if (ssh->cfg.sshbug_rekey2 == FORCE_ON ||
2092 (ssh->cfg.sshbug_rekey2 == AUTO &&
2093 (wc_match("OpenSSH_2.[0-4]*", imp) ||
2094 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2095 wc_match("Sun_SSH_1.0", imp) ||
2096 wc_match("Sun_SSH_1.0.1", imp)))) {
2098 * These versions have the SSH-2 rekey bug.
2100 ssh->remote_bugs |= BUG_SSH2_REKEY;
2101 logevent("We believe remote version has SSH-2 rekey bug");
2106 * The `software version' part of an SSH version string is required
2107 * to contain no spaces or minus signs.
2109 static void ssh_fix_verstring(char *str)
2111 /* Eat "SSH-<protoversion>-". */
2112 assert(*str == 'S'); str++;
2113 assert(*str == 'S'); str++;
2114 assert(*str == 'H'); str++;
2115 assert(*str == '-'); str++;
2116 while (*str && *str != '-') str++;
2117 assert(*str == '-'); str++;
2119 /* Convert minus signs and spaces in the remaining string into
2122 if (*str == '-' || *str == ' ')
2128 static int do_ssh_init(Ssh ssh, unsigned char c)
2130 struct do_ssh_init_state {
2138 crState(do_ssh_init_state);
2140 crBegin(ssh->do_ssh_init_crstate);
2142 /* Search for the string "SSH-" in the input. */
2145 static const int transS[] = { 1, 2, 2, 1 };
2146 static const int transH[] = { 0, 0, 3, 0 };
2147 static const int transminus[] = { 0, 0, 0, -1 };
2149 s->i = transS[s->i];
2151 s->i = transH[s->i];
2153 s->i = transminus[s->i];
2158 crReturn(1); /* get another character */
2162 s->vstring = snewn(s->vstrsize, char);
2163 strcpy(s->vstring, "SSH-");
2167 crReturn(1); /* get another char */
2168 if (s->vslen >= s->vstrsize - 1) {
2170 s->vstring = sresize(s->vstring, s->vstrsize, char);
2172 s->vstring[s->vslen++] = c;
2175 s->version[s->i] = '\0';
2177 } else if (s->i < sizeof(s->version) - 1)
2178 s->version[s->i++] = c;
2179 } else if (c == '\012')
2183 ssh->agentfwd_enabled = FALSE;
2184 ssh->rdpkt2_state.incoming_sequence = 0;
2186 s->vstring[s->vslen] = 0;
2187 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
2188 logeventf(ssh, "Server version: %s", s->vstring);
2189 ssh_detect_bugs(ssh, s->vstring);
2192 * Decide which SSH protocol version to support.
2195 /* Anything strictly below "2.0" means protocol 1 is supported. */
2196 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
2197 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2198 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
2200 if (ssh->cfg.sshprot == 0 && !s->proto1) {
2201 bombout(("SSH protocol version 1 required by user but not provided by server"));
2204 if (ssh->cfg.sshprot == 3 && !s->proto2) {
2205 bombout(("SSH protocol version 2 required by user but not provided by server"));
2212 if (s->proto2 && (ssh->cfg.sshprot >= 2 || !s->proto1)) {
2214 * Construct a v2 version string.
2216 verstring = dupprintf("SSH-2.0-%s\015\012", sshver);
2220 * Construct a v1 version string.
2222 verstring = dupprintf("SSH-%s-%s\012",
2223 (ssh_versioncmp(s->version, "1.5") <= 0 ?
2224 s->version : "1.5"),
2229 ssh_fix_verstring(verstring);
2231 if (ssh->version == 2) {
2233 * Hash our version string and their version string.
2235 SHA_Init(&ssh->exhashbase);
2236 sha_string(&ssh->exhashbase, verstring,
2237 strcspn(verstring, "\015\012"));
2238 sha_string(&ssh->exhashbase, s->vstring,
2239 strcspn(s->vstring, "\015\012"));
2242 * Initialise SSH-2 protocol.
2244 ssh->protocol = ssh2_protocol;
2245 ssh2_protocol_setup(ssh);
2246 ssh->s_rdpkt = ssh2_rdpkt;
2249 * Initialise SSH-1 protocol.
2251 ssh->protocol = ssh1_protocol;
2252 ssh1_protocol_setup(ssh);
2253 ssh->s_rdpkt = ssh1_rdpkt;
2255 logeventf(ssh, "We claim version: %.*s",
2256 strcspn(verstring, "\015\012"), verstring);
2257 sk_write(ssh->s, verstring, strlen(verstring));
2261 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
2263 update_specials_menu(ssh->frontend);
2264 ssh->state = SSH_STATE_BEFORE_SIZE;
2265 ssh->pinger = pinger_new(&ssh->cfg, &ssh_backend, ssh);
2272 static void ssh_process_incoming_data(Ssh ssh,
2273 unsigned char **data, int *datalen)
2275 struct Packet *pktin = ssh->s_rdpkt(ssh, data, datalen);
2277 ssh->protocol(ssh, NULL, 0, pktin);
2278 ssh_free_packet(pktin);
2282 static void ssh_queue_incoming_data(Ssh ssh,
2283 unsigned char **data, int *datalen)
2285 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
2290 static void ssh_process_queued_incoming_data(Ssh ssh)
2293 unsigned char *data;
2296 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
2297 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
2301 while (!ssh->frozen && len > 0)
2302 ssh_process_incoming_data(ssh, &data, &len);
2305 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
2309 static void ssh_set_frozen(Ssh ssh, int frozen)
2312 sk_set_frozen(ssh->s, frozen);
2313 ssh->frozen = frozen;
2316 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
2318 crBegin(ssh->ssh_gotdata_crstate);
2321 * To begin with, feed the characters one by one to the
2322 * protocol initialisation / selection function do_ssh_init().
2323 * When that returns 0, we're done with the initial greeting
2324 * exchange and can move on to packet discipline.
2327 int ret; /* need not be kept across crReturn */
2329 crReturnV; /* more data please */
2330 ret = do_ssh_init(ssh, *data);
2338 * We emerge from that loop when the initial negotiation is
2339 * over and we have selected an s_rdpkt function. Now pass
2340 * everything to s_rdpkt, and then pass the resulting packets
2341 * to the proper protocol handler.
2347 * Process queued data if there is any.
2349 ssh_process_queued_incoming_data(ssh);
2352 while (datalen > 0) {
2354 ssh_queue_incoming_data(ssh, &data, &datalen);
2356 ssh_process_incoming_data(ssh, &data, &datalen);
2358 if (ssh->state == SSH_STATE_CLOSED)
2366 static int ssh_do_close(Ssh ssh, int notify_exit)
2369 struct ssh_channel *c;
2371 ssh->state = SSH_STATE_CLOSED;
2372 expire_timer_context(ssh);
2377 notify_remote_exit(ssh->frontend);
2382 * Now we must shut down any port- and X-forwarded channels going
2383 * through this connection.
2385 if (ssh->channels) {
2386 while (NULL != (c = index234(ssh->channels, 0))) {
2389 x11_close(c->u.x11.s);
2392 pfd_close(c->u.pfd.s);
2395 del234(ssh->channels, c); /* moving next one to index 0 */
2396 if (ssh->version == 2)
2397 bufchain_clear(&c->v.v2.outbuffer);
2402 * Go through port-forwardings, and close any associated
2403 * listening sockets.
2405 if (ssh->portfwds) {
2406 struct ssh_portfwd *pf;
2407 while (NULL != (pf = index234(ssh->portfwds, 0))) {
2408 /* Dispose of any listening socket. */
2410 pfd_terminate(pf->local);
2411 del234(ssh->portfwds, pf); /* moving next one to index 0 */
2419 static void ssh_log(Plug plug, int type, SockAddr addr, int port,
2420 const char *error_msg, int error_code)
2422 Ssh ssh = (Ssh) plug;
2423 char addrbuf[256], *msg;
2425 sk_getaddr(addr, addrbuf, lenof(addrbuf));
2428 msg = dupprintf("Connecting to %s port %d", addrbuf, port);
2430 msg = dupprintf("Failed to connect to %s: %s", addrbuf, error_msg);
2436 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
2439 Ssh ssh = (Ssh) plug;
2440 int need_notify = ssh_do_close(ssh, FALSE);
2442 if (!error_msg && !ssh->close_expected) {
2443 error_msg = "Server unexpectedly closed network connection";
2447 notify_remote_exit(ssh->frontend);
2450 /* A socket error has occurred. */
2451 logevent(error_msg);
2452 connection_fatal(ssh->frontend, "%s", error_msg);
2454 logevent("Server closed network connection");
2459 static int ssh_receive(Plug plug, int urgent, char *data, int len)
2461 Ssh ssh = (Ssh) plug;
2462 ssh_gotdata(ssh, (unsigned char *)data, len);
2463 if (ssh->state == SSH_STATE_CLOSED) {
2464 ssh_do_close(ssh, TRUE);
2470 static void ssh_sent(Plug plug, int bufsize)
2472 Ssh ssh = (Ssh) plug;
2474 * If the send backlog on the SSH socket itself clears, we
2475 * should unthrottle the whole world if it was throttled.
2477 if (bufsize < SSH_MAX_BACKLOG)
2478 ssh_throttle_all(ssh, 0, bufsize);
2482 * Connect to specified host and port.
2483 * Returns an error message, or NULL on success.
2484 * Also places the canonical host name into `realhost'. It must be
2485 * freed by the caller.
2487 static const char *connect_to_host(Ssh ssh, char *host, int port,
2488 char **realhost, int nodelay, int keepalive)
2490 static const struct plug_function_table fn_table = {
2501 ssh->savedhost = snewn(1 + strlen(host), char);
2502 if (!ssh->savedhost)
2503 fatalbox("Out of memory");
2504 strcpy(ssh->savedhost, host);
2507 port = 22; /* default ssh port */
2508 ssh->savedport = port;
2513 logeventf(ssh, "Looking up host \"%s\"%s", host,
2514 (ssh->cfg.addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
2515 (ssh->cfg.addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" : "")));
2516 addr = name_lookup(host, port, realhost, &ssh->cfg,
2517 ssh->cfg.addressfamily);
2518 if ((err = sk_addr_error(addr)) != NULL) {
2526 ssh->fn = &fn_table;
2527 ssh->s = new_connection(addr, *realhost, port,
2528 0, 1, nodelay, keepalive, (Plug) ssh, &ssh->cfg);
2529 if ((err = sk_socket_error(ssh->s)) != NULL) {
2531 notify_remote_exit(ssh->frontend);
2539 * Throttle or unthrottle the SSH connection.
2541 static void ssh1_throttle(Ssh ssh, int adjust)
2543 int old_count = ssh->v1_throttle_count;
2544 ssh->v1_throttle_count += adjust;
2545 assert(ssh->v1_throttle_count >= 0);
2546 if (ssh->v1_throttle_count && !old_count) {
2547 ssh_set_frozen(ssh, 1);
2548 } else if (!ssh->v1_throttle_count && old_count) {
2549 ssh_set_frozen(ssh, 0);
2554 * Throttle or unthrottle _all_ local data streams (for when sends
2555 * on the SSH connection itself back up).
2557 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
2560 struct ssh_channel *c;
2562 if (enable == ssh->throttled_all)
2564 ssh->throttled_all = enable;
2565 ssh->overall_bufsize = bufsize;
2568 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
2570 case CHAN_MAINSESSION:
2572 * This is treated separately, outside the switch.
2576 x11_override_throttle(c->u.x11.s, enable);
2579 /* Agent channels require no buffer management. */
2582 pfd_override_throttle(c->u.pfd.s, enable);
2589 * Username and password input, abstracted off into routines
2590 * reusable in several places - even between SSH-1 and SSH-2.
2593 /* Set up a username or password input loop on a given buffer. */
2594 static void setup_userpass_input(Ssh ssh, char *buffer, int buflen, int echo)
2596 ssh->userpass_input_buffer = buffer;
2597 ssh->userpass_input_buflen = buflen;
2598 ssh->userpass_input_bufpos = 0;
2599 ssh->userpass_input_echo = echo;
2603 * Process some terminal data in the course of username/password
2604 * input. Returns >0 for success (line of input returned in
2605 * buffer), <0 for failure (user hit ^C/^D, bomb out and exit), 0
2606 * for inconclusive (keep waiting for more input please).
2608 static int process_userpass_input(Ssh ssh, unsigned char *in, int inlen)
2613 switch (c = *in++) {
2616 ssh->userpass_input_buffer[ssh->userpass_input_bufpos] = 0;
2617 ssh->userpass_input_buffer[ssh->userpass_input_buflen-1] = 0;
2622 if (ssh->userpass_input_bufpos > 0) {
2623 if (ssh->userpass_input_echo)
2624 c_write_str(ssh, "\b \b");
2625 ssh->userpass_input_bufpos--;
2630 while (ssh->userpass_input_bufpos > 0) {
2631 if (ssh->userpass_input_echo)
2632 c_write_str(ssh, "\b \b");
2633 ssh->userpass_input_bufpos--;
2642 * This simplistic check for printability is disabled
2643 * when we're doing password input, because some people
2644 * have control characters in their passwords.o
2646 if ((!ssh->userpass_input_echo ||
2647 (c >= ' ' && c <= '~') ||
2648 ((unsigned char) c >= 160))
2649 && ssh->userpass_input_bufpos < ssh->userpass_input_buflen-1) {
2650 ssh->userpass_input_buffer[ssh->userpass_input_bufpos++] = c;
2651 if (ssh->userpass_input_echo)
2652 c_write(ssh, &c, 1);
2660 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
2662 Ssh ssh = (Ssh) sshv;
2664 ssh->agent_response = reply;
2665 ssh->agent_response_len = replylen;
2667 if (ssh->version == 1)
2668 do_ssh1_login(ssh, NULL, -1, NULL);
2670 do_ssh2_authconn(ssh, NULL, -1, NULL);
2673 static void ssh_dialog_callback(void *sshv, int ret)
2675 Ssh ssh = (Ssh) sshv;
2677 ssh->user_response = ret;
2679 if (ssh->version == 1)
2680 do_ssh1_login(ssh, NULL, -1, NULL);
2682 do_ssh2_transport(ssh, NULL, -1, NULL);
2685 * This may have unfrozen the SSH connection, so do a
2688 ssh_process_queued_incoming_data(ssh);
2691 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
2693 struct ssh_channel *c = (struct ssh_channel *)cv;
2695 void *sentreply = reply;
2698 /* Fake SSH_AGENT_FAILURE. */
2699 sentreply = "\0\0\0\1\5";
2702 if (ssh->version == 2) {
2703 ssh2_add_channel_data(c, sentreply, replylen);
2706 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
2707 PKT_INT, c->remoteid,
2710 PKT_DATA, sentreply, replylen,
2719 * Handle the key exchange and user authentication phases.
2721 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
2722 struct Packet *pktin)
2725 unsigned char cookie[8], *ptr;
2726 struct RSAKey servkey, hostkey;
2727 struct MD5Context md5c;
2728 struct do_ssh1_login_state {
2730 unsigned char *rsabuf, *keystr1, *keystr2;
2731 unsigned long supported_ciphers_mask, supported_auths_mask;
2732 int tried_publickey, tried_agent;
2733 int tis_auth_refused, ccard_auth_refused;
2734 unsigned char session_id[16];
2737 void *publickey_blob;
2738 int publickey_bloblen;
2744 unsigned char request[5], *response, *p;
2754 crState(do_ssh1_login_state);
2756 crBegin(ssh->do_ssh1_login_crstate);
2761 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
2762 bombout(("Public key packet not received"));
2766 logevent("Received public keys");
2768 ptr = ssh_pkt_getdata(pktin, 8);
2770 bombout(("SSH-1 public key packet stopped before random cookie"));
2773 memcpy(cookie, ptr, 8);
2775 if (!ssh1_pkt_getrsakey(pktin, &servkey, &s->keystr1) ||
2776 !ssh1_pkt_getrsakey(pktin, &hostkey, &s->keystr2)) {
2777 bombout(("Failed to read SSH-1 public keys from public key packet"));
2782 * Log the host key fingerprint.
2786 logevent("Host key fingerprint is:");
2787 strcpy(logmsg, " ");
2788 hostkey.comment = NULL;
2789 rsa_fingerprint(logmsg + strlen(logmsg),
2790 sizeof(logmsg) - strlen(logmsg), &hostkey);
2794 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
2795 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
2796 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
2798 ssh->v1_local_protoflags =
2799 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
2800 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
2803 MD5Update(&md5c, s->keystr2, hostkey.bytes);
2804 MD5Update(&md5c, s->keystr1, servkey.bytes);
2805 MD5Update(&md5c, cookie, 8);
2806 MD5Final(s->session_id, &md5c);
2808 for (i = 0; i < 32; i++)
2809 ssh->session_key[i] = random_byte();
2812 * Verify that the `bits' and `bytes' parameters match.
2814 if (hostkey.bits > hostkey.bytes * 8 ||
2815 servkey.bits > servkey.bytes * 8) {
2816 bombout(("SSH-1 public keys were badly formatted"));
2820 s->len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
2822 s->rsabuf = snewn(s->len, unsigned char);
2824 fatalbox("Out of memory");
2827 * Verify the host key.
2831 * First format the key into a string.
2833 int len = rsastr_len(&hostkey);
2834 char fingerprint[100];
2835 char *keystr = snewn(len, char);
2837 fatalbox("Out of memory");
2838 rsastr_fmt(keystr, &hostkey);
2839 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
2841 ssh_set_frozen(ssh, 1);
2842 s->dlgret = verify_ssh_host_key(ssh->frontend,
2843 ssh->savedhost, ssh->savedport,
2844 "rsa", keystr, fingerprint,
2845 ssh_dialog_callback, ssh);
2847 if (s->dlgret < 0) {
2851 bombout(("Unexpected data from server while waiting"
2852 " for user host key response"));
2855 } while (pktin || inlen > 0);
2856 s->dlgret = ssh->user_response;
2858 ssh_set_frozen(ssh, 0);
2860 if (s->dlgret == 0) {
2861 ssh->close_expected = TRUE;
2862 ssh_closing((Plug)ssh, NULL, 0, 0);
2867 for (i = 0; i < 32; i++) {
2868 s->rsabuf[i] = ssh->session_key[i];
2870 s->rsabuf[i] ^= s->session_id[i];
2873 if (hostkey.bytes > servkey.bytes) {
2874 ret = rsaencrypt(s->rsabuf, 32, &servkey);
2876 ret = rsaencrypt(s->rsabuf, servkey.bytes, &hostkey);
2878 ret = rsaencrypt(s->rsabuf, 32, &hostkey);
2880 ret = rsaencrypt(s->rsabuf, hostkey.bytes, &servkey);
2883 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
2887 logevent("Encrypted session key");
2890 int cipher_chosen = 0, warn = 0;
2891 char *cipher_string = NULL;
2893 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
2894 int next_cipher = ssh->cfg.ssh_cipherlist[i];
2895 if (next_cipher == CIPHER_WARN) {
2896 /* If/when we choose a cipher, warn about it */
2898 } else if (next_cipher == CIPHER_AES) {
2899 /* XXX Probably don't need to mention this. */
2900 logevent("AES not supported in SSH-1, skipping");
2902 switch (next_cipher) {
2903 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
2904 cipher_string = "3DES"; break;
2905 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
2906 cipher_string = "Blowfish"; break;
2907 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
2908 cipher_string = "single-DES"; break;
2910 if (s->supported_ciphers_mask & (1 << s->cipher_type))
2914 if (!cipher_chosen) {
2915 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
2916 bombout(("Server violates SSH-1 protocol by not "
2917 "supporting 3DES encryption"));
2919 /* shouldn't happen */
2920 bombout(("No supported ciphers found"));
2924 /* Warn about chosen cipher if necessary. */
2926 ssh_set_frozen(ssh, 1);
2927 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
2928 ssh_dialog_callback, ssh);
2929 if (s->dlgret < 0) {
2933 bombout(("Unexpected data from server while waiting"
2934 " for user response"));
2937 } while (pktin || inlen > 0);
2938 s->dlgret = ssh->user_response;
2940 ssh_set_frozen(ssh, 0);
2941 if (s->dlgret == 0) {
2942 ssh->close_expected = TRUE;
2943 ssh_closing((Plug)ssh, NULL, 0, 0);
2949 switch (s->cipher_type) {
2950 case SSH_CIPHER_3DES:
2951 logevent("Using 3DES encryption");
2953 case SSH_CIPHER_DES:
2954 logevent("Using single-DES encryption");
2956 case SSH_CIPHER_BLOWFISH:
2957 logevent("Using Blowfish encryption");
2961 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
2962 PKT_CHAR, s->cipher_type,
2963 PKT_DATA, cookie, 8,
2964 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
2965 PKT_DATA, s->rsabuf, s->len,
2966 PKT_INT, ssh->v1_local_protoflags, PKT_END);
2968 logevent("Trying to enable encryption...");
2972 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
2973 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
2975 ssh->v1_cipher_ctx = ssh->cipher->make_context();
2976 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
2977 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
2979 ssh->crcda_ctx = crcda_make_context();
2980 logevent("Installing CRC compensation attack detector");
2982 if (servkey.modulus) {
2983 sfree(servkey.modulus);
2984 servkey.modulus = NULL;
2986 if (servkey.exponent) {
2987 sfree(servkey.exponent);
2988 servkey.exponent = NULL;
2990 if (hostkey.modulus) {
2991 sfree(hostkey.modulus);
2992 hostkey.modulus = NULL;
2994 if (hostkey.exponent) {
2995 sfree(hostkey.exponent);
2996 hostkey.exponent = NULL;
3000 if (pktin->type != SSH1_SMSG_SUCCESS) {
3001 bombout(("Encryption not successfully enabled"));
3005 logevent("Successfully started encryption");
3009 if (!*ssh->cfg.username) {
3010 if (ssh_get_line && !ssh_getline_pw_only) {
3011 if (!ssh_get_line("login as: ",
3012 s->username, sizeof(s->username), FALSE)) {
3014 * get_line failed to get a username.
3017 logevent("No username provided. Abandoning session.");
3018 ssh->close_expected = TRUE;
3019 ssh_closing((Plug)ssh, NULL, 0, 0);
3023 int ret; /* need not be kept over crReturn */
3024 c_write_str(ssh, "login as: ");
3027 setup_userpass_input(ssh, s->username, sizeof(s->username), 1);
3029 crWaitUntil(!pktin);
3030 ret = process_userpass_input(ssh, in, inlen);
3034 c_write_str(ssh, "\r\n");
3037 strncpy(s->username, ssh->cfg.username, sizeof(s->username));
3038 s->username[sizeof(s->username)-1] = '\0';
3041 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, s->username, PKT_END);
3043 char userlog[22 + sizeof(s->username)];
3044 sprintf(userlog, "Sent username \"%s\"", s->username);
3046 if (flags & FLAG_INTERACTIVE &&
3047 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
3048 strcat(userlog, "\r\n");
3049 c_write_str(ssh, userlog);
3056 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA)) {
3057 /* We must not attempt PK auth. Pretend we've already tried it. */
3058 s->tried_publickey = s->tried_agent = 1;
3060 s->tried_publickey = s->tried_agent = 0;
3062 s->tis_auth_refused = s->ccard_auth_refused = 0;
3063 /* Load the public half of ssh->cfg.keyfile so we notice if it's in Pageant */
3064 if (!filename_is_null(ssh->cfg.keyfile)) {
3065 if (!rsakey_pubblob(&ssh->cfg.keyfile,
3066 &s->publickey_blob, &s->publickey_bloblen, NULL))
3067 s->publickey_blob = NULL;
3069 s->publickey_blob = NULL;
3071 while (pktin->type == SSH1_SMSG_FAILURE) {
3072 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
3074 if (agent_exists() && !s->tried_agent) {
3076 * Attempt RSA authentication using Pageant.
3082 logevent("Pageant is running. Requesting keys.");
3084 /* Request the keys held by the agent. */
3085 PUT_32BIT(s->request, 1);
3086 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
3087 if (!agent_query(s->request, 5, &r, &s->responselen,
3088 ssh_agent_callback, ssh)) {
3092 bombout(("Unexpected data from server while waiting"
3093 " for agent response"));
3096 } while (pktin || inlen > 0);
3097 r = ssh->agent_response;
3098 s->responselen = ssh->agent_response_len;
3100 s->response = (unsigned char *) r;
3101 if (s->response && s->responselen >= 5 &&
3102 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
3103 s->p = s->response + 5;
3104 s->nkeys = GET_32BIT(s->p);
3106 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
3107 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
3108 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
3109 if (s->publickey_blob &&
3110 !memcmp(s->p, s->publickey_blob,
3111 s->publickey_bloblen)) {
3112 logevent("This key matches configured key file");
3113 s->tried_publickey = 1;
3118 do { /* do while (0) to make breaking easy */
3119 n = ssh1_read_bignum
3120 (s->p, s->responselen-(s->p-s->response),
3125 n = ssh1_read_bignum
3126 (s->p, s->responselen-(s->p-s->response),
3131 if (s->responselen - (s->p-s->response) < 4)
3133 s->commentlen = GET_32BIT(s->p);
3135 if (s->responselen - (s->p-s->response) <
3138 s->commentp = (char *)s->p;
3139 s->p += s->commentlen;
3143 logevent("Pageant key list packet was truncated");
3147 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3148 PKT_BIGNUM, s->key.modulus, PKT_END);
3150 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3151 logevent("Key refused");
3154 logevent("Received RSA challenge");
3155 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3156 bombout(("Server's RSA challenge was badly formatted"));
3161 char *agentreq, *q, *ret;
3164 len = 1 + 4; /* message type, bit count */
3165 len += ssh1_bignum_length(s->key.exponent);
3166 len += ssh1_bignum_length(s->key.modulus);
3167 len += ssh1_bignum_length(s->challenge);
3168 len += 16; /* session id */
3169 len += 4; /* response format */
3170 agentreq = snewn(4 + len, char);
3171 PUT_32BIT(agentreq, len);
3173 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
3174 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
3176 q += ssh1_write_bignum(q, s->key.exponent);
3177 q += ssh1_write_bignum(q, s->key.modulus);
3178 q += ssh1_write_bignum(q, s->challenge);
3179 memcpy(q, s->session_id, 16);
3181 PUT_32BIT(q, 1); /* response format */
3182 if (!agent_query(agentreq, len + 4, &vret, &retlen,
3183 ssh_agent_callback, ssh)) {
3188 bombout(("Unexpected data from server"
3189 " while waiting for agent"
3193 } while (pktin || inlen > 0);
3194 vret = ssh->agent_response;
3195 retlen = ssh->agent_response_len;
3200 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
3201 logevent("Sending Pageant's response");
3202 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3203 PKT_DATA, ret + 5, 16,
3207 if (pktin->type == SSH1_SMSG_SUCCESS) {
3209 ("Pageant's response accepted");
3210 if (flags & FLAG_VERBOSE) {
3211 c_write_str(ssh, "Authenticated using"
3213 c_write(ssh, s->commentp,
3215 c_write_str(ssh, "\" from agent\r\n");
3220 ("Pageant's response not accepted");
3223 ("Pageant failed to answer challenge");
3227 logevent("No reply received from Pageant");
3230 freebn(s->key.exponent);
3231 freebn(s->key.modulus);
3232 freebn(s->challenge);
3241 if (!filename_is_null(ssh->cfg.keyfile) && !s->tried_publickey)
3242 s->pwpkt_type = SSH1_CMSG_AUTH_RSA;
3244 if (ssh->cfg.try_tis_auth &&
3245 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
3246 !s->tis_auth_refused) {
3247 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
3248 logevent("Requested TIS authentication");
3249 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
3251 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
3252 logevent("TIS authentication declined");
3253 if (flags & FLAG_INTERACTIVE)
3254 c_write_str(ssh, "TIS authentication refused.\r\n");
3255 s->tis_auth_refused = 1;
3261 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3263 bombout(("TIS challenge packet was badly formed"));
3266 c_write_str(ssh, "Using TIS authentication.\r\n");
3267 logevent("Received TIS challenge");
3268 if (challengelen > sizeof(s->prompt) - 1)
3269 challengelen = sizeof(s->prompt) - 1;/* prevent overrun */
3270 memcpy(s->prompt, challenge, challengelen);
3271 /* Prompt heuristic comes from OpenSSH */
3272 strncpy(s->prompt + challengelen,
3273 memchr(s->prompt, '\n', challengelen) ?
3274 "": "\r\nResponse: ",
3275 (sizeof s->prompt) - challengelen);
3276 s->prompt[(sizeof s->prompt) - 1] = '\0';
3279 if (ssh->cfg.try_tis_auth &&
3280 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
3281 !s->ccard_auth_refused) {
3282 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
3283 logevent("Requested CryptoCard authentication");
3284 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
3286 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
3287 logevent("CryptoCard authentication declined");
3288 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
3289 s->ccard_auth_refused = 1;
3295 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3297 bombout(("CryptoCard challenge packet was badly formed"));
3300 c_write_str(ssh, "Using CryptoCard authentication.\r\n");
3301 logevent("Received CryptoCard challenge");
3302 if (challengelen > sizeof(s->prompt) - 1)
3303 challengelen = sizeof(s->prompt) - 1;/* prevent overrun */
3304 memcpy(s->prompt, challenge, challengelen);
3305 strncpy(s->prompt + challengelen,
3306 memchr(s->prompt, '\n', challengelen) ?
3307 "" : "\r\nResponse: ",
3308 sizeof(s->prompt) - challengelen);
3309 s->prompt[sizeof(s->prompt) - 1] = '\0';
3312 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
3313 sprintf(s->prompt, "%.90s@%.90s's password: ",
3314 s->username, ssh->savedhost);
3316 if (s->pwpkt_type == SSH1_CMSG_AUTH_RSA) {
3317 char *comment = NULL;
3319 if (flags & FLAG_VERBOSE)
3320 c_write_str(ssh, "Trying public key authentication.\r\n");
3321 logeventf(ssh, "Trying public key \"%s\"",
3322 filename_to_str(&ssh->cfg.keyfile));
3323 type = key_type(&ssh->cfg.keyfile);
3324 if (type != SSH_KEYTYPE_SSH1) {
3325 char *msg = dupprintf("Key is of wrong type (%s)",
3326 key_type_to_str(type));
3328 c_write_str(ssh, msg);
3329 c_write_str(ssh, "\r\n");
3331 s->tried_publickey = 1;
3334 if (!rsakey_encrypted(&ssh->cfg.keyfile, &comment)) {
3335 if (flags & FLAG_VERBOSE)
3336 c_write_str(ssh, "No passphrase required.\r\n");
3339 sprintf(s->prompt, "Passphrase for key \"%.100s\": ", comment);
3344 * Show password prompt, having first obtained it via a TIS
3345 * or CryptoCard exchange if we're doing TIS or CryptoCard
3349 if (!ssh_get_line(s->prompt, s->password,
3350 sizeof(s->password), TRUE)) {
3352 * get_line failed to get a password (for example
3353 * because one was supplied on the command line
3354 * which has already failed to work). Terminate.
3356 send_packet(ssh, SSH1_MSG_DISCONNECT,
3357 PKT_STR, "No more passwords available to try",
3359 logevent("Unable to authenticate");
3360 connection_fatal(ssh->frontend, "Unable to authenticate");
3361 ssh->close_expected = TRUE;
3362 ssh_closing((Plug)ssh, NULL, 0, 0);
3366 /* Prompt may have come from server. We've munged it a bit, so
3367 * we know it to be zero-terminated at least once. */
3368 int ret; /* need not be saved over crReturn */
3369 c_write_untrusted(ssh, s->prompt, strlen(s->prompt));
3372 setup_userpass_input(ssh, s->password, sizeof(s->password), 0);
3374 crWaitUntil(!pktin);
3375 ret = process_userpass_input(ssh, in, inlen);
3379 c_write_str(ssh, "\r\n");
3383 if (s->pwpkt_type == SSH1_CMSG_AUTH_RSA) {
3385 * Try public key authentication with the specified
3388 s->tried_publickey = 1;
3391 const char *error = NULL;
3392 int ret = loadrsakey(&ssh->cfg.keyfile, &s->key, s->password,
3395 c_write_str(ssh, "Couldn't load private key from ");
3396 c_write_str(ssh, filename_to_str(&ssh->cfg.keyfile));
3397 c_write_str(ssh, " (");
3398 c_write_str(ssh, error);
3399 c_write_str(ssh, ").\r\n");
3400 continue; /* go and try password */
3403 c_write_str(ssh, "Wrong passphrase.\r\n");
3404 s->tried_publickey = 0;
3405 continue; /* try again */
3410 * Send a public key attempt.
3412 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3413 PKT_BIGNUM, s->key.modulus, PKT_END);
3416 if (pktin->type == SSH1_SMSG_FAILURE) {
3417 c_write_str(ssh, "Server refused our public key.\r\n");
3418 continue; /* go and try password */
3420 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3421 bombout(("Bizarre response to offer of public key"));
3427 unsigned char buffer[32];
3428 Bignum challenge, response;
3430 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3431 bombout(("Server's RSA challenge was badly formatted"));
3434 response = rsadecrypt(challenge, &s->key);
3435 freebn(s->key.private_exponent);/* burn the evidence */
3437 for (i = 0; i < 32; i++) {
3438 buffer[i] = bignum_byte(response, 31 - i);
3442 MD5Update(&md5c, buffer, 32);
3443 MD5Update(&md5c, s->session_id, 16);
3444 MD5Final(buffer, &md5c);
3446 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3447 PKT_DATA, buffer, 16, PKT_END);
3454 if (pktin->type == SSH1_SMSG_FAILURE) {
3455 if (flags & FLAG_VERBOSE)
3456 c_write_str(ssh, "Failed to authenticate with"
3457 " our public key.\r\n");
3458 continue; /* go and try password */
3459 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
3460 bombout(("Bizarre response to RSA authentication response"));
3464 break; /* we're through! */
3466 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
3468 * Defence against traffic analysis: we send a
3469 * whole bunch of packets containing strings of
3470 * different lengths. One of these strings is the
3471 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
3472 * The others are all random data in
3473 * SSH1_MSG_IGNORE packets. This way a passive
3474 * listener can't tell which is the password, and
3475 * hence can't deduce the password length.
3477 * Anybody with a password length greater than 16
3478 * bytes is going to have enough entropy in their
3479 * password that a listener won't find it _that_
3480 * much help to know how long it is. So what we'll
3483 * - if password length < 16, we send 15 packets
3484 * containing string lengths 1 through 15
3486 * - otherwise, we let N be the nearest multiple
3487 * of 8 below the password length, and send 8
3488 * packets containing string lengths N through
3489 * N+7. This won't obscure the order of
3490 * magnitude of the password length, but it will
3491 * introduce a bit of extra uncertainty.
3493 * A few servers (the old 1.2.18 through 1.2.22)
3494 * can't deal with SSH1_MSG_IGNORE. For these
3495 * servers, we need an alternative defence. We make
3496 * use of the fact that the password is interpreted
3497 * as a C string: so we can append a NUL, then some
3500 * One server (a Cisco one) can deal with neither
3501 * SSH1_MSG_IGNORE _nor_ a padded password string.
3502 * For this server we are left with no defences
3503 * against password length sniffing.
3505 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE)) {
3507 * The server can deal with SSH1_MSG_IGNORE, so
3508 * we can use the primary defence.
3510 int bottom, top, pwlen, i;
3513 pwlen = strlen(s->password);
3515 bottom = 0; /* zero length passwords are OK! :-) */
3518 bottom = pwlen & ~7;
3522 assert(pwlen >= bottom && pwlen <= top);
3524 randomstr = snewn(top + 1, char);
3526 for (i = bottom; i <= top; i++) {
3528 defer_packet(ssh, s->pwpkt_type,
3529 PKTT_PASSWORD, PKT_STR, s->password,
3530 PKTT_OTHER, PKT_END);
3532 for (j = 0; j < i; j++) {
3534 randomstr[j] = random_byte();
3535 } while (randomstr[j] == '\0');
3537 randomstr[i] = '\0';
3538 defer_packet(ssh, SSH1_MSG_IGNORE,
3539 PKT_STR, randomstr, PKT_END);
3542 logevent("Sending password with camouflage packets");
3543 ssh_pkt_defersend(ssh);
3546 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
3548 * The server can't deal with SSH1_MSG_IGNORE
3549 * but can deal with padded passwords, so we
3550 * can use the secondary defence.
3556 len = strlen(s->password);
3557 if (len < sizeof(string)) {
3559 strcpy(string, s->password);
3560 len++; /* cover the zero byte */
3561 while (len < sizeof(string)) {
3562 string[len++] = (char) random_byte();
3567 logevent("Sending length-padded password");
3568 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
3569 PKT_INT, len, PKT_DATA, ss, len,
3570 PKTT_OTHER, PKT_END);
3573 * The server has _both_
3574 * BUG_CHOKES_ON_SSH1_IGNORE and
3575 * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
3576 * therefore nothing we can do.
3579 len = strlen(s->password);
3580 logevent("Sending unpadded password");
3581 send_packet(ssh, s->pwpkt_type,
3582 PKTT_PASSWORD, PKT_INT, len,
3583 PKT_DATA, s->password, len,
3584 PKTT_OTHER, PKT_END);
3587 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
3588 PKT_STR, s->password, PKTT_OTHER, PKT_END);
3591 logevent("Sent password");
3592 memset(s->password, 0, strlen(s->password));
3594 if (pktin->type == SSH1_SMSG_FAILURE) {
3595 if (flags & FLAG_VERBOSE)
3596 c_write_str(ssh, "Access denied\r\n");
3597 logevent("Authentication refused");
3598 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
3599 bombout(("Strange packet received, type %d", pktin->type));
3604 logevent("Authentication successful");
3609 void sshfwd_close(struct ssh_channel *c)
3613 if (ssh->state == SSH_STATE_CLOSED)
3616 if (c && !c->closes) {
3618 * If halfopen is true, we have sent
3619 * CHANNEL_OPEN for this channel, but it hasn't even been
3620 * acknowledged by the server. So we must set a close flag
3621 * on it now, and then when the server acks the channel
3622 * open, we can close it then.
3625 if (ssh->version == 1) {
3626 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
3629 struct Packet *pktout;
3630 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
3631 ssh2_pkt_adduint32(pktout, c->remoteid);
3632 ssh2_pkt_send(ssh, pktout);
3635 c->closes = 1; /* sent MSG_CLOSE */
3636 if (c->type == CHAN_X11) {
3638 logevent("Forwarded X11 connection terminated");
3639 } else if (c->type == CHAN_SOCKDATA ||
3640 c->type == CHAN_SOCKDATA_DORMANT) {
3642 logevent("Forwarded port closed");
3647 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
3651 if (ssh->state == SSH_STATE_CLOSED)
3654 if (ssh->version == 1) {
3655 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3656 PKT_INT, c->remoteid,
3658 PKT_INT, len, PKT_DATA, buf, len,
3659 PKTT_OTHER, PKT_END);
3661 * In SSH-1 we can return 0 here - implying that forwarded
3662 * connections are never individually throttled - because
3663 * the only circumstance that can cause throttling will be
3664 * the whole SSH connection backing up, in which case
3665 * _everything_ will be throttled as a whole.
3669 ssh2_add_channel_data(c, buf, len);
3670 return ssh2_try_send(c);
3674 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
3678 if (ssh->state == SSH_STATE_CLOSED)
3681 if (ssh->version == 1) {
3682 if (c->v.v1.throttling && bufsize < SSH1_BUFFER_LIMIT) {
3683 c->v.v1.throttling = 0;
3684 ssh1_throttle(ssh, -1);
3687 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
3691 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
3693 struct queued_handler *qh = ssh->qhead;
3697 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
3700 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
3701 ssh->packet_dispatch[qh->msg1] = NULL;
3704 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
3705 ssh->packet_dispatch[qh->msg2] = NULL;
3709 ssh->qhead = qh->next;
3711 if (ssh->qhead->msg1 > 0) {
3712 assert(ssh->packet_dispatch[ssh->qhead->msg1] == NULL);
3713 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
3715 if (ssh->qhead->msg2 > 0) {
3716 assert(ssh->packet_dispatch[ssh->qhead->msg2] == NULL);
3717 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
3720 ssh->qhead = ssh->qtail = NULL;
3721 ssh->packet_dispatch[pktin->type] = NULL;
3724 qh->handler(ssh, pktin, qh->ctx);
3729 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
3730 chandler_fn_t handler, void *ctx)
3732 struct queued_handler *qh;
3734 qh = snew(struct queued_handler);
3737 qh->handler = handler;
3741 if (ssh->qtail == NULL) {
3745 assert(ssh->packet_dispatch[qh->msg1] == NULL);
3746 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
3749 assert(ssh->packet_dispatch[qh->msg2] == NULL);
3750 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
3753 ssh->qtail->next = qh;
3758 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
3760 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
3762 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
3763 SSH2_MSG_REQUEST_SUCCESS)) {
3764 logeventf(ssh, "Remote port forwarding from %s enabled",
3767 logeventf(ssh, "Remote port forwarding from %s refused",
3770 rpf = del234(ssh->rportfwds, pf);
3776 static void ssh_setup_portfwd(Ssh ssh, const Config *cfg)
3778 const char *portfwd_strptr = cfg->portfwd;
3779 struct ssh_portfwd *epf;
3782 if (!ssh->portfwds) {
3783 ssh->portfwds = newtree234(ssh_portcmp);
3786 * Go through the existing port forwardings and tag them
3787 * with status==DESTROY. Any that we want to keep will be
3788 * re-enabled (status==KEEP) as we go through the
3789 * configuration and find out which bits are the same as
3792 struct ssh_portfwd *epf;
3794 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
3795 epf->status = DESTROY;
3798 while (*portfwd_strptr) {
3799 char address_family, type;
3800 int sport,dport,sserv,dserv;
3801 char sports[256], dports[256], saddr[256], host[256];
3804 address_family = 'A';
3806 if (*portfwd_strptr == 'A' ||
3807 *portfwd_strptr == '4' ||
3808 *portfwd_strptr == '6')
3809 address_family = *portfwd_strptr++;
3810 if (*portfwd_strptr == 'L' ||
3811 *portfwd_strptr == 'R' ||
3812 *portfwd_strptr == 'D')
3813 type = *portfwd_strptr++;
3818 while (*portfwd_strptr && *portfwd_strptr != '\t') {
3819 if (*portfwd_strptr == ':') {
3821 * We've seen a colon in the middle of the
3822 * source port number. This means that
3823 * everything we've seen until now is the
3824 * source _address_, so we'll move it into
3825 * saddr and start sports from the beginning
3830 if (ssh->version == 1 && type == 'R') {
3831 logeventf(ssh, "SSH-1 cannot handle remote source address "
3832 "spec \"%s\"; ignoring", sports);
3834 strcpy(saddr, sports);
3837 if (n < lenof(sports)-1) sports[n++] = *portfwd_strptr++;
3841 if (*portfwd_strptr == '\t')
3844 while (*portfwd_strptr && *portfwd_strptr != ':') {
3845 if (n < lenof(host)-1) host[n++] = *portfwd_strptr++;
3848 if (*portfwd_strptr == ':')
3851 while (*portfwd_strptr) {
3852 if (n < lenof(dports)-1) dports[n++] = *portfwd_strptr++;
3856 dport = atoi(dports);
3860 dport = net_service_lookup(dports);
3862 logeventf(ssh, "Service lookup failed for destination"
3863 " port \"%s\"", dports);
3867 while (*portfwd_strptr) portfwd_strptr++;
3871 portfwd_strptr++; /* eat the NUL and move to next one */
3873 sport = atoi(sports);
3877 sport = net_service_lookup(sports);
3879 logeventf(ssh, "Service lookup failed for source"
3880 " port \"%s\"", sports);
3883 if (sport && dport) {
3884 /* Set up a description of the source port. */
3885 struct ssh_portfwd *pfrec, *epfrec;
3887 pfrec = snew(struct ssh_portfwd);
3889 pfrec->saddr = *saddr ? dupstr(saddr) : NULL;
3890 pfrec->sserv = sserv ? dupstr(sports) : NULL;
3891 pfrec->sport = sport;
3892 pfrec->daddr = *host ? dupstr(host) : NULL;
3893 pfrec->dserv = dserv ? dupstr(dports) : NULL;
3894 pfrec->dport = dport;
3895 pfrec->local = NULL;
3896 pfrec->remote = NULL;
3897 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
3898 address_family == '6' ? ADDRTYPE_IPV6 :
3901 epfrec = add234(ssh->portfwds, pfrec);
3902 if (epfrec != pfrec) {
3904 * We already have a port forwarding with precisely
3905 * these parameters. Hence, no need to do anything;
3906 * simply tag the existing one as KEEP.
3908 epfrec->status = KEEP;
3909 free_portfwd(pfrec);
3911 pfrec->status = CREATE;
3917 * Now go through and destroy any port forwardings which were
3920 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
3921 if (epf->status == DESTROY) {
3924 message = dupprintf("%s port forwarding from %s%s%d",
3925 epf->type == 'L' ? "local" :
3926 epf->type == 'R' ? "remote" : "dynamic",
3927 epf->saddr ? epf->saddr : "",
3928 epf->saddr ? ":" : "",
3931 if (epf->type != 'D') {
3932 char *msg2 = dupprintf("%s to %s:%d", message,
3933 epf->daddr, epf->dport);
3938 logeventf(ssh, "Cancelling %s", message);
3942 struct ssh_rportfwd *rpf = epf->remote;
3943 struct Packet *pktout;
3946 * Cancel the port forwarding at the server
3949 if (ssh->version == 1) {
3951 * We cannot cancel listening ports on the
3952 * server side in SSH-1! There's no message
3953 * to support it. Instead, we simply remove
3954 * the rportfwd record from the local end
3955 * so that any connections the server tries
3956 * to make on it are rejected.
3959 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
3960 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
3961 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
3963 ssh2_pkt_addstring(pktout, epf->saddr);
3964 } else if (ssh->cfg.rport_acceptall) {
3965 /* XXX: ssh->cfg.rport_acceptall may not represent
3966 * what was used to open the original connection,
3967 * since it's reconfigurable. */
3968 ssh2_pkt_addstring(pktout, "0.0.0.0");
3970 ssh2_pkt_addstring(pktout, "127.0.0.1");
3972 ssh2_pkt_adduint32(pktout, epf->sport);
3973 ssh2_pkt_send(ssh, pktout);
3976 del234(ssh->rportfwds, rpf);
3978 } else if (epf->local) {
3979 pfd_terminate(epf->local);
3982 delpos234(ssh->portfwds, i);
3984 i--; /* so we don't skip one in the list */
3988 * And finally, set up any new port forwardings (status==CREATE).
3990 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
3991 if (epf->status == CREATE) {
3992 char *sportdesc, *dportdesc;
3993 sportdesc = dupprintf("%s%s%s%s%d%s",
3994 epf->saddr ? epf->saddr : "",
3995 epf->saddr ? ":" : "",
3996 epf->sserv ? epf->sserv : "",
3997 epf->sserv ? "(" : "",
3999 epf->sserv ? ")" : "");
4000 if (epf->type == 'D') {
4003 dportdesc = dupprintf("%s:%s%s%d%s",
4005 epf->dserv ? epf->dserv : "",
4006 epf->dserv ? "(" : "",
4008 epf->dserv ? ")" : "");
4011 if (epf->type == 'L') {
4012 const char *err = pfd_addforward(epf->daddr, epf->dport,
4013 epf->saddr, epf->sport,
4016 epf->addressfamily);
4018 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
4019 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4020 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4021 sportdesc, dportdesc,
4022 err ? " failed: " : "", err ? err : "");
4023 } else if (epf->type == 'D') {
4024 const char *err = pfd_addforward(NULL, -1,
4025 epf->saddr, epf->sport,
4028 epf->addressfamily);
4030 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
4031 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4032 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4034 err ? " failed: " : "", err ? err : "");
4036 struct ssh_rportfwd *pf;
4039 * Ensure the remote port forwardings tree exists.
4041 if (!ssh->rportfwds) {
4042 if (ssh->version == 1)
4043 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
4045 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
4048 pf = snew(struct ssh_rportfwd);
4049 strncpy(pf->dhost, epf->daddr, lenof(pf->dhost)-1);
4050 pf->dhost[lenof(pf->dhost)-1] = '\0';
4051 pf->dport = epf->dport;
4052 pf->sport = epf->sport;
4053 if (add234(ssh->rportfwds, pf) != pf) {
4054 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
4055 epf->daddr, epf->dport);
4058 logeventf(ssh, "Requesting remote port %s"
4059 " forward to %s", sportdesc, dportdesc);
4061 pf->sportdesc = sportdesc;
4066 if (ssh->version == 1) {
4067 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
4068 PKT_INT, epf->sport,
4069 PKT_STR, epf->daddr,
4070 PKT_INT, epf->dport,
4072 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
4074 ssh_rportfwd_succfail, pf);
4076 struct Packet *pktout;
4077 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4078 ssh2_pkt_addstring(pktout, "tcpip-forward");
4079 ssh2_pkt_addbool(pktout, 1);/* want reply */
4081 ssh2_pkt_addstring(pktout, epf->saddr);
4082 } else if (cfg->rport_acceptall) {
4083 ssh2_pkt_addstring(pktout, "0.0.0.0");
4085 ssh2_pkt_addstring(pktout, "127.0.0.1");
4087 ssh2_pkt_adduint32(pktout, epf->sport);
4088 ssh2_pkt_send(ssh, pktout);
4090 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
4091 SSH2_MSG_REQUEST_FAILURE,
4092 ssh_rportfwd_succfail, pf);
4101 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
4104 int stringlen, bufsize;
4106 ssh_pkt_getstring(pktin, &string, &stringlen);
4107 if (string == NULL) {
4108 bombout(("Incoming terminal data packet was badly formed"));
4112 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
4114 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
4115 ssh->v1_stdout_throttling = 1;
4116 ssh1_throttle(ssh, +1);
4120 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
4122 /* Remote side is trying to open a channel to talk to our
4123 * X-Server. Give them back a local channel number. */
4124 struct ssh_channel *c;
4125 int remoteid = ssh_pkt_getuint32(pktin);
4127 logevent("Received X11 connect request");
4128 /* Refuse if X11 forwarding is disabled. */
4129 if (!ssh->X11_fwd_enabled) {
4130 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4131 PKT_INT, remoteid, PKT_END);
4132 logevent("Rejected X11 connect request");
4134 c = snew(struct ssh_channel);
4137 if (x11_init(&c->u.x11.s, ssh->cfg.x11_display, c,
4138 ssh->x11auth, NULL, -1, &ssh->cfg) != NULL) {
4139 logevent("Opening X11 forward connection failed");
4141 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4142 PKT_INT, remoteid, PKT_END);
4145 ("Opening X11 forward connection succeeded");
4146 c->remoteid = remoteid;
4147 c->halfopen = FALSE;
4148 c->localid = alloc_channel_id(ssh);
4150 c->v.v1.throttling = 0;
4151 c->type = CHAN_X11; /* identify channel type */
4152 add234(ssh->channels, c);
4153 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4154 PKT_INT, c->remoteid, PKT_INT,
4155 c->localid, PKT_END);
4156 logevent("Opened X11 forward channel");
4161 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
4163 /* Remote side is trying to open a channel to talk to our
4164 * agent. Give them back a local channel number. */
4165 struct ssh_channel *c;
4166 int remoteid = ssh_pkt_getuint32(pktin);
4168 /* Refuse if agent forwarding is disabled. */
4169 if (!ssh->agentfwd_enabled) {
4170 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4171 PKT_INT, remoteid, PKT_END);
4173 c = snew(struct ssh_channel);
4175 c->remoteid = remoteid;
4176 c->halfopen = FALSE;
4177 c->localid = alloc_channel_id(ssh);
4179 c->v.v1.throttling = 0;
4180 c->type = CHAN_AGENT; /* identify channel type */
4181 c->u.a.lensofar = 0;
4182 add234(ssh->channels, c);
4183 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4184 PKT_INT, c->remoteid, PKT_INT, c->localid,
4189 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
4191 /* Remote side is trying to open a channel to talk to a
4192 * forwarded port. Give them back a local channel number. */
4193 struct ssh_channel *c;
4194 struct ssh_rportfwd pf, *pfp;
4199 c = snew(struct ssh_channel);
4202 remoteid = ssh_pkt_getuint32(pktin);
4203 ssh_pkt_getstring(pktin, &host, &hostsize);
4204 port = ssh_pkt_getuint32(pktin);
4206 if (hostsize >= lenof(pf.dhost))
4207 hostsize = lenof(pf.dhost)-1;
4208 memcpy(pf.dhost, host, hostsize);
4209 pf.dhost[hostsize] = '\0';
4211 pfp = find234(ssh->rportfwds, &pf, NULL);
4214 logeventf(ssh, "Rejected remote port open request for %s:%d",
4216 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4217 PKT_INT, remoteid, PKT_END);
4219 logeventf(ssh, "Received remote port open request for %s:%d",
4221 e = pfd_newconnect(&c->u.pfd.s, pf.dhost, port,
4222 c, &ssh->cfg, pfp->pfrec->addressfamily);
4224 logeventf(ssh, "Port open failed: %s", e);
4226 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4227 PKT_INT, remoteid, PKT_END);
4229 c->remoteid = remoteid;
4230 c->halfopen = FALSE;
4231 c->localid = alloc_channel_id(ssh);
4233 c->v.v1.throttling = 0;
4234 c->type = CHAN_SOCKDATA; /* identify channel type */
4235 add234(ssh->channels, c);
4236 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4237 PKT_INT, c->remoteid, PKT_INT,
4238 c->localid, PKT_END);
4239 logevent("Forwarded port opened successfully");
4244 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
4246 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4247 unsigned int localid = ssh_pkt_getuint32(pktin);
4248 struct ssh_channel *c;
4250 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4251 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4252 c->remoteid = localid;
4253 c->halfopen = FALSE;
4254 c->type = CHAN_SOCKDATA;
4255 c->v.v1.throttling = 0;
4256 pfd_confirm(c->u.pfd.s);
4259 if (c && c->closes) {
4261 * We have a pending close on this channel,
4262 * which we decided on before the server acked
4263 * the channel open. So now we know the
4264 * remoteid, we can close it again.
4266 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE,
4267 PKT_INT, c->remoteid, PKT_END);
4271 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
4273 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4274 struct ssh_channel *c;
4276 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4277 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4278 logevent("Forwarded connection refused by server");
4279 pfd_close(c->u.pfd.s);
4280 del234(ssh->channels, c);
4285 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
4287 /* Remote side closes a channel. */
4288 unsigned i = ssh_pkt_getuint32(pktin);
4289 struct ssh_channel *c;
4290 c = find234(ssh->channels, &i, ssh_channelfind);
4291 if (c && !c->halfopen) {
4294 (pktin->type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
4296 if ((c->closes == 0) && (c->type == CHAN_X11)) {
4297 logevent("Forwarded X11 connection terminated");
4298 assert(c->u.x11.s != NULL);
4299 x11_close(c->u.x11.s);
4302 if ((c->closes == 0) && (c->type == CHAN_SOCKDATA)) {
4303 logevent("Forwarded port closed");
4304 assert(c->u.pfd.s != NULL);
4305 pfd_close(c->u.pfd.s);
4309 c->closes |= (closetype << 2); /* seen this message */
4310 if (!(c->closes & closetype)) {
4311 send_packet(ssh, pktin->type, PKT_INT, c->remoteid,
4313 c->closes |= closetype; /* sent it too */
4316 if (c->closes == 15) {
4317 del234(ssh->channels, c);
4321 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
4322 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
4323 "_CONFIRMATION", c ? "half-open" : "nonexistent",
4328 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
4330 /* Data sent down one of our channels. */
4331 int i = ssh_pkt_getuint32(pktin);
4334 struct ssh_channel *c;
4336 ssh_pkt_getstring(pktin, &p, &len);
4338 c = find234(ssh->channels, &i, ssh_channelfind);
4343 bufsize = x11_send(c->u.x11.s, p, len);
4346 bufsize = pfd_send(c->u.pfd.s, p, len);
4349 /* Data for an agent message. Buffer it. */
4351 if (c->u.a.lensofar < 4) {
4352 unsigned int l = min(4 - c->u.a.lensofar, len);
4353 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
4357 c->u.a.lensofar += l;
4359 if (c->u.a.lensofar == 4) {
4361 4 + GET_32BIT(c->u.a.msglen);
4362 c->u.a.message = snewn(c->u.a.totallen,
4364 memcpy(c->u.a.message, c->u.a.msglen, 4);
4366 if (c->u.a.lensofar >= 4 && len > 0) {
4368 min(c->u.a.totallen - c->u.a.lensofar,
4370 memcpy(c->u.a.message + c->u.a.lensofar, p,
4374 c->u.a.lensofar += l;
4376 if (c->u.a.lensofar == c->u.a.totallen) {
4379 if (agent_query(c->u.a.message,
4382 ssh_agentf_callback, c))
4383 ssh_agentf_callback(c, reply, replylen);
4384 sfree(c->u.a.message);
4385 c->u.a.lensofar = 0;
4388 bufsize = 0; /* agent channels never back up */
4391 if (!c->v.v1.throttling && bufsize > SSH1_BUFFER_LIMIT) {
4392 c->v.v1.throttling = 1;
4393 ssh1_throttle(ssh, +1);
4398 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
4400 ssh->exitcode = ssh_pkt_getuint32(pktin);
4401 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
4402 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
4404 * In case `helpful' firewalls or proxies tack
4405 * extra human-readable text on the end of the
4406 * session which we might mistake for another
4407 * encrypted packet, we close the session once
4408 * we've sent EXIT_CONFIRMATION.
4410 ssh->close_expected = TRUE;
4411 ssh_closing((Plug)ssh, NULL, 0, 0);
4414 static void do_ssh1_connection(Ssh ssh, unsigned char *in, int inlen,
4415 struct Packet *pktin)
4417 crBegin(ssh->do_ssh1_connection_crstate);
4419 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
4420 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
4421 ssh1_smsg_stdout_stderr_data;
4423 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
4424 ssh1_msg_channel_open_confirmation;
4425 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
4426 ssh1_msg_channel_open_failure;
4427 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
4428 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
4429 ssh1_msg_channel_close;
4430 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
4431 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
4433 if (ssh->cfg.agentfwd && agent_exists()) {
4434 logevent("Requesting agent forwarding");
4435 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
4439 if (pktin->type != SSH1_SMSG_SUCCESS
4440 && pktin->type != SSH1_SMSG_FAILURE) {
4441 bombout(("Protocol confusion"));
4443 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4444 logevent("Agent forwarding refused");
4446 logevent("Agent forwarding enabled");
4447 ssh->agentfwd_enabled = TRUE;
4448 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
4452 if (ssh->cfg.x11_forward) {
4453 char proto[20], data[64];
4454 logevent("Requesting X11 forwarding");
4455 ssh->x11auth = x11_invent_auth(proto, sizeof(proto),
4456 data, sizeof(data), ssh->cfg.x11_auth);
4457 x11_get_real_auth(ssh->x11auth, ssh->cfg.x11_display);
4458 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
4459 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
4460 PKT_STR, proto, PKT_STR, data,
4461 PKT_INT, x11_get_screen_number(ssh->cfg.x11_display),
4464 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
4465 PKT_STR, proto, PKT_STR, data, PKT_END);
4470 if (pktin->type != SSH1_SMSG_SUCCESS
4471 && pktin->type != SSH1_SMSG_FAILURE) {
4472 bombout(("Protocol confusion"));
4474 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4475 logevent("X11 forwarding refused");
4477 logevent("X11 forwarding enabled");
4478 ssh->X11_fwd_enabled = TRUE;
4479 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
4483 ssh_setup_portfwd(ssh, &ssh->cfg);
4484 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
4486 if (!ssh->cfg.nopty) {
4487 /* Unpick the terminal-speed string. */
4488 /* XXX perhaps we should allow no speeds to be sent. */
4489 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
4490 sscanf(ssh->cfg.termspeed, "%d,%d", &ssh->ospeed, &ssh->ispeed);
4491 /* Send the pty request. */
4492 send_packet(ssh, SSH1_CMSG_REQUEST_PTY,
4493 PKT_STR, ssh->cfg.termtype,
4494 PKT_INT, ssh->term_height,
4495 PKT_INT, ssh->term_width,
4496 PKT_INT, 0, PKT_INT, 0, /* width,height in pixels */
4497 PKT_CHAR, 192, PKT_INT, ssh->ispeed, /* TTY_OP_ISPEED */
4498 PKT_CHAR, 193, PKT_INT, ssh->ospeed, /* TTY_OP_OSPEED */
4499 PKT_CHAR, 0, PKT_END);
4500 ssh->state = SSH_STATE_INTERMED;
4504 if (pktin->type != SSH1_SMSG_SUCCESS
4505 && pktin->type != SSH1_SMSG_FAILURE) {
4506 bombout(("Protocol confusion"));
4508 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4509 c_write_str(ssh, "Server refused to allocate pty\r\n");
4510 ssh->editing = ssh->echoing = 1;
4512 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
4513 ssh->ospeed, ssh->ispeed);
4515 ssh->editing = ssh->echoing = 1;
4518 if (ssh->cfg.compression) {
4519 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
4523 if (pktin->type != SSH1_SMSG_SUCCESS
4524 && pktin->type != SSH1_SMSG_FAILURE) {
4525 bombout(("Protocol confusion"));
4527 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4528 c_write_str(ssh, "Server refused to compress\r\n");
4530 logevent("Started compression");
4531 ssh->v1_compressing = TRUE;
4532 ssh->cs_comp_ctx = zlib_compress_init();
4533 logevent("Initialised zlib (RFC1950) compression");
4534 ssh->sc_comp_ctx = zlib_decompress_init();
4535 logevent("Initialised zlib (RFC1950) decompression");
4539 * Start the shell or command.
4541 * Special case: if the first-choice command is an SSH-2
4542 * subsystem (hence not usable here) and the second choice
4543 * exists, we fall straight back to that.
4546 char *cmd = ssh->cfg.remote_cmd_ptr;
4548 if (!cmd) cmd = ssh->cfg.remote_cmd;
4550 if (ssh->cfg.ssh_subsys && ssh->cfg.remote_cmd_ptr2) {
4551 cmd = ssh->cfg.remote_cmd_ptr2;
4552 ssh->fallback_cmd = TRUE;
4555 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
4557 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
4558 logevent("Started session");
4561 ssh->state = SSH_STATE_SESSION;
4562 if (ssh->size_needed)
4563 ssh_size(ssh, ssh->term_width, ssh->term_height);
4564 if (ssh->eof_needed)
4565 ssh_special(ssh, TS_EOF);
4568 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
4570 ssh->channels = newtree234(ssh_channelcmp);
4574 * By this point, most incoming packets are already being
4575 * handled by the dispatch table, and we need only pay
4576 * attention to the unusual ones.
4581 if (pktin->type == SSH1_SMSG_SUCCESS) {
4582 /* may be from EXEC_SHELL on some servers */
4583 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4584 /* may be from EXEC_SHELL on some servers
4585 * if no pty is available or in other odd cases. Ignore */
4587 bombout(("Strange packet received: type %d", pktin->type));
4592 int len = min(inlen, 512);
4593 send_packet(ssh, SSH1_CMSG_STDIN_DATA, PKTT_DATA,
4594 PKT_INT, len, PKT_DATA, in, len,
4595 PKTT_OTHER, PKT_END);
4606 * Handle the top-level SSH-2 protocol.
4608 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
4613 ssh_pkt_getstring(pktin, &msg, &msglen);
4614 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
4617 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
4619 /* log reason code in disconnect message */
4623 ssh_pkt_getstring(pktin, &msg, &msglen);
4624 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
4627 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
4629 /* Do nothing, because we're ignoring it! Duhh. */
4632 static void ssh1_protocol_setup(Ssh ssh)
4637 * Most messages are handled by the coroutines.
4639 for (i = 0; i < 256; i++)
4640 ssh->packet_dispatch[i] = NULL;
4643 * These special message types we install handlers for.
4645 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
4646 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
4647 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
4650 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
4651 struct Packet *pktin)
4653 unsigned char *in=(unsigned char*)vin;
4654 if (ssh->state == SSH_STATE_CLOSED)
4657 if (pktin && ssh->packet_dispatch[pktin->type]) {
4658 ssh->packet_dispatch[pktin->type](ssh, pktin);
4662 if (!ssh->protocol_initial_phase_done) {
4663 if (do_ssh1_login(ssh, in, inlen, pktin))
4664 ssh->protocol_initial_phase_done = TRUE;
4669 do_ssh1_connection(ssh, in, inlen, pktin);
4673 * Utility routine for decoding comma-separated strings in KEXINIT.
4675 static int in_commasep_string(char *needle, char *haystack, int haylen)
4678 if (!needle || !haystack) /* protect against null pointers */
4680 needlen = strlen(needle);
4683 * Is it at the start of the string?
4685 if (haylen >= needlen && /* haystack is long enough */
4686 !memcmp(needle, haystack, needlen) && /* initial match */
4687 (haylen == needlen || haystack[needlen] == ',')
4688 /* either , or EOS follows */
4692 * If not, search for the next comma and resume after that.
4693 * If no comma found, terminate.
4695 while (haylen > 0 && *haystack != ',')
4696 haylen--, haystack++;
4699 haylen--, haystack++; /* skip over comma itself */
4704 * Similar routine for checking whether we have the first string in a list.
4706 static int first_in_commasep_string(char *needle, char *haystack, int haylen)
4709 if (!needle || !haystack) /* protect against null pointers */
4711 needlen = strlen(needle);
4713 * Is it at the start of the string?
4715 if (haylen >= needlen && /* haystack is long enough */
4716 !memcmp(needle, haystack, needlen) && /* initial match */
4717 (haylen == needlen || haystack[needlen] == ',')
4718 /* either , or EOS follows */
4726 * SSH-2 key creation method.
4728 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H,
4729 unsigned char *sessid, char chr,
4730 unsigned char *keyspace)
4733 /* First 20 bytes. */
4735 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
4737 SHA_Bytes(&s, H, 20);
4738 SHA_Bytes(&s, &chr, 1);
4739 SHA_Bytes(&s, sessid, 20);
4740 SHA_Final(&s, keyspace);
4741 /* Next 20 bytes. */
4743 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
4745 SHA_Bytes(&s, H, 20);
4746 SHA_Bytes(&s, keyspace, 20);
4747 SHA_Final(&s, keyspace + 20);
4751 * Handle the SSH-2 transport layer.
4753 static int do_ssh2_transport(Ssh ssh, void *vin, int inlen,
4754 struct Packet *pktin)
4756 unsigned char *in = (unsigned char *)vin;
4757 struct do_ssh2_transport_state {
4758 int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
4759 Bignum p, g, e, f, K;
4760 int kex_init_value, kex_reply_value;
4761 const struct ssh_mac **maclist;
4763 const struct ssh2_cipher *cscipher_tobe;
4764 const struct ssh2_cipher *sccipher_tobe;
4765 const struct ssh_mac *csmac_tobe;
4766 const struct ssh_mac *scmac_tobe;
4767 const struct ssh_compress *cscomp_tobe;
4768 const struct ssh_compress *sccomp_tobe;
4769 char *hostkeydata, *sigdata, *keystr, *fingerprint;
4770 int hostkeylen, siglen;
4771 void *hkey; /* actual host key */
4772 unsigned char exchange_hash[20];
4773 int n_preferred_kex;
4774 const struct ssh_kex *preferred_kex[KEX_MAX];
4775 int n_preferred_ciphers;
4776 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
4777 const struct ssh_compress *preferred_comp;
4778 int got_session_id, activated_authconn;
4779 struct Packet *pktout;
4784 crState(do_ssh2_transport_state);
4786 crBegin(ssh->do_ssh2_transport_crstate);
4788 s->cscipher_tobe = s->sccipher_tobe = NULL;
4789 s->csmac_tobe = s->scmac_tobe = NULL;
4790 s->cscomp_tobe = s->sccomp_tobe = NULL;
4792 s->got_session_id = s->activated_authconn = FALSE;
4795 * Be prepared to work around the buggy MAC problem.
4797 if (ssh->remote_bugs & BUG_SSH2_HMAC)
4798 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
4800 s->maclist = macs, s->nmacs = lenof(macs);
4803 ssh->pkt_ctx &= ~SSH2_PKTCTX_KEX_MASK;
4805 int i, j, commalist_started;
4808 * Set up the preferred key exchange. (NULL => warn below here)
4810 s->n_preferred_kex = 0;
4811 for (i = 0; i < KEX_MAX; i++) {
4812 switch (ssh->cfg.ssh_kexlist[i]) {
4814 s->preferred_kex[s->n_preferred_kex++] =
4815 &ssh_diffiehellman_gex;
4818 s->preferred_kex[s->n_preferred_kex++] =
4819 &ssh_diffiehellman_group14;
4822 s->preferred_kex[s->n_preferred_kex++] =
4823 &ssh_diffiehellman_group1;
4826 /* Flag for later. Don't bother if it's the last in
4828 if (i < KEX_MAX - 1) {
4829 s->preferred_kex[s->n_preferred_kex++] = NULL;
4836 * Set up the preferred ciphers. (NULL => warn below here)
4838 s->n_preferred_ciphers = 0;
4839 for (i = 0; i < CIPHER_MAX; i++) {
4840 switch (ssh->cfg.ssh_cipherlist[i]) {
4841 case CIPHER_BLOWFISH:
4842 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
4845 if (ssh->cfg.ssh2_des_cbc) {
4846 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
4850 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
4853 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
4855 case CIPHER_ARCFOUR:
4856 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
4859 /* Flag for later. Don't bother if it's the last in
4861 if (i < CIPHER_MAX - 1) {
4862 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
4869 * Set up preferred compression.
4871 if (ssh->cfg.compression)
4872 s->preferred_comp = &ssh_zlib;
4874 s->preferred_comp = &ssh_comp_none;
4877 * Enable queueing of outgoing auth- or connection-layer
4878 * packets while we are in the middle of a key exchange.
4880 ssh->queueing = TRUE;
4883 * Flag that KEX is in progress.
4885 ssh->kex_in_progress = TRUE;
4888 * Construct and send our key exchange packet.
4890 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
4891 for (i = 0; i < 16; i++)
4892 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
4893 /* List key exchange algorithms. */
4894 ssh2_pkt_addstring_start(s->pktout);
4895 commalist_started = 0;
4896 for (i = 0; i < s->n_preferred_kex; i++) {
4897 const struct ssh_kex *k = s->preferred_kex[i];
4898 if (!k) continue; /* warning flag */
4899 if (commalist_started)
4900 ssh2_pkt_addstring_str(s->pktout, ",");
4901 ssh2_pkt_addstring_str(s->pktout, s->preferred_kex[i]->name);
4902 commalist_started = 1;
4904 /* List server host key algorithms. */
4905 ssh2_pkt_addstring_start(s->pktout);
4906 for (i = 0; i < lenof(hostkey_algs); i++) {
4907 ssh2_pkt_addstring_str(s->pktout, hostkey_algs[i]->name);
4908 if (i < lenof(hostkey_algs) - 1)
4909 ssh2_pkt_addstring_str(s->pktout, ",");
4911 /* List client->server encryption algorithms. */
4912 ssh2_pkt_addstring_start(s->pktout);
4913 commalist_started = 0;
4914 for (i = 0; i < s->n_preferred_ciphers; i++) {
4915 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
4916 if (!c) continue; /* warning flag */
4917 for (j = 0; j < c->nciphers; j++) {
4918 if (commalist_started)
4919 ssh2_pkt_addstring_str(s->pktout, ",");
4920 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
4921 commalist_started = 1;
4924 /* List server->client encryption algorithms. */
4925 ssh2_pkt_addstring_start(s->pktout);
4926 commalist_started = 0;
4927 for (i = 0; i < s->n_preferred_ciphers; i++) {
4928 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
4929 if (!c) continue; /* warning flag */
4930 for (j = 0; j < c->nciphers; j++) {
4931 if (commalist_started)
4932 ssh2_pkt_addstring_str(s->pktout, ",");
4933 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
4934 commalist_started = 1;
4937 /* List client->server MAC algorithms. */
4938 ssh2_pkt_addstring_start(s->pktout);
4939 for (i = 0; i < s->nmacs; i++) {
4940 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
4941 if (i < s->nmacs - 1)
4942 ssh2_pkt_addstring_str(s->pktout, ",");
4944 /* List server->client MAC algorithms. */
4945 ssh2_pkt_addstring_start(s->pktout);
4946 for (i = 0; i < s->nmacs; i++) {
4947 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
4948 if (i < s->nmacs - 1)
4949 ssh2_pkt_addstring_str(s->pktout, ",");
4951 /* List client->server compression algorithms. */
4952 ssh2_pkt_addstring_start(s->pktout);
4953 assert(lenof(compressions) > 1);
4954 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
4955 for (i = 0; i < lenof(compressions); i++) {
4956 const struct ssh_compress *c = compressions[i];
4957 if (c != s->preferred_comp) {
4958 ssh2_pkt_addstring_str(s->pktout, ",");
4959 ssh2_pkt_addstring_str(s->pktout, c->name);
4962 /* List server->client compression algorithms. */
4963 ssh2_pkt_addstring_start(s->pktout);
4964 assert(lenof(compressions) > 1);
4965 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
4966 for (i = 0; i < lenof(compressions); i++) {
4967 const struct ssh_compress *c = compressions[i];
4968 if (c != s->preferred_comp) {
4969 ssh2_pkt_addstring_str(s->pktout, ",");
4970 ssh2_pkt_addstring_str(s->pktout, c->name);
4973 /* List client->server languages. Empty list. */
4974 ssh2_pkt_addstring_start(s->pktout);
4975 /* List server->client languages. Empty list. */
4976 ssh2_pkt_addstring_start(s->pktout);
4977 /* First KEX packet does _not_ follow, because we're not that brave. */
4978 ssh2_pkt_addbool(s->pktout, FALSE);
4980 ssh2_pkt_adduint32(s->pktout, 0);
4983 ssh->exhash = ssh->exhashbase;
4984 sha_string(&ssh->exhash, s->pktout->data + 5, s->pktout->length - 5);
4986 ssh2_pkt_send_noqueue(ssh, s->pktout);
4990 if (pktin->length > 5)
4991 sha_string(&ssh->exhash, pktin->data + 5, pktin->length - 5);
4994 * Now examine the other side's KEXINIT to see what we're up
4998 char *str, *preferred;
5001 if (pktin->type != SSH2_MSG_KEXINIT) {
5002 bombout(("expected key exchange packet from server"));
5006 ssh->hostkey = NULL;
5007 s->cscipher_tobe = NULL;
5008 s->sccipher_tobe = NULL;
5009 s->csmac_tobe = NULL;
5010 s->scmac_tobe = NULL;
5011 s->cscomp_tobe = NULL;
5012 s->sccomp_tobe = NULL;
5013 s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
5015 pktin->savedpos += 16; /* skip garbage cookie */
5016 ssh_pkt_getstring(pktin, &str, &len); /* key exchange algorithms */
5019 for (i = 0; i < s->n_preferred_kex; i++) {
5020 const struct ssh_kex *k = s->preferred_kex[i];
5024 if (!preferred) preferred = k->name;
5025 if (in_commasep_string(k->name, str, len))
5032 bombout(("Couldn't agree a key exchange algorithm (available: %s)",
5033 str ? str : "(null)"));
5037 * Note that the server's guess is considered wrong if it doesn't match
5038 * the first algorithm in our list, even if it's still the algorithm
5041 s->guessok = first_in_commasep_string(preferred, str, len);
5042 ssh_pkt_getstring(pktin, &str, &len); /* host key algorithms */
5043 for (i = 0; i < lenof(hostkey_algs); i++) {
5044 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
5045 ssh->hostkey = hostkey_algs[i];
5049 s->guessok = s->guessok &&
5050 first_in_commasep_string(hostkey_algs[0]->name, str, len);
5051 ssh_pkt_getstring(pktin, &str, &len); /* client->server cipher */
5052 for (i = 0; i < s->n_preferred_ciphers; i++) {
5053 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5055 s->warn_cscipher = TRUE;
5057 for (j = 0; j < c->nciphers; j++) {
5058 if (in_commasep_string(c->list[j]->name, str, len)) {
5059 s->cscipher_tobe = c->list[j];
5064 if (s->cscipher_tobe)
5067 if (!s->cscipher_tobe) {
5068 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
5069 str ? str : "(null)"));
5073 ssh_pkt_getstring(pktin, &str, &len); /* server->client cipher */
5074 for (i = 0; i < s->n_preferred_ciphers; i++) {
5075 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5077 s->warn_sccipher = TRUE;
5079 for (j = 0; j < c->nciphers; j++) {
5080 if (in_commasep_string(c->list[j]->name, str, len)) {
5081 s->sccipher_tobe = c->list[j];
5086 if (s->sccipher_tobe)
5089 if (!s->sccipher_tobe) {
5090 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
5091 str ? str : "(null)"));
5095 ssh_pkt_getstring(pktin, &str, &len); /* client->server mac */
5096 for (i = 0; i < s->nmacs; i++) {
5097 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5098 s->csmac_tobe = s->maclist[i];
5102 ssh_pkt_getstring(pktin, &str, &len); /* server->client mac */
5103 for (i = 0; i < s->nmacs; i++) {
5104 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5105 s->scmac_tobe = s->maclist[i];
5109 ssh_pkt_getstring(pktin, &str, &len); /* client->server compression */
5110 for (i = 0; i < lenof(compressions) + 1; i++) {
5111 const struct ssh_compress *c =
5112 i == 0 ? s->preferred_comp : compressions[i - 1];
5113 if (in_commasep_string(c->name, str, len)) {
5118 ssh_pkt_getstring(pktin, &str, &len); /* server->client compression */
5119 for (i = 0; i < lenof(compressions) + 1; i++) {
5120 const struct ssh_compress *c =
5121 i == 0 ? s->preferred_comp : compressions[i - 1];
5122 if (in_commasep_string(c->name, str, len)) {
5127 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
5128 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
5129 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
5132 ssh_set_frozen(ssh, 1);
5133 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
5135 ssh_dialog_callback, ssh);
5136 if (s->dlgret < 0) {
5140 bombout(("Unexpected data from server while"
5141 " waiting for user response"));
5144 } while (pktin || inlen > 0);
5145 s->dlgret = ssh->user_response;
5147 ssh_set_frozen(ssh, 0);
5148 if (s->dlgret == 0) {
5149 ssh->close_expected = TRUE;
5150 ssh_closing((Plug)ssh, NULL, 0, 0);
5155 if (s->warn_cscipher) {
5156 ssh_set_frozen(ssh, 1);
5157 s->dlgret = askalg(ssh->frontend,
5158 "client-to-server cipher",
5159 s->cscipher_tobe->name,
5160 ssh_dialog_callback, ssh);
5161 if (s->dlgret < 0) {
5165 bombout(("Unexpected data from server while"
5166 " waiting for user response"));
5169 } while (pktin || inlen > 0);
5170 s->dlgret = ssh->user_response;
5172 ssh_set_frozen(ssh, 0);
5173 if (s->dlgret == 0) {
5174 ssh->close_expected = TRUE;
5175 ssh_closing((Plug)ssh, NULL, 0, 0);
5180 if (s->warn_sccipher) {
5181 ssh_set_frozen(ssh, 1);
5182 s->dlgret = askalg(ssh->frontend,
5183 "server-to-client cipher",
5184 s->sccipher_tobe->name,
5185 ssh_dialog_callback, ssh);
5186 if (s->dlgret < 0) {
5190 bombout(("Unexpected data from server while"
5191 " waiting for user response"));
5194 } while (pktin || inlen > 0);
5195 s->dlgret = ssh->user_response;
5197 ssh_set_frozen(ssh, 0);
5198 if (s->dlgret == 0) {
5199 ssh->close_expected = TRUE;
5200 ssh_closing((Plug)ssh, NULL, 0, 0);
5205 if (s->ignorepkt) /* first_kex_packet_follows */
5206 crWaitUntil(pktin); /* Ignore packet */
5210 * Work out the number of bits of key we will need from the key
5211 * exchange. We start with the maximum key length of either
5217 csbits = s->cscipher_tobe->keylen;
5218 scbits = s->sccipher_tobe->keylen;
5219 s->nbits = (csbits > scbits ? csbits : scbits);
5221 /* The keys only have 160-bit entropy, since they're based on
5222 * a SHA-1 hash. So cap the key size at 160 bits. */
5227 * If we're doing Diffie-Hellman group exchange, start by
5228 * requesting a group.
5230 if (!ssh->kex->pdata) {
5231 logevent("Doing Diffie-Hellman group exchange");
5232 ssh->pkt_ctx |= SSH2_PKTCTX_DHGEX;
5234 * Work out how big a DH group we will need to allow that
5237 s->pbits = 512 << ((s->nbits - 1) / 64);
5238 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
5239 ssh2_pkt_adduint32(s->pktout, s->pbits);
5240 ssh2_pkt_send_noqueue(ssh, s->pktout);
5243 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
5244 bombout(("expected key exchange group packet from server"));
5247 s->p = ssh2_pkt_getmp(pktin);
5248 s->g = ssh2_pkt_getmp(pktin);
5249 if (!s->p || !s->g) {
5250 bombout(("unable to read mp-ints from incoming group packet"));
5253 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
5254 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
5255 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
5257 ssh->pkt_ctx |= SSH2_PKTCTX_DHGROUP;
5258 ssh->kex_ctx = dh_setup_group(ssh->kex);
5259 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
5260 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
5261 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
5262 ssh->kex->groupname);
5265 logevent("Doing Diffie-Hellman key exchange");
5267 * Now generate and send e for Diffie-Hellman.
5269 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
5270 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
5271 s->pktout = ssh2_pkt_init(s->kex_init_value);
5272 ssh2_pkt_addmp(s->pktout, s->e);
5273 ssh2_pkt_send_noqueue(ssh, s->pktout);
5275 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
5277 if (pktin->type != s->kex_reply_value) {
5278 bombout(("expected key exchange reply packet from server"));
5281 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
5282 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
5283 s->f = ssh2_pkt_getmp(pktin);
5285 bombout(("unable to parse key exchange reply packet"));
5288 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
5290 s->K = dh_find_K(ssh->kex_ctx, s->f);
5292 /* We assume everything from now on will be quick, and it might
5293 * involve user interaction. */
5294 set_busy_status(ssh->frontend, BUSY_NOT);
5296 sha_string(&ssh->exhash, s->hostkeydata, s->hostkeylen);
5297 if (ssh->kex == &ssh_diffiehellman_gex) {
5298 sha_uint32(&ssh->exhash, s->pbits);
5299 sha_mpint(&ssh->exhash, s->p);
5300 sha_mpint(&ssh->exhash, s->g);
5302 sha_mpint(&ssh->exhash, s->e);
5303 sha_mpint(&ssh->exhash, s->f);
5304 sha_mpint(&ssh->exhash, s->K);
5305 SHA_Final(&ssh->exhash, s->exchange_hash);
5307 dh_cleanup(ssh->kex_ctx);
5308 ssh->kex_ctx = NULL;
5311 debug(("Exchange hash is:\n"));
5312 dmemdump(s->exchange_hash, 20);
5315 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
5317 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
5318 (char *)s->exchange_hash, 20)) {
5319 bombout(("Server's host key did not match the signature supplied"));
5324 * Authenticate remote host: verify host key. (We've already
5325 * checked the signature of the exchange hash.)
5327 s->keystr = ssh->hostkey->fmtkey(s->hkey);
5328 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
5329 ssh_set_frozen(ssh, 1);
5330 s->dlgret = verify_ssh_host_key(ssh->frontend,
5331 ssh->savedhost, ssh->savedport,
5332 ssh->hostkey->keytype, s->keystr,
5334 ssh_dialog_callback, ssh);
5335 if (s->dlgret < 0) {
5339 bombout(("Unexpected data from server while waiting"
5340 " for user host key response"));
5343 } while (pktin || inlen > 0);
5344 s->dlgret = ssh->user_response;
5346 ssh_set_frozen(ssh, 0);
5347 if (s->dlgret == 0) {
5348 ssh->close_expected = TRUE;
5349 ssh_closing((Plug)ssh, NULL, 0, 0);
5352 if (!s->got_session_id) { /* don't bother logging this in rekeys */
5353 logevent("Host key fingerprint is:");
5354 logevent(s->fingerprint);
5356 sfree(s->fingerprint);
5358 ssh->hostkey->freekey(s->hkey);
5361 * The exchange hash from the very first key exchange is also
5362 * the session id, used in session key construction and
5365 if (!s->got_session_id) {
5366 memcpy(ssh->v2_session_id, s->exchange_hash,
5367 sizeof(s->exchange_hash));
5368 s->got_session_id = TRUE;
5372 * Send SSH2_MSG_NEWKEYS.
5374 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
5375 ssh2_pkt_send_noqueue(ssh, s->pktout);
5376 ssh->outgoing_data_size = 0; /* start counting from here */
5379 * We've sent client NEWKEYS, so create and initialise
5380 * client-to-server session keys.
5382 if (ssh->cs_cipher_ctx)
5383 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
5384 ssh->cscipher = s->cscipher_tobe;
5385 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
5387 if (ssh->cs_mac_ctx)
5388 ssh->csmac->free_context(ssh->cs_mac_ctx);
5389 ssh->csmac = s->csmac_tobe;
5390 ssh->cs_mac_ctx = ssh->csmac->make_context();
5392 if (ssh->cs_comp_ctx)
5393 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
5394 ssh->cscomp = s->cscomp_tobe;
5395 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
5398 * Set IVs on client-to-server keys. Here we use the exchange
5399 * hash from the _first_ key exchange.
5402 unsigned char keyspace[40];
5403 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'C',keyspace);
5404 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
5405 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'A',keyspace);
5406 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
5407 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'E',keyspace);
5408 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
5411 logeventf(ssh, "Initialised %.200s client->server encryption",
5412 ssh->cscipher->text_name);
5413 logeventf(ssh, "Initialised %.200s client->server MAC algorithm",
5414 ssh->csmac->text_name);
5415 if (ssh->cscomp->text_name)
5416 logeventf(ssh, "Initialised %s compression",
5417 ssh->cscomp->text_name);
5420 * Now our end of the key exchange is complete, we can send all
5421 * our queued higher-layer packets.
5423 ssh->queueing = FALSE;
5424 ssh2_pkt_queuesend(ssh);
5427 * Expect SSH2_MSG_NEWKEYS from server.
5430 if (pktin->type != SSH2_MSG_NEWKEYS) {
5431 bombout(("expected new-keys packet from server"));
5434 ssh->incoming_data_size = 0; /* start counting from here */
5437 * We've seen server NEWKEYS, so create and initialise
5438 * server-to-client session keys.
5440 if (ssh->sc_cipher_ctx)
5441 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
5442 ssh->sccipher = s->sccipher_tobe;
5443 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
5445 if (ssh->sc_mac_ctx)
5446 ssh->scmac->free_context(ssh->sc_mac_ctx);
5447 ssh->scmac = s->scmac_tobe;
5448 ssh->sc_mac_ctx = ssh->scmac->make_context();
5450 if (ssh->sc_comp_ctx)
5451 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
5452 ssh->sccomp = s->sccomp_tobe;
5453 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
5456 * Set IVs on server-to-client keys. Here we use the exchange
5457 * hash from the _first_ key exchange.
5460 unsigned char keyspace[40];
5461 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'D',keyspace);
5462 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
5463 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'B',keyspace);
5464 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
5465 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'F',keyspace);
5466 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
5468 logeventf(ssh, "Initialised %.200s server->client encryption",
5469 ssh->sccipher->text_name);
5470 logeventf(ssh, "Initialised %.200s server->client MAC algorithm",
5471 ssh->scmac->text_name);
5472 if (ssh->sccomp->text_name)
5473 logeventf(ssh, "Initialised %s decompression",
5474 ssh->sccomp->text_name);
5477 * Free key exchange data.
5481 if (ssh->kex == &ssh_diffiehellman_gex) {
5487 * Key exchange is over. Loop straight back round if we have a
5488 * deferred rekey reason.
5490 if (ssh->deferred_rekey_reason) {
5491 logevent(ssh->deferred_rekey_reason);
5493 ssh->deferred_rekey_reason = NULL;
5494 goto begin_key_exchange;
5498 * Otherwise, schedule a timer for our next rekey.
5500 ssh->kex_in_progress = FALSE;
5501 ssh->last_rekey = GETTICKCOUNT();
5502 if (ssh->cfg.ssh_rekey_time != 0)
5503 ssh->next_rekey = schedule_timer(ssh->cfg.ssh_rekey_time*60*TICKSPERSEC,
5507 * If this is the first key exchange phase, we must pass the
5508 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
5509 * wants to see it but because it will need time to initialise
5510 * itself before it sees an actual packet. In subsequent key
5511 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
5512 * it would only confuse the layer above.
5514 if (s->activated_authconn) {
5517 s->activated_authconn = TRUE;
5520 * Now we're encrypting. Begin returning 1 to the protocol main
5521 * function so that other things can run on top of the
5522 * transport. If we ever see a KEXINIT, we must go back to the
5525 * We _also_ go back to the start if we see pktin==NULL and
5526 * inlen==-1, because this is a special signal meaning
5527 * `initiate client-driven rekey', and `in' contains a message
5528 * giving the reason for the rekey.
5530 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
5531 (!pktin && inlen == -1))) {
5536 logevent("Server initiated key re-exchange");
5539 * Special case: if the server bug is set that doesn't
5540 * allow rekeying, we give a different log message and
5541 * continue waiting. (If such a server _initiates_ a rekey,
5542 * we process it anyway!)
5544 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
5545 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
5547 /* Reset the counters, so that at least this message doesn't
5548 * hit the event log _too_ often. */
5549 ssh->outgoing_data_size = 0;
5550 ssh->incoming_data_size = 0;
5551 if (ssh->cfg.ssh_rekey_time != 0) {
5553 schedule_timer(ssh->cfg.ssh_rekey_time*60*TICKSPERSEC,
5556 goto wait_for_rekey; /* this is utterly horrid */
5558 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
5561 goto begin_key_exchange;
5567 * Add data to an SSH-2 channel output buffer.
5569 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
5572 bufchain_add(&c->v.v2.outbuffer, buf, len);
5576 * Attempt to send data on an SSH-2 channel.
5578 static int ssh2_try_send(struct ssh_channel *c)
5581 struct Packet *pktout;
5583 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
5586 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
5587 if ((unsigned)len > c->v.v2.remwindow)
5588 len = c->v.v2.remwindow;
5589 if ((unsigned)len > c->v.v2.remmaxpkt)
5590 len = c->v.v2.remmaxpkt;
5591 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
5592 ssh2_pkt_adduint32(pktout, c->remoteid);
5593 dont_log_data(ssh, pktout, PKTLOG_OMIT);
5594 ssh2_pkt_addstring_start(pktout);
5595 ssh2_pkt_addstring_data(pktout, data, len);
5596 end_log_omission(ssh, pktout);
5597 ssh2_pkt_send(ssh, pktout);
5598 bufchain_consume(&c->v.v2.outbuffer, len);
5599 c->v.v2.remwindow -= len;
5603 * After having sent as much data as we can, return the amount
5606 return bufchain_size(&c->v.v2.outbuffer);
5609 static void ssh2_try_send_and_unthrottle(struct ssh_channel *c)
5613 return; /* don't send on closing channels */
5614 bufsize = ssh2_try_send(c);
5617 case CHAN_MAINSESSION:
5618 /* stdin need not receive an unthrottle
5619 * notification since it will be polled */
5622 x11_unthrottle(c->u.x11.s);
5625 /* agent sockets are request/response and need no
5626 * buffer management */
5629 pfd_unthrottle(c->u.pfd.s);
5636 * Potentially enlarge the window on an SSH-2 channel.
5638 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin)
5643 * Never send WINDOW_ADJUST for a channel that the remote side
5644 * already thinks it's closed; there's no point, since it won't
5645 * be sending any more data anyway.
5651 * Only send a WINDOW_ADJUST if there's significantly more window
5652 * available than the other end thinks there is. This saves us
5653 * sending a WINDOW_ADJUST for every character in a shell session.
5655 * "Significant" is arbitrarily defined as half the window size.
5657 if (newwin > c->v.v2.locwindow * 2) {
5658 struct Packet *pktout;
5660 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5661 ssh2_pkt_adduint32(pktout, c->remoteid);
5662 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
5663 ssh2_pkt_send(ssh, pktout);
5664 c->v.v2.locwindow = newwin;
5668 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
5670 unsigned i = ssh_pkt_getuint32(pktin);
5671 struct ssh_channel *c;
5672 c = find234(ssh->channels, &i, ssh_channelfind);
5673 if (c && !c->closes) {
5674 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
5675 ssh2_try_send_and_unthrottle(c);
5679 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
5683 unsigned i = ssh_pkt_getuint32(pktin);
5684 struct ssh_channel *c;
5685 c = find234(ssh->channels, &i, ssh_channelfind);
5687 return; /* nonexistent channel */
5688 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
5689 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
5690 return; /* extended but not stderr */
5691 ssh_pkt_getstring(pktin, &data, &length);
5694 c->v.v2.locwindow -= length;
5696 case CHAN_MAINSESSION:
5698 from_backend(ssh->frontend, pktin->type ==
5699 SSH2_MSG_CHANNEL_EXTENDED_DATA,
5703 bufsize = x11_send(c->u.x11.s, data, length);
5706 bufsize = pfd_send(c->u.pfd.s, data, length);
5709 while (length > 0) {
5710 if (c->u.a.lensofar < 4) {
5711 unsigned int l = min(4 - c->u.a.lensofar, length);
5712 memcpy(c->u.a.msglen + c->u.a.lensofar,
5716 c->u.a.lensofar += l;
5718 if (c->u.a.lensofar == 4) {
5720 4 + GET_32BIT(c->u.a.msglen);
5721 c->u.a.message = snewn(c->u.a.totallen,
5723 memcpy(c->u.a.message, c->u.a.msglen, 4);
5725 if (c->u.a.lensofar >= 4 && length > 0) {
5727 min(c->u.a.totallen - c->u.a.lensofar,
5729 memcpy(c->u.a.message + c->u.a.lensofar,
5733 c->u.a.lensofar += l;
5735 if (c->u.a.lensofar == c->u.a.totallen) {
5738 if (agent_query(c->u.a.message,
5741 ssh_agentf_callback, c))
5742 ssh_agentf_callback(c, reply, replylen);
5743 sfree(c->u.a.message);
5744 c->u.a.lensofar = 0;
5751 * If we are not buffering too much data,
5752 * enlarge the window again at the remote side.
5754 if (bufsize < OUR_V2_WINSIZE)
5755 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
5759 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
5761 unsigned i = ssh_pkt_getuint32(pktin);
5762 struct ssh_channel *c;
5764 c = find234(ssh->channels, &i, ssh_channelfind);
5766 return; /* nonexistent channel */
5768 if (c->type == CHAN_X11) {
5770 * Remote EOF on an X11 channel means we should
5771 * wrap up and close the channel ourselves.
5773 x11_close(c->u.x11.s);
5775 } else if (c->type == CHAN_AGENT) {
5777 } else if (c->type == CHAN_SOCKDATA) {
5778 pfd_close(c->u.pfd.s);
5783 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
5785 unsigned i = ssh_pkt_getuint32(pktin);
5786 struct ssh_channel *c;
5787 struct Packet *pktout;
5789 c = find234(ssh->channels, &i, ssh_channelfind);
5790 if (!c || c->halfopen) {
5791 bombout(("Received CHANNEL_CLOSE for %s channel %d\n",
5792 c ? "half-open" : "nonexistent", i));
5795 /* Do pre-close processing on the channel. */
5797 case CHAN_MAINSESSION:
5798 ssh->mainchan = NULL;
5799 update_specials_menu(ssh->frontend);
5802 if (c->u.x11.s != NULL)
5803 x11_close(c->u.x11.s);
5810 if (c->u.pfd.s != NULL)
5811 pfd_close(c->u.pfd.s);
5815 if (c->closes == 0) {
5816 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
5817 ssh2_pkt_adduint32(pktout, c->remoteid);
5818 ssh2_pkt_send(ssh, pktout);
5820 del234(ssh->channels, c);
5821 bufchain_clear(&c->v.v2.outbuffer);
5825 * See if that was the last channel left open.
5826 * (This is only our termination condition if we're
5827 * not running in -N mode.)
5829 if (!ssh->cfg.ssh_no_shell && count234(ssh->channels) == 0) {
5830 logevent("All channels closed. Disconnecting");
5833 * We used to send SSH_MSG_DISCONNECT here,
5834 * because I'd believed that _every_ conforming
5835 * SSH-2 connection had to end with a disconnect
5836 * being sent by at least one side; apparently
5837 * I was wrong and it's perfectly OK to
5838 * unceremoniously slam the connection shut
5839 * when you're done, and indeed OpenSSH feels
5840 * this is more polite than sending a
5841 * DISCONNECT. So now we don't.
5843 s->pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
5844 ssh2_pkt_adduint32(s->pktout, SSH2_DISCONNECT_BY_APPLICATION);
5845 ssh2_pkt_addstring(s->pktout, "All open channels closed");
5846 ssh2_pkt_addstring(s->pktout, "en"); /* language tag */
5847 ssh2_pkt_send_noqueue(ssh, s->pktout);
5849 ssh->close_expected = TRUE;
5850 ssh_closing((Plug)ssh, NULL, 0, 0);
5854 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
5856 unsigned i = ssh_pkt_getuint32(pktin);
5857 struct ssh_channel *c;
5858 struct Packet *pktout;
5860 c = find234(ssh->channels, &i, ssh_channelfind);
5862 return; /* nonexistent channel */
5863 if (c->type != CHAN_SOCKDATA_DORMANT)
5864 return; /* dunno why they're confirming this */
5865 c->remoteid = ssh_pkt_getuint32(pktin);
5866 c->halfopen = FALSE;
5867 c->type = CHAN_SOCKDATA;
5868 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
5869 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
5871 pfd_confirm(c->u.pfd.s);
5874 * We have a pending close on this channel,
5875 * which we decided on before the server acked
5876 * the channel open. So now we know the
5877 * remoteid, we can close it again.
5879 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
5880 ssh2_pkt_adduint32(pktout, c->remoteid);
5881 ssh2_pkt_send(ssh, pktout);
5885 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
5887 static const char *const reasons[] = {
5888 "<unknown reason code>",
5889 "Administratively prohibited",
5891 "Unknown channel type",
5892 "Resource shortage",
5894 unsigned i = ssh_pkt_getuint32(pktin);
5895 unsigned reason_code;
5896 char *reason_string;
5898 struct ssh_channel *c;
5899 c = find234(ssh->channels, &i, ssh_channelfind);
5901 return; /* nonexistent channel */
5902 if (c->type != CHAN_SOCKDATA_DORMANT)
5903 return; /* dunno why they're failing this */
5905 reason_code = ssh_pkt_getuint32(pktin);
5906 if (reason_code >= lenof(reasons))
5907 reason_code = 0; /* ensure reasons[reason_code] in range */
5908 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
5909 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
5910 reasons[reason_code], reason_length, reason_string);
5912 pfd_close(c->u.pfd.s);
5914 del234(ssh->channels, c);
5918 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
5922 int typelen, want_reply;
5923 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
5924 struct ssh_channel *c;
5925 struct Packet *pktout;
5927 localid = ssh_pkt_getuint32(pktin);
5928 ssh_pkt_getstring(pktin, &type, &typelen);
5929 want_reply = ssh2_pkt_getbool(pktin);
5932 * First, check that the channel exists. Otherwise,
5933 * we can instantly disconnect with a rude message.
5935 c = find234(ssh->channels, &localid, ssh_channelfind);
5938 sprintf(buf, "Received channel request for nonexistent"
5939 " channel %d", localid);
5941 pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
5942 ssh2_pkt_adduint32(pktout, SSH2_DISCONNECT_BY_APPLICATION);
5943 ssh2_pkt_addstring(pktout, buf);
5944 ssh2_pkt_addstring(pktout, "en"); /* language tag */
5945 ssh2_pkt_send_noqueue(ssh, pktout);
5946 connection_fatal(ssh->frontend, "%s", buf);
5947 ssh->close_expected = TRUE;
5948 ssh_closing((Plug)ssh, NULL, 0, 0);
5953 * Having got the channel number, we now look at
5954 * the request type string to see if it's something
5957 if (c == ssh->mainchan) {
5959 * We recognise "exit-status" and "exit-signal" on
5960 * the primary channel.
5962 if (typelen == 11 &&
5963 !memcmp(type, "exit-status", 11)) {
5965 ssh->exitcode = ssh_pkt_getuint32(pktin);
5966 logeventf(ssh, "Server sent command exit status %d",
5968 reply = SSH2_MSG_CHANNEL_SUCCESS;
5970 } else if (typelen == 11 &&
5971 !memcmp(type, "exit-signal", 11)) {
5973 int is_plausible = TRUE, is_int = FALSE;
5974 char *fmt_sig = "", *fmt_msg = "";
5976 int msglen = 0, core = FALSE;
5977 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
5978 * provide an `int' for the signal, despite its
5979 * having been a `string' in the drafts since at
5980 * least 2001. (Fixed in session.c 1.147.) Try to
5981 * infer which we can safely parse it as. */
5983 unsigned char *p = pktin->body +
5985 long len = pktin->length - pktin->savedpos;
5986 unsigned long num = GET_32BIT(p); /* what is it? */
5987 /* If it's 0, it hardly matters; assume string */
5991 int maybe_int = FALSE, maybe_str = FALSE;
5992 #define CHECK_HYPOTHESIS(offset, result) \
5995 if (q >= 0 && q+4 <= len) { \
5996 q = q + 4 + GET_32BIT(p+q); \
5997 if (q >= 0 && q+4 <= len && \
5998 ((q = q + 4 + GET_32BIT(p+q))!= 0) && q == len) \
6002 CHECK_HYPOTHESIS(4+1, maybe_int);
6003 CHECK_HYPOTHESIS(4+num+1, maybe_str);
6004 #undef CHECK_HYPOTHESIS
6005 if (maybe_int && !maybe_str)
6007 else if (!maybe_int && maybe_str)
6010 /* Crikey. Either or neither. Panic. */
6011 is_plausible = FALSE;
6016 /* Old non-standard OpenSSH. */
6017 int signum = ssh_pkt_getuint32(pktin);
6018 fmt_sig = dupprintf(" %d", signum);
6020 /* As per the drafts. */
6023 ssh_pkt_getstring(pktin, &sig, &siglen);
6024 /* Signal name isn't supposed to be blank, but
6025 * let's cope gracefully if it is. */
6027 fmt_sig = dupprintf(" \"%.*s\"",
6031 core = ssh2_pkt_getbool(pktin);
6032 ssh_pkt_getstring(pktin, &msg, &msglen);
6034 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
6036 /* ignore lang tag */
6037 } /* else don't attempt to parse */
6038 logeventf(ssh, "Server exited on signal%s%s%s",
6039 fmt_sig, core ? " (core dumped)" : "",
6041 if (*fmt_sig) sfree(fmt_sig);
6042 if (*fmt_msg) sfree(fmt_msg);
6043 reply = SSH2_MSG_CHANNEL_SUCCESS;
6048 * This is a channel request we don't know
6049 * about, so we now either ignore the request
6050 * or respond with CHANNEL_FAILURE, depending
6053 reply = SSH2_MSG_CHANNEL_FAILURE;
6056 pktout = ssh2_pkt_init(reply);
6057 ssh2_pkt_adduint32(pktout, c->remoteid);
6058 ssh2_pkt_send(ssh, pktout);
6062 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
6065 int typelen, want_reply;
6066 struct Packet *pktout;
6068 ssh_pkt_getstring(pktin, &type, &typelen);
6069 want_reply = ssh2_pkt_getbool(pktin);
6072 * We currently don't support any global requests
6073 * at all, so we either ignore the request or
6074 * respond with REQUEST_FAILURE, depending on
6078 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
6079 ssh2_pkt_send(ssh, pktout);
6083 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
6091 struct ssh_channel *c;
6092 unsigned remid, winsize, pktsize;
6093 struct Packet *pktout;
6095 ssh_pkt_getstring(pktin, &type, &typelen);
6096 c = snew(struct ssh_channel);
6099 remid = ssh_pkt_getuint32(pktin);
6100 winsize = ssh_pkt_getuint32(pktin);
6101 pktsize = ssh_pkt_getuint32(pktin);
6103 if (typelen == 3 && !memcmp(type, "x11", 3)) {
6106 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
6107 addrstr = snewn(peeraddrlen+1, char);
6108 memcpy(addrstr, peeraddr, peeraddrlen);
6109 addrstr[peeraddrlen] = '\0';
6110 peerport = ssh_pkt_getuint32(pktin);
6112 logeventf(ssh, "Received X11 connect request from %s:%d",
6115 if (!ssh->X11_fwd_enabled)
6116 error = "X11 forwarding is not enabled";
6117 else if (x11_init(&c->u.x11.s, ssh->cfg.x11_display, c,
6118 ssh->x11auth, addrstr, peerport,
6119 &ssh->cfg) != NULL) {
6120 error = "Unable to open an X11 connection";
6122 logevent("Opening X11 forward connection succeeded");
6127 } else if (typelen == 15 &&
6128 !memcmp(type, "forwarded-tcpip", 15)) {
6129 struct ssh_rportfwd pf, *realpf;
6132 ssh_pkt_getstring(pktin, &dummy, &dummylen);/* skip address */
6133 pf.sport = ssh_pkt_getuint32(pktin);
6134 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
6135 peerport = ssh_pkt_getuint32(pktin);
6136 realpf = find234(ssh->rportfwds, &pf, NULL);
6137 logeventf(ssh, "Received remote port %d open request "
6138 "from %s:%d", pf.sport, peeraddr, peerport);
6139 if (realpf == NULL) {
6140 error = "Remote port is not recognised";
6142 const char *e = pfd_newconnect(&c->u.pfd.s,
6146 realpf->pfrec->addressfamily);
6147 logeventf(ssh, "Attempting to forward remote port to "
6148 "%s:%d", realpf->dhost, realpf->dport);
6150 logeventf(ssh, "Port open failed: %s", e);
6151 error = "Port open failed";
6153 logevent("Forwarded port opened successfully");
6154 c->type = CHAN_SOCKDATA;
6157 } else if (typelen == 22 &&
6158 !memcmp(type, "auth-agent@openssh.com", 3)) {
6159 if (!ssh->agentfwd_enabled)
6160 error = "Agent forwarding is not enabled";
6162 c->type = CHAN_AGENT; /* identify channel type */
6163 c->u.a.lensofar = 0;
6166 error = "Unsupported channel type requested";
6169 c->remoteid = remid;
6170 c->halfopen = FALSE;
6172 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
6173 ssh2_pkt_adduint32(pktout, c->remoteid);
6174 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
6175 ssh2_pkt_addstring(pktout, error);
6176 ssh2_pkt_addstring(pktout, "en"); /* language tag */
6177 ssh2_pkt_send(ssh, pktout);
6178 logeventf(ssh, "Rejected channel open: %s", error);
6181 c->localid = alloc_channel_id(ssh);
6183 c->v.v2.locwindow = OUR_V2_WINSIZE;
6184 c->v.v2.remwindow = winsize;
6185 c->v.v2.remmaxpkt = pktsize;
6186 bufchain_init(&c->v.v2.outbuffer);
6187 add234(ssh->channels, c);
6188 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
6189 ssh2_pkt_adduint32(pktout, c->remoteid);
6190 ssh2_pkt_adduint32(pktout, c->localid);
6191 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
6192 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
6193 ssh2_pkt_send(ssh, pktout);
6198 * Handle the SSH-2 userauth and connection layers.
6200 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
6201 struct Packet *pktin)
6203 struct do_ssh2_authconn_state {
6205 AUTH_INVALID, AUTH_PUBLICKEY_AGENT, AUTH_PUBLICKEY_FILE,
6207 AUTH_KEYBOARD_INTERACTIVE
6211 AUTH_TYPE_PUBLICKEY,
6212 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
6213 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
6215 AUTH_TYPE_KEYBOARD_INTERACTIVE,
6216 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
6218 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
6219 int tried_pubkey_config, tried_agent;
6220 int kbd_inter_running, kbd_inter_refused;
6222 int num_prompts, curr_prompt, echo;
6227 void *publickey_blob;
6228 int publickey_bloblen;
6229 unsigned char request[5], *response, *p;
6233 char *pkblob, *alg, *commentp;
6234 int pklen, alglen, commentlen;
6235 int siglen, retlen, len;
6236 char *q, *agentreq, *ret;
6238 int num_env, env_left, env_ok;
6239 struct Packet *pktout;
6241 crState(do_ssh2_authconn_state);
6243 crBegin(ssh->do_ssh2_authconn_crstate);
6246 * Request userauth protocol, and await a response to it.
6248 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
6249 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
6250 ssh2_pkt_send(ssh, s->pktout);
6251 crWaitUntilV(pktin);
6252 if (pktin->type != SSH2_MSG_SERVICE_ACCEPT) {
6253 bombout(("Server refused user authentication protocol"));
6258 * We repeat this whole loop, including the username prompt,
6259 * until we manage a successful authentication. If the user
6260 * types the wrong _password_, they can be sent back to the
6261 * beginning to try another username, if this is configured on.
6262 * (If they specify a username in the config, they are never
6263 * asked, even if they do give a wrong password.)
6265 * I think this best serves the needs of
6267 * - the people who have no configuration, no keys, and just
6268 * want to try repeated (username,password) pairs until they
6269 * type both correctly
6271 * - people who have keys and configuration but occasionally
6272 * need to fall back to passwords
6274 * - people with a key held in Pageant, who might not have
6275 * logged in to a particular machine before; so they want to
6276 * type a username, and then _either_ their key will be
6277 * accepted, _or_ they will type a password. If they mistype
6278 * the username they will want to be able to get back and
6281 s->username[0] = '\0';
6282 s->got_username = FALSE;
6287 if (s->got_username && !ssh->cfg.change_username) {
6289 * We got a username last time round this loop, and
6290 * with change_username turned off we don't try to get
6293 } else if (!*ssh->cfg.username) {
6294 if (ssh_get_line && !ssh_getline_pw_only) {
6295 if (!ssh_get_line("login as: ",
6296 s->username, sizeof(s->username), FALSE)) {
6298 * get_line failed to get a username.
6301 logevent("No username provided. Abandoning session.");
6302 ssh->close_expected = TRUE;
6303 ssh_closing((Plug)ssh, NULL, 0, 0);
6307 int ret; /* need not be saved across crReturn */
6308 c_write_str(ssh, "login as: ");
6310 setup_userpass_input(ssh, s->username, sizeof(s->username), 1);
6312 crWaitUntilV(!pktin);
6313 ret = process_userpass_input(ssh, in, inlen);
6317 c_write_str(ssh, "\r\n");
6319 s->username[strcspn(s->username, "\n\r")] = '\0';
6322 strncpy(s->username, ssh->cfg.username, sizeof(s->username));
6323 s->username[sizeof(s->username)-1] = '\0';
6324 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
6325 stuff = dupprintf("Using username \"%s\".\r\n", s->username);
6326 c_write_str(ssh, stuff);
6330 s->got_username = TRUE;
6333 * Send an authentication request using method "none": (a)
6334 * just in case it succeeds, and (b) so that we know what
6335 * authentication methods we can usefully try next.
6337 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6339 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6340 ssh2_pkt_addstring(s->pktout, s->username);
6341 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
6342 ssh2_pkt_addstring(s->pktout, "none"); /* method */
6343 ssh2_pkt_send(ssh, s->pktout);
6344 s->type = AUTH_TYPE_NONE;
6346 s->we_are_in = FALSE;
6348 s->tried_pubkey_config = FALSE;
6349 s->tried_agent = FALSE;
6350 s->kbd_inter_running = FALSE;
6351 s->kbd_inter_refused = FALSE;
6352 /* Load the pub half of ssh->cfg.keyfile so we notice if it's in Pageant */
6353 if (!filename_is_null(ssh->cfg.keyfile)) {
6355 logeventf(ssh, "Reading private key file \"%.150s\"",
6356 filename_to_str(&ssh->cfg.keyfile));
6357 keytype = key_type(&ssh->cfg.keyfile);
6358 if (keytype == SSH_KEYTYPE_SSH2) {
6360 ssh2_userkey_loadpub(&ssh->cfg.keyfile, NULL,
6361 &s->publickey_bloblen, NULL);
6364 logeventf(ssh, "Unable to use this key file (%s)",
6365 key_type_to_str(keytype));
6366 msgbuf = dupprintf("Unable to use key file \"%.150s\""
6368 filename_to_str(&ssh->cfg.keyfile),
6369 key_type_to_str(keytype));
6370 c_write_str(ssh, msgbuf);
6372 s->publickey_blob = NULL;
6375 s->publickey_blob = NULL;
6379 * Wait for the result of the last authentication request.
6382 crWaitUntilV(pktin);
6383 while (pktin->type == SSH2_MSG_USERAUTH_BANNER) {
6387 * Don't show the banner if we're operating in
6388 * non-verbose non-interactive mode. (It's probably
6389 * a script, which means nobody will read the
6390 * banner _anyway_, and moreover the printing of
6391 * the banner will screw up processing on the
6392 * output of (say) plink.)
6394 if (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE)) {
6395 ssh_pkt_getstring(pktin, &banner, &size);
6397 c_write_untrusted(ssh, banner, size);
6399 crWaitUntilV(pktin);
6401 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
6402 logevent("Access granted");
6403 s->we_are_in = TRUE;
6407 if (s->kbd_inter_running &&
6408 pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
6410 * This is either a further set-of-prompts packet
6411 * in keyboard-interactive authentication, or it's
6412 * the same one and we came back here with `gotit'
6413 * set. In the former case, we must reset the
6414 * curr_prompt variable.
6418 } else if (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
6419 /* FIXME: perhaps we should support this? */
6420 bombout(("PASSWD_CHANGEREQ not yet supported"));
6422 } else if (pktin->type != SSH2_MSG_USERAUTH_FAILURE) {
6423 bombout(("Strange packet received during authentication: type %d",
6431 * OK, we're now sitting on a USERAUTH_FAILURE message, so
6432 * we can look at the string in it and know what we can
6433 * helpfully try next.
6435 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
6438 ssh_pkt_getstring(pktin, &methods, &methlen);
6439 s->kbd_inter_running = FALSE;
6440 if (!ssh2_pkt_getbool(pktin)) {
6442 * We have received an unequivocal Access
6443 * Denied. This can translate to a variety of
6446 * - if we'd just tried "none" authentication,
6447 * it's not worth printing anything at all
6449 * - if we'd just tried a public key _offer_,
6450 * the message should be "Server refused our
6451 * key" (or no message at all if the key
6452 * came from Pageant)
6454 * - if we'd just tried anything else, the
6455 * message really should be "Access denied".
6457 * Additionally, if we'd just tried password
6458 * authentication, we should break out of this
6459 * whole loop so as to go back to the username
6460 * prompt (iff we're configured to allow
6461 * username change attempts).
6463 if (s->type == AUTH_TYPE_NONE) {
6465 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
6466 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
6467 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
6468 c_write_str(ssh, "Server refused our key\r\n");
6469 logevent("Server refused public key");
6470 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
6471 /* server declined keyboard-interactive; ignore */
6473 c_write_str(ssh, "Access denied\r\n");
6474 logevent("Access denied");
6475 if (s->type == AUTH_TYPE_PASSWORD &&
6476 ssh->cfg.change_username) {
6477 /* XXX perhaps we should allow
6478 * keyboard-interactive to do this too? */
6479 s->we_are_in = FALSE;
6484 c_write_str(ssh, "Further authentication required\r\n");
6485 logevent("Further authentication required");
6489 in_commasep_string("publickey", methods, methlen);
6491 in_commasep_string("password", methods, methlen);
6492 s->can_keyb_inter = ssh->cfg.try_ki_auth &&
6493 in_commasep_string("keyboard-interactive", methods, methlen);
6497 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6501 * Most password/passphrase prompts will be
6502 * non-echoing, so we set this to 0 by default.
6503 * Exception is that some keyboard-interactive prompts
6504 * can be echoing, in which case we'll set this to 1.
6508 if (!s->method && s->can_pubkey &&
6509 agent_exists() && !s->tried_agent) {
6511 * Attempt public-key authentication using Pageant.
6516 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6517 ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
6519 s->tried_agent = TRUE;
6521 logevent("Pageant is running. Requesting keys.");
6523 /* Request the keys held by the agent. */
6524 PUT_32BIT(s->request, 1);
6525 s->request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
6526 if (!agent_query(s->request, 5, &r, &s->responselen,
6527 ssh_agent_callback, ssh)) {
6531 bombout(("Unexpected data from server while"
6532 " waiting for agent response"));
6535 } while (pktin || inlen > 0);
6536 r = ssh->agent_response;
6537 s->responselen = ssh->agent_response_len;
6539 s->response = (unsigned char *) r;
6540 if (s->response && s->responselen >= 5 &&
6541 s->response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
6542 s->p = s->response + 5;
6543 s->nkeys = GET_32BIT(s->p);
6545 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
6546 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
6549 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
6550 s->pklen = GET_32BIT(s->p);
6552 if (s->publickey_blob &&
6553 s->pklen == s->publickey_bloblen &&
6554 !memcmp(s->p, s->publickey_blob,
6555 s->publickey_bloblen)) {
6556 logevent("This key matches configured key file");
6557 s->tried_pubkey_config = 1;
6559 s->pkblob = (char *)s->p;
6561 s->alglen = GET_32BIT(s->pkblob);
6562 s->alg = s->pkblob + 4;
6563 s->commentlen = GET_32BIT(s->p);
6565 s->commentp = (char *)s->p;
6566 s->p += s->commentlen;
6567 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6568 ssh2_pkt_addstring(s->pktout, s->username);
6569 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
6570 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
6571 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
6572 ssh2_pkt_addstring_start(s->pktout);
6573 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
6574 ssh2_pkt_addstring_start(s->pktout);
6575 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
6576 ssh2_pkt_send(ssh, s->pktout);
6578 crWaitUntilV(pktin);
6579 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
6580 logevent("Key refused");
6584 if (flags & FLAG_VERBOSE) {
6585 c_write_str(ssh, "Authenticating with "
6587 c_write(ssh, s->commentp, s->commentlen);
6588 c_write_str(ssh, "\" from agent\r\n");
6592 * Server is willing to accept the key.
6593 * Construct a SIGN_REQUEST.
6595 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6596 ssh2_pkt_addstring(s->pktout, s->username);
6597 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
6598 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
6599 ssh2_pkt_addbool(s->pktout, TRUE);
6600 ssh2_pkt_addstring_start(s->pktout);
6601 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
6602 ssh2_pkt_addstring_start(s->pktout);
6603 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
6605 s->siglen = s->pktout->length - 5 + 4 + 20;
6606 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
6608 s->len = 1; /* message type */
6609 s->len += 4 + s->pklen; /* key blob */
6610 s->len += 4 + s->siglen; /* data to sign */
6611 s->len += 4; /* flags */
6612 s->agentreq = snewn(4 + s->len, char);
6613 PUT_32BIT(s->agentreq, s->len);
6614 s->q = s->agentreq + 4;
6615 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
6616 PUT_32BIT(s->q, s->pklen);
6618 memcpy(s->q, s->pkblob, s->pklen);
6620 PUT_32BIT(s->q, s->siglen);
6622 /* Now the data to be signed... */
6623 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
6624 PUT_32BIT(s->q, 20);
6627 memcpy(s->q, ssh->v2_session_id, 20);
6629 memcpy(s->q, s->pktout->data + 5,
6630 s->pktout->length - 5);
6631 s->q += s->pktout->length - 5;
6632 /* And finally the (zero) flags word. */
6634 if (!agent_query(s->agentreq, s->len + 4,
6636 ssh_agent_callback, ssh)) {
6640 bombout(("Unexpected data from server"
6641 " while waiting for agent"
6645 } while (pktin || inlen > 0);
6646 vret = ssh->agent_response;
6647 s->retlen = ssh->agent_response_len;
6652 if (s->ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
6653 logevent("Sending Pageant's response");
6654 ssh2_add_sigblob(ssh, s->pktout,
6655 s->pkblob, s->pklen,
6657 GET_32BIT(s->ret + 5));
6658 ssh2_pkt_send(ssh, s->pktout);
6663 ("Pageant failed to answer challenge");
6674 if (!s->method && s->can_pubkey && s->publickey_blob
6675 && !s->tried_pubkey_config) {
6676 unsigned char *pub_blob;
6677 char *algorithm, *comment;
6680 s->tried_pubkey_config = TRUE;
6682 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6683 ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
6686 * Try the public key supplied in the configuration.
6688 * First, offer the public blob to see if the server is
6689 * willing to accept it.
6692 (unsigned char *)ssh2_userkey_loadpub(&ssh->cfg.keyfile,
6697 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6698 ssh2_pkt_addstring(s->pktout, s->username);
6699 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
6700 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
6701 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
6702 ssh2_pkt_addstring(s->pktout, algorithm);
6703 ssh2_pkt_addstring_start(s->pktout);
6704 ssh2_pkt_addstring_data(s->pktout, (char *)pub_blob,
6706 ssh2_pkt_send(ssh, s->pktout);
6707 logevent("Offered public key");
6709 crWaitUntilV(pktin);
6710 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
6712 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
6713 continue; /* key refused; give up on it */
6716 logevent("Offer of public key accepted");
6718 * Actually attempt a serious authentication using
6721 if (ssh2_userkey_encrypted(&ssh->cfg.keyfile, &comment)) {
6722 sprintf(s->pwprompt,
6723 "Passphrase for key \"%.100s\": ",
6729 if (flags & FLAG_VERBOSE) {
6730 c_write_str(ssh, "Authenticating with public key \"");
6731 c_write_str(ssh, comment);
6732 c_write_str(ssh, "\"\r\n");
6734 s->method = AUTH_PUBLICKEY_FILE;
6738 if (!s->method && s->can_keyb_inter && !s->kbd_inter_refused &&
6739 !s->kbd_inter_running) {
6740 s->method = AUTH_KEYBOARD_INTERACTIVE;
6741 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
6743 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6744 ssh->pkt_ctx |= SSH2_PKTCTX_KBDINTER;
6746 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6747 ssh2_pkt_addstring(s->pktout, s->username);
6748 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
6749 ssh2_pkt_addstring(s->pktout, "keyboard-interactive"); /* method */
6750 ssh2_pkt_addstring(s->pktout, ""); /* lang */
6751 ssh2_pkt_addstring(s->pktout, "");
6752 ssh2_pkt_send(ssh, s->pktout);
6754 crWaitUntilV(pktin);
6755 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
6756 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE)
6758 logevent("Keyboard-interactive authentication refused");
6759 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
6760 s->kbd_inter_refused = TRUE; /* don't try it again */
6764 c_write_str(ssh, "Using keyboard-interactive authentication.\r\n");
6765 s->kbd_inter_running = TRUE;
6769 if (s->kbd_inter_running) {
6770 s->method = AUTH_KEYBOARD_INTERACTIVE;
6771 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
6773 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6774 ssh->pkt_ctx |= SSH2_PKTCTX_KBDINTER;
6776 if (s->curr_prompt == 0) {
6778 * We've got a fresh USERAUTH_INFO_REQUEST.
6779 * Display header data, and start going through
6782 char *name, *inst, *lang;
6783 int name_len, inst_len, lang_len;
6785 ssh_pkt_getstring(pktin, &name, &name_len);
6786 ssh_pkt_getstring(pktin, &inst, &inst_len);
6787 ssh_pkt_getstring(pktin, &lang, &lang_len);
6789 c_write_untrusted(ssh, name, name_len);
6790 c_write_str(ssh, "\r\n");
6793 c_write_untrusted(ssh, inst, inst_len);
6794 c_write_str(ssh, "\r\n");
6796 s->num_prompts = ssh_pkt_getuint32(pktin);
6800 * If there are prompts remaining in the packet,
6801 * display one and get a response.
6803 if (s->curr_prompt < s->num_prompts) {
6807 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
6808 if (prompt_len > 0) {
6809 static const char trunc[] = "<prompt truncated>: ";
6810 static const int prlen = sizeof(s->pwprompt) -
6812 if (prompt_len > prlen) {
6813 memcpy(s->pwprompt, prompt, prlen);
6814 strcpy(s->pwprompt + prlen, trunc);
6816 memcpy(s->pwprompt, prompt, prompt_len);
6817 s->pwprompt[prompt_len] = '\0';
6821 "<server failed to send prompt>: ");
6823 s->echo = ssh2_pkt_getbool(pktin);
6829 if (!s->method && s->can_passwd) {
6830 s->method = AUTH_PASSWORD;
6831 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6832 ssh->pkt_ctx |= SSH2_PKTCTX_PASSWORD;
6833 sprintf(s->pwprompt, "%.90s@%.90s's password: ", s->username,
6840 if (!ssh_get_line(s->pwprompt, s->password,
6841 sizeof(s->password), TRUE)) {
6843 * get_line failed to get a password (for
6844 * example because one was supplied on the
6845 * command line which has already failed to
6848 s->pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
6849 ssh2_pkt_adduint32(s->pktout,SSH2_DISCONNECT_BY_APPLICATION);
6850 ssh2_pkt_addstring(s->pktout, "No more passwords available"
6852 ssh2_pkt_addstring(s->pktout, "en"); /* language tag */
6853 ssh2_pkt_send_noqueue(ssh, s->pktout);
6854 logevent("Unable to authenticate");
6855 connection_fatal(ssh->frontend,
6856 "Unable to authenticate");
6857 ssh->close_expected = TRUE;
6858 ssh_closing((Plug)ssh, NULL, 0, 0);
6862 int ret; /* need not be saved across crReturn */
6863 c_write_untrusted(ssh, s->pwprompt, strlen(s->pwprompt));
6866 setup_userpass_input(ssh, s->password,
6867 sizeof(s->password), s->echo);
6869 crWaitUntilV(!pktin);
6870 ret = process_userpass_input(ssh, in, inlen);
6874 c_write_str(ssh, "\r\n");
6878 if (s->method == AUTH_PUBLICKEY_FILE) {
6880 * We have our passphrase. Now try the actual authentication.
6882 struct ssh2_userkey *key;
6883 const char *error = NULL;
6885 key = ssh2_load_userkey(&ssh->cfg.keyfile, s->password,
6887 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
6888 if (key == SSH2_WRONG_PASSPHRASE) {
6889 c_write_str(ssh, "Wrong passphrase\r\n");
6890 s->tried_pubkey_config = FALSE;
6892 c_write_str(ssh, "Unable to load private key (");
6893 c_write_str(ssh, error);
6894 c_write_str(ssh, ")\r\n");
6895 s->tried_pubkey_config = TRUE;
6897 /* Send a spurious AUTH_NONE to return to the top. */
6898 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6899 ssh2_pkt_addstring(s->pktout, s->username);
6900 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
6901 ssh2_pkt_addstring(s->pktout, "none"); /* method */
6902 ssh2_pkt_send(ssh, s->pktout);
6903 s->type = AUTH_TYPE_NONE;
6905 unsigned char *pkblob, *sigblob, *sigdata;
6906 int pkblob_len, sigblob_len, sigdata_len;
6910 * We have loaded the private key and the server
6911 * has announced that it's willing to accept it.
6912 * Hallelujah. Generate a signature and send it.
6914 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6915 ssh2_pkt_addstring(s->pktout, s->username);
6916 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
6917 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
6918 ssh2_pkt_addbool(s->pktout, TRUE);
6919 ssh2_pkt_addstring(s->pktout, key->alg->name);
6920 pkblob = key->alg->public_blob(key->data, &pkblob_len);
6921 ssh2_pkt_addstring_start(s->pktout);
6922 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob, pkblob_len);
6925 * The data to be signed is:
6929 * followed by everything so far placed in the
6932 sigdata_len = s->pktout->length - 5 + 4 + 20;
6933 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
6935 sigdata = snewn(sigdata_len, unsigned char);
6937 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
6938 PUT_32BIT(sigdata+p, 20);
6941 memcpy(sigdata+p, ssh->v2_session_id, 20); p += 20;
6942 memcpy(sigdata+p, s->pktout->data + 5,
6943 s->pktout->length - 5);
6944 p += s->pktout->length - 5;
6945 assert(p == sigdata_len);
6946 sigblob = key->alg->sign(key->data, (char *)sigdata,
6947 sigdata_len, &sigblob_len);
6948 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
6949 sigblob, sigblob_len);
6954 ssh2_pkt_send(ssh, s->pktout);
6955 s->type = AUTH_TYPE_PUBLICKEY;
6956 key->alg->freekey(key->data);
6958 } else if (s->method == AUTH_PASSWORD) {
6960 * We pad out the password packet to 256 bytes to make
6961 * it harder for an attacker to find the length of the
6964 * Anyone using a password longer than 256 bytes
6965 * probably doesn't have much to worry about from
6966 * people who find out how long their password is!
6968 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6969 s->pktout->forcepad = 256;
6970 ssh2_pkt_addstring(s->pktout, s->username);
6971 ssh2_pkt_addstring(s->pktout, "ssh-connection"); /* service requested */
6972 ssh2_pkt_addstring(s->pktout, "password");
6973 ssh2_pkt_addbool(s->pktout, FALSE);
6974 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
6975 ssh2_pkt_addstring(s->pktout, s->password);
6976 memset(s->password, 0, sizeof(s->password));
6977 end_log_omission(ssh, s->pktout);
6978 ssh2_pkt_send(ssh, s->pktout);
6979 logevent("Sent password");
6980 s->type = AUTH_TYPE_PASSWORD;
6981 } else if (s->method == AUTH_KEYBOARD_INTERACTIVE) {
6982 if (s->curr_prompt == 0) {
6983 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
6984 s->pktout->forcepad = 256;
6985 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
6987 if (s->need_pw) { /* only add pw if we just got one! */
6988 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
6989 ssh2_pkt_addstring(s->pktout, s->password);
6990 memset(s->password, 0, sizeof(s->password));
6991 end_log_omission(ssh, s->pktout);
6994 if (s->curr_prompt >= s->num_prompts) {
6995 ssh2_pkt_send(ssh, s->pktout);
6998 * If there are prompts remaining, we set
6999 * `gotit' so that we won't attempt to get
7000 * another packet. Then we go back round the
7001 * loop and will end up retrieving another
7002 * prompt out of the existing packet. Funky or
7007 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
7009 c_write_str(ssh, "No supported authentication methods"
7010 " left to try!\r\n");
7011 logevent("No supported authentications offered."
7013 s->pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
7014 ssh2_pkt_adduint32(s->pktout, SSH2_DISCONNECT_BY_APPLICATION);
7015 ssh2_pkt_addstring(s->pktout, "No supported authentication"
7016 " methods available");
7017 ssh2_pkt_addstring(s->pktout, "en"); /* language tag */
7018 ssh2_pkt_send_noqueue(ssh, s->pktout);
7019 ssh->close_expected = TRUE;
7020 ssh_closing((Plug)ssh, NULL, 0, 0);
7024 } while (!s->we_are_in);
7027 * Now we're authenticated for the connection protocol. The
7028 * connection protocol will automatically have started at this
7029 * point; there's no need to send SERVICE_REQUEST.
7032 ssh->channels = newtree234(ssh_channelcmp);
7035 * Set up handlers for some connection protocol messages, so we
7036 * don't have to handle them repeatedly in this coroutine.
7038 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
7039 ssh2_msg_channel_window_adjust;
7040 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
7041 ssh2_msg_global_request;
7044 * Create the main session channel.
7046 if (!ssh->cfg.ssh_no_shell) {
7047 ssh->mainchan = snew(struct ssh_channel);
7048 ssh->mainchan->ssh = ssh;
7049 ssh->mainchan->localid = alloc_channel_id(ssh);
7050 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7051 ssh2_pkt_addstring(s->pktout, "session");
7052 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
7053 ssh->mainchan->v.v2.locwindow = OUR_V2_WINSIZE;
7054 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
7055 ssh2_pkt_adduint32(s->pktout, OUR_V2_MAXPKT); /* our max pkt size */
7056 ssh2_pkt_send(ssh, s->pktout);
7057 crWaitUntilV(pktin);
7058 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
7059 bombout(("Server refused to open a session"));
7061 /* FIXME: error data comes back in FAILURE packet */
7063 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
7064 bombout(("Server's channel confirmation cited wrong channel"));
7067 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
7068 ssh->mainchan->halfopen = FALSE;
7069 ssh->mainchan->type = CHAN_MAINSESSION;
7070 ssh->mainchan->closes = 0;
7071 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
7072 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
7073 bufchain_init(&ssh->mainchan->v.v2.outbuffer);
7074 add234(ssh->channels, ssh->mainchan);
7075 update_specials_menu(ssh->frontend);
7076 logevent("Opened channel for session");
7078 ssh->mainchan = NULL;
7081 * Now we have a channel, make dispatch table entries for
7082 * general channel-based messages.
7084 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
7085 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
7086 ssh2_msg_channel_data;
7087 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
7088 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
7089 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
7090 ssh2_msg_channel_open_confirmation;
7091 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
7092 ssh2_msg_channel_open_failure;
7093 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
7094 ssh2_msg_channel_request;
7095 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
7096 ssh2_msg_channel_open;
7099 * Potentially enable X11 forwarding.
7101 if (ssh->mainchan && ssh->cfg.x11_forward) {
7102 char proto[20], data[64];
7103 logevent("Requesting X11 forwarding");
7104 ssh->x11auth = x11_invent_auth(proto, sizeof(proto),
7105 data, sizeof(data), ssh->cfg.x11_auth);
7106 x11_get_real_auth(ssh->x11auth, ssh->cfg.x11_display);
7107 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7108 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
7109 ssh2_pkt_addstring(s->pktout, "x11-req");
7110 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
7111 ssh2_pkt_addbool(s->pktout, 0); /* many connections */
7112 ssh2_pkt_addstring(s->pktout, proto);
7113 ssh2_pkt_addstring(s->pktout, data);
7114 ssh2_pkt_adduint32(s->pktout, x11_get_screen_number(ssh->cfg.x11_display));
7115 ssh2_pkt_send(ssh, s->pktout);
7117 crWaitUntilV(pktin);
7119 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
7120 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
7121 bombout(("Unexpected response to X11 forwarding request:"
7122 " packet type %d", pktin->type));
7125 logevent("X11 forwarding refused");
7127 logevent("X11 forwarding enabled");
7128 ssh->X11_fwd_enabled = TRUE;
7133 * Enable port forwardings.
7135 ssh_setup_portfwd(ssh, &ssh->cfg);
7138 * Potentially enable agent forwarding.
7140 if (ssh->mainchan && ssh->cfg.agentfwd && agent_exists()) {
7141 logevent("Requesting OpenSSH-style agent forwarding");
7142 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7143 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
7144 ssh2_pkt_addstring(s->pktout, "auth-agent-req@openssh.com");
7145 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
7146 ssh2_pkt_send(ssh, s->pktout);
7148 crWaitUntilV(pktin);
7150 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
7151 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
7152 bombout(("Unexpected response to agent forwarding request:"
7153 " packet type %d", pktin->type));
7156 logevent("Agent forwarding refused");
7158 logevent("Agent forwarding enabled");
7159 ssh->agentfwd_enabled = TRUE;
7164 * Now allocate a pty for the session.
7166 if (ssh->mainchan && !ssh->cfg.nopty) {
7167 /* Unpick the terminal-speed string. */
7168 /* XXX perhaps we should allow no speeds to be sent. */
7169 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
7170 sscanf(ssh->cfg.termspeed, "%d,%d", &ssh->ospeed, &ssh->ispeed);
7171 /* Build the pty request. */
7172 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7173 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
7174 ssh2_pkt_addstring(s->pktout, "pty-req");
7175 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
7176 ssh2_pkt_addstring(s->pktout, ssh->cfg.termtype);
7177 ssh2_pkt_adduint32(s->pktout, ssh->term_width);
7178 ssh2_pkt_adduint32(s->pktout, ssh->term_height);
7179 ssh2_pkt_adduint32(s->pktout, 0); /* pixel width */
7180 ssh2_pkt_adduint32(s->pktout, 0); /* pixel height */
7181 ssh2_pkt_addstring_start(s->pktout);
7182 ssh2_pkt_addbyte(s->pktout, 128); /* TTY_OP_ISPEED */
7183 ssh2_pkt_adduint32(s->pktout, ssh->ispeed);
7184 ssh2_pkt_addbyte(s->pktout, 129); /* TTY_OP_OSPEED */
7185 ssh2_pkt_adduint32(s->pktout, ssh->ospeed);
7186 ssh2_pkt_addstring_data(s->pktout, "\0", 1); /* TTY_OP_END */
7187 ssh2_pkt_send(ssh, s->pktout);
7188 ssh->state = SSH_STATE_INTERMED;
7190 crWaitUntilV(pktin);
7192 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
7193 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
7194 bombout(("Unexpected response to pty request:"
7195 " packet type %d", pktin->type));
7198 c_write_str(ssh, "Server refused to allocate pty\r\n");
7199 ssh->editing = ssh->echoing = 1;
7201 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
7202 ssh->ospeed, ssh->ispeed);
7205 ssh->editing = ssh->echoing = 1;
7209 * Send environment variables.
7211 * Simplest thing here is to send all the requests at once, and
7212 * then wait for a whole bunch of successes or failures.
7214 if (ssh->mainchan && *ssh->cfg.environmt) {
7215 char *e = ssh->cfg.environmt;
7216 char *var, *varend, *val;
7222 while (*e && *e != '\t') e++;
7224 if (*e == '\t') e++;
7229 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7230 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
7231 ssh2_pkt_addstring(s->pktout, "env");
7232 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
7233 ssh2_pkt_addstring_start(s->pktout);
7234 ssh2_pkt_addstring_data(s->pktout, var, varend-var);
7235 ssh2_pkt_addstring(s->pktout, val);
7236 ssh2_pkt_send(ssh, s->pktout);
7241 logeventf(ssh, "Sent %d environment variables", s->num_env);
7244 s->env_left = s->num_env;
7246 while (s->env_left > 0) {
7247 crWaitUntilV(pktin);
7249 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
7250 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
7251 bombout(("Unexpected response to environment request:"
7252 " packet type %d", pktin->type));
7262 if (s->env_ok == s->num_env) {
7263 logevent("All environment variables successfully set");
7264 } else if (s->env_ok == 0) {
7265 logevent("All environment variables refused");
7266 c_write_str(ssh, "Server refused to set environment variables\r\n");
7268 logeventf(ssh, "%d environment variables refused",
7269 s->num_env - s->env_ok);
7270 c_write_str(ssh, "Server refused to set all environment variables\r\n");
7275 * Start a shell or a remote command. We may have to attempt
7276 * this twice if the config data has provided a second choice
7279 if (ssh->mainchan) while (1) {
7283 if (ssh->fallback_cmd) {
7284 subsys = ssh->cfg.ssh_subsys2;
7285 cmd = ssh->cfg.remote_cmd_ptr2;
7287 subsys = ssh->cfg.ssh_subsys;
7288 cmd = ssh->cfg.remote_cmd_ptr;
7289 if (!cmd) cmd = ssh->cfg.remote_cmd;
7292 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7293 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
7295 ssh2_pkt_addstring(s->pktout, "subsystem");
7296 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
7297 ssh2_pkt_addstring(s->pktout, cmd);
7299 ssh2_pkt_addstring(s->pktout, "exec");
7300 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
7301 ssh2_pkt_addstring(s->pktout, cmd);
7303 ssh2_pkt_addstring(s->pktout, "shell");
7304 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
7306 ssh2_pkt_send(ssh, s->pktout);
7308 crWaitUntilV(pktin);
7310 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
7311 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
7312 bombout(("Unexpected response to shell/command request:"
7313 " packet type %d", pktin->type));
7317 * We failed to start the command. If this is the
7318 * fallback command, we really are finished; if it's
7319 * not, and if the fallback command exists, try falling
7320 * back to it before complaining.
7322 if (!ssh->fallback_cmd && ssh->cfg.remote_cmd_ptr2 != NULL) {
7323 logevent("Primary command failed; attempting fallback");
7324 ssh->fallback_cmd = TRUE;
7327 bombout(("Server refused to start a shell/command"));
7330 logevent("Started a shell/command");
7335 ssh->state = SSH_STATE_SESSION;
7336 if (ssh->size_needed)
7337 ssh_size(ssh, ssh->term_width, ssh->term_height);
7338 if (ssh->eof_needed)
7339 ssh_special(ssh, TS_EOF);
7345 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
7350 s->try_send = FALSE;
7354 * _All_ the connection-layer packets we expect to
7355 * receive are now handled by the dispatch table.
7356 * Anything that reaches here must be bogus.
7359 bombout(("Strange packet received: type %d", pktin->type));
7361 } else if (ssh->mainchan) {
7363 * We have spare data. Add it to the channel buffer.
7365 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
7370 struct ssh_channel *c;
7372 * Try to send data on all channels if we can.
7374 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
7375 ssh2_try_send_and_unthrottle(c);
7383 * Handlers for SSH-2 messages that might arrive at any moment.
7385 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
7387 /* log reason code in disconnect message */
7389 int nowlen, reason, msglen;
7391 reason = ssh_pkt_getuint32(pktin);
7392 ssh_pkt_getstring(pktin, &msg, &msglen);
7394 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
7395 buf = dupprintf("Received disconnect message (%s)",
7396 ssh2_disconnect_reasons[reason]);
7398 buf = dupprintf("Received disconnect message (unknown"
7399 " type %d)", reason);
7403 buf = dupprintf("Disconnection message text: %n%.*s",
7404 &nowlen, msglen, msg);
7406 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
7408 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
7409 ssh2_disconnect_reasons[reason] : "unknown",
7414 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
7416 /* log the debug message */
7421 /* XXX maybe we should actually take notice of this */
7422 always_display = ssh2_pkt_getbool(pktin);
7423 ssh_pkt_getstring(pktin, &msg, &msglen);
7425 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
7428 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
7430 struct Packet *pktout;
7431 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
7432 ssh2_pkt_adduint32(pktout, pktin->sequence);
7434 * UNIMPLEMENTED messages MUST appear in the same order as the
7435 * messages they respond to. Hence, never queue them.
7437 ssh2_pkt_send_noqueue(ssh, pktout);
7441 * Handle the top-level SSH-2 protocol.
7443 static void ssh2_protocol_setup(Ssh ssh)
7448 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
7450 for (i = 0; i < 256; i++)
7451 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
7454 * Any message we actually understand, we set to NULL so that
7455 * the coroutines will get it.
7457 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = NULL;
7458 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = NULL;
7459 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = NULL;
7460 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = NULL;
7461 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = NULL;
7462 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = NULL;
7463 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = NULL;
7464 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = NULL; duplicate case value */
7465 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = NULL; duplicate case value */
7466 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = NULL;
7467 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = NULL;
7468 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = NULL;
7469 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = NULL;
7470 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = NULL;
7471 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
7472 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = NULL;
7473 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = NULL; duplicate case value */
7474 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = NULL; duplicate case value */
7475 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = NULL;
7476 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = NULL;
7477 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = NULL;
7478 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = NULL;
7479 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = NULL;
7480 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = NULL;
7481 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = NULL;
7482 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = NULL;
7483 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = NULL;
7484 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = NULL;
7485 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = NULL;
7486 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = NULL;
7487 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = NULL;
7488 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = NULL;
7489 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = NULL;
7492 * These special message types we install handlers for.
7494 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
7495 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
7496 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
7499 static void ssh2_timer(void *ctx, long now)
7503 if (ssh->state == SSH_STATE_CLOSED)
7506 if (!ssh->kex_in_progress && ssh->cfg.ssh_rekey_time != 0 &&
7507 now - ssh->next_rekey >= 0) {
7508 do_ssh2_transport(ssh, "timeout", -1, NULL);
7512 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
7513 struct Packet *pktin)
7515 unsigned char *in = (unsigned char *)vin;
7516 if (ssh->state == SSH_STATE_CLOSED)
7520 ssh->incoming_data_size += pktin->encrypted_len;
7521 if (!ssh->kex_in_progress &&
7522 ssh->max_data_size != 0 &&
7523 ssh->incoming_data_size > ssh->max_data_size)
7524 do_ssh2_transport(ssh, "too much data received", -1, NULL);
7527 if (pktin && ssh->packet_dispatch[pktin->type]) {
7528 ssh->packet_dispatch[pktin->type](ssh, pktin);
7532 if (!ssh->protocol_initial_phase_done ||
7533 (pktin && pktin->type >= 20 && pktin->type < 50)) {
7534 if (do_ssh2_transport(ssh, in, inlen, pktin) &&
7535 !ssh->protocol_initial_phase_done) {
7536 ssh->protocol_initial_phase_done = TRUE;
7538 * Allow authconn to initialise itself.
7540 do_ssh2_authconn(ssh, NULL, 0, NULL);
7543 do_ssh2_authconn(ssh, in, inlen, pktin);
7548 * Called to set up the connection.
7550 * Returns an error message, or NULL on success.
7552 static const char *ssh_init(void *frontend_handle, void **backend_handle,
7554 char *host, int port, char **realhost, int nodelay,
7560 ssh = snew(struct ssh_tag);
7561 ssh->cfg = *cfg; /* STRUCTURE COPY */
7562 ssh->version = 0; /* when not ready yet */
7565 ssh->v1_cipher_ctx = NULL;
7566 ssh->crcda_ctx = NULL;
7567 ssh->cscipher = NULL;
7568 ssh->cs_cipher_ctx = NULL;
7569 ssh->sccipher = NULL;
7570 ssh->sc_cipher_ctx = NULL;
7572 ssh->cs_mac_ctx = NULL;
7574 ssh->sc_mac_ctx = NULL;
7576 ssh->cs_comp_ctx = NULL;
7578 ssh->sc_comp_ctx = NULL;
7580 ssh->kex_ctx = NULL;
7581 ssh->hostkey = NULL;
7583 ssh->close_expected = FALSE;
7584 ssh->state = SSH_STATE_PREPACKET;
7585 ssh->size_needed = FALSE;
7586 ssh->eof_needed = FALSE;
7589 ssh->deferred_send_data = NULL;
7590 ssh->deferred_len = 0;
7591 ssh->deferred_size = 0;
7592 ssh->fallback_cmd = 0;
7594 ssh->x11auth = NULL;
7595 ssh->v1_compressing = FALSE;
7596 ssh->v2_outgoing_sequence = 0;
7597 ssh->ssh1_rdpkt_crstate = 0;
7598 ssh->ssh2_rdpkt_crstate = 0;
7599 ssh->do_ssh_init_crstate = 0;
7600 ssh->ssh_gotdata_crstate = 0;
7601 ssh->do_ssh1_connection_crstate = 0;
7602 ssh->do_ssh1_login_crstate = 0;
7603 ssh->do_ssh2_transport_crstate = 0;
7604 ssh->do_ssh2_authconn_crstate = 0;
7605 ssh->do_ssh_init_state = NULL;
7606 ssh->do_ssh1_login_state = NULL;
7607 ssh->do_ssh2_transport_state = NULL;
7608 ssh->do_ssh2_authconn_state = NULL;
7609 ssh->mainchan = NULL;
7610 ssh->throttled_all = 0;
7611 ssh->v1_stdout_throttling = 0;
7613 ssh->queuelen = ssh->queuesize = 0;
7614 ssh->queueing = FALSE;
7615 ssh->qhead = ssh->qtail = NULL;
7616 ssh->deferred_rekey_reason = NULL;
7617 bufchain_init(&ssh->queued_incoming_data);
7618 ssh->frozen = FALSE;
7620 *backend_handle = ssh;
7623 if (crypto_startup() == 0)
7624 return "Microsoft high encryption pack not installed!";
7627 ssh->frontend = frontend_handle;
7628 ssh->term_width = ssh->cfg.width;
7629 ssh->term_height = ssh->cfg.height;
7631 ssh->channels = NULL;
7632 ssh->rportfwds = NULL;
7633 ssh->portfwds = NULL;
7638 ssh->v1_throttle_count = 0;
7639 ssh->overall_bufsize = 0;
7640 ssh->fallback_cmd = 0;
7642 ssh->protocol = NULL;
7644 ssh->protocol_initial_phase_done = FALSE;
7648 ssh->incoming_data_size = ssh->outgoing_data_size =
7649 ssh->deferred_data_size = 0L;
7650 ssh->max_data_size = parse_blocksize(ssh->cfg.ssh_rekey_data);
7651 ssh->kex_in_progress = FALSE;
7653 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
7662 static void ssh_free(void *handle)
7664 Ssh ssh = (Ssh) handle;
7665 struct ssh_channel *c;
7666 struct ssh_rportfwd *pf;
7668 if (ssh->v1_cipher_ctx)
7669 ssh->cipher->free_context(ssh->v1_cipher_ctx);
7670 if (ssh->cs_cipher_ctx)
7671 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
7672 if (ssh->sc_cipher_ctx)
7673 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
7674 if (ssh->cs_mac_ctx)
7675 ssh->csmac->free_context(ssh->cs_mac_ctx);
7676 if (ssh->sc_mac_ctx)
7677 ssh->scmac->free_context(ssh->sc_mac_ctx);
7678 if (ssh->cs_comp_ctx) {
7680 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
7682 zlib_compress_cleanup(ssh->cs_comp_ctx);
7684 if (ssh->sc_comp_ctx) {
7686 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
7688 zlib_decompress_cleanup(ssh->sc_comp_ctx);
7691 dh_cleanup(ssh->kex_ctx);
7692 sfree(ssh->savedhost);
7694 while (ssh->queuelen-- > 0)
7695 ssh_free_packet(ssh->queue[ssh->queuelen]);
7698 while (ssh->qhead) {
7699 struct queued_handler *qh = ssh->qhead;
7700 ssh->qhead = qh->next;
7703 ssh->qhead = ssh->qtail = NULL;
7705 if (ssh->channels) {
7706 while ((c = delpos234(ssh->channels, 0)) != NULL) {
7709 if (c->u.x11.s != NULL)
7710 x11_close(c->u.x11.s);
7713 if (c->u.pfd.s != NULL)
7714 pfd_close(c->u.pfd.s);
7719 freetree234(ssh->channels);
7720 ssh->channels = NULL;
7723 if (ssh->rportfwds) {
7724 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
7726 freetree234(ssh->rportfwds);
7727 ssh->rportfwds = NULL;
7729 sfree(ssh->deferred_send_data);
7731 x11_free_auth(ssh->x11auth);
7732 sfree(ssh->do_ssh_init_state);
7733 sfree(ssh->do_ssh1_login_state);
7734 sfree(ssh->do_ssh2_transport_state);
7735 sfree(ssh->do_ssh2_authconn_state);
7736 if (ssh->crcda_ctx) {
7737 crcda_free_context(ssh->crcda_ctx);
7738 ssh->crcda_ctx = NULL;
7741 ssh_do_close(ssh, TRUE);
7742 expire_timer_context(ssh);
7744 pinger_free(ssh->pinger);
7745 bufchain_clear(&ssh->queued_incoming_data);
7752 * Reconfigure the SSH backend.
7754 static void ssh_reconfig(void *handle, Config *cfg)
7756 Ssh ssh = (Ssh) handle;
7757 char *rekeying = NULL, rekey_mandatory = FALSE;
7758 unsigned long old_max_data_size;
7760 pinger_reconfig(ssh->pinger, &ssh->cfg, cfg);
7761 ssh_setup_portfwd(ssh, cfg);
7763 if (ssh->cfg.ssh_rekey_time != cfg->ssh_rekey_time &&
7764 cfg->ssh_rekey_time != 0) {
7765 long new_next = ssh->last_rekey + cfg->ssh_rekey_time*60*TICKSPERSEC;
7766 long now = GETTICKCOUNT();
7768 if (new_next - now < 0) {
7769 rekeying = "timeout shortened";
7771 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
7775 old_max_data_size = ssh->max_data_size;
7776 ssh->max_data_size = parse_blocksize(cfg->ssh_rekey_data);
7777 if (old_max_data_size != ssh->max_data_size &&
7778 ssh->max_data_size != 0) {
7779 if (ssh->outgoing_data_size > ssh->max_data_size ||
7780 ssh->incoming_data_size > ssh->max_data_size)
7781 rekeying = "data limit lowered";
7784 if (ssh->cfg.compression != cfg->compression) {
7785 rekeying = "compression setting changed";
7786 rekey_mandatory = TRUE;
7789 if (ssh->cfg.ssh2_des_cbc != cfg->ssh2_des_cbc ||
7790 memcmp(ssh->cfg.ssh_cipherlist, cfg->ssh_cipherlist,
7791 sizeof(ssh->cfg.ssh_cipherlist))) {
7792 rekeying = "cipher settings changed";
7793 rekey_mandatory = TRUE;
7796 ssh->cfg = *cfg; /* STRUCTURE COPY */
7799 if (!ssh->kex_in_progress) {
7800 do_ssh2_transport(ssh, rekeying, -1, NULL);
7801 } else if (rekey_mandatory) {
7802 ssh->deferred_rekey_reason = rekeying;
7808 * Called to send data down the Telnet connection.
7810 static int ssh_send(void *handle, char *buf, int len)
7812 Ssh ssh = (Ssh) handle;
7814 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
7817 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
7819 return ssh_sendbuffer(ssh);
7823 * Called to query the current amount of buffered stdin data.
7825 static int ssh_sendbuffer(void *handle)
7827 Ssh ssh = (Ssh) handle;
7830 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
7834 * If the SSH socket itself has backed up, add the total backup
7835 * size on that to any individual buffer on the stdin channel.
7838 if (ssh->throttled_all)
7839 override_value = ssh->overall_bufsize;
7841 if (ssh->version == 1) {
7842 return override_value;
7843 } else if (ssh->version == 2) {
7844 if (!ssh->mainchan || ssh->mainchan->closes > 0)
7845 return override_value;
7847 return (override_value +
7848 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
7855 * Called to set the size of the window from SSH's POV.
7857 static void ssh_size(void *handle, int width, int height)
7859 Ssh ssh = (Ssh) handle;
7860 struct Packet *pktout;
7862 ssh->term_width = width;
7863 ssh->term_height = height;
7865 switch (ssh->state) {
7866 case SSH_STATE_BEFORE_SIZE:
7867 case SSH_STATE_PREPACKET:
7868 case SSH_STATE_CLOSED:
7869 break; /* do nothing */
7870 case SSH_STATE_INTERMED:
7871 ssh->size_needed = TRUE; /* buffer for later */
7873 case SSH_STATE_SESSION:
7874 if (!ssh->cfg.nopty) {
7875 if (ssh->version == 1) {
7876 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
7877 PKT_INT, ssh->term_height,
7878 PKT_INT, ssh->term_width,
7879 PKT_INT, 0, PKT_INT, 0, PKT_END);
7880 } else if (ssh->mainchan) {
7881 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7882 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
7883 ssh2_pkt_addstring(pktout, "window-change");
7884 ssh2_pkt_addbool(pktout, 0);
7885 ssh2_pkt_adduint32(pktout, ssh->term_width);
7886 ssh2_pkt_adduint32(pktout, ssh->term_height);
7887 ssh2_pkt_adduint32(pktout, 0);
7888 ssh2_pkt_adduint32(pktout, 0);
7889 ssh2_pkt_send(ssh, pktout);
7897 * Return a list of the special codes that make sense in this
7900 static const struct telnet_special *ssh_get_specials(void *handle)
7902 static const struct telnet_special ssh1_ignore_special[] = {
7903 {"IGNORE message", TS_NOP}
7905 static const struct telnet_special ssh2_transport_specials[] = {
7906 {"IGNORE message", TS_NOP},
7907 {"Repeat key exchange", TS_REKEY},
7909 static const struct telnet_special ssh2_session_specials[] = {
7912 /* These are the signal names defined by draft-ietf-secsh-connect-23.
7913 * They include all the ISO C signals, but are a subset of the POSIX
7914 * required signals. */
7915 {"SIGINT (Interrupt)", TS_SIGINT},
7916 {"SIGTERM (Terminate)", TS_SIGTERM},
7917 {"SIGKILL (Kill)", TS_SIGKILL},
7918 {"SIGQUIT (Quit)", TS_SIGQUIT},
7919 {"SIGHUP (Hangup)", TS_SIGHUP},
7920 {"More signals", TS_SUBMENU},
7921 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
7922 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
7923 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
7924 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
7927 static const struct telnet_special specials_end[] = {
7930 /* XXX review this length for any changes: */
7931 static struct telnet_special ssh_specials[lenof(ssh2_transport_specials) +
7932 lenof(ssh2_session_specials) +
7933 lenof(specials_end)];
7934 Ssh ssh = (Ssh) handle;
7936 #define ADD_SPECIALS(name) \
7938 assert((i + lenof(name)) <= lenof(ssh_specials)); \
7939 memcpy(&ssh_specials[i], name, sizeof name); \
7943 if (ssh->version == 1) {
7944 /* Don't bother offering IGNORE if we've decided the remote
7945 * won't cope with it, since we wouldn't bother sending it if
7947 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
7948 ADD_SPECIALS(ssh1_ignore_special);
7949 } else if (ssh->version == 2) {
7950 ADD_SPECIALS(ssh2_transport_specials);
7952 ADD_SPECIALS(ssh2_session_specials);
7953 } /* else we're not ready yet */
7956 ADD_SPECIALS(specials_end);
7957 return ssh_specials;
7965 * Send Telnet special codes. TS_EOF is useful for `plink', so you
7966 * can send an EOF and collect resulting output (e.g. `plink
7969 static void ssh_special(void *handle, Telnet_Special code)
7971 Ssh ssh = (Ssh) handle;
7972 struct Packet *pktout;
7974 if (code == TS_EOF) {
7975 if (ssh->state != SSH_STATE_SESSION) {
7977 * Buffer the EOF in case we are pre-SESSION, so we can
7978 * send it as soon as we reach SESSION.
7981 ssh->eof_needed = TRUE;
7984 if (ssh->version == 1) {
7985 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
7986 } else if (ssh->mainchan) {
7987 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
7988 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
7989 ssh2_pkt_send(ssh, pktout);
7990 ssh->send_ok = 0; /* now stop trying to read from stdin */
7992 logevent("Sent EOF message");
7993 } else if (code == TS_PING || code == TS_NOP) {
7994 if (ssh->state == SSH_STATE_CLOSED
7995 || ssh->state == SSH_STATE_PREPACKET) return;
7996 if (ssh->version == 1) {
7997 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
7998 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
8000 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
8001 ssh2_pkt_addstring_start(pktout);
8002 ssh2_pkt_send_noqueue(ssh, pktout);
8004 } else if (code == TS_REKEY) {
8005 if (!ssh->kex_in_progress && ssh->version == 2) {
8006 do_ssh2_transport(ssh, "at user request", -1, NULL);
8008 } else if (code == TS_BRK) {
8009 if (ssh->state == SSH_STATE_CLOSED
8010 || ssh->state == SSH_STATE_PREPACKET) return;
8011 if (ssh->version == 1) {
8012 logevent("Unable to send BREAK signal in SSH-1");
8013 } else if (ssh->mainchan) {
8014 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8015 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
8016 ssh2_pkt_addstring(pktout, "break");
8017 ssh2_pkt_addbool(pktout, 0);
8018 ssh2_pkt_adduint32(pktout, 0); /* default break length */
8019 ssh2_pkt_send(ssh, pktout);
8022 /* Is is a POSIX signal? */
8023 char *signame = NULL;
8024 if (code == TS_SIGABRT) signame = "ABRT";
8025 if (code == TS_SIGALRM) signame = "ALRM";
8026 if (code == TS_SIGFPE) signame = "FPE";
8027 if (code == TS_SIGHUP) signame = "HUP";
8028 if (code == TS_SIGILL) signame = "ILL";
8029 if (code == TS_SIGINT) signame = "INT";
8030 if (code == TS_SIGKILL) signame = "KILL";
8031 if (code == TS_SIGPIPE) signame = "PIPE";
8032 if (code == TS_SIGQUIT) signame = "QUIT";
8033 if (code == TS_SIGSEGV) signame = "SEGV";
8034 if (code == TS_SIGTERM) signame = "TERM";
8035 if (code == TS_SIGUSR1) signame = "USR1";
8036 if (code == TS_SIGUSR2) signame = "USR2";
8037 /* The SSH-2 protocol does in principle support arbitrary named
8038 * signals, including signame@domain, but we don't support those. */
8040 /* It's a signal. */
8041 if (ssh->version == 2 && ssh->mainchan) {
8042 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8043 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
8044 ssh2_pkt_addstring(pktout, "signal");
8045 ssh2_pkt_addbool(pktout, 0);
8046 ssh2_pkt_addstring(pktout, signame);
8047 ssh2_pkt_send(ssh, pktout);
8048 logeventf(ssh, "Sent signal SIG%s", signame);
8051 /* Never heard of it. Do nothing */
8056 void *new_sock_channel(void *handle, Socket s)
8058 Ssh ssh = (Ssh) handle;
8059 struct ssh_channel *c;
8060 c = snew(struct ssh_channel);
8065 c->localid = alloc_channel_id(ssh);
8067 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
8069 bufchain_init(&c->v.v2.outbuffer);
8070 add234(ssh->channels, c);
8076 * This is called when stdout/stderr (the entity to which
8077 * from_backend sends data) manages to clear some backlog.
8079 static void ssh_unthrottle(void *handle, int bufsize)
8081 Ssh ssh = (Ssh) handle;
8082 if (ssh->version == 1) {
8083 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
8084 ssh->v1_stdout_throttling = 0;
8085 ssh1_throttle(ssh, -1);
8088 if (ssh->mainchan && ssh->mainchan->closes == 0)
8089 ssh2_set_window(ssh->mainchan, OUR_V2_WINSIZE - bufsize);
8093 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
8095 struct ssh_channel *c = (struct ssh_channel *)channel;
8097 struct Packet *pktout;
8099 logeventf(ssh, "Opening forwarded connection to %s:%d", hostname, port);
8101 if (ssh->version == 1) {
8102 send_packet(ssh, SSH1_MSG_PORT_OPEN,
8103 PKT_INT, c->localid,
8106 /* PKT_STR, <org:orgport>, */
8109 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
8110 ssh2_pkt_addstring(pktout, "direct-tcpip");
8111 ssh2_pkt_adduint32(pktout, c->localid);
8112 c->v.v2.locwindow = OUR_V2_WINSIZE;
8113 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
8114 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
8115 ssh2_pkt_addstring(pktout, hostname);
8116 ssh2_pkt_adduint32(pktout, port);
8118 * We make up values for the originator data; partly it's
8119 * too much hassle to keep track, and partly I'm not
8120 * convinced the server should be told details like that
8121 * about my local network configuration.
8123 ssh2_pkt_addstring(pktout, "client-side-connection");
8124 ssh2_pkt_adduint32(pktout, 0);
8125 ssh2_pkt_send(ssh, pktout);
8129 static Socket ssh_socket(void *handle)
8131 Ssh ssh = (Ssh) handle;
8135 static int ssh_sendok(void *handle)
8137 Ssh ssh = (Ssh) handle;
8138 return ssh->send_ok;
8141 static int ssh_ldisc(void *handle, int option)
8143 Ssh ssh = (Ssh) handle;
8144 if (option == LD_ECHO)
8145 return ssh->echoing;
8146 if (option == LD_EDIT)
8147 return ssh->editing;
8151 static void ssh_provide_ldisc(void *handle, void *ldisc)
8153 Ssh ssh = (Ssh) handle;
8157 static void ssh_provide_logctx(void *handle, void *logctx)
8159 Ssh ssh = (Ssh) handle;
8160 ssh->logctx = logctx;
8163 static int ssh_return_exitcode(void *handle)
8165 Ssh ssh = (Ssh) handle;
8169 return (ssh->exitcode >= 0 ? ssh->exitcode : 0);
8173 * cfg_info for SSH is the currently running version of the
8174 * protocol. (1 for 1; 2 for 2; 0 for not-decided-yet.)
8176 static int ssh_cfg_info(void *handle)
8178 Ssh ssh = (Ssh) handle;
8179 return ssh->version;
8183 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
8184 * that fails. This variable is the means by which scp.c can reach
8185 * into the SSH code and find out which one it got.
8187 extern int ssh_fallback_cmd(void *handle)
8189 Ssh ssh = (Ssh) handle;
8190 return ssh->fallback_cmd;
8193 Backend ssh_backend = {
8203 ssh_return_exitcode,