13 #include "pageant.h" /* for AGENT_MAX_MSGLEN */
30 * Packet type contexts, so that ssh2_pkt_type can correctly decode
31 * the ambiguous type numbers back into the correct type strings.
42 SSH2_PKTCTX_PUBLICKEY,
48 static const char *const ssh2_disconnect_reasons[] = {
50 "host not allowed to connect",
52 "key exchange failed",
53 "host authentication failed",
56 "service not available",
57 "protocol version not supported",
58 "host key not verifiable",
61 "too many connections",
62 "auth cancelled by user",
63 "no more auth methods available",
68 * Various remote-bug flags.
70 #define BUG_CHOKES_ON_SSH1_IGNORE 1
71 #define BUG_SSH2_HMAC 2
72 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
73 #define BUG_CHOKES_ON_RSA 8
74 #define BUG_SSH2_RSA_PADDING 16
75 #define BUG_SSH2_DERIVEKEY 32
76 #define BUG_SSH2_REKEY 64
77 #define BUG_SSH2_PK_SESSIONID 128
78 #define BUG_SSH2_MAXPKT 256
79 #define BUG_CHOKES_ON_SSH2_IGNORE 512
80 #define BUG_CHOKES_ON_WINADJ 1024
81 #define BUG_SENDS_LATE_REQUEST_REPLY 2048
82 #define BUG_SSH2_OLDGEX 4096
84 #define DH_MIN_SIZE 1024
85 #define DH_MAX_SIZE 8192
88 * Codes for terminal modes.
89 * Most of these are the same in SSH-1 and SSH-2.
90 * This list is derived from RFC 4254 and
93 static const struct ssh_ttymode {
94 const char* const mode;
96 enum { TTY_OP_CHAR, TTY_OP_BOOL } type;
98 /* "V" prefix discarded for special characters relative to SSH specs */
99 { "INTR", 1, TTY_OP_CHAR },
100 { "QUIT", 2, TTY_OP_CHAR },
101 { "ERASE", 3, TTY_OP_CHAR },
102 { "KILL", 4, TTY_OP_CHAR },
103 { "EOF", 5, TTY_OP_CHAR },
104 { "EOL", 6, TTY_OP_CHAR },
105 { "EOL2", 7, TTY_OP_CHAR },
106 { "START", 8, TTY_OP_CHAR },
107 { "STOP", 9, TTY_OP_CHAR },
108 { "SUSP", 10, TTY_OP_CHAR },
109 { "DSUSP", 11, TTY_OP_CHAR },
110 { "REPRINT", 12, TTY_OP_CHAR },
111 { "WERASE", 13, TTY_OP_CHAR },
112 { "LNEXT", 14, TTY_OP_CHAR },
113 { "FLUSH", 15, TTY_OP_CHAR },
114 { "SWTCH", 16, TTY_OP_CHAR },
115 { "STATUS", 17, TTY_OP_CHAR },
116 { "DISCARD", 18, TTY_OP_CHAR },
117 { "IGNPAR", 30, TTY_OP_BOOL },
118 { "PARMRK", 31, TTY_OP_BOOL },
119 { "INPCK", 32, TTY_OP_BOOL },
120 { "ISTRIP", 33, TTY_OP_BOOL },
121 { "INLCR", 34, TTY_OP_BOOL },
122 { "IGNCR", 35, TTY_OP_BOOL },
123 { "ICRNL", 36, TTY_OP_BOOL },
124 { "IUCLC", 37, TTY_OP_BOOL },
125 { "IXON", 38, TTY_OP_BOOL },
126 { "IXANY", 39, TTY_OP_BOOL },
127 { "IXOFF", 40, TTY_OP_BOOL },
128 { "IMAXBEL", 41, TTY_OP_BOOL },
129 { "IUTF8", 42, TTY_OP_BOOL },
130 { "ISIG", 50, TTY_OP_BOOL },
131 { "ICANON", 51, TTY_OP_BOOL },
132 { "XCASE", 52, TTY_OP_BOOL },
133 { "ECHO", 53, TTY_OP_BOOL },
134 { "ECHOE", 54, TTY_OP_BOOL },
135 { "ECHOK", 55, TTY_OP_BOOL },
136 { "ECHONL", 56, TTY_OP_BOOL },
137 { "NOFLSH", 57, TTY_OP_BOOL },
138 { "TOSTOP", 58, TTY_OP_BOOL },
139 { "IEXTEN", 59, TTY_OP_BOOL },
140 { "ECHOCTL", 60, TTY_OP_BOOL },
141 { "ECHOKE", 61, TTY_OP_BOOL },
142 { "PENDIN", 62, TTY_OP_BOOL }, /* XXX is this a real mode? */
143 { "OPOST", 70, TTY_OP_BOOL },
144 { "OLCUC", 71, TTY_OP_BOOL },
145 { "ONLCR", 72, TTY_OP_BOOL },
146 { "OCRNL", 73, TTY_OP_BOOL },
147 { "ONOCR", 74, TTY_OP_BOOL },
148 { "ONLRET", 75, TTY_OP_BOOL },
149 { "CS7", 90, TTY_OP_BOOL },
150 { "CS8", 91, TTY_OP_BOOL },
151 { "PARENB", 92, TTY_OP_BOOL },
152 { "PARODD", 93, TTY_OP_BOOL }
155 /* Miscellaneous other tty-related constants. */
156 #define SSH_TTY_OP_END 0
157 /* The opcodes for ISPEED/OSPEED differ between SSH-1 and SSH-2. */
158 #define SSH1_TTY_OP_ISPEED 192
159 #define SSH1_TTY_OP_OSPEED 193
160 #define SSH2_TTY_OP_ISPEED 128
161 #define SSH2_TTY_OP_OSPEED 129
163 /* Helper functions for parsing tty-related config. */
164 static unsigned int ssh_tty_parse_specchar(char *s)
169 ret = ctrlparse(s, &next);
170 if (!next) ret = s[0];
172 ret = 255; /* special value meaning "don't set" */
176 static unsigned int ssh_tty_parse_boolean(char *s)
178 if (stricmp(s, "yes") == 0 ||
179 stricmp(s, "on") == 0 ||
180 stricmp(s, "true") == 0 ||
181 stricmp(s, "+") == 0)
183 else if (stricmp(s, "no") == 0 ||
184 stricmp(s, "off") == 0 ||
185 stricmp(s, "false") == 0 ||
186 stricmp(s, "-") == 0)
187 return 0; /* false */
189 return (atoi(s) != 0);
192 #define translate(x) if (type == x) return #x
193 #define translatek(x,ctx) if (type == x && (pkt_kctx == ctx)) return #x
194 #define translatea(x,ctx) if (type == x && (pkt_actx == ctx)) return #x
195 static const char *ssh1_pkt_type(int type)
197 translate(SSH1_MSG_DISCONNECT);
198 translate(SSH1_SMSG_PUBLIC_KEY);
199 translate(SSH1_CMSG_SESSION_KEY);
200 translate(SSH1_CMSG_USER);
201 translate(SSH1_CMSG_AUTH_RSA);
202 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
203 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
204 translate(SSH1_CMSG_AUTH_PASSWORD);
205 translate(SSH1_CMSG_REQUEST_PTY);
206 translate(SSH1_CMSG_WINDOW_SIZE);
207 translate(SSH1_CMSG_EXEC_SHELL);
208 translate(SSH1_CMSG_EXEC_CMD);
209 translate(SSH1_SMSG_SUCCESS);
210 translate(SSH1_SMSG_FAILURE);
211 translate(SSH1_CMSG_STDIN_DATA);
212 translate(SSH1_SMSG_STDOUT_DATA);
213 translate(SSH1_SMSG_STDERR_DATA);
214 translate(SSH1_CMSG_EOF);
215 translate(SSH1_SMSG_EXIT_STATUS);
216 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
217 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
218 translate(SSH1_MSG_CHANNEL_DATA);
219 translate(SSH1_MSG_CHANNEL_CLOSE);
220 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
221 translate(SSH1_SMSG_X11_OPEN);
222 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
223 translate(SSH1_MSG_PORT_OPEN);
224 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
225 translate(SSH1_SMSG_AGENT_OPEN);
226 translate(SSH1_MSG_IGNORE);
227 translate(SSH1_CMSG_EXIT_CONFIRMATION);
228 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
229 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
230 translate(SSH1_MSG_DEBUG);
231 translate(SSH1_CMSG_REQUEST_COMPRESSION);
232 translate(SSH1_CMSG_AUTH_TIS);
233 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
234 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
235 translate(SSH1_CMSG_AUTH_CCARD);
236 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
237 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
240 static const char *ssh2_pkt_type(Pkt_KCtx pkt_kctx, Pkt_ACtx pkt_actx,
243 translatea(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE,SSH2_PKTCTX_GSSAPI);
244 translatea(SSH2_MSG_USERAUTH_GSSAPI_TOKEN,SSH2_PKTCTX_GSSAPI);
245 translatea(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE,SSH2_PKTCTX_GSSAPI);
246 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERROR,SSH2_PKTCTX_GSSAPI);
247 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK,SSH2_PKTCTX_GSSAPI);
248 translatea(SSH2_MSG_USERAUTH_GSSAPI_MIC, SSH2_PKTCTX_GSSAPI);
249 translate(SSH2_MSG_DISCONNECT);
250 translate(SSH2_MSG_IGNORE);
251 translate(SSH2_MSG_UNIMPLEMENTED);
252 translate(SSH2_MSG_DEBUG);
253 translate(SSH2_MSG_SERVICE_REQUEST);
254 translate(SSH2_MSG_SERVICE_ACCEPT);
255 translate(SSH2_MSG_KEXINIT);
256 translate(SSH2_MSG_NEWKEYS);
257 translatek(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP);
258 translatek(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP);
259 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD, SSH2_PKTCTX_DHGEX);
260 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
261 translatek(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
262 translatek(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
263 translatek(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
264 translatek(SSH2_MSG_KEXRSA_PUBKEY, SSH2_PKTCTX_RSAKEX);
265 translatek(SSH2_MSG_KEXRSA_SECRET, SSH2_PKTCTX_RSAKEX);
266 translatek(SSH2_MSG_KEXRSA_DONE, SSH2_PKTCTX_RSAKEX);
267 translatek(SSH2_MSG_KEX_ECDH_INIT, SSH2_PKTCTX_ECDHKEX);
268 translatek(SSH2_MSG_KEX_ECDH_REPLY, SSH2_PKTCTX_ECDHKEX);
269 translate(SSH2_MSG_USERAUTH_REQUEST);
270 translate(SSH2_MSG_USERAUTH_FAILURE);
271 translate(SSH2_MSG_USERAUTH_SUCCESS);
272 translate(SSH2_MSG_USERAUTH_BANNER);
273 translatea(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
274 translatea(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
275 translatea(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
276 translatea(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
277 translate(SSH2_MSG_GLOBAL_REQUEST);
278 translate(SSH2_MSG_REQUEST_SUCCESS);
279 translate(SSH2_MSG_REQUEST_FAILURE);
280 translate(SSH2_MSG_CHANNEL_OPEN);
281 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
282 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
283 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
284 translate(SSH2_MSG_CHANNEL_DATA);
285 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
286 translate(SSH2_MSG_CHANNEL_EOF);
287 translate(SSH2_MSG_CHANNEL_CLOSE);
288 translate(SSH2_MSG_CHANNEL_REQUEST);
289 translate(SSH2_MSG_CHANNEL_SUCCESS);
290 translate(SSH2_MSG_CHANNEL_FAILURE);
296 /* Enumeration values for fields in SSH-1 packets */
298 PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
302 * Coroutine mechanics for the sillier bits of the code. If these
303 * macros look impenetrable to you, you might find it helpful to
306 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
308 * which explains the theory behind these macros.
310 * In particular, if you are getting `case expression not constant'
311 * errors when building with MS Visual Studio, this is because MS's
312 * Edit and Continue debugging feature causes their compiler to
313 * violate ANSI C. To disable Edit and Continue debugging:
315 * - right-click ssh.c in the FileView
317 * - select the C/C++ tab and the General category
318 * - under `Debug info:', select anything _other_ than `Program
319 * Database for Edit and Continue'.
321 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
322 #define crBeginState crBegin(s->crLine)
323 #define crStateP(t, v) \
325 if (!(v)) { s = (v) = snew(struct t); s->crLine = 0; } \
327 #define crState(t) crStateP(t, ssh->t)
328 #define crFinish(z) } *crLine = 0; return (z); }
329 #define crFinishV } *crLine = 0; return; }
330 #define crFinishFree(z) } sfree(s); return (z); }
331 #define crFinishFreeV } sfree(s); return; }
332 #define crReturn(z) \
334 *crLine =__LINE__; return (z); case __LINE__:;\
338 *crLine=__LINE__; return; case __LINE__:;\
340 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
341 #define crStopV do{ *crLine = 0; return; }while(0)
342 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
343 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
347 static struct Packet *ssh1_pkt_init(int pkt_type);
348 static struct Packet *ssh2_pkt_init(int pkt_type);
349 static void ssh_pkt_ensure(struct Packet *, int length);
350 static void ssh_pkt_adddata(struct Packet *, const void *data, int len);
351 static void ssh_pkt_addbyte(struct Packet *, unsigned char value);
352 static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
353 static void ssh_pkt_adduint32(struct Packet *, unsigned long value);
354 static void ssh_pkt_addstring_start(struct Packet *);
355 static void ssh_pkt_addstring_str(struct Packet *, const char *data);
356 static void ssh_pkt_addstring_data(struct Packet *, const char *data, int len);
357 static void ssh_pkt_addstring(struct Packet *, const char *data);
358 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
359 static void ssh1_pkt_addmp(struct Packet *, Bignum b);
360 static void ssh2_pkt_addmp(struct Packet *, Bignum b);
361 static int ssh2_pkt_construct(Ssh, struct Packet *);
362 static void ssh2_pkt_send(Ssh, struct Packet *);
363 static void ssh2_pkt_send_noqueue(Ssh, struct Packet *);
364 static int do_ssh1_login(Ssh ssh, const unsigned char *in, int inlen,
365 struct Packet *pktin);
366 static void do_ssh2_authconn(Ssh ssh, const unsigned char *in, int inlen,
367 struct Packet *pktin);
368 static void ssh_channel_init(struct ssh_channel *c);
369 static struct ssh_channel *ssh_channel_msg(Ssh ssh, struct Packet *pktin);
370 static void ssh_channel_got_eof(struct ssh_channel *c);
371 static void ssh2_channel_check_close(struct ssh_channel *c);
372 static void ssh_channel_close_local(struct ssh_channel *c, char const *reason);
373 static void ssh_channel_destroy(struct ssh_channel *c);
374 static void ssh_channel_unthrottle(struct ssh_channel *c, int bufsize);
375 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin);
378 * Buffer management constants. There are several of these for
379 * various different purposes:
381 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
382 * on a local data stream before we throttle the whole SSH
383 * connection (in SSH-1 only). Throttling the whole connection is
384 * pretty drastic so we set this high in the hope it won't
387 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
388 * on the SSH connection itself before we defensively throttle
389 * _all_ local data streams. This is pretty drastic too (though
390 * thankfully unlikely in SSH-2 since the window mechanism should
391 * ensure that the server never has any need to throttle its end
392 * of the connection), so we set this high as well.
394 * - OUR_V2_WINSIZE is the default window size we present on SSH-2
397 * - OUR_V2_BIGWIN is the window size we advertise for the only
398 * channel in a simple connection. It must be <= INT_MAX.
400 * - OUR_V2_MAXPKT is the official "maximum packet size" we send
401 * to the remote side. This actually has nothing to do with the
402 * size of the _packet_, but is instead a limit on the amount
403 * of data we're willing to receive in a single SSH2 channel
406 * - OUR_V2_PACKETLIMIT is actually the maximum size of SSH
407 * _packet_ we're prepared to cope with. It must be a multiple
408 * of the cipher block size, and must be at least 35000.
411 #define SSH1_BUFFER_LIMIT 32768
412 #define SSH_MAX_BACKLOG 32768
413 #define OUR_V2_WINSIZE 16384
414 #define OUR_V2_BIGWIN 0x7fffffff
415 #define OUR_V2_MAXPKT 0x4000UL
416 #define OUR_V2_PACKETLIMIT 0x9000UL
418 struct ssh_signkey_with_user_pref_id {
419 const struct ssh_signkey *alg;
422 const static struct ssh_signkey_with_user_pref_id hostkey_algs[] = {
423 { &ssh_ecdsa_ed25519, HK_ED25519 },
424 { &ssh_ecdsa_nistp256, HK_ECDSA },
425 { &ssh_ecdsa_nistp384, HK_ECDSA },
426 { &ssh_ecdsa_nistp521, HK_ECDSA },
427 { &ssh_dss, HK_DSA },
428 { &ssh_rsa, HK_RSA },
431 const static struct ssh_mac *const macs[] = {
432 &ssh_hmac_sha256, &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
434 const static struct ssh_mac *const buggymacs[] = {
435 &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
438 static void *ssh_comp_none_init(void)
442 static void ssh_comp_none_cleanup(void *handle)
445 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
446 unsigned char **outblock, int *outlen)
450 static int ssh_comp_none_disable(void *handle)
454 const static struct ssh_compress ssh_comp_none = {
456 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
457 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
458 ssh_comp_none_disable, NULL
460 extern const struct ssh_compress ssh_zlib;
461 const static struct ssh_compress *const compressions[] = {
462 &ssh_zlib, &ssh_comp_none
465 enum { /* channel types */
471 * CHAN_SHARING indicates a channel which is tracked here on
472 * behalf of a connection-sharing downstream. We do almost nothing
473 * with these channels ourselves: all messages relating to them
474 * get thrown straight to sshshare.c and passed on almost
475 * unmodified to downstream.
479 * CHAN_ZOMBIE is used to indicate a channel for which we've
480 * already destroyed the local data source: for instance, if a
481 * forwarded port experiences a socket error on the local side, we
482 * immediately destroy its local socket and turn the SSH channel
488 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
489 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
490 typedef void (*cchandler_fn_t)(struct ssh_channel *, struct Packet *, void *);
493 * Each channel has a queue of outstanding CHANNEL_REQUESTS and their
496 struct outstanding_channel_request {
497 cchandler_fn_t handler;
499 struct outstanding_channel_request *next;
503 * 2-3-4 tree storing channels.
506 Ssh ssh; /* pointer back to main context */
507 unsigned remoteid, localid;
509 /* True if we opened this channel but server hasn't confirmed. */
512 * In SSH-1, this value contains four bits:
514 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
515 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
516 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
517 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
519 * A channel is completely finished with when all four bits are set.
521 * In SSH-2, the four bits mean:
523 * 1 We have sent SSH2_MSG_CHANNEL_EOF.
524 * 2 We have sent SSH2_MSG_CHANNEL_CLOSE.
525 * 4 We have received SSH2_MSG_CHANNEL_EOF.
526 * 8 We have received SSH2_MSG_CHANNEL_CLOSE.
528 * A channel is completely finished with when we have both sent
529 * and received CLOSE.
531 * The symbolic constants below use the SSH-2 terminology, which
532 * is a bit confusing in SSH-1, but we have to use _something_.
534 #define CLOSES_SENT_EOF 1
535 #define CLOSES_SENT_CLOSE 2
536 #define CLOSES_RCVD_EOF 4
537 #define CLOSES_RCVD_CLOSE 8
541 * This flag indicates that an EOF is pending on the outgoing side
542 * of the channel: that is, wherever we're getting the data for
543 * this channel has sent us some data followed by EOF. We can't
544 * actually send the EOF until we've finished sending the data, so
545 * we set this flag instead to remind us to do so once our buffer
551 * True if this channel is causing the underlying connection to be
556 struct ssh2_data_channel {
558 unsigned remwindow, remmaxpkt;
559 /* locwindow is signed so we can cope with excess data. */
560 int locwindow, locmaxwin;
562 * remlocwin is the amount of local window that we think
563 * the remote end had available to it after it sent the
564 * last data packet or window adjust ack.
568 * These store the list of channel requests that haven't
571 struct outstanding_channel_request *chanreq_head, *chanreq_tail;
572 enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
576 struct ssh_agent_channel {
578 agent_pending_query *pending;
580 struct ssh_x11_channel {
581 struct X11Connection *xconn;
584 struct ssh_pfd_channel {
585 struct PortForwarding *pf;
587 struct ssh_sharing_channel {
594 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
595 * use this structure in different ways, reflecting SSH-2's
596 * altogether saner approach to port forwarding.
598 * In SSH-1, you arrange a remote forwarding by sending the server
599 * the remote port number, and the local destination host:port.
600 * When a connection comes in, the server sends you back that
601 * host:port pair, and you connect to it. This is a ready-made
602 * security hole if you're not on the ball: a malicious server
603 * could send you back _any_ host:port pair, so if you trustingly
604 * connect to the address it gives you then you've just opened the
605 * entire inside of your corporate network just by connecting
606 * through it to a dodgy SSH server. Hence, we must store a list of
607 * host:port pairs we _are_ trying to forward to, and reject a
608 * connection request from the server if it's not in the list.
610 * In SSH-2, each side of the connection minds its own business and
611 * doesn't send unnecessary information to the other. You arrange a
612 * remote forwarding by sending the server just the remote port
613 * number. When a connection comes in, the server tells you which
614 * of its ports was connected to; and _you_ have to remember what
615 * local host:port pair went with that port number.
617 * Hence, in SSH-1 this structure is indexed by destination
618 * host:port pair, whereas in SSH-2 it is indexed by source port.
620 struct ssh_portfwd; /* forward declaration */
622 struct ssh_rportfwd {
623 unsigned sport, dport;
627 struct ssh_portfwd *pfrec;
630 static void free_rportfwd(struct ssh_rportfwd *pf)
633 sfree(pf->sportdesc);
641 * Separately to the rportfwd tree (which is for looking up port
642 * open requests from the server), a tree of _these_ structures is
643 * used to keep track of all the currently open port forwardings,
644 * so that we can reconfigure in mid-session if the user requests
648 enum { DESTROY, KEEP, CREATE } status;
650 unsigned sport, dport;
653 struct ssh_rportfwd *remote;
655 struct PortListener *local;
657 #define free_portfwd(pf) ( \
658 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
659 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
662 long length; /* length of packet: see below */
663 long forcepad; /* SSH-2: force padding to at least this length */
664 int type; /* only used for incoming packets */
665 unsigned long sequence; /* SSH-2 incoming sequence number */
666 unsigned char *data; /* allocated storage */
667 unsigned char *body; /* offset of payload within `data' */
668 long savedpos; /* dual-purpose saved packet position: see below */
669 long maxlen; /* amount of storage allocated for `data' */
670 long encrypted_len; /* for SSH-2 total-size counting */
673 * A note on the 'length' and 'savedpos' fields above.
675 * Incoming packets are set up so that pkt->length is measured
676 * relative to pkt->body, which itself points to a few bytes after
677 * pkt->data (skipping some uninteresting header fields including
678 * the packet type code). The ssh_pkt_get* functions all expect
679 * this setup, and they also use pkt->savedpos to indicate how far
680 * through the packet being decoded they've got - and that, too,
681 * is an offset from pkt->body rather than pkt->data.
683 * During construction of an outgoing packet, however, pkt->length
684 * is measured relative to the base pointer pkt->data, and
685 * pkt->body is not really used for anything until the packet is
686 * ready for sending. In this mode, pkt->savedpos is reused as a
687 * temporary variable by the addstring functions, which write out
688 * a string length field and then keep going back and updating it
689 * as more data is appended to the subsequent string data field;
690 * pkt->savedpos stores the offset (again relative to pkt->data)
691 * of the start of the string data field.
694 /* Extra metadata used in SSH packet logging mode, allowing us to
695 * log in the packet header line that the packet came from a
696 * connection-sharing downstream and what if anything unusual was
697 * done to it. The additional_log_text field is expected to be a
698 * static string - it will not be freed. */
699 unsigned downstream_id;
700 const char *additional_log_text;
703 static void ssh1_protocol(Ssh ssh, const void *vin, int inlen,
704 struct Packet *pktin);
705 static void ssh2_protocol(Ssh ssh, const void *vin, int inlen,
706 struct Packet *pktin);
707 static void ssh2_bare_connection_protocol(Ssh ssh, const void *vin, int inlen,
708 struct Packet *pktin);
709 static void ssh1_protocol_setup(Ssh ssh);
710 static void ssh2_protocol_setup(Ssh ssh);
711 static void ssh2_bare_connection_protocol_setup(Ssh ssh);
712 static void ssh_size(void *handle, int width, int height);
713 static void ssh_special(void *handle, Telnet_Special);
714 static int ssh2_try_send(struct ssh_channel *c);
715 static int ssh_send_channel_data(struct ssh_channel *c,
716 const char *buf, int len);
717 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
718 static void ssh2_set_window(struct ssh_channel *c, int newwin);
719 static int ssh_sendbuffer(void *handle);
720 static int ssh_do_close(Ssh ssh, int notify_exit);
721 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
722 static int ssh2_pkt_getbool(struct Packet *pkt);
723 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
724 static void ssh2_timer(void *ctx, unsigned long now);
725 static void do_ssh2_transport(Ssh ssh, const void *vin, int inlen,
726 struct Packet *pktin);
727 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin);
729 struct rdpkt1_state_tag {
730 long len, pad, biglen, to_read;
731 unsigned long realcrc, gotcrc;
735 struct Packet *pktin;
738 struct rdpkt2_state_tag {
739 long len, pad, payload, packetlen, maclen;
742 unsigned long incoming_sequence;
743 struct Packet *pktin;
746 struct rdpkt2_bare_state_tag {
750 unsigned long incoming_sequence;
751 struct Packet *pktin;
754 struct queued_handler;
755 struct queued_handler {
757 chandler_fn_t handler;
759 struct queued_handler *next;
763 const struct plug_function_table *fn;
764 /* the above field _must_ be first in the structure */
774 unsigned char session_key[32];
776 int v1_remote_protoflags;
777 int v1_local_protoflags;
778 int agentfwd_enabled;
781 const struct ssh_cipher *cipher;
784 const struct ssh2_cipher *cscipher, *sccipher;
785 void *cs_cipher_ctx, *sc_cipher_ctx;
786 const struct ssh_mac *csmac, *scmac;
787 int csmac_etm, scmac_etm;
788 void *cs_mac_ctx, *sc_mac_ctx;
789 const struct ssh_compress *cscomp, *sccomp;
790 void *cs_comp_ctx, *sc_comp_ctx;
791 const struct ssh_kex *kex;
792 const struct ssh_signkey *hostkey;
793 char *hostkey_str; /* string representation, for easy checking in rekeys */
794 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
795 int v2_session_id_len;
799 int attempting_connshare;
805 int echoing, editing;
810 int ospeed, ispeed; /* temporaries */
811 int term_width, term_height;
813 tree234 *channels; /* indexed by local id */
814 struct ssh_channel *mainchan; /* primary session channel */
815 int ncmode; /* is primary channel direct-tcpip? */
820 tree234 *rportfwds, *portfwds;
824 SSH_STATE_BEFORE_SIZE,
830 int size_needed, eof_needed;
831 int sent_console_eof;
832 int got_pty; /* affects EOF behaviour on main channel */
834 struct Packet **queue;
835 int queuelen, queuesize;
837 unsigned char *deferred_send_data;
838 int deferred_len, deferred_size;
841 * Gross hack: pscp will try to start SFTP but fall back to
842 * scp1 if that fails. This variable is the means by which
843 * scp.c can reach into the SSH code and find out which one it
848 bufchain banner; /* accumulates banners during do_ssh2_authconn */
853 struct X11Display *x11disp;
854 struct X11FakeAuth *x11auth;
855 tree234 *x11authtree;
858 int conn_throttle_count;
861 int v1_stdout_throttling;
862 unsigned long v2_outgoing_sequence;
864 int ssh1_rdpkt_crstate;
865 int ssh2_rdpkt_crstate;
866 int ssh2_bare_rdpkt_crstate;
867 int ssh_gotdata_crstate;
868 int do_ssh1_connection_crstate;
870 void *do_ssh_init_state;
871 void *do_ssh1_login_state;
872 void *do_ssh2_transport_state;
873 void *do_ssh2_authconn_state;
874 void *do_ssh_connection_init_state;
876 struct rdpkt1_state_tag rdpkt1_state;
877 struct rdpkt2_state_tag rdpkt2_state;
878 struct rdpkt2_bare_state_tag rdpkt2_bare_state;
880 /* SSH-1 and SSH-2 use this for different things, but both use it */
881 int protocol_initial_phase_done;
883 void (*protocol) (Ssh ssh, const void *vin, int inlen,
885 struct Packet *(*s_rdpkt) (Ssh ssh, const unsigned char **data,
887 int (*do_ssh_init)(Ssh ssh, unsigned char c);
890 * We maintain our own copy of a Conf structure here. That way,
891 * when we're passed a new one for reconfiguration, we can check
892 * the differences and potentially reconfigure port forwardings
893 * etc in mid-session.
898 * Values cached out of conf so as to avoid the tree234 lookup
899 * cost every time they're used.
904 * Dynamically allocated username string created during SSH
905 * login. Stored in here rather than in the coroutine state so
906 * that it'll be reliably freed if we shut down the SSH session
907 * at some unexpected moment.
912 * Used to transfer data back from async callbacks.
914 void *agent_response;
915 int agent_response_len;
919 * The SSH connection can be set as `frozen', meaning we are
920 * not currently accepting incoming data from the network. This
921 * is slightly more serious than setting the _socket_ as
922 * frozen, because we may already have had data passed to us
923 * from the network which we need to delay processing until
924 * after the freeze is lifted, so we also need a bufchain to
928 bufchain queued_incoming_data;
931 * Dispatch table for packet types that we may have to deal
934 handler_fn_t packet_dispatch[256];
937 * Queues of one-off handler functions for success/failure
938 * indications from a request.
940 struct queued_handler *qhead, *qtail;
941 handler_fn_t q_saved_handler1, q_saved_handler2;
944 * This module deals with sending keepalives.
949 * Track incoming and outgoing data sizes and time, for
952 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
953 unsigned long max_data_size;
955 unsigned long next_rekey, last_rekey;
956 const char *deferred_rekey_reason;
959 * Fully qualified host name, which we need if doing GSSAPI.
965 * GSSAPI libraries for this session.
967 struct ssh_gss_liblist *gsslibs;
971 * The last list returned from get_specials.
973 struct telnet_special *specials;
976 * List of host key algorithms for which we _don't_ have a stored
977 * host key. These are indices into the main hostkey_algs[] array
979 int uncert_hostkeys[lenof(hostkey_algs)];
980 int n_uncert_hostkeys;
983 * Flag indicating that the current rekey is intended to finish
984 * with a newly cross-certified host key.
986 int cross_certifying;
989 * Any asynchronous query to our SSH agent that we might have in
990 * flight from the main authentication loop. (Queries from
991 * agent-forwarding channels live in their channel structure.)
993 agent_pending_query *auth_agent_query;
996 static const char *ssh_pkt_type(Ssh ssh, int type)
998 if (ssh->version == 1)
999 return ssh1_pkt_type(type);
1001 return ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, type);
1004 #define logevent(s) logevent(ssh->frontend, s)
1006 /* logevent, only printf-formatted. */
1007 static void logeventf(Ssh ssh, const char *fmt, ...)
1013 buf = dupvprintf(fmt, ap);
1019 static void bomb_out(Ssh ssh, char *text)
1021 ssh_do_close(ssh, FALSE);
1023 connection_fatal(ssh->frontend, "%s", text);
1027 #define bombout(msg) bomb_out(ssh, dupprintf msg)
1029 /* Helper function for common bits of parsing ttymodes. */
1030 static void parse_ttymodes(Ssh ssh,
1031 void (*do_mode)(void *data,
1032 const struct ssh_ttymode *mode,
1037 const struct ssh_ttymode *mode;
1039 char default_val[2];
1041 strcpy(default_val, "A");
1043 for (i = 0; i < lenof(ssh_ttymodes); i++) {
1044 mode = ssh_ttymodes + i;
1045 val = conf_get_str_str_opt(ssh->conf, CONF_ttymodes, mode->mode);
1050 * val[0] is either 'V', indicating that an explicit value
1051 * follows it, or 'A' indicating that we should pass the
1052 * value through from the local environment via get_ttymode.
1054 if (val[0] == 'A') {
1055 val = get_ttymode(ssh->frontend, mode->mode);
1057 do_mode(data, mode, val);
1061 do_mode(data, mode, val + 1); /* skip the 'V' */
1065 static int ssh_channelcmp(void *av, void *bv)
1067 struct ssh_channel *a = (struct ssh_channel *) av;
1068 struct ssh_channel *b = (struct ssh_channel *) bv;
1069 if (a->localid < b->localid)
1071 if (a->localid > b->localid)
1075 static int ssh_channelfind(void *av, void *bv)
1077 unsigned *a = (unsigned *) av;
1078 struct ssh_channel *b = (struct ssh_channel *) bv;
1079 if (*a < b->localid)
1081 if (*a > b->localid)
1086 static int ssh_rportcmp_ssh1(void *av, void *bv)
1088 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1089 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1091 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
1092 return i < 0 ? -1 : +1;
1093 if (a->dport > b->dport)
1095 if (a->dport < b->dport)
1100 static int ssh_rportcmp_ssh2(void *av, void *bv)
1102 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1103 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1105 if ( (i = strcmp(a->shost, b->shost)) != 0)
1106 return i < 0 ? -1 : +1;
1107 if (a->sport > b->sport)
1109 if (a->sport < b->sport)
1115 * Special form of strcmp which can cope with NULL inputs. NULL is
1116 * defined to sort before even the empty string.
1118 static int nullstrcmp(const char *a, const char *b)
1120 if (a == NULL && b == NULL)
1126 return strcmp(a, b);
1129 static int ssh_portcmp(void *av, void *bv)
1131 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1132 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1134 if (a->type > b->type)
1136 if (a->type < b->type)
1138 if (a->addressfamily > b->addressfamily)
1140 if (a->addressfamily < b->addressfamily)
1142 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1143 return i < 0 ? -1 : +1;
1144 if (a->sport > b->sport)
1146 if (a->sport < b->sport)
1148 if (a->type != 'D') {
1149 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1150 return i < 0 ? -1 : +1;
1151 if (a->dport > b->dport)
1153 if (a->dport < b->dport)
1159 static int alloc_channel_id(Ssh ssh)
1161 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1162 unsigned low, high, mid;
1164 struct ssh_channel *c;
1167 * First-fit allocation of channel numbers: always pick the
1168 * lowest unused one. To do this, binary-search using the
1169 * counted B-tree to find the largest channel ID which is in a
1170 * contiguous sequence from the beginning. (Precisely
1171 * everything in that sequence must have ID equal to its tree
1172 * index plus CHANNEL_NUMBER_OFFSET.)
1174 tsize = count234(ssh->channels);
1178 while (high - low > 1) {
1179 mid = (high + low) / 2;
1180 c = index234(ssh->channels, mid);
1181 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1182 low = mid; /* this one is fine */
1184 high = mid; /* this one is past it */
1187 * Now low points to either -1, or the tree index of the
1188 * largest ID in the initial sequence.
1191 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1192 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1194 return low + 1 + CHANNEL_NUMBER_OFFSET;
1197 static void c_write_stderr(int trusted, const char *buf, int len)
1200 for (i = 0; i < len; i++)
1201 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1202 fputc(buf[i], stderr);
1205 static void c_write(Ssh ssh, const char *buf, int len)
1207 if (flags & FLAG_STDERR)
1208 c_write_stderr(1, buf, len);
1210 from_backend(ssh->frontend, 1, buf, len);
1213 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1215 if (flags & FLAG_STDERR)
1216 c_write_stderr(0, buf, len);
1218 from_backend_untrusted(ssh->frontend, buf, len);
1221 static void c_write_str(Ssh ssh, const char *buf)
1223 c_write(ssh, buf, strlen(buf));
1226 static void ssh_free_packet(struct Packet *pkt)
1231 static struct Packet *ssh_new_packet(void)
1233 struct Packet *pkt = snew(struct Packet);
1235 pkt->body = pkt->data = NULL;
1241 static void ssh1_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1244 struct logblank_t blanks[4];
1250 if (ssh->logomitdata &&
1251 (pkt->type == SSH1_SMSG_STDOUT_DATA ||
1252 pkt->type == SSH1_SMSG_STDERR_DATA ||
1253 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1254 /* "Session data" packets - omit the data string. */
1255 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1256 ssh_pkt_getuint32(pkt); /* skip channel id */
1257 blanks[nblanks].offset = pkt->savedpos + 4;
1258 blanks[nblanks].type = PKTLOG_OMIT;
1259 ssh_pkt_getstring(pkt, &str, &slen);
1261 blanks[nblanks].len = slen;
1265 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1266 ssh1_pkt_type(pkt->type),
1267 pkt->body, pkt->length, nblanks, blanks, NULL,
1271 static void ssh1_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1274 struct logblank_t blanks[4];
1279 * For outgoing packets, pkt->length represents the length of the
1280 * whole packet starting at pkt->data (including some header), and
1281 * pkt->body refers to the point within that where the log-worthy
1282 * payload begins. However, incoming packets expect pkt->length to
1283 * represent only the payload length (that is, it's measured from
1284 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1285 * packet to conform to the incoming-packet semantics, so that we
1286 * can analyse it with the ssh_pkt_get functions.
1288 pkt->length -= (pkt->body - pkt->data);
1291 if (ssh->logomitdata &&
1292 (pkt->type == SSH1_CMSG_STDIN_DATA ||
1293 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1294 /* "Session data" packets - omit the data string. */
1295 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1296 ssh_pkt_getuint32(pkt); /* skip channel id */
1297 blanks[nblanks].offset = pkt->savedpos + 4;
1298 blanks[nblanks].type = PKTLOG_OMIT;
1299 ssh_pkt_getstring(pkt, &str, &slen);
1301 blanks[nblanks].len = slen;
1306 if ((pkt->type == SSH1_CMSG_AUTH_PASSWORD ||
1307 pkt->type == SSH1_CMSG_AUTH_TIS_RESPONSE ||
1308 pkt->type == SSH1_CMSG_AUTH_CCARD_RESPONSE) &&
1309 conf_get_int(ssh->conf, CONF_logomitpass)) {
1310 /* If this is a password or similar packet, blank the password(s). */
1311 blanks[nblanks].offset = 0;
1312 blanks[nblanks].len = pkt->length;
1313 blanks[nblanks].type = PKTLOG_BLANK;
1315 } else if (pkt->type == SSH1_CMSG_X11_REQUEST_FORWARDING &&
1316 conf_get_int(ssh->conf, CONF_logomitpass)) {
1318 * If this is an X forwarding request packet, blank the fake
1321 * Note that while we blank the X authentication data here, we
1322 * don't take any special action to blank the start of an X11
1323 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1324 * an X connection without having session blanking enabled is
1325 * likely to leak your cookie into the log.
1328 ssh_pkt_getstring(pkt, &str, &slen);
1329 blanks[nblanks].offset = pkt->savedpos;
1330 blanks[nblanks].type = PKTLOG_BLANK;
1331 ssh_pkt_getstring(pkt, &str, &slen);
1333 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1338 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1339 ssh1_pkt_type(pkt->data[12]),
1340 pkt->body, pkt->length,
1341 nblanks, blanks, NULL, 0, NULL);
1344 * Undo the above adjustment of pkt->length, to put the packet
1345 * back in the state we found it.
1347 pkt->length += (pkt->body - pkt->data);
1351 * Collect incoming data in the incoming packet buffer.
1352 * Decipher and verify the packet when it is completely read.
1353 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1354 * Update the *data and *datalen variables.
1355 * Return a Packet structure when a packet is completed.
1357 static struct Packet *ssh1_rdpkt(Ssh ssh, const unsigned char **data,
1360 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1362 crBegin(ssh->ssh1_rdpkt_crstate);
1364 st->pktin = ssh_new_packet();
1366 st->pktin->type = 0;
1367 st->pktin->length = 0;
1369 for (st->i = st->len = 0; st->i < 4; st->i++) {
1370 while ((*datalen) == 0)
1372 st->len = (st->len << 8) + **data;
1373 (*data)++, (*datalen)--;
1376 st->pad = 8 - (st->len % 8);
1377 st->biglen = st->len + st->pad;
1378 st->pktin->length = st->len - 5;
1380 if (st->biglen < 0) {
1381 bombout(("Extremely large packet length from server suggests"
1382 " data stream corruption"));
1383 ssh_free_packet(st->pktin);
1387 st->pktin->maxlen = st->biglen;
1388 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1390 st->to_read = st->biglen;
1391 st->p = st->pktin->data;
1392 while (st->to_read > 0) {
1393 st->chunk = st->to_read;
1394 while ((*datalen) == 0)
1396 if (st->chunk > (*datalen))
1397 st->chunk = (*datalen);
1398 memcpy(st->p, *data, st->chunk);
1400 *datalen -= st->chunk;
1402 st->to_read -= st->chunk;
1405 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1406 st->biglen, NULL)) {
1407 bombout(("Network attack (CRC compensation) detected!"));
1408 ssh_free_packet(st->pktin);
1413 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1415 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1416 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1417 if (st->gotcrc != st->realcrc) {
1418 bombout(("Incorrect CRC received on packet"));
1419 ssh_free_packet(st->pktin);
1423 st->pktin->body = st->pktin->data + st->pad + 1;
1425 if (ssh->v1_compressing) {
1426 unsigned char *decompblk;
1428 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1429 st->pktin->body - 1, st->pktin->length + 1,
1430 &decompblk, &decomplen)) {
1431 bombout(("Zlib decompression encountered invalid data"));
1432 ssh_free_packet(st->pktin);
1436 if (st->pktin->maxlen < st->pad + decomplen) {
1437 st->pktin->maxlen = st->pad + decomplen;
1438 st->pktin->data = sresize(st->pktin->data,
1439 st->pktin->maxlen + APIEXTRA,
1441 st->pktin->body = st->pktin->data + st->pad + 1;
1444 memcpy(st->pktin->body - 1, decompblk, decomplen);
1446 st->pktin->length = decomplen - 1;
1449 st->pktin->type = st->pktin->body[-1];
1452 * Now pktin->body and pktin->length identify the semantic content
1453 * of the packet, excluding the initial type byte.
1457 ssh1_log_incoming_packet(ssh, st->pktin);
1459 st->pktin->savedpos = 0;
1461 crFinish(st->pktin);
1464 static void ssh2_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1467 struct logblank_t blanks[4];
1473 if (ssh->logomitdata &&
1474 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1475 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1476 /* "Session data" packets - omit the data string. */
1477 ssh_pkt_getuint32(pkt); /* skip channel id */
1478 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1479 ssh_pkt_getuint32(pkt); /* skip extended data type */
1480 blanks[nblanks].offset = pkt->savedpos + 4;
1481 blanks[nblanks].type = PKTLOG_OMIT;
1482 ssh_pkt_getstring(pkt, &str, &slen);
1484 blanks[nblanks].len = slen;
1489 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1490 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->type),
1491 pkt->body, pkt->length, nblanks, blanks, &pkt->sequence,
1495 static void ssh2_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1498 struct logblank_t blanks[4];
1503 * For outgoing packets, pkt->length represents the length of the
1504 * whole packet starting at pkt->data (including some header), and
1505 * pkt->body refers to the point within that where the log-worthy
1506 * payload begins. However, incoming packets expect pkt->length to
1507 * represent only the payload length (that is, it's measured from
1508 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1509 * packet to conform to the incoming-packet semantics, so that we
1510 * can analyse it with the ssh_pkt_get functions.
1512 pkt->length -= (pkt->body - pkt->data);
1515 if (ssh->logomitdata &&
1516 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1517 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1518 /* "Session data" packets - omit the data string. */
1519 ssh_pkt_getuint32(pkt); /* skip channel id */
1520 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1521 ssh_pkt_getuint32(pkt); /* skip extended data type */
1522 blanks[nblanks].offset = pkt->savedpos + 4;
1523 blanks[nblanks].type = PKTLOG_OMIT;
1524 ssh_pkt_getstring(pkt, &str, &slen);
1526 blanks[nblanks].len = slen;
1531 if (pkt->type == SSH2_MSG_USERAUTH_REQUEST &&
1532 conf_get_int(ssh->conf, CONF_logomitpass)) {
1533 /* If this is a password packet, blank the password(s). */
1535 ssh_pkt_getstring(pkt, &str, &slen);
1536 ssh_pkt_getstring(pkt, &str, &slen);
1537 ssh_pkt_getstring(pkt, &str, &slen);
1538 if (slen == 8 && !memcmp(str, "password", 8)) {
1539 ssh2_pkt_getbool(pkt);
1540 /* Blank the password field. */
1541 blanks[nblanks].offset = pkt->savedpos;
1542 blanks[nblanks].type = PKTLOG_BLANK;
1543 ssh_pkt_getstring(pkt, &str, &slen);
1545 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1547 /* If there's another password field beyond it (change of
1548 * password), blank that too. */
1549 ssh_pkt_getstring(pkt, &str, &slen);
1551 blanks[nblanks-1].len =
1552 pkt->savedpos - blanks[nblanks].offset;
1555 } else if (ssh->pkt_actx == SSH2_PKTCTX_KBDINTER &&
1556 pkt->type == SSH2_MSG_USERAUTH_INFO_RESPONSE &&
1557 conf_get_int(ssh->conf, CONF_logomitpass)) {
1558 /* If this is a keyboard-interactive response packet, blank
1561 ssh_pkt_getuint32(pkt);
1562 blanks[nblanks].offset = pkt->savedpos;
1563 blanks[nblanks].type = PKTLOG_BLANK;
1565 ssh_pkt_getstring(pkt, &str, &slen);
1569 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1571 } else if (pkt->type == SSH2_MSG_CHANNEL_REQUEST &&
1572 conf_get_int(ssh->conf, CONF_logomitpass)) {
1574 * If this is an X forwarding request packet, blank the fake
1577 * Note that while we blank the X authentication data here, we
1578 * don't take any special action to blank the start of an X11
1579 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1580 * an X connection without having session blanking enabled is
1581 * likely to leak your cookie into the log.
1584 ssh_pkt_getuint32(pkt);
1585 ssh_pkt_getstring(pkt, &str, &slen);
1586 if (slen == 7 && !memcmp(str, "x11-req", 0)) {
1587 ssh2_pkt_getbool(pkt);
1588 ssh2_pkt_getbool(pkt);
1589 ssh_pkt_getstring(pkt, &str, &slen);
1590 blanks[nblanks].offset = pkt->savedpos;
1591 blanks[nblanks].type = PKTLOG_BLANK;
1592 ssh_pkt_getstring(pkt, &str, &slen);
1594 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1600 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1601 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1602 pkt->body, pkt->length, nblanks, blanks,
1603 &ssh->v2_outgoing_sequence,
1604 pkt->downstream_id, pkt->additional_log_text);
1607 * Undo the above adjustment of pkt->length, to put the packet
1608 * back in the state we found it.
1610 pkt->length += (pkt->body - pkt->data);
1613 static struct Packet *ssh2_rdpkt(Ssh ssh, const unsigned char **data,
1616 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1618 crBegin(ssh->ssh2_rdpkt_crstate);
1620 st->pktin = ssh_new_packet();
1622 st->pktin->type = 0;
1623 st->pktin->length = 0;
1625 st->cipherblk = ssh->sccipher->blksize;
1628 if (st->cipherblk < 8)
1630 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1632 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1633 ssh->scmac && !ssh->scmac_etm) {
1635 * When dealing with a CBC-mode cipher, we want to avoid the
1636 * possibility of an attacker's tweaking the ciphertext stream
1637 * so as to cause us to feed the same block to the block
1638 * cipher more than once and thus leak information
1639 * (VU#958563). The way we do this is not to take any
1640 * decisions on the basis of anything we've decrypted until
1641 * we've verified it with a MAC. That includes the packet
1642 * length, so we just read data and check the MAC repeatedly,
1643 * and when the MAC passes, see if the length we've got is
1646 * This defence is unnecessary in OpenSSH ETM mode, because
1647 * the whole point of ETM mode is that the attacker can't
1648 * tweak the ciphertext stream at all without the MAC
1649 * detecting it before we decrypt anything.
1652 /* May as well allocate the whole lot now. */
1653 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1656 /* Read an amount corresponding to the MAC. */
1657 for (st->i = 0; st->i < st->maclen; st->i++) {
1658 while ((*datalen) == 0)
1660 st->pktin->data[st->i] = *(*data)++;
1666 unsigned char seq[4];
1667 ssh->scmac->start(ssh->sc_mac_ctx);
1668 PUT_32BIT(seq, st->incoming_sequence);
1669 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1672 for (;;) { /* Once around this loop per cipher block. */
1673 /* Read another cipher-block's worth, and tack it onto the end. */
1674 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1675 while ((*datalen) == 0)
1677 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1680 /* Decrypt one more block (a little further back in the stream). */
1681 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1682 st->pktin->data + st->packetlen,
1684 /* Feed that block to the MAC. */
1685 ssh->scmac->bytes(ssh->sc_mac_ctx,
1686 st->pktin->data + st->packetlen, st->cipherblk);
1687 st->packetlen += st->cipherblk;
1688 /* See if that gives us a valid packet. */
1689 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1690 st->pktin->data + st->packetlen) &&
1691 ((st->len = toint(GET_32BIT(st->pktin->data))) ==
1694 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1695 bombout(("No valid incoming packet found"));
1696 ssh_free_packet(st->pktin);
1700 st->pktin->maxlen = st->packetlen + st->maclen;
1701 st->pktin->data = sresize(st->pktin->data,
1702 st->pktin->maxlen + APIEXTRA,
1704 } else if (ssh->scmac && ssh->scmac_etm) {
1705 st->pktin->data = snewn(4 + APIEXTRA, unsigned char);
1708 * OpenSSH encrypt-then-MAC mode: the packet length is
1709 * unencrypted, unless the cipher supports length encryption.
1711 for (st->i = st->len = 0; st->i < 4; st->i++) {
1712 while ((*datalen) == 0)
1714 st->pktin->data[st->i] = *(*data)++;
1717 /* Cipher supports length decryption, so do it */
1718 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_SEPARATE_LENGTH)) {
1719 /* Keep the packet the same though, so the MAC passes */
1720 unsigned char len[4];
1721 memcpy(len, st->pktin->data, 4);
1722 ssh->sccipher->decrypt_length(ssh->sc_cipher_ctx, len, 4, st->incoming_sequence);
1723 st->len = toint(GET_32BIT(len));
1725 st->len = toint(GET_32BIT(st->pktin->data));
1729 * _Completely_ silly lengths should be stomped on before they
1730 * do us any more damage.
1732 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1733 st->len % st->cipherblk != 0) {
1734 bombout(("Incoming packet length field was garbled"));
1735 ssh_free_packet(st->pktin);
1740 * So now we can work out the total packet length.
1742 st->packetlen = st->len + 4;
1745 * Allocate memory for the rest of the packet.
1747 st->pktin->maxlen = st->packetlen + st->maclen;
1748 st->pktin->data = sresize(st->pktin->data,
1749 st->pktin->maxlen + APIEXTRA,
1753 * Read the remainder of the packet.
1755 for (st->i = 4; st->i < st->packetlen + st->maclen; st->i++) {
1756 while ((*datalen) == 0)
1758 st->pktin->data[st->i] = *(*data)++;
1766 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1767 st->len + 4, st->incoming_sequence)) {
1768 bombout(("Incorrect MAC received on packet"));
1769 ssh_free_packet(st->pktin);
1773 /* Decrypt everything between the length field and the MAC. */
1775 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1776 st->pktin->data + 4,
1779 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1782 * Acquire and decrypt the first block of the packet. This will
1783 * contain the length and padding details.
1785 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1786 while ((*datalen) == 0)
1788 st->pktin->data[st->i] = *(*data)++;
1793 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1794 st->pktin->data, st->cipherblk);
1797 * Now get the length figure.
1799 st->len = toint(GET_32BIT(st->pktin->data));
1802 * _Completely_ silly lengths should be stomped on before they
1803 * do us any more damage.
1805 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1806 (st->len + 4) % st->cipherblk != 0) {
1807 bombout(("Incoming packet was garbled on decryption"));
1808 ssh_free_packet(st->pktin);
1813 * So now we can work out the total packet length.
1815 st->packetlen = st->len + 4;
1818 * Allocate memory for the rest of the packet.
1820 st->pktin->maxlen = st->packetlen + st->maclen;
1821 st->pktin->data = sresize(st->pktin->data,
1822 st->pktin->maxlen + APIEXTRA,
1826 * Read and decrypt the remainder of the packet.
1828 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1830 while ((*datalen) == 0)
1832 st->pktin->data[st->i] = *(*data)++;
1835 /* Decrypt everything _except_ the MAC. */
1837 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1838 st->pktin->data + st->cipherblk,
1839 st->packetlen - st->cipherblk);
1845 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1846 st->len + 4, st->incoming_sequence)) {
1847 bombout(("Incorrect MAC received on packet"));
1848 ssh_free_packet(st->pktin);
1852 /* Get and sanity-check the amount of random padding. */
1853 st->pad = st->pktin->data[4];
1854 if (st->pad < 4 || st->len - st->pad < 1) {
1855 bombout(("Invalid padding length on received packet"));
1856 ssh_free_packet(st->pktin);
1860 * This enables us to deduce the payload length.
1862 st->payload = st->len - st->pad - 1;
1864 st->pktin->length = st->payload + 5;
1865 st->pktin->encrypted_len = st->packetlen;
1867 st->pktin->sequence = st->incoming_sequence++;
1869 st->pktin->length = st->packetlen - st->pad;
1870 assert(st->pktin->length >= 0);
1873 * Decompress packet payload.
1876 unsigned char *newpayload;
1879 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1880 st->pktin->data + 5, st->pktin->length - 5,
1881 &newpayload, &newlen)) {
1882 if (st->pktin->maxlen < newlen + 5) {
1883 st->pktin->maxlen = newlen + 5;
1884 st->pktin->data = sresize(st->pktin->data,
1885 st->pktin->maxlen + APIEXTRA,
1888 st->pktin->length = 5 + newlen;
1889 memcpy(st->pktin->data + 5, newpayload, newlen);
1895 * RFC 4253 doesn't explicitly say that completely empty packets
1896 * with no type byte are forbidden, so treat them as deserving
1897 * an SSH_MSG_UNIMPLEMENTED.
1899 if (st->pktin->length <= 5) { /* == 5 we hope, but robustness */
1900 ssh2_msg_something_unimplemented(ssh, st->pktin);
1904 * pktin->body and pktin->length should identify the semantic
1905 * content of the packet, excluding the initial type byte.
1907 st->pktin->type = st->pktin->data[5];
1908 st->pktin->body = st->pktin->data + 6;
1909 st->pktin->length -= 6;
1910 assert(st->pktin->length >= 0); /* one last double-check */
1913 ssh2_log_incoming_packet(ssh, st->pktin);
1915 st->pktin->savedpos = 0;
1917 crFinish(st->pktin);
1920 static struct Packet *ssh2_bare_connection_rdpkt(Ssh ssh,
1921 const unsigned char **data,
1924 struct rdpkt2_bare_state_tag *st = &ssh->rdpkt2_bare_state;
1926 crBegin(ssh->ssh2_bare_rdpkt_crstate);
1929 * Read the packet length field.
1931 for (st->i = 0; st->i < 4; st->i++) {
1932 while ((*datalen) == 0)
1934 st->length[st->i] = *(*data)++;
1938 st->packetlen = toint(GET_32BIT_MSB_FIRST(st->length));
1939 if (st->packetlen <= 0 || st->packetlen >= OUR_V2_PACKETLIMIT) {
1940 bombout(("Invalid packet length received"));
1944 st->pktin = ssh_new_packet();
1945 st->pktin->data = snewn(st->packetlen, unsigned char);
1947 st->pktin->encrypted_len = st->packetlen;
1949 st->pktin->sequence = st->incoming_sequence++;
1952 * Read the remainder of the packet.
1954 for (st->i = 0; st->i < st->packetlen; st->i++) {
1955 while ((*datalen) == 0)
1957 st->pktin->data[st->i] = *(*data)++;
1962 * pktin->body and pktin->length should identify the semantic
1963 * content of the packet, excluding the initial type byte.
1965 st->pktin->type = st->pktin->data[0];
1966 st->pktin->body = st->pktin->data + 1;
1967 st->pktin->length = st->packetlen - 1;
1970 * Log incoming packet, possibly omitting sensitive fields.
1973 ssh2_log_incoming_packet(ssh, st->pktin);
1975 st->pktin->savedpos = 0;
1977 crFinish(st->pktin);
1980 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1982 int pad, biglen, i, pktoffs;
1986 * XXX various versions of SC (including 8.8.4) screw up the
1987 * register allocation in this function and use the same register
1988 * (D6) for len and as a temporary, with predictable results. The
1989 * following sledgehammer prevents this.
1996 ssh1_log_outgoing_packet(ssh, pkt);
1998 if (ssh->v1_compressing) {
1999 unsigned char *compblk;
2001 zlib_compress_block(ssh->cs_comp_ctx,
2002 pkt->data + 12, pkt->length - 12,
2003 &compblk, &complen);
2004 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
2005 memcpy(pkt->data + 12, compblk, complen);
2007 pkt->length = complen + 12;
2010 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
2012 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
2013 pad = 8 - (len % 8);
2015 biglen = len + pad; /* len(padding+type+data+CRC) */
2017 for (i = pktoffs; i < 4+8; i++)
2018 pkt->data[i] = random_byte();
2019 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
2020 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
2021 PUT_32BIT(pkt->data + pktoffs, len);
2024 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
2025 pkt->data + pktoffs + 4, biglen);
2027 if (offset_p) *offset_p = pktoffs;
2028 return biglen + 4; /* len(length+padding+type+data+CRC) */
2031 static int s_write(Ssh ssh, void *data, int len)
2034 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
2035 0, NULL, NULL, 0, NULL);
2038 return sk_write(ssh->s, (char *)data, len);
2041 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
2043 int len, backlog, offset;
2044 len = s_wrpkt_prepare(ssh, pkt, &offset);
2045 backlog = s_write(ssh, pkt->data + offset, len);
2046 if (backlog > SSH_MAX_BACKLOG)
2047 ssh_throttle_all(ssh, 1, backlog);
2048 ssh_free_packet(pkt);
2051 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
2054 len = s_wrpkt_prepare(ssh, pkt, &offset);
2055 if (ssh->deferred_len + len > ssh->deferred_size) {
2056 ssh->deferred_size = ssh->deferred_len + len + 128;
2057 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2061 memcpy(ssh->deferred_send_data + ssh->deferred_len,
2062 pkt->data + offset, len);
2063 ssh->deferred_len += len;
2064 ssh_free_packet(pkt);
2068 * Construct a SSH-1 packet with the specified contents.
2069 * (This all-at-once interface used to be the only one, but now SSH-1
2070 * packets can also be constructed incrementally.)
2072 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
2078 pkt = ssh1_pkt_init(pkttype);
2080 while ((argtype = va_arg(ap, int)) != PKT_END) {
2081 unsigned char *argp, argchar;
2083 unsigned long argint;
2086 /* Actual fields in the packet */
2088 argint = va_arg(ap, int);
2089 ssh_pkt_adduint32(pkt, argint);
2092 argchar = (unsigned char) va_arg(ap, int);
2093 ssh_pkt_addbyte(pkt, argchar);
2096 argp = va_arg(ap, unsigned char *);
2097 arglen = va_arg(ap, int);
2098 ssh_pkt_adddata(pkt, argp, arglen);
2101 sargp = va_arg(ap, char *);
2102 ssh_pkt_addstring(pkt, sargp);
2105 bn = va_arg(ap, Bignum);
2106 ssh1_pkt_addmp(pkt, bn);
2114 static void send_packet(Ssh ssh, int pkttype, ...)
2118 va_start(ap, pkttype);
2119 pkt = construct_packet(ssh, pkttype, ap);
2124 static void defer_packet(Ssh ssh, int pkttype, ...)
2128 va_start(ap, pkttype);
2129 pkt = construct_packet(ssh, pkttype, ap);
2131 s_wrpkt_defer(ssh, pkt);
2134 static int ssh_versioncmp(const char *a, const char *b)
2137 unsigned long av, bv;
2139 av = strtoul(a, &ae, 10);
2140 bv = strtoul(b, &be, 10);
2142 return (av < bv ? -1 : +1);
2147 av = strtoul(ae, &ae, 10);
2148 bv = strtoul(be, &be, 10);
2150 return (av < bv ? -1 : +1);
2155 * Utility routines for putting an SSH-protocol `string' and
2156 * `uint32' into a hash state.
2158 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
2160 unsigned char lenblk[4];
2161 PUT_32BIT(lenblk, len);
2162 h->bytes(s, lenblk, 4);
2163 h->bytes(s, str, len);
2166 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
2168 unsigned char intblk[4];
2169 PUT_32BIT(intblk, i);
2170 h->bytes(s, intblk, 4);
2174 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
2176 static void ssh_pkt_ensure(struct Packet *pkt, int length)
2178 if (pkt->maxlen < length) {
2179 unsigned char *body = pkt->body;
2180 int offset = body ? body - pkt->data : 0;
2181 pkt->maxlen = length + 256;
2182 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
2183 if (body) pkt->body = pkt->data + offset;
2186 static void ssh_pkt_adddata(struct Packet *pkt, const void *data, int len)
2189 ssh_pkt_ensure(pkt, pkt->length);
2190 memcpy(pkt->data + pkt->length - len, data, len);
2192 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
2194 ssh_pkt_adddata(pkt, &byte, 1);
2196 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
2198 ssh_pkt_adddata(pkt, &value, 1);
2200 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
2203 PUT_32BIT(x, value);
2204 ssh_pkt_adddata(pkt, x, 4);
2206 static void ssh_pkt_addstring_start(struct Packet *pkt)
2208 ssh_pkt_adduint32(pkt, 0);
2209 pkt->savedpos = pkt->length;
2211 static void ssh_pkt_addstring_data(struct Packet *pkt, const char *data,
2214 ssh_pkt_adddata(pkt, data, len);
2215 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
2217 static void ssh_pkt_addstring_str(struct Packet *pkt, const char *data)
2219 ssh_pkt_addstring_data(pkt, data, strlen(data));
2221 static void ssh_pkt_addstring(struct Packet *pkt, const char *data)
2223 ssh_pkt_addstring_start(pkt);
2224 ssh_pkt_addstring_str(pkt, data);
2226 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
2228 int len = ssh1_bignum_length(b);
2229 unsigned char *data = snewn(len, unsigned char);
2230 (void) ssh1_write_bignum(data, b);
2231 ssh_pkt_adddata(pkt, data, len);
2234 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
2237 int i, n = (bignum_bitcount(b) + 7) / 8;
2238 p = snewn(n + 1, unsigned char);
2240 for (i = 1; i <= n; i++)
2241 p[i] = bignum_byte(b, n - i);
2243 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
2245 memmove(p, p + i, n + 1 - i);
2249 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
2253 p = ssh2_mpint_fmt(b, &len);
2254 ssh_pkt_addstring_start(pkt);
2255 ssh_pkt_addstring_data(pkt, (char *)p, len);
2259 static struct Packet *ssh1_pkt_init(int pkt_type)
2261 struct Packet *pkt = ssh_new_packet();
2262 pkt->length = 4 + 8; /* space for length + max padding */
2263 ssh_pkt_addbyte(pkt, pkt_type);
2264 pkt->body = pkt->data + pkt->length;
2265 pkt->type = pkt_type;
2266 pkt->downstream_id = 0;
2267 pkt->additional_log_text = NULL;
2271 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
2272 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
2273 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
2274 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
2275 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
2276 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
2277 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
2278 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
2279 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
2281 static struct Packet *ssh2_pkt_init(int pkt_type)
2283 struct Packet *pkt = ssh_new_packet();
2284 pkt->length = 5; /* space for packet length + padding length */
2286 pkt->type = pkt_type;
2287 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
2288 pkt->body = pkt->data + pkt->length; /* after packet type */
2289 pkt->downstream_id = 0;
2290 pkt->additional_log_text = NULL;
2295 * Construct an SSH-2 final-form packet: compress it, encrypt it,
2296 * put the MAC on it. Final packet, ready to be sent, is stored in
2297 * pkt->data. Total length is returned.
2299 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
2301 int cipherblk, maclen, padding, unencrypted_prefix, i;
2304 ssh2_log_outgoing_packet(ssh, pkt);
2306 if (ssh->bare_connection) {
2308 * Trivial packet construction for the bare connection
2311 PUT_32BIT(pkt->data + 1, pkt->length - 5);
2312 pkt->body = pkt->data + 1;
2313 ssh->v2_outgoing_sequence++; /* only for diagnostics, really */
2314 return pkt->length - 1;
2318 * Compress packet payload.
2321 unsigned char *newpayload;
2324 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
2326 &newpayload, &newlen)) {
2328 ssh2_pkt_adddata(pkt, newpayload, newlen);
2334 * Add padding. At least four bytes, and must also bring total
2335 * length (minus MAC) up to a multiple of the block size.
2336 * If pkt->forcepad is set, make sure the packet is at least that size
2339 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
2340 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
2342 unencrypted_prefix = (ssh->csmac && ssh->csmac_etm) ? 4 : 0;
2343 if (pkt->length + padding < pkt->forcepad)
2344 padding = pkt->forcepad - pkt->length;
2346 (cipherblk - (pkt->length - unencrypted_prefix + padding) % cipherblk)
2348 assert(padding <= 255);
2349 maclen = ssh->csmac ? ssh->csmac->len : 0;
2350 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
2351 pkt->data[4] = padding;
2352 for (i = 0; i < padding; i++)
2353 pkt->data[pkt->length + i] = random_byte();
2354 PUT_32BIT(pkt->data, pkt->length + padding - 4);
2356 /* Encrypt length if the scheme requires it */
2357 if (ssh->cscipher && (ssh->cscipher->flags & SSH_CIPHER_SEPARATE_LENGTH)) {
2358 ssh->cscipher->encrypt_length(ssh->cs_cipher_ctx, pkt->data, 4,
2359 ssh->v2_outgoing_sequence);
2362 if (ssh->csmac && ssh->csmac_etm) {
2364 * OpenSSH-defined encrypt-then-MAC protocol.
2367 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2368 pkt->data + 4, pkt->length + padding - 4);
2369 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2370 pkt->length + padding,
2371 ssh->v2_outgoing_sequence);
2374 * SSH-2 standard protocol.
2377 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2378 pkt->length + padding,
2379 ssh->v2_outgoing_sequence);
2381 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2382 pkt->data, pkt->length + padding);
2385 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
2386 pkt->encrypted_len = pkt->length + padding;
2388 /* Ready-to-send packet starts at pkt->data. We return length. */
2389 pkt->body = pkt->data;
2390 return pkt->length + padding + maclen;
2394 * Routines called from the main SSH code to send packets. There
2395 * are quite a few of these, because we have two separate
2396 * mechanisms for delaying the sending of packets:
2398 * - In order to send an IGNORE message and a password message in
2399 * a single fixed-length blob, we require the ability to
2400 * concatenate the encrypted forms of those two packets _into_ a
2401 * single blob and then pass it to our <network.h> transport
2402 * layer in one go. Hence, there's a deferment mechanism which
2403 * works after packet encryption.
2405 * - In order to avoid sending any connection-layer messages
2406 * during repeat key exchange, we have to queue up any such
2407 * outgoing messages _before_ they are encrypted (and in
2408 * particular before they're allocated sequence numbers), and
2409 * then send them once we've finished.
2411 * I call these mechanisms `defer' and `queue' respectively, so as
2412 * to distinguish them reasonably easily.
2414 * The functions send_noqueue() and defer_noqueue() free the packet
2415 * structure they are passed. Every outgoing packet goes through
2416 * precisely one of these functions in its life; packets passed to
2417 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
2418 * these or get queued, and then when the queue is later emptied
2419 * the packets are all passed to defer_noqueue().
2421 * When using a CBC-mode cipher, it's necessary to ensure that an
2422 * attacker can't provide data to be encrypted using an IV that they
2423 * know. We ensure this by prefixing each packet that might contain
2424 * user data with an SSH_MSG_IGNORE. This is done using the deferral
2425 * mechanism, so in this case send_noqueue() ends up redirecting to
2426 * defer_noqueue(). If you don't like this inefficiency, don't use
2430 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
2431 static void ssh_pkt_defersend(Ssh);
2434 * Send an SSH-2 packet immediately, without queuing or deferring.
2436 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
2440 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
2441 /* We need to send two packets, so use the deferral mechanism. */
2442 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2443 ssh_pkt_defersend(ssh);
2446 len = ssh2_pkt_construct(ssh, pkt);
2447 backlog = s_write(ssh, pkt->body, len);
2448 if (backlog > SSH_MAX_BACKLOG)
2449 ssh_throttle_all(ssh, 1, backlog);
2451 ssh->outgoing_data_size += pkt->encrypted_len;
2452 if (!ssh->kex_in_progress &&
2453 !ssh->bare_connection &&
2454 ssh->max_data_size != 0 &&
2455 ssh->outgoing_data_size > ssh->max_data_size)
2456 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2458 ssh_free_packet(pkt);
2462 * Defer an SSH-2 packet.
2464 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2467 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2468 ssh->deferred_len == 0 && !noignore &&
2469 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2471 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2472 * get encrypted with a known IV.
2474 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2475 ssh2_pkt_addstring_start(ipkt);
2476 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2478 len = ssh2_pkt_construct(ssh, pkt);
2479 if (ssh->deferred_len + len > ssh->deferred_size) {
2480 ssh->deferred_size = ssh->deferred_len + len + 128;
2481 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2485 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->body, len);
2486 ssh->deferred_len += len;
2487 ssh->deferred_data_size += pkt->encrypted_len;
2488 ssh_free_packet(pkt);
2492 * Queue an SSH-2 packet.
2494 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2496 assert(ssh->queueing);
2498 if (ssh->queuelen >= ssh->queuesize) {
2499 ssh->queuesize = ssh->queuelen + 32;
2500 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2503 ssh->queue[ssh->queuelen++] = pkt;
2507 * Either queue or send a packet, depending on whether queueing is
2510 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2513 ssh2_pkt_queue(ssh, pkt);
2515 ssh2_pkt_send_noqueue(ssh, pkt);
2519 * Either queue or defer a packet, depending on whether queueing is
2522 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2525 ssh2_pkt_queue(ssh, pkt);
2527 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2531 * Send the whole deferred data block constructed by
2532 * ssh2_pkt_defer() or SSH-1's defer_packet().
2534 * The expected use of the defer mechanism is that you call
2535 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2536 * not currently queueing, this simply sets up deferred_send_data
2537 * and then sends it. If we _are_ currently queueing, the calls to
2538 * ssh2_pkt_defer() put the deferred packets on to the queue
2539 * instead, and therefore ssh_pkt_defersend() has no deferred data
2540 * to send. Hence, there's no need to make it conditional on
2543 static void ssh_pkt_defersend(Ssh ssh)
2546 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2547 ssh->deferred_len = ssh->deferred_size = 0;
2548 sfree(ssh->deferred_send_data);
2549 ssh->deferred_send_data = NULL;
2550 if (backlog > SSH_MAX_BACKLOG)
2551 ssh_throttle_all(ssh, 1, backlog);
2553 if (ssh->version == 2) {
2554 ssh->outgoing_data_size += ssh->deferred_data_size;
2555 ssh->deferred_data_size = 0;
2556 if (!ssh->kex_in_progress &&
2557 !ssh->bare_connection &&
2558 ssh->max_data_size != 0 &&
2559 ssh->outgoing_data_size > ssh->max_data_size)
2560 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2565 * Send a packet whose length needs to be disguised (typically
2566 * passwords or keyboard-interactive responses).
2568 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2574 * The simplest way to do this is to adjust the
2575 * variable-length padding field in the outgoing packet.
2577 * Currently compiled out, because some Cisco SSH servers
2578 * don't like excessively padded packets (bah, why's it
2581 pkt->forcepad = padsize;
2582 ssh2_pkt_send(ssh, pkt);
2587 * If we can't do that, however, an alternative approach is
2588 * to use the pkt_defer mechanism to bundle the packet
2589 * tightly together with an SSH_MSG_IGNORE such that their
2590 * combined length is a constant. So first we construct the
2591 * final form of this packet and defer its sending.
2593 ssh2_pkt_defer(ssh, pkt);
2596 * Now construct an SSH_MSG_IGNORE which includes a string
2597 * that's an exact multiple of the cipher block size. (If
2598 * the cipher is NULL so that the block size is
2599 * unavailable, we don't do this trick at all, because we
2600 * gain nothing by it.)
2602 if (ssh->cscipher &&
2603 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2606 stringlen = (256 - ssh->deferred_len);
2607 stringlen += ssh->cscipher->blksize - 1;
2608 stringlen -= (stringlen % ssh->cscipher->blksize);
2611 * Temporarily disable actual compression, so we
2612 * can guarantee to get this string exactly the
2613 * length we want it. The compression-disabling
2614 * routine should return an integer indicating how
2615 * many bytes we should adjust our string length
2619 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2621 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2622 ssh2_pkt_addstring_start(pkt);
2623 for (i = 0; i < stringlen; i++) {
2624 char c = (char) random_byte();
2625 ssh2_pkt_addstring_data(pkt, &c, 1);
2627 ssh2_pkt_defer(ssh, pkt);
2629 ssh_pkt_defersend(ssh);
2634 * Send all queued SSH-2 packets. We send them by means of
2635 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2636 * packets that needed to be lumped together.
2638 static void ssh2_pkt_queuesend(Ssh ssh)
2642 assert(!ssh->queueing);
2644 for (i = 0; i < ssh->queuelen; i++)
2645 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2648 ssh_pkt_defersend(ssh);
2652 void bndebug(char *string, Bignum b)
2656 p = ssh2_mpint_fmt(b, &len);
2657 debug(("%s", string));
2658 for (i = 0; i < len; i++)
2659 debug((" %02x", p[i]));
2665 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2669 p = ssh2_mpint_fmt(b, &len);
2670 hash_string(h, s, p, len);
2675 * Packet decode functions for both SSH-1 and SSH-2.
2677 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2679 unsigned long value;
2680 if (pkt->length - pkt->savedpos < 4)
2681 return 0; /* arrgh, no way to decline (FIXME?) */
2682 value = GET_32BIT(pkt->body + pkt->savedpos);
2686 static int ssh2_pkt_getbool(struct Packet *pkt)
2688 unsigned long value;
2689 if (pkt->length - pkt->savedpos < 1)
2690 return 0; /* arrgh, no way to decline (FIXME?) */
2691 value = pkt->body[pkt->savedpos] != 0;
2695 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2700 if (pkt->length - pkt->savedpos < 4)
2702 len = toint(GET_32BIT(pkt->body + pkt->savedpos));
2707 if (pkt->length - pkt->savedpos < *length)
2709 *p = (char *)(pkt->body + pkt->savedpos);
2710 pkt->savedpos += *length;
2712 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2714 if (pkt->length - pkt->savedpos < length)
2716 pkt->savedpos += length;
2717 return pkt->body + (pkt->savedpos - length);
2719 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2720 const unsigned char **keystr)
2724 j = makekey(pkt->body + pkt->savedpos,
2725 pkt->length - pkt->savedpos,
2732 assert(pkt->savedpos < pkt->length);
2736 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2741 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2742 pkt->length - pkt->savedpos, &b);
2750 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2756 ssh_pkt_getstring(pkt, &p, &length);
2761 b = bignum_from_bytes((unsigned char *)p, length);
2766 * Helper function to add an SSH-2 signature blob to a packet.
2767 * Expects to be shown the public key blob as well as the signature
2768 * blob. Normally works just like ssh2_pkt_addstring, but will
2769 * fiddle with the signature packet if necessary for
2770 * BUG_SSH2_RSA_PADDING.
2772 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2773 void *pkblob_v, int pkblob_len,
2774 void *sigblob_v, int sigblob_len)
2776 unsigned char *pkblob = (unsigned char *)pkblob_v;
2777 unsigned char *sigblob = (unsigned char *)sigblob_v;
2779 /* dmemdump(pkblob, pkblob_len); */
2780 /* dmemdump(sigblob, sigblob_len); */
2783 * See if this is in fact an ssh-rsa signature and a buggy
2784 * server; otherwise we can just do this the easy way.
2786 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) && pkblob_len > 4+7+4 &&
2787 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2788 int pos, len, siglen;
2791 * Find the byte length of the modulus.
2794 pos = 4+7; /* skip over "ssh-rsa" */
2795 len = toint(GET_32BIT(pkblob+pos)); /* get length of exponent */
2796 if (len < 0 || len > pkblob_len - pos - 4)
2798 pos += 4 + len; /* skip over exponent */
2799 if (pkblob_len - pos < 4)
2801 len = toint(GET_32BIT(pkblob+pos)); /* find length of modulus */
2802 if (len < 0 || len > pkblob_len - pos - 4)
2804 pos += 4; /* find modulus itself */
2805 while (len > 0 && pkblob[pos] == 0)
2807 /* debug(("modulus length is %d\n", len)); */
2810 * Now find the signature integer.
2812 pos = 4+7; /* skip over "ssh-rsa" */
2813 if (sigblob_len < pos+4)
2815 siglen = toint(GET_32BIT(sigblob+pos));
2816 if (siglen != sigblob_len - pos - 4)
2818 /* debug(("signature length is %d\n", siglen)); */
2820 if (len != siglen) {
2821 unsigned char newlen[4];
2822 ssh2_pkt_addstring_start(pkt);
2823 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2824 /* dmemdump(sigblob, pos); */
2825 pos += 4; /* point to start of actual sig */
2826 PUT_32BIT(newlen, len);
2827 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2828 /* dmemdump(newlen, 4); */
2830 while (len-- > siglen) {
2831 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2832 /* dmemdump(newlen, 1); */
2834 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2835 /* dmemdump(sigblob+pos, siglen); */
2839 /* Otherwise fall through and do it the easy way. We also come
2840 * here as a fallback if we discover above that the key blob
2841 * is misformatted in some way. */
2845 ssh2_pkt_addstring_start(pkt);
2846 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2850 * Examine the remote side's version string and compare it against
2851 * a list of known buggy implementations.
2853 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2855 char *imp; /* pointer to implementation part */
2857 imp += strcspn(imp, "-");
2859 imp += strcspn(imp, "-");
2862 ssh->remote_bugs = 0;
2865 * General notes on server version strings:
2866 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2867 * here -- in particular, we've heard of one that's perfectly happy
2868 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2869 * so we can't distinguish them.
2871 if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
2872 (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
2873 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2874 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2875 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2876 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2878 * These versions don't support SSH1_MSG_IGNORE, so we have
2879 * to use a different defence against password length
2882 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2883 logevent("We believe remote version has SSH-1 ignore bug");
2886 if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
2887 (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
2888 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2890 * These versions need a plain password sent; they can't
2891 * handle having a null and a random length of data after
2894 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2895 logevent("We believe remote version needs a plain SSH-1 password");
2898 if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
2899 (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
2900 (!strcmp(imp, "Cisco-1.25")))) {
2902 * These versions apparently have no clue whatever about
2903 * RSA authentication and will panic and die if they see
2904 * an AUTH_RSA message.
2906 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2907 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2910 if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
2911 (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
2912 !wc_match("* VShell", imp) &&
2913 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2914 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2915 wc_match("2.1 *", imp)))) {
2917 * These versions have the HMAC bug.
2919 ssh->remote_bugs |= BUG_SSH2_HMAC;
2920 logevent("We believe remote version has SSH-2 HMAC bug");
2923 if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
2924 (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
2925 !wc_match("* VShell", imp) &&
2926 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2928 * These versions have the key-derivation bug (failing to
2929 * include the literal shared secret in the hashes that
2930 * generate the keys).
2932 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2933 logevent("We believe remote version has SSH-2 key-derivation bug");
2936 if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
2937 (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
2938 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2939 wc_match("OpenSSH_3.[0-2]*", imp) ||
2940 wc_match("mod_sftp/0.[0-8]*", imp) ||
2941 wc_match("mod_sftp/0.9.[0-8]", imp)))) {
2943 * These versions have the SSH-2 RSA padding bug.
2945 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2946 logevent("We believe remote version has SSH-2 RSA padding bug");
2949 if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
2950 (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
2951 wc_match("OpenSSH_2.[0-2]*", imp))) {
2953 * These versions have the SSH-2 session-ID bug in
2954 * public-key authentication.
2956 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2957 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2960 if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
2961 (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
2962 (wc_match("DigiSSH_2.0", imp) ||
2963 wc_match("OpenSSH_2.[0-4]*", imp) ||
2964 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2965 wc_match("Sun_SSH_1.0", imp) ||
2966 wc_match("Sun_SSH_1.0.1", imp) ||
2967 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2968 wc_match("WeOnlyDo-*", imp)))) {
2970 * These versions have the SSH-2 rekey bug.
2972 ssh->remote_bugs |= BUG_SSH2_REKEY;
2973 logevent("We believe remote version has SSH-2 rekey bug");
2976 if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
2977 (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
2978 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2979 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2981 * This version ignores our makpkt and needs to be throttled.
2983 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2984 logevent("We believe remote version ignores SSH-2 maximum packet size");
2987 if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
2989 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2990 * none detected automatically.
2992 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2993 logevent("We believe remote version has SSH-2 ignore bug");
2996 if (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == FORCE_ON ||
2997 (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == AUTO &&
2998 (wc_match("OpenSSH_2.[235]*", imp)))) {
3000 * These versions only support the original (pre-RFC4419)
3001 * SSH-2 GEX request, and disconnect with a protocol error if
3002 * we use the newer version.
3004 ssh->remote_bugs |= BUG_SSH2_OLDGEX;
3005 logevent("We believe remote version has outdated SSH-2 GEX");
3008 if (conf_get_int(ssh->conf, CONF_sshbug_winadj) == FORCE_ON) {
3010 * Servers that don't support our winadj request for one
3011 * reason or another. Currently, none detected automatically.
3013 ssh->remote_bugs |= BUG_CHOKES_ON_WINADJ;
3014 logevent("We believe remote version has winadj bug");
3017 if (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == FORCE_ON ||
3018 (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == AUTO &&
3019 (wc_match("OpenSSH_[2-5].*", imp) ||
3020 wc_match("OpenSSH_6.[0-6]*", imp) ||
3021 wc_match("dropbear_0.[2-4][0-9]*", imp) ||
3022 wc_match("dropbear_0.5[01]*", imp)))) {
3024 * These versions have the SSH-2 channel request bug.
3025 * OpenSSH 6.7 and above do not:
3026 * https://bugzilla.mindrot.org/show_bug.cgi?id=1818
3027 * dropbear_0.52 and above do not:
3028 * https://secure.ucc.asn.au/hg/dropbear/rev/cd02449b709c
3030 ssh->remote_bugs |= BUG_SENDS_LATE_REQUEST_REPLY;
3031 logevent("We believe remote version has SSH-2 channel request bug");
3036 * The `software version' part of an SSH version string is required
3037 * to contain no spaces or minus signs.
3039 static void ssh_fix_verstring(char *str)
3041 /* Eat "<protoversion>-". */
3042 while (*str && *str != '-') str++;
3043 assert(*str == '-'); str++;
3045 /* Convert minus signs and spaces in the remaining string into
3048 if (*str == '-' || *str == ' ')
3055 * Send an appropriate SSH version string.
3057 static void ssh_send_verstring(Ssh ssh, const char *protoname, char *svers)
3061 if (ssh->version == 2) {
3063 * Construct a v2 version string.
3065 verstring = dupprintf("%s2.0-%s\015\012", protoname, sshver);
3068 * Construct a v1 version string.
3070 assert(!strcmp(protoname, "SSH-")); /* no v1 bare connection protocol */
3071 verstring = dupprintf("SSH-%s-%s\012",
3072 (ssh_versioncmp(svers, "1.5") <= 0 ?
3077 ssh_fix_verstring(verstring + strlen(protoname));
3079 /* FUZZING make PuTTY insecure, so make live use difficult. */
3083 if (ssh->version == 2) {
3086 * Record our version string.
3088 len = strcspn(verstring, "\015\012");
3089 ssh->v_c = snewn(len + 1, char);
3090 memcpy(ssh->v_c, verstring, len);
3094 logeventf(ssh, "We claim version: %.*s",
3095 strcspn(verstring, "\015\012"), verstring);
3096 s_write(ssh, verstring, strlen(verstring));
3100 static int do_ssh_init(Ssh ssh, unsigned char c)
3102 static const char protoname[] = "SSH-";
3104 struct do_ssh_init_state {
3113 crState(do_ssh_init_state);
3117 /* Search for a line beginning with the protocol name prefix in
3120 for (s->i = 0; protoname[s->i]; s->i++) {
3121 if ((char)c != protoname[s->i]) goto no;
3131 ssh->session_started = TRUE;
3133 s->vstrsize = sizeof(protoname) + 16;
3134 s->vstring = snewn(s->vstrsize, char);
3135 strcpy(s->vstring, protoname);
3136 s->vslen = strlen(protoname);
3139 if (s->vslen >= s->vstrsize - 1) {
3141 s->vstring = sresize(s->vstring, s->vstrsize, char);
3143 s->vstring[s->vslen++] = c;
3146 s->version[s->i] = '\0';
3148 } else if (s->i < sizeof(s->version) - 1)
3149 s->version[s->i++] = c;
3150 } else if (c == '\012')
3152 crReturn(1); /* get another char */
3155 ssh->agentfwd_enabled = FALSE;
3156 ssh->rdpkt2_state.incoming_sequence = 0;
3158 s->vstring[s->vslen] = 0;
3159 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3160 logeventf(ssh, "Server version: %s", s->vstring);
3161 ssh_detect_bugs(ssh, s->vstring);
3164 * Decide which SSH protocol version to support.
3167 /* Anything strictly below "2.0" means protocol 1 is supported. */
3168 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
3169 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
3170 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
3172 if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
3174 bombout(("SSH protocol version 1 required by our configuration "
3175 "but not provided by server"));
3178 } else if (conf_get_int(ssh->conf, CONF_sshprot) == 3) {
3180 bombout(("SSH protocol version 2 required by our configuration "
3181 "but server only provides (old, insecure) SSH-1"));
3185 /* No longer support values 1 or 2 for CONF_sshprot */
3186 assert(!"Unexpected value for CONF_sshprot");
3189 if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
3194 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
3196 /* Send the version string, if we haven't already */
3197 if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
3198 ssh_send_verstring(ssh, protoname, s->version);
3200 if (ssh->version == 2) {
3203 * Record their version string.
3205 len = strcspn(s->vstring, "\015\012");
3206 ssh->v_s = snewn(len + 1, char);
3207 memcpy(ssh->v_s, s->vstring, len);
3211 * Initialise SSH-2 protocol.
3213 ssh->protocol = ssh2_protocol;
3214 ssh2_protocol_setup(ssh);
3215 ssh->s_rdpkt = ssh2_rdpkt;
3218 * Initialise SSH-1 protocol.
3220 ssh->protocol = ssh1_protocol;
3221 ssh1_protocol_setup(ssh);
3222 ssh->s_rdpkt = ssh1_rdpkt;
3224 if (ssh->version == 2)
3225 do_ssh2_transport(ssh, NULL, -1, NULL);
3227 update_specials_menu(ssh->frontend);
3228 ssh->state = SSH_STATE_BEFORE_SIZE;
3229 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3236 static int do_ssh_connection_init(Ssh ssh, unsigned char c)
3239 * Ordinary SSH begins with the banner "SSH-x.y-...". This is just
3240 * the ssh-connection part, extracted and given a trivial binary
3241 * packet protocol, so we replace 'SSH-' at the start with a new
3242 * name. In proper SSH style (though of course this part of the
3243 * proper SSH protocol _isn't_ subject to this kind of
3244 * DNS-domain-based extension), we define the new name in our
3247 static const char protoname[] =
3248 "SSHCONNECTION@putty.projects.tartarus.org-";
3250 struct do_ssh_connection_init_state {
3258 crState(do_ssh_connection_init_state);
3262 /* Search for a line beginning with the protocol name prefix in
3265 for (s->i = 0; protoname[s->i]; s->i++) {
3266 if ((char)c != protoname[s->i]) goto no;
3276 s->vstrsize = sizeof(protoname) + 16;
3277 s->vstring = snewn(s->vstrsize, char);
3278 strcpy(s->vstring, protoname);
3279 s->vslen = strlen(protoname);
3282 if (s->vslen >= s->vstrsize - 1) {
3284 s->vstring = sresize(s->vstring, s->vstrsize, char);
3286 s->vstring[s->vslen++] = c;
3289 s->version[s->i] = '\0';
3291 } else if (s->i < sizeof(s->version) - 1)
3292 s->version[s->i++] = c;
3293 } else if (c == '\012')
3295 crReturn(1); /* get another char */
3298 ssh->agentfwd_enabled = FALSE;
3299 ssh->rdpkt2_bare_state.incoming_sequence = 0;
3301 s->vstring[s->vslen] = 0;
3302 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3303 logeventf(ssh, "Server version: %s", s->vstring);
3304 ssh_detect_bugs(ssh, s->vstring);
3307 * Decide which SSH protocol version to support. This is easy in
3308 * bare ssh-connection mode: only 2.0 is legal.
3310 if (ssh_versioncmp(s->version, "2.0") < 0) {
3311 bombout(("Server announces compatibility with SSH-1 in bare ssh-connection protocol"));
3314 if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
3315 bombout(("Bare ssh-connection protocol cannot be run in SSH-1-only mode"));
3321 logeventf(ssh, "Using bare ssh-connection protocol");
3323 /* Send the version string, if we haven't already */
3324 ssh_send_verstring(ssh, protoname, s->version);
3327 * Initialise bare connection protocol.
3329 ssh->protocol = ssh2_bare_connection_protocol;
3330 ssh2_bare_connection_protocol_setup(ssh);
3331 ssh->s_rdpkt = ssh2_bare_connection_rdpkt;
3333 update_specials_menu(ssh->frontend);
3334 ssh->state = SSH_STATE_BEFORE_SIZE;
3335 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3338 * Get authconn (really just conn) under way.
3340 do_ssh2_authconn(ssh, NULL, 0, NULL);
3347 static void ssh_process_incoming_data(Ssh ssh,
3348 const unsigned char **data, int *datalen)
3350 struct Packet *pktin;
3352 pktin = ssh->s_rdpkt(ssh, data, datalen);
3354 ssh->protocol(ssh, NULL, 0, pktin);
3355 ssh_free_packet(pktin);
3359 static void ssh_queue_incoming_data(Ssh ssh,
3360 const unsigned char **data, int *datalen)
3362 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
3367 static void ssh_process_queued_incoming_data(Ssh ssh)
3370 const unsigned char *data;
3373 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
3374 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
3378 while (!ssh->frozen && len > 0)
3379 ssh_process_incoming_data(ssh, &data, &len);
3382 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
3386 static void ssh_set_frozen(Ssh ssh, int frozen)
3389 sk_set_frozen(ssh->s, frozen);
3390 ssh->frozen = frozen;
3393 static void ssh_gotdata(Ssh ssh, const unsigned char *data, int datalen)
3395 /* Log raw data, if we're in that mode. */
3397 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
3398 0, NULL, NULL, 0, NULL);
3400 crBegin(ssh->ssh_gotdata_crstate);
3403 * To begin with, feed the characters one by one to the
3404 * protocol initialisation / selection function do_ssh_init().
3405 * When that returns 0, we're done with the initial greeting
3406 * exchange and can move on to packet discipline.
3409 int ret; /* need not be kept across crReturn */
3411 crReturnV; /* more data please */
3412 ret = ssh->do_ssh_init(ssh, *data);
3420 * We emerge from that loop when the initial negotiation is
3421 * over and we have selected an s_rdpkt function. Now pass
3422 * everything to s_rdpkt, and then pass the resulting packets
3423 * to the proper protocol handler.
3427 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
3429 ssh_queue_incoming_data(ssh, &data, &datalen);
3430 /* This uses up all data and cannot cause anything interesting
3431 * to happen; indeed, for anything to happen at all, we must
3432 * return, so break out. */
3434 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
3435 /* This uses up some or all data, and may freeze the
3437 ssh_process_queued_incoming_data(ssh);
3439 /* This uses up some or all data, and may freeze the
3441 ssh_process_incoming_data(ssh, &data, &datalen);
3443 /* FIXME this is probably EBW. */
3444 if (ssh->state == SSH_STATE_CLOSED)
3447 /* We're out of data. Go and get some more. */
3453 static int ssh_do_close(Ssh ssh, int notify_exit)
3456 struct ssh_channel *c;
3458 ssh->state = SSH_STATE_CLOSED;
3459 expire_timer_context(ssh);
3464 notify_remote_exit(ssh->frontend);
3469 * Now we must shut down any port- and X-forwarded channels going
3470 * through this connection.
3472 if (ssh->channels) {
3473 while (NULL != (c = index234(ssh->channels, 0))) {
3474 ssh_channel_close_local(c, NULL);
3475 del234(ssh->channels, c); /* moving next one to index 0 */
3476 if (ssh->version == 2)
3477 bufchain_clear(&c->v.v2.outbuffer);
3482 * Go through port-forwardings, and close any associated
3483 * listening sockets.
3485 if (ssh->portfwds) {
3486 struct ssh_portfwd *pf;
3487 while (NULL != (pf = index234(ssh->portfwds, 0))) {
3488 /* Dispose of any listening socket. */
3490 pfl_terminate(pf->local);
3491 del234(ssh->portfwds, pf); /* moving next one to index 0 */
3494 freetree234(ssh->portfwds);
3495 ssh->portfwds = NULL;
3499 * Also stop attempting to connection-share.
3501 if (ssh->connshare) {
3502 sharestate_free(ssh->connshare);
3503 ssh->connshare = NULL;
3509 static void ssh_socket_log(Plug plug, int type, SockAddr addr, int port,
3510 const char *error_msg, int error_code)
3512 Ssh ssh = (Ssh) plug;
3515 * While we're attempting connection sharing, don't loudly log
3516 * everything that happens. Real TCP connections need to be logged
3517 * when we _start_ trying to connect, because it might be ages
3518 * before they respond if something goes wrong; but connection
3519 * sharing is local and quick to respond, and it's sufficient to
3520 * simply wait and see whether it worked afterwards.
3523 if (!ssh->attempting_connshare)
3524 backend_socket_log(ssh->frontend, type, addr, port,
3525 error_msg, error_code, ssh->conf,
3526 ssh->session_started);
3529 void ssh_connshare_log(Ssh ssh, int event, const char *logtext,
3530 const char *ds_err, const char *us_err)
3532 if (event == SHARE_NONE) {
3533 /* In this case, 'logtext' is an error message indicating a
3534 * reason why connection sharing couldn't be set up _at all_.
3535 * Failing that, ds_err and us_err indicate why we couldn't be
3536 * a downstream and an upstream respectively. */
3538 logeventf(ssh, "Could not set up connection sharing: %s", logtext);
3541 logeventf(ssh, "Could not set up connection sharing"
3542 " as downstream: %s", ds_err);
3544 logeventf(ssh, "Could not set up connection sharing"
3545 " as upstream: %s", us_err);
3547 } else if (event == SHARE_DOWNSTREAM) {
3548 /* In this case, 'logtext' is a local endpoint address */
3549 logeventf(ssh, "Using existing shared connection at %s", logtext);
3550 /* Also we should mention this in the console window to avoid
3551 * confusing users as to why this window doesn't behave the
3553 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
3554 c_write_str(ssh,"Reusing a shared connection to this server.\r\n");
3556 } else if (event == SHARE_UPSTREAM) {
3557 /* In this case, 'logtext' is a local endpoint address too */
3558 logeventf(ssh, "Sharing this connection at %s", logtext);
3562 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
3565 Ssh ssh = (Ssh) plug;
3566 int need_notify = ssh_do_close(ssh, FALSE);
3569 if (!ssh->close_expected)
3570 error_msg = "Server unexpectedly closed network connection";
3572 error_msg = "Server closed network connection";
3575 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
3579 notify_remote_exit(ssh->frontend);
3582 logevent(error_msg);
3583 if (!ssh->close_expected || !ssh->clean_exit)
3584 connection_fatal(ssh->frontend, "%s", error_msg);
3588 static int ssh_receive(Plug plug, int urgent, char *data, int len)
3590 Ssh ssh = (Ssh) plug;
3591 ssh_gotdata(ssh, (unsigned char *)data, len);
3592 if (ssh->state == SSH_STATE_CLOSED) {
3593 ssh_do_close(ssh, TRUE);
3599 static void ssh_sent(Plug plug, int bufsize)
3601 Ssh ssh = (Ssh) plug;
3603 * If the send backlog on the SSH socket itself clears, we
3604 * should unthrottle the whole world if it was throttled.
3606 if (bufsize < SSH_MAX_BACKLOG)
3607 ssh_throttle_all(ssh, 0, bufsize);
3610 static void ssh_hostport_setup(const char *host, int port, Conf *conf,
3611 char **savedhost, int *savedport,
3614 char *loghost = conf_get_str(conf, CONF_loghost);
3616 *loghost_ret = loghost;
3622 tmphost = dupstr(loghost);
3623 *savedport = 22; /* default ssh port */
3626 * A colon suffix on the hostname string also lets us affect
3627 * savedport. (Unless there are multiple colons, in which case
3628 * we assume this is an unbracketed IPv6 literal.)
3630 colon = host_strrchr(tmphost, ':');
3631 if (colon && colon == host_strchr(tmphost, ':')) {
3634 *savedport = atoi(colon);
3637 *savedhost = host_strduptrim(tmphost);
3640 *savedhost = host_strduptrim(host);
3642 port = 22; /* default ssh port */
3647 static int ssh_test_for_upstream(const char *host, int port, Conf *conf)
3653 random_ref(); /* platform may need this to determine share socket name */
3654 ssh_hostport_setup(host, port, conf, &savedhost, &savedport, NULL);
3655 ret = ssh_share_test_for_upstream(savedhost, savedport, conf);
3663 * Connect to specified host and port.
3664 * Returns an error message, or NULL on success.
3665 * Also places the canonical host name into `realhost'. It must be
3666 * freed by the caller.
3668 static const char *connect_to_host(Ssh ssh, const char *host, int port,
3669 char **realhost, int nodelay, int keepalive)
3671 static const struct plug_function_table fn_table = {
3682 int addressfamily, sshprot;
3684 ssh_hostport_setup(host, port, ssh->conf,
3685 &ssh->savedhost, &ssh->savedport, &loghost);
3687 ssh->fn = &fn_table; /* make 'ssh' usable as a Plug */
3690 * Try connection-sharing, in case that means we don't open a
3691 * socket after all. ssh_connection_sharing_init will connect to a
3692 * previously established upstream if it can, and failing that,
3693 * establish a listening socket for _us_ to be the upstream. In
3694 * the latter case it will return NULL just as if it had done
3695 * nothing, because here we only need to care if we're a
3696 * downstream and need to do our connection setup differently.
3698 ssh->connshare = NULL;
3699 ssh->attempting_connshare = TRUE; /* affects socket logging behaviour */
3700 ssh->s = ssh_connection_sharing_init(ssh->savedhost, ssh->savedport,
3701 ssh->conf, ssh, &ssh->connshare);
3702 ssh->attempting_connshare = FALSE;
3703 if (ssh->s != NULL) {
3705 * We are a downstream.
3707 ssh->bare_connection = TRUE;
3708 ssh->do_ssh_init = do_ssh_connection_init;
3709 ssh->fullhostname = NULL;
3710 *realhost = dupstr(host); /* best we can do */
3713 * We're not a downstream, so open a normal socket.
3715 ssh->do_ssh_init = do_ssh_init;
3720 addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
3721 addr = name_lookup(host, port, realhost, ssh->conf, addressfamily,
3722 ssh->frontend, "SSH connection");
3723 if ((err = sk_addr_error(addr)) != NULL) {
3727 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
3729 ssh->s = new_connection(addr, *realhost, port,
3730 0, 1, nodelay, keepalive,
3731 (Plug) ssh, ssh->conf);
3732 if ((err = sk_socket_error(ssh->s)) != NULL) {
3734 notify_remote_exit(ssh->frontend);
3740 * The SSH version number is always fixed (since we no longer support
3741 * fallback between versions), so set it now, and if it's SSH-2,
3742 * send the version string now too.
3744 sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3745 assert(sshprot == 0 || sshprot == 3);
3749 if (sshprot == 3 && !ssh->bare_connection) {
3752 ssh_send_verstring(ssh, "SSH-", NULL);
3756 * loghost, if configured, overrides realhost.
3760 *realhost = dupstr(loghost);
3767 * Throttle or unthrottle the SSH connection.
3769 static void ssh_throttle_conn(Ssh ssh, int adjust)
3771 int old_count = ssh->conn_throttle_count;
3772 ssh->conn_throttle_count += adjust;
3773 assert(ssh->conn_throttle_count >= 0);
3774 if (ssh->conn_throttle_count && !old_count) {
3775 ssh_set_frozen(ssh, 1);
3776 } else if (!ssh->conn_throttle_count && old_count) {
3777 ssh_set_frozen(ssh, 0);
3781 static void ssh_agentf_try_forward(struct ssh_channel *c);
3784 * Throttle or unthrottle _all_ local data streams (for when sends
3785 * on the SSH connection itself back up).
3787 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3790 struct ssh_channel *c;
3792 if (enable == ssh->throttled_all)
3794 ssh->throttled_all = enable;
3795 ssh->overall_bufsize = bufsize;
3798 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3800 case CHAN_MAINSESSION:
3802 * This is treated separately, outside the switch.
3806 x11_override_throttle(c->u.x11.xconn, enable);
3809 /* Agent forwarding channels are buffer-managed by
3810 * checking ssh->throttled_all in ssh_agentf_try_forward.
3811 * So at the moment we _un_throttle again, we must make an
3812 * attempt to do something. */
3814 ssh_agentf_try_forward(c);
3817 pfd_override_throttle(c->u.pfd.pf, enable);
3823 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3825 Ssh ssh = (Ssh) sshv;
3827 ssh->auth_agent_query = NULL;
3829 ssh->agent_response = reply;
3830 ssh->agent_response_len = replylen;
3832 if (ssh->version == 1)
3833 do_ssh1_login(ssh, NULL, -1, NULL);
3835 do_ssh2_authconn(ssh, NULL, -1, NULL);
3838 static void ssh_dialog_callback(void *sshv, int ret)
3840 Ssh ssh = (Ssh) sshv;
3842 ssh->user_response = ret;
3844 if (ssh->version == 1)
3845 do_ssh1_login(ssh, NULL, -1, NULL);
3847 do_ssh2_transport(ssh, NULL, -1, NULL);
3850 * This may have unfrozen the SSH connection, so do a
3853 ssh_process_queued_incoming_data(ssh);
3856 static void ssh_agentf_got_response(struct ssh_channel *c,
3857 void *reply, int replylen)
3859 c->u.a.pending = NULL;
3861 assert(!(c->closes & CLOSES_SENT_EOF));
3864 /* The real agent didn't send any kind of reply at all for
3865 * some reason, so fake an SSH_AGENT_FAILURE. */
3866 reply = "\0\0\0\1\5";
3870 ssh_send_channel_data(c, reply, replylen);
3873 static void ssh_agentf_callback(void *cv, void *reply, int replylen);
3875 static void ssh_agentf_try_forward(struct ssh_channel *c)
3877 unsigned datalen, lengthfield, messagelen;
3878 unsigned char *message;
3879 unsigned char msglen[4];
3884 * Don't try to parallelise agent requests. Wait for each one to
3885 * return before attempting the next.
3891 * If the outgoing side of the channel connection is currently
3892 * throttled (for any reason, either that channel's window size or
3893 * the entire SSH connection being throttled), don't submit any
3894 * new forwarded requests to the real agent. This causes the input
3895 * side of the agent forwarding not to be emptied, exerting the
3896 * required back-pressure on the remote client, and encouraging it
3897 * to read our responses before sending too many more requests.
3899 if (c->ssh->throttled_all ||
3900 (c->ssh->version == 2 && c->v.v2.remwindow == 0))
3903 if (c->closes & CLOSES_SENT_EOF) {
3905 * If we've already sent outgoing EOF, there's nothing we can
3906 * do with incoming data except consume it and throw it away.
3908 bufchain_clear(&c->u.a.inbuffer);
3914 * Try to extract a complete message from the input buffer.
3916 datalen = bufchain_size(&c->u.a.inbuffer);
3918 break; /* not even a length field available yet */
3920 bufchain_fetch(&c->u.a.inbuffer, msglen, 4);
3921 lengthfield = GET_32BIT(msglen);
3923 if (lengthfield > AGENT_MAX_MSGLEN) {
3925 * If the remote has sent a message that's just _too_
3926 * long, we should reject it in advance of seeing the rest
3927 * of the incoming message, and also close the connection
3928 * for good measure (which avoids us having to faff about
3929 * with carefully ignoring just the right number of bytes
3930 * from the overlong message).
3932 ssh_agentf_got_response(c, NULL, 0);
3933 sshfwd_write_eof(c);
3937 if (lengthfield > datalen - 4)
3938 break; /* a whole message is not yet available */
3940 messagelen = lengthfield + 4;
3942 message = snewn(messagelen, unsigned char);
3943 bufchain_fetch(&c->u.a.inbuffer, message, messagelen);
3944 bufchain_consume(&c->u.a.inbuffer, messagelen);
3945 c->u.a.pending = agent_query(
3946 message, messagelen, &reply, &replylen, ssh_agentf_callback, c);
3950 return; /* agent_query promised to reply in due course */
3953 * If the agent gave us an answer immediately, pass it
3954 * straight on and go round this loop again.
3956 ssh_agentf_got_response(c, reply, replylen);
3960 * If we get here (i.e. we left the above while loop via 'break'
3961 * rather than 'return'), that means we've determined that the
3962 * input buffer for the agent forwarding connection doesn't
3963 * contain a complete request.
3965 * So if there's potentially more data to come, we can return now,
3966 * and wait for the remote client to send it. But if the remote
3967 * has sent EOF, it would be a mistake to do that, because we'd be
3968 * waiting a long time. So this is the moment to check for EOF,
3969 * and respond appropriately.
3971 if (c->closes & CLOSES_RCVD_EOF)
3972 sshfwd_write_eof(c);
3975 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3977 struct ssh_channel *c = (struct ssh_channel *)cv;
3979 ssh_agentf_got_response(c, reply, replylen);
3983 * Now try to extract and send further messages from the channel's
3984 * input-side buffer.
3986 ssh_agentf_try_forward(c);
3990 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3991 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3992 * => log `wire_reason'.
3994 static void ssh_disconnect(Ssh ssh, const char *client_reason,
3995 const char *wire_reason,
3996 int code, int clean_exit)
4000 client_reason = wire_reason;
4002 error = dupprintf("Disconnected: %s", client_reason);
4004 error = dupstr("Disconnected");
4006 if (ssh->version == 1) {
4007 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
4009 } else if (ssh->version == 2) {
4010 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
4011 ssh2_pkt_adduint32(pktout, code);
4012 ssh2_pkt_addstring(pktout, wire_reason);
4013 ssh2_pkt_addstring(pktout, "en"); /* language tag */
4014 ssh2_pkt_send_noqueue(ssh, pktout);
4017 ssh->close_expected = TRUE;
4018 ssh->clean_exit = clean_exit;
4019 ssh_closing((Plug)ssh, error, 0, 0);
4023 int verify_ssh_manual_host_key(Ssh ssh, const char *fingerprint,
4024 const struct ssh_signkey *ssh2keytype,
4027 if (!conf_get_str_nthstrkey(ssh->conf, CONF_ssh_manual_hostkeys, 0)) {
4028 return -1; /* no manual keys configured */
4033 * The fingerprint string we've been given will have things
4034 * like 'ssh-rsa 2048' at the front of it. Strip those off and
4035 * narrow down to just the colon-separated hex block at the
4036 * end of the string.
4038 const char *p = strrchr(fingerprint, ' ');
4039 fingerprint = p ? p+1 : fingerprint;
4040 /* Quick sanity checks, including making sure it's in lowercase */
4041 assert(strlen(fingerprint) == 16*3 - 1);
4042 assert(fingerprint[2] == ':');
4043 assert(fingerprint[strspn(fingerprint, "0123456789abcdef:")] == 0);
4045 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
4047 return 1; /* success */
4052 * Construct the base64-encoded public key blob and see if
4055 unsigned char *binblob;
4057 int binlen, atoms, i;
4058 binblob = ssh2keytype->public_blob(ssh2keydata, &binlen);
4059 atoms = (binlen + 2) / 3;
4060 base64blob = snewn(atoms * 4 + 1, char);
4061 for (i = 0; i < atoms; i++)
4062 base64_encode_atom(binblob + 3*i, binlen - 3*i, base64blob + 4*i);
4063 base64blob[atoms * 4] = '\0';
4065 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
4068 return 1; /* success */
4077 * Handle the key exchange and user authentication phases.
4079 static int do_ssh1_login(Ssh ssh, const unsigned char *in, int inlen,
4080 struct Packet *pktin)
4083 unsigned char cookie[8], *ptr;
4084 struct MD5Context md5c;
4085 struct do_ssh1_login_state {
4088 unsigned char *rsabuf;
4089 const unsigned char *keystr1, *keystr2;
4090 unsigned long supported_ciphers_mask, supported_auths_mask;
4091 int tried_publickey, tried_agent;
4092 int tis_auth_refused, ccard_auth_refused;
4093 unsigned char session_id[16];
4095 void *publickey_blob;
4096 int publickey_bloblen;
4097 char *publickey_comment;
4098 int privatekey_available, privatekey_encrypted;
4099 prompts_t *cur_prompt;
4102 unsigned char request[5], *response, *p;
4112 struct RSAKey servkey, hostkey;
4114 crState(do_ssh1_login_state);
4121 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
4122 bombout(("Public key packet not received"));
4126 logevent("Received public keys");
4128 ptr = ssh_pkt_getdata(pktin, 8);
4130 bombout(("SSH-1 public key packet stopped before random cookie"));
4133 memcpy(cookie, ptr, 8);
4135 if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
4136 !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) {
4137 bombout(("Failed to read SSH-1 public keys from public key packet"));
4142 * Log the host key fingerprint.
4146 logevent("Host key fingerprint is:");
4147 strcpy(logmsg, " ");
4148 s->hostkey.comment = NULL;
4149 rsa_fingerprint(logmsg + strlen(logmsg),
4150 sizeof(logmsg) - strlen(logmsg), &s->hostkey);
4154 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
4155 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
4156 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
4157 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
4158 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
4160 ssh->v1_local_protoflags =
4161 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
4162 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
4165 MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
4166 MD5Update(&md5c, s->keystr1, s->servkey.bytes);
4167 MD5Update(&md5c, cookie, 8);
4168 MD5Final(s->session_id, &md5c);
4170 for (i = 0; i < 32; i++)
4171 ssh->session_key[i] = random_byte();
4174 * Verify that the `bits' and `bytes' parameters match.
4176 if (s->hostkey.bits > s->hostkey.bytes * 8 ||
4177 s->servkey.bits > s->servkey.bytes * 8) {
4178 bombout(("SSH-1 public keys were badly formatted"));
4182 s->len = (s->hostkey.bytes > s->servkey.bytes ?
4183 s->hostkey.bytes : s->servkey.bytes);
4185 s->rsabuf = snewn(s->len, unsigned char);
4188 * Verify the host key.
4192 * First format the key into a string.
4194 int len = rsastr_len(&s->hostkey);
4195 char fingerprint[100];
4196 char *keystr = snewn(len, char);
4197 rsastr_fmt(keystr, &s->hostkey);
4198 rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
4200 /* First check against manually configured host keys. */
4201 s->dlgret = verify_ssh_manual_host_key(ssh, fingerprint, NULL, NULL);
4202 if (s->dlgret == 0) { /* did not match */
4203 bombout(("Host key did not appear in manually configured list"));
4206 } else if (s->dlgret < 0) { /* none configured; use standard handling */
4207 ssh_set_frozen(ssh, 1);
4208 s->dlgret = verify_ssh_host_key(ssh->frontend,
4209 ssh->savedhost, ssh->savedport,
4210 "rsa", keystr, fingerprint,
4211 ssh_dialog_callback, ssh);
4216 if (s->dlgret < 0) {
4220 bombout(("Unexpected data from server while waiting"
4221 " for user host key response"));
4224 } while (pktin || inlen > 0);
4225 s->dlgret = ssh->user_response;
4227 ssh_set_frozen(ssh, 0);
4229 if (s->dlgret == 0) {
4230 ssh_disconnect(ssh, "User aborted at host key verification",
4239 for (i = 0; i < 32; i++) {
4240 s->rsabuf[i] = ssh->session_key[i];
4242 s->rsabuf[i] ^= s->session_id[i];
4245 if (s->hostkey.bytes > s->servkey.bytes) {
4246 ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
4248 ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
4250 ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
4252 ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
4255 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
4259 logevent("Encrypted session key");
4262 int cipher_chosen = 0, warn = 0;
4263 const char *cipher_string = NULL;
4265 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
4266 int next_cipher = conf_get_int_int(ssh->conf,
4267 CONF_ssh_cipherlist, i);
4268 if (next_cipher == CIPHER_WARN) {
4269 /* If/when we choose a cipher, warn about it */
4271 } else if (next_cipher == CIPHER_AES) {
4272 /* XXX Probably don't need to mention this. */
4273 logevent("AES not supported in SSH-1, skipping");
4275 switch (next_cipher) {
4276 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
4277 cipher_string = "3DES"; break;
4278 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
4279 cipher_string = "Blowfish"; break;
4280 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
4281 cipher_string = "single-DES"; break;
4283 if (s->supported_ciphers_mask & (1 << s->cipher_type))
4287 if (!cipher_chosen) {
4288 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
4289 bombout(("Server violates SSH-1 protocol by not "
4290 "supporting 3DES encryption"));
4292 /* shouldn't happen */
4293 bombout(("No supported ciphers found"));
4297 /* Warn about chosen cipher if necessary. */
4299 ssh_set_frozen(ssh, 1);
4300 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
4301 ssh_dialog_callback, ssh);
4302 if (s->dlgret < 0) {
4306 bombout(("Unexpected data from server while waiting"
4307 " for user response"));
4310 } while (pktin || inlen > 0);
4311 s->dlgret = ssh->user_response;
4313 ssh_set_frozen(ssh, 0);
4314 if (s->dlgret == 0) {
4315 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
4322 switch (s->cipher_type) {
4323 case SSH_CIPHER_3DES:
4324 logevent("Using 3DES encryption");
4326 case SSH_CIPHER_DES:
4327 logevent("Using single-DES encryption");
4329 case SSH_CIPHER_BLOWFISH:
4330 logevent("Using Blowfish encryption");
4334 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
4335 PKT_CHAR, s->cipher_type,
4336 PKT_DATA, cookie, 8,
4337 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
4338 PKT_DATA, s->rsabuf, s->len,
4339 PKT_INT, ssh->v1_local_protoflags, PKT_END);
4341 logevent("Trying to enable encryption...");
4345 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
4346 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
4348 ssh->v1_cipher_ctx = ssh->cipher->make_context();
4349 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
4350 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
4352 ssh->crcda_ctx = crcda_make_context();
4353 logevent("Installing CRC compensation attack detector");
4355 if (s->servkey.modulus) {
4356 sfree(s->servkey.modulus);
4357 s->servkey.modulus = NULL;
4359 if (s->servkey.exponent) {
4360 sfree(s->servkey.exponent);
4361 s->servkey.exponent = NULL;
4363 if (s->hostkey.modulus) {
4364 sfree(s->hostkey.modulus);
4365 s->hostkey.modulus = NULL;
4367 if (s->hostkey.exponent) {
4368 sfree(s->hostkey.exponent);
4369 s->hostkey.exponent = NULL;
4373 if (pktin->type != SSH1_SMSG_SUCCESS) {
4374 bombout(("Encryption not successfully enabled"));
4378 logevent("Successfully started encryption");
4380 fflush(stdout); /* FIXME eh? */
4382 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
4383 int ret; /* need not be kept over crReturn */
4384 s->cur_prompt = new_prompts(ssh->frontend);
4385 s->cur_prompt->to_server = TRUE;
4386 s->cur_prompt->name = dupstr("SSH login name");
4387 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
4388 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4391 crWaitUntil(!pktin);
4392 ret = get_userpass_input(s->cur_prompt, in, inlen);
4397 * Failed to get a username. Terminate.
4399 free_prompts(s->cur_prompt);
4400 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
4403 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
4404 free_prompts(s->cur_prompt);
4407 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
4409 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
4411 if (flags & FLAG_INTERACTIVE &&
4412 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
4413 c_write_str(ssh, userlog);
4414 c_write_str(ssh, "\r\n");
4422 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
4423 /* We must not attempt PK auth. Pretend we've already tried it. */
4424 s->tried_publickey = s->tried_agent = 1;
4426 s->tried_publickey = s->tried_agent = 0;
4428 s->tis_auth_refused = s->ccard_auth_refused = 0;
4430 * Load the public half of any configured keyfile for later use.
4432 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4433 if (!filename_is_null(s->keyfile)) {
4435 logeventf(ssh, "Reading key file \"%.150s\"",
4436 filename_to_str(s->keyfile));
4437 keytype = key_type(s->keyfile);
4438 if (keytype == SSH_KEYTYPE_SSH1 ||
4439 keytype == SSH_KEYTYPE_SSH1_PUBLIC) {
4441 if (rsakey_pubblob(s->keyfile,
4442 &s->publickey_blob, &s->publickey_bloblen,
4443 &s->publickey_comment, &error)) {
4444 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH1);
4445 if (!s->privatekey_available)
4446 logeventf(ssh, "Key file contains public key only");
4447 s->privatekey_encrypted = rsakey_encrypted(s->keyfile,
4451 logeventf(ssh, "Unable to load key (%s)", error);
4452 msgbuf = dupprintf("Unable to load key file "
4453 "\"%.150s\" (%s)\r\n",
4454 filename_to_str(s->keyfile),
4456 c_write_str(ssh, msgbuf);
4458 s->publickey_blob = NULL;
4462 logeventf(ssh, "Unable to use this key file (%s)",
4463 key_type_to_str(keytype));
4464 msgbuf = dupprintf("Unable to use key file \"%.150s\""
4466 filename_to_str(s->keyfile),
4467 key_type_to_str(keytype));
4468 c_write_str(ssh, msgbuf);
4470 s->publickey_blob = NULL;
4473 s->publickey_blob = NULL;
4475 while (pktin->type == SSH1_SMSG_FAILURE) {
4476 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
4478 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
4480 * Attempt RSA authentication using Pageant.
4486 logevent("Pageant is running. Requesting keys.");
4488 /* Request the keys held by the agent. */
4489 PUT_32BIT(s->request, 1);
4490 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
4491 ssh->auth_agent_query = agent_query(
4492 s->request, 5, &r, &s->responselen, ssh_agent_callback, ssh);
4493 if (ssh->auth_agent_query) {
4497 bombout(("Unexpected data from server while waiting"
4498 " for agent response"));
4501 } while (pktin || inlen > 0);
4502 r = ssh->agent_response;
4503 s->responselen = ssh->agent_response_len;
4505 s->response = (unsigned char *) r;
4506 if (s->response && s->responselen >= 5 &&
4507 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
4508 s->p = s->response + 5;
4509 s->nkeys = toint(GET_32BIT(s->p));
4511 logeventf(ssh, "Pageant reported negative key count %d",
4516 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
4517 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
4518 unsigned char *pkblob = s->p;
4522 do { /* do while (0) to make breaking easy */
4523 n = ssh1_read_bignum
4524 (s->p, toint(s->responselen-(s->p-s->response)),
4529 n = ssh1_read_bignum
4530 (s->p, toint(s->responselen-(s->p-s->response)),
4535 if (s->responselen - (s->p-s->response) < 4)
4537 s->commentlen = toint(GET_32BIT(s->p));
4539 if (s->commentlen < 0 ||
4540 toint(s->responselen - (s->p-s->response)) <
4543 s->commentp = (char *)s->p;
4544 s->p += s->commentlen;
4548 logevent("Pageant key list packet was truncated");
4552 if (s->publickey_blob) {
4553 if (!memcmp(pkblob, s->publickey_blob,
4554 s->publickey_bloblen)) {
4555 logeventf(ssh, "Pageant key #%d matches "
4556 "configured key file", s->keyi);
4557 s->tried_publickey = 1;
4559 /* Skip non-configured key */
4562 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
4563 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4564 PKT_BIGNUM, s->key.modulus, PKT_END);
4566 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4567 logevent("Key refused");
4570 logevent("Received RSA challenge");
4571 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4572 bombout(("Server's RSA challenge was badly formatted"));
4577 char *agentreq, *q, *ret;
4580 len = 1 + 4; /* message type, bit count */
4581 len += ssh1_bignum_length(s->key.exponent);
4582 len += ssh1_bignum_length(s->key.modulus);
4583 len += ssh1_bignum_length(s->challenge);
4584 len += 16; /* session id */
4585 len += 4; /* response format */
4586 agentreq = snewn(4 + len, char);
4587 PUT_32BIT(agentreq, len);
4589 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
4590 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
4592 q += ssh1_write_bignum(q, s->key.exponent);
4593 q += ssh1_write_bignum(q, s->key.modulus);
4594 q += ssh1_write_bignum(q, s->challenge);
4595 memcpy(q, s->session_id, 16);
4597 PUT_32BIT(q, 1); /* response format */
4598 ssh->auth_agent_query = agent_query(
4599 agentreq, len + 4, &vret, &retlen,
4600 ssh_agent_callback, ssh);
4601 if (ssh->auth_agent_query) {
4606 bombout(("Unexpected data from server"
4607 " while waiting for agent"
4611 } while (pktin || inlen > 0);
4612 vret = ssh->agent_response;
4613 retlen = ssh->agent_response_len;
4618 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
4619 logevent("Sending Pageant's response");
4620 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4621 PKT_DATA, ret + 5, 16,
4625 if (pktin->type == SSH1_SMSG_SUCCESS) {
4627 ("Pageant's response accepted");
4628 if (flags & FLAG_VERBOSE) {
4629 c_write_str(ssh, "Authenticated using"
4631 c_write(ssh, s->commentp,
4633 c_write_str(ssh, "\" from agent\r\n");
4638 ("Pageant's response not accepted");
4641 ("Pageant failed to answer challenge");
4645 logevent("No reply received from Pageant");
4648 freebn(s->key.exponent);
4649 freebn(s->key.modulus);
4650 freebn(s->challenge);
4655 if (s->publickey_blob && !s->tried_publickey)
4656 logevent("Configured key file not in Pageant");
4658 logevent("Failed to get reply from Pageant");
4663 if (s->publickey_blob && s->privatekey_available &&
4664 !s->tried_publickey) {
4666 * Try public key authentication with the specified
4669 int got_passphrase; /* need not be kept over crReturn */
4670 if (flags & FLAG_VERBOSE)
4671 c_write_str(ssh, "Trying public key authentication.\r\n");
4672 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4673 logeventf(ssh, "Trying public key \"%s\"",
4674 filename_to_str(s->keyfile));
4675 s->tried_publickey = 1;
4676 got_passphrase = FALSE;
4677 while (!got_passphrase) {
4679 * Get a passphrase, if necessary.
4681 char *passphrase = NULL; /* only written after crReturn */
4683 if (!s->privatekey_encrypted) {
4684 if (flags & FLAG_VERBOSE)
4685 c_write_str(ssh, "No passphrase required.\r\n");
4688 int ret; /* need not be kept over crReturn */
4689 s->cur_prompt = new_prompts(ssh->frontend);
4690 s->cur_prompt->to_server = FALSE;
4691 s->cur_prompt->name = dupstr("SSH key passphrase");
4692 add_prompt(s->cur_prompt,
4693 dupprintf("Passphrase for key \"%.100s\": ",
4694 s->publickey_comment), FALSE);
4695 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4698 crWaitUntil(!pktin);
4699 ret = get_userpass_input(s->cur_prompt, in, inlen);
4703 /* Failed to get a passphrase. Terminate. */
4704 free_prompts(s->cur_prompt);
4705 ssh_disconnect(ssh, NULL, "Unable to authenticate",
4709 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
4710 free_prompts(s->cur_prompt);
4713 * Try decrypting key with passphrase.
4715 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4716 ret = loadrsakey(s->keyfile, &s->key, passphrase,
4719 smemclr(passphrase, strlen(passphrase));
4723 /* Correct passphrase. */
4724 got_passphrase = TRUE;
4725 } else if (ret == 0) {
4726 c_write_str(ssh, "Couldn't load private key from ");
4727 c_write_str(ssh, filename_to_str(s->keyfile));
4728 c_write_str(ssh, " (");
4729 c_write_str(ssh, error);
4730 c_write_str(ssh, ").\r\n");
4731 got_passphrase = FALSE;
4732 break; /* go and try something else */
4733 } else if (ret == -1) {
4734 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
4735 got_passphrase = FALSE;
4738 assert(0 && "unexpected return from loadrsakey()");
4739 got_passphrase = FALSE; /* placate optimisers */
4743 if (got_passphrase) {
4746 * Send a public key attempt.
4748 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4749 PKT_BIGNUM, s->key.modulus, PKT_END);
4752 if (pktin->type == SSH1_SMSG_FAILURE) {
4753 c_write_str(ssh, "Server refused our public key.\r\n");
4754 continue; /* go and try something else */
4756 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4757 bombout(("Bizarre response to offer of public key"));
4763 unsigned char buffer[32];
4764 Bignum challenge, response;
4766 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4767 bombout(("Server's RSA challenge was badly formatted"));
4770 response = rsadecrypt(challenge, &s->key);
4771 freebn(s->key.private_exponent);/* burn the evidence */
4773 for (i = 0; i < 32; i++) {
4774 buffer[i] = bignum_byte(response, 31 - i);
4778 MD5Update(&md5c, buffer, 32);
4779 MD5Update(&md5c, s->session_id, 16);
4780 MD5Final(buffer, &md5c);
4782 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4783 PKT_DATA, buffer, 16, PKT_END);
4790 if (pktin->type == SSH1_SMSG_FAILURE) {
4791 if (flags & FLAG_VERBOSE)
4792 c_write_str(ssh, "Failed to authenticate with"
4793 " our public key.\r\n");
4794 continue; /* go and try something else */
4795 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4796 bombout(("Bizarre response to RSA authentication response"));
4800 break; /* we're through! */
4806 * Otherwise, try various forms of password-like authentication.
4808 s->cur_prompt = new_prompts(ssh->frontend);
4810 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4811 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
4812 !s->tis_auth_refused) {
4813 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
4814 logevent("Requested TIS authentication");
4815 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
4817 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
4818 logevent("TIS authentication declined");
4819 if (flags & FLAG_INTERACTIVE)
4820 c_write_str(ssh, "TIS authentication refused.\r\n");
4821 s->tis_auth_refused = 1;
4826 char *instr_suf, *prompt;
4828 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4830 bombout(("TIS challenge packet was badly formed"));
4833 logevent("Received TIS challenge");
4834 s->cur_prompt->to_server = TRUE;
4835 s->cur_prompt->name = dupstr("SSH TIS authentication");
4836 /* Prompt heuristic comes from OpenSSH */
4837 if (memchr(challenge, '\n', challengelen)) {
4838 instr_suf = dupstr("");
4839 prompt = dupprintf("%.*s", challengelen, challenge);
4841 instr_suf = dupprintf("%.*s", challengelen, challenge);
4842 prompt = dupstr("Response: ");
4844 s->cur_prompt->instruction =
4845 dupprintf("Using TIS authentication.%s%s",
4846 (*instr_suf) ? "\n" : "",
4848 s->cur_prompt->instr_reqd = TRUE;
4849 add_prompt(s->cur_prompt, prompt, FALSE);
4853 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4854 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
4855 !s->ccard_auth_refused) {
4856 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
4857 logevent("Requested CryptoCard authentication");
4858 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
4860 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
4861 logevent("CryptoCard authentication declined");
4862 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
4863 s->ccard_auth_refused = 1;
4868 char *instr_suf, *prompt;
4870 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4872 bombout(("CryptoCard challenge packet was badly formed"));
4875 logevent("Received CryptoCard challenge");
4876 s->cur_prompt->to_server = TRUE;
4877 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4878 s->cur_prompt->name_reqd = FALSE;
4879 /* Prompt heuristic comes from OpenSSH */
4880 if (memchr(challenge, '\n', challengelen)) {
4881 instr_suf = dupstr("");
4882 prompt = dupprintf("%.*s", challengelen, challenge);
4884 instr_suf = dupprintf("%.*s", challengelen, challenge);
4885 prompt = dupstr("Response: ");
4887 s->cur_prompt->instruction =
4888 dupprintf("Using CryptoCard authentication.%s%s",
4889 (*instr_suf) ? "\n" : "",
4891 s->cur_prompt->instr_reqd = TRUE;
4892 add_prompt(s->cur_prompt, prompt, FALSE);
4896 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4897 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4898 bombout(("No supported authentication methods available"));
4901 s->cur_prompt->to_server = TRUE;
4902 s->cur_prompt->name = dupstr("SSH password");
4903 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4904 ssh->username, ssh->savedhost),
4909 * Show password prompt, having first obtained it via a TIS
4910 * or CryptoCard exchange if we're doing TIS or CryptoCard
4914 int ret; /* need not be kept over crReturn */
4915 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4918 crWaitUntil(!pktin);
4919 ret = get_userpass_input(s->cur_prompt, in, inlen);
4924 * Failed to get a password (for example
4925 * because one was supplied on the command line
4926 * which has already failed to work). Terminate.
4928 free_prompts(s->cur_prompt);
4929 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4934 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4936 * Defence against traffic analysis: we send a
4937 * whole bunch of packets containing strings of
4938 * different lengths. One of these strings is the
4939 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4940 * The others are all random data in
4941 * SSH1_MSG_IGNORE packets. This way a passive
4942 * listener can't tell which is the password, and
4943 * hence can't deduce the password length.
4945 * Anybody with a password length greater than 16
4946 * bytes is going to have enough entropy in their
4947 * password that a listener won't find it _that_
4948 * much help to know how long it is. So what we'll
4951 * - if password length < 16, we send 15 packets
4952 * containing string lengths 1 through 15
4954 * - otherwise, we let N be the nearest multiple
4955 * of 8 below the password length, and send 8
4956 * packets containing string lengths N through
4957 * N+7. This won't obscure the order of
4958 * magnitude of the password length, but it will
4959 * introduce a bit of extra uncertainty.
4961 * A few servers can't deal with SSH1_MSG_IGNORE, at
4962 * least in this context. For these servers, we need
4963 * an alternative defence. We make use of the fact
4964 * that the password is interpreted as a C string:
4965 * so we can append a NUL, then some random data.
4967 * A few servers can deal with neither SSH1_MSG_IGNORE
4968 * here _nor_ a padded password string.
4969 * For these servers we are left with no defences
4970 * against password length sniffing.
4972 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4973 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4975 * The server can deal with SSH1_MSG_IGNORE, so
4976 * we can use the primary defence.
4978 int bottom, top, pwlen, i;
4981 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4983 bottom = 0; /* zero length passwords are OK! :-) */
4986 bottom = pwlen & ~7;
4990 assert(pwlen >= bottom && pwlen <= top);
4992 randomstr = snewn(top + 1, char);
4994 for (i = bottom; i <= top; i++) {
4996 defer_packet(ssh, s->pwpkt_type,
4997 PKT_STR,s->cur_prompt->prompts[0]->result,
5000 for (j = 0; j < i; j++) {
5002 randomstr[j] = random_byte();
5003 } while (randomstr[j] == '\0');
5005 randomstr[i] = '\0';
5006 defer_packet(ssh, SSH1_MSG_IGNORE,
5007 PKT_STR, randomstr, PKT_END);
5010 logevent("Sending password with camouflage packets");
5011 ssh_pkt_defersend(ssh);
5014 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
5016 * The server can't deal with SSH1_MSG_IGNORE
5017 * but can deal with padded passwords, so we
5018 * can use the secondary defence.
5024 len = strlen(s->cur_prompt->prompts[0]->result);
5025 if (len < sizeof(string)) {
5027 strcpy(string, s->cur_prompt->prompts[0]->result);
5028 len++; /* cover the zero byte */
5029 while (len < sizeof(string)) {
5030 string[len++] = (char) random_byte();
5033 ss = s->cur_prompt->prompts[0]->result;
5035 logevent("Sending length-padded password");
5036 send_packet(ssh, s->pwpkt_type,
5037 PKT_INT, len, PKT_DATA, ss, len,
5041 * The server is believed unable to cope with
5042 * any of our password camouflage methods.
5045 len = strlen(s->cur_prompt->prompts[0]->result);
5046 logevent("Sending unpadded password");
5047 send_packet(ssh, s->pwpkt_type,
5049 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
5053 send_packet(ssh, s->pwpkt_type,
5054 PKT_STR, s->cur_prompt->prompts[0]->result,
5057 logevent("Sent password");
5058 free_prompts(s->cur_prompt);
5060 if (pktin->type == SSH1_SMSG_FAILURE) {
5061 if (flags & FLAG_VERBOSE)
5062 c_write_str(ssh, "Access denied\r\n");
5063 logevent("Authentication refused");
5064 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
5065 bombout(("Strange packet received, type %d", pktin->type));
5071 if (s->publickey_blob) {
5072 sfree(s->publickey_blob);
5073 sfree(s->publickey_comment);
5076 logevent("Authentication successful");
5081 static void ssh_channel_try_eof(struct ssh_channel *c)
5084 assert(c->pending_eof); /* precondition for calling us */
5086 return; /* can't close: not even opened yet */
5087 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
5088 return; /* can't send EOF: pending outgoing data */
5090 c->pending_eof = FALSE; /* we're about to send it */
5091 if (ssh->version == 1) {
5092 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
5094 c->closes |= CLOSES_SENT_EOF;
5096 struct Packet *pktout;
5097 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
5098 ssh2_pkt_adduint32(pktout, c->remoteid);
5099 ssh2_pkt_send(ssh, pktout);
5100 c->closes |= CLOSES_SENT_EOF;
5101 ssh2_channel_check_close(c);
5105 Conf *sshfwd_get_conf(struct ssh_channel *c)
5111 void sshfwd_write_eof(struct ssh_channel *c)
5115 if (ssh->state == SSH_STATE_CLOSED)
5118 if (c->closes & CLOSES_SENT_EOF)
5121 c->pending_eof = TRUE;
5122 ssh_channel_try_eof(c);
5125 void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
5130 if (ssh->state == SSH_STATE_CLOSED)
5133 reason = dupprintf("due to local error: %s", err);
5134 ssh_channel_close_local(c, reason);
5136 c->pending_eof = FALSE; /* this will confuse a zombie channel */
5138 ssh2_channel_check_close(c);
5141 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
5145 if (ssh->state == SSH_STATE_CLOSED)
5148 return ssh_send_channel_data(c, buf, len);
5151 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
5155 if (ssh->state == SSH_STATE_CLOSED)
5158 ssh_channel_unthrottle(c, bufsize);
5161 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
5163 struct queued_handler *qh = ssh->qhead;
5167 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
5170 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
5171 ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
5174 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
5175 ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
5179 ssh->qhead = qh->next;
5181 if (ssh->qhead->msg1 > 0) {
5182 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5183 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
5185 if (ssh->qhead->msg2 > 0) {
5186 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5187 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
5190 ssh->qhead = ssh->qtail = NULL;
5193 qh->handler(ssh, pktin, qh->ctx);
5198 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
5199 chandler_fn_t handler, void *ctx)
5201 struct queued_handler *qh;
5203 qh = snew(struct queued_handler);
5206 qh->handler = handler;
5210 if (ssh->qtail == NULL) {
5214 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5215 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
5218 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5219 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
5222 ssh->qtail->next = qh;
5227 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
5229 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
5231 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
5232 SSH2_MSG_REQUEST_SUCCESS)) {
5233 logeventf(ssh, "Remote port forwarding from %s enabled",
5236 logeventf(ssh, "Remote port forwarding from %s refused",
5239 rpf = del234(ssh->rportfwds, pf);
5241 pf->pfrec->remote = NULL;
5246 int ssh_alloc_sharing_rportfwd(Ssh ssh, const char *shost, int sport,
5249 struct ssh_rportfwd *pf = snew(struct ssh_rportfwd);
5252 pf->share_ctx = share_ctx;
5253 pf->shost = dupstr(shost);
5255 pf->sportdesc = NULL;
5256 if (!ssh->rportfwds) {
5257 assert(ssh->version == 2);
5258 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5260 if (add234(ssh->rportfwds, pf) != pf) {
5268 static void ssh_sharing_global_request_response(Ssh ssh, struct Packet *pktin,
5271 share_got_pkt_from_server(ctx, pktin->type,
5272 pktin->body, pktin->length);
5275 void ssh_sharing_queue_global_request(Ssh ssh, void *share_ctx)
5277 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE,
5278 ssh_sharing_global_request_response, share_ctx);
5281 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
5283 struct ssh_portfwd *epf;
5287 if (!ssh->portfwds) {
5288 ssh->portfwds = newtree234(ssh_portcmp);
5291 * Go through the existing port forwardings and tag them
5292 * with status==DESTROY. Any that we want to keep will be
5293 * re-enabled (status==KEEP) as we go through the
5294 * configuration and find out which bits are the same as
5297 struct ssh_portfwd *epf;
5299 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5300 epf->status = DESTROY;
5303 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
5305 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
5306 char *kp, *kp2, *vp, *vp2;
5307 char address_family, type;
5308 int sport,dport,sserv,dserv;
5309 char *sports, *dports, *saddr, *host;
5313 address_family = 'A';
5315 if (*kp == 'A' || *kp == '4' || *kp == '6')
5316 address_family = *kp++;
5317 if (*kp == 'L' || *kp == 'R')
5320 if ((kp2 = host_strchr(kp, ':')) != NULL) {
5322 * There's a colon in the middle of the source port
5323 * string, which means that the part before it is
5324 * actually a source address.
5326 char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp);
5327 saddr = host_strduptrim(saddr_tmp);
5334 sport = atoi(sports);
5338 sport = net_service_lookup(sports);
5340 logeventf(ssh, "Service lookup failed for source"
5341 " port \"%s\"", sports);
5345 if (type == 'L' && !strcmp(val, "D")) {
5346 /* dynamic forwarding */
5353 /* ordinary forwarding */
5355 vp2 = vp + host_strcspn(vp, ":");
5356 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
5360 dport = atoi(dports);
5364 dport = net_service_lookup(dports);
5366 logeventf(ssh, "Service lookup failed for destination"
5367 " port \"%s\"", dports);
5372 if (sport && dport) {
5373 /* Set up a description of the source port. */
5374 struct ssh_portfwd *pfrec, *epfrec;
5376 pfrec = snew(struct ssh_portfwd);
5378 pfrec->saddr = saddr;
5379 pfrec->sserv = sserv ? dupstr(sports) : NULL;
5380 pfrec->sport = sport;
5381 pfrec->daddr = host;
5382 pfrec->dserv = dserv ? dupstr(dports) : NULL;
5383 pfrec->dport = dport;
5384 pfrec->local = NULL;
5385 pfrec->remote = NULL;
5386 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
5387 address_family == '6' ? ADDRTYPE_IPV6 :
5390 epfrec = add234(ssh->portfwds, pfrec);
5391 if (epfrec != pfrec) {
5392 if (epfrec->status == DESTROY) {
5394 * We already have a port forwarding up and running
5395 * with precisely these parameters. Hence, no need
5396 * to do anything; simply re-tag the existing one
5399 epfrec->status = KEEP;
5402 * Anything else indicates that there was a duplicate
5403 * in our input, which we'll silently ignore.
5405 free_portfwd(pfrec);
5407 pfrec->status = CREATE;
5416 * Now go through and destroy any port forwardings which were
5419 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5420 if (epf->status == DESTROY) {
5423 message = dupprintf("%s port forwarding from %s%s%d",
5424 epf->type == 'L' ? "local" :
5425 epf->type == 'R' ? "remote" : "dynamic",
5426 epf->saddr ? epf->saddr : "",
5427 epf->saddr ? ":" : "",
5430 if (epf->type != 'D') {
5431 char *msg2 = dupprintf("%s to %s:%d", message,
5432 epf->daddr, epf->dport);
5437 logeventf(ssh, "Cancelling %s", message);
5440 /* epf->remote or epf->local may be NULL if setting up a
5441 * forwarding failed. */
5443 struct ssh_rportfwd *rpf = epf->remote;
5444 struct Packet *pktout;
5447 * Cancel the port forwarding at the server
5450 if (ssh->version == 1) {
5452 * We cannot cancel listening ports on the
5453 * server side in SSH-1! There's no message
5454 * to support it. Instead, we simply remove
5455 * the rportfwd record from the local end
5456 * so that any connections the server tries
5457 * to make on it are rejected.
5460 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5461 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
5462 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
5464 ssh2_pkt_addstring(pktout, epf->saddr);
5465 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5466 /* XXX: rport_acceptall may not represent
5467 * what was used to open the original connection,
5468 * since it's reconfigurable. */
5469 ssh2_pkt_addstring(pktout, "");
5471 ssh2_pkt_addstring(pktout, "localhost");
5473 ssh2_pkt_adduint32(pktout, epf->sport);
5474 ssh2_pkt_send(ssh, pktout);
5477 del234(ssh->rportfwds, rpf);
5479 } else if (epf->local) {
5480 pfl_terminate(epf->local);
5483 delpos234(ssh->portfwds, i);
5485 i--; /* so we don't skip one in the list */
5489 * And finally, set up any new port forwardings (status==CREATE).
5491 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5492 if (epf->status == CREATE) {
5493 char *sportdesc, *dportdesc;
5494 sportdesc = dupprintf("%s%s%s%s%d%s",
5495 epf->saddr ? epf->saddr : "",
5496 epf->saddr ? ":" : "",
5497 epf->sserv ? epf->sserv : "",
5498 epf->sserv ? "(" : "",
5500 epf->sserv ? ")" : "");
5501 if (epf->type == 'D') {
5504 dportdesc = dupprintf("%s:%s%s%d%s",
5506 epf->dserv ? epf->dserv : "",
5507 epf->dserv ? "(" : "",
5509 epf->dserv ? ")" : "");
5512 if (epf->type == 'L') {
5513 char *err = pfl_listen(epf->daddr, epf->dport,
5514 epf->saddr, epf->sport,
5515 ssh, conf, &epf->local,
5516 epf->addressfamily);
5518 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
5519 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5520 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5521 sportdesc, dportdesc,
5522 err ? " failed: " : "", err ? err : "");
5525 } else if (epf->type == 'D') {
5526 char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport,
5527 ssh, conf, &epf->local,
5528 epf->addressfamily);
5530 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
5531 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5532 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5534 err ? " failed: " : "", err ? err : "");
5539 struct ssh_rportfwd *pf;
5542 * Ensure the remote port forwardings tree exists.
5544 if (!ssh->rportfwds) {
5545 if (ssh->version == 1)
5546 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
5548 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5551 pf = snew(struct ssh_rportfwd);
5552 pf->share_ctx = NULL;
5553 pf->dhost = dupstr(epf->daddr);
5554 pf->dport = epf->dport;
5556 pf->shost = dupstr(epf->saddr);
5557 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5558 pf->shost = dupstr("");
5560 pf->shost = dupstr("localhost");
5562 pf->sport = epf->sport;
5563 if (add234(ssh->rportfwds, pf) != pf) {
5564 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
5565 epf->daddr, epf->dport);
5568 logeventf(ssh, "Requesting remote port %s"
5569 " forward to %s", sportdesc, dportdesc);
5571 pf->sportdesc = sportdesc;
5576 if (ssh->version == 1) {
5577 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
5578 PKT_INT, epf->sport,
5579 PKT_STR, epf->daddr,
5580 PKT_INT, epf->dport,
5582 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
5584 ssh_rportfwd_succfail, pf);
5586 struct Packet *pktout;
5587 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5588 ssh2_pkt_addstring(pktout, "tcpip-forward");
5589 ssh2_pkt_addbool(pktout, 1);/* want reply */
5590 ssh2_pkt_addstring(pktout, pf->shost);
5591 ssh2_pkt_adduint32(pktout, pf->sport);
5592 ssh2_pkt_send(ssh, pktout);
5594 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
5595 SSH2_MSG_REQUEST_FAILURE,
5596 ssh_rportfwd_succfail, pf);
5605 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
5608 int stringlen, bufsize;
5610 ssh_pkt_getstring(pktin, &string, &stringlen);
5611 if (string == NULL) {
5612 bombout(("Incoming terminal data packet was badly formed"));
5616 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
5618 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
5619 ssh->v1_stdout_throttling = 1;
5620 ssh_throttle_conn(ssh, +1);
5624 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
5626 /* Remote side is trying to open a channel to talk to our
5627 * X-Server. Give them back a local channel number. */
5628 struct ssh_channel *c;
5629 int remoteid = ssh_pkt_getuint32(pktin);
5631 logevent("Received X11 connect request");
5632 /* Refuse if X11 forwarding is disabled. */
5633 if (!ssh->X11_fwd_enabled) {
5634 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5635 PKT_INT, remoteid, PKT_END);
5636 logevent("Rejected X11 connect request");
5638 c = snew(struct ssh_channel);
5641 ssh_channel_init(c);
5642 c->u.x11.xconn = x11_init(ssh->x11authtree, c, NULL, -1);
5643 c->remoteid = remoteid;
5644 c->halfopen = FALSE;
5645 c->type = CHAN_X11; /* identify channel type */
5646 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5647 PKT_INT, c->remoteid, PKT_INT,
5648 c->localid, PKT_END);
5649 logevent("Opened X11 forward channel");
5653 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
5655 /* Remote side is trying to open a channel to talk to our
5656 * agent. Give them back a local channel number. */
5657 struct ssh_channel *c;
5658 int remoteid = ssh_pkt_getuint32(pktin);
5660 /* Refuse if agent forwarding is disabled. */
5661 if (!ssh->agentfwd_enabled) {
5662 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5663 PKT_INT, remoteid, PKT_END);
5665 c = snew(struct ssh_channel);
5667 ssh_channel_init(c);
5668 c->remoteid = remoteid;
5669 c->halfopen = FALSE;
5670 c->type = CHAN_AGENT; /* identify channel type */
5671 c->u.a.pending = NULL;
5672 bufchain_init(&c->u.a.inbuffer);
5673 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5674 PKT_INT, c->remoteid, PKT_INT, c->localid,
5679 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
5681 /* Remote side is trying to open a channel to talk to a
5682 * forwarded port. Give them back a local channel number. */
5683 struct ssh_rportfwd pf, *pfp;
5689 remoteid = ssh_pkt_getuint32(pktin);
5690 ssh_pkt_getstring(pktin, &host, &hostsize);
5691 port = ssh_pkt_getuint32(pktin);
5693 pf.dhost = dupprintf("%.*s", hostsize, NULLTOEMPTY(host));
5695 pfp = find234(ssh->rportfwds, &pf, NULL);
5698 logeventf(ssh, "Rejected remote port open request for %s:%d",
5700 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5701 PKT_INT, remoteid, PKT_END);
5703 struct ssh_channel *c = snew(struct ssh_channel);
5706 logeventf(ssh, "Received remote port open request for %s:%d",
5708 err = pfd_connect(&c->u.pfd.pf, pf.dhost, port,
5709 c, ssh->conf, pfp->pfrec->addressfamily);
5711 logeventf(ssh, "Port open failed: %s", err);
5714 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5715 PKT_INT, remoteid, PKT_END);
5717 ssh_channel_init(c);
5718 c->remoteid = remoteid;
5719 c->halfopen = FALSE;
5720 c->type = CHAN_SOCKDATA; /* identify channel type */
5721 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5722 PKT_INT, c->remoteid, PKT_INT,
5723 c->localid, PKT_END);
5724 logevent("Forwarded port opened successfully");
5731 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
5733 struct ssh_channel *c;
5735 c = ssh_channel_msg(ssh, pktin);
5736 if (c && c->type == CHAN_SOCKDATA) {
5737 c->remoteid = ssh_pkt_getuint32(pktin);
5738 c->halfopen = FALSE;
5739 c->throttling_conn = 0;
5740 pfd_confirm(c->u.pfd.pf);
5743 if (c && c->pending_eof) {
5745 * We have a pending close on this channel,
5746 * which we decided on before the server acked
5747 * the channel open. So now we know the
5748 * remoteid, we can close it again.
5750 ssh_channel_try_eof(c);
5754 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
5756 struct ssh_channel *c;
5758 c = ssh_channel_msg(ssh, pktin);
5759 if (c && c->type == CHAN_SOCKDATA) {
5760 logevent("Forwarded connection refused by server");
5761 pfd_close(c->u.pfd.pf);
5762 del234(ssh->channels, c);
5767 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
5769 /* Remote side closes a channel. */
5770 struct ssh_channel *c;
5772 c = ssh_channel_msg(ssh, pktin);
5775 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE) {
5777 * Received CHANNEL_CLOSE, which we translate into
5780 ssh_channel_got_eof(c);
5783 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
5784 !(c->closes & CLOSES_RCVD_CLOSE)) {
5786 if (!(c->closes & CLOSES_SENT_EOF)) {
5787 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %u"
5788 " for which we never sent CHANNEL_CLOSE\n",
5792 c->closes |= CLOSES_RCVD_CLOSE;
5795 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
5796 !(c->closes & CLOSES_SENT_CLOSE)) {
5797 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
5798 PKT_INT, c->remoteid, PKT_END);
5799 c->closes |= CLOSES_SENT_CLOSE;
5802 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
5803 ssh_channel_destroy(c);
5808 * Handle incoming data on an SSH-1 or SSH-2 agent-forwarding channel.
5810 static int ssh_agent_channel_data(struct ssh_channel *c, char *data,
5813 bufchain_add(&c->u.a.inbuffer, data, length);
5814 ssh_agentf_try_forward(c);
5817 * We exert back-pressure on an agent forwarding client if and
5818 * only if we're waiting for the response to an asynchronous agent
5819 * request. This prevents the client running out of window while
5820 * receiving the _first_ message, but means that if any message
5821 * takes time to process, the client will be discouraged from
5822 * sending an endless stream of further ones after it.
5824 return (c->u.a.pending ? bufchain_size(&c->u.a.inbuffer) : 0);
5827 static int ssh_channel_data(struct ssh_channel *c, int is_stderr,
5828 char *data, int length)
5831 case CHAN_MAINSESSION:
5832 return from_backend(c->ssh->frontend, is_stderr, data, length);
5834 return x11_send(c->u.x11.xconn, data, length);
5836 return pfd_send(c->u.pfd.pf, data, length);
5838 return ssh_agent_channel_data(c, data, length);
5843 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
5845 /* Data sent down one of our channels. */
5848 struct ssh_channel *c;
5850 c = ssh_channel_msg(ssh, pktin);
5851 ssh_pkt_getstring(pktin, &p, &len);
5854 int bufsize = ssh_channel_data(c, FALSE, p, len);
5855 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5856 c->throttling_conn = 1;
5857 ssh_throttle_conn(ssh, +1);
5862 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5864 ssh->exitcode = ssh_pkt_getuint32(pktin);
5865 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5866 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5868 * In case `helpful' firewalls or proxies tack
5869 * extra human-readable text on the end of the
5870 * session which we might mistake for another
5871 * encrypted packet, we close the session once
5872 * we've sent EXIT_CONFIRMATION.
5874 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5877 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5878 static void ssh1_send_ttymode(void *data,
5879 const struct ssh_ttymode *mode, char *val)
5881 struct Packet *pktout = (struct Packet *)data;
5882 unsigned int arg = 0;
5884 switch (mode->type) {
5886 arg = ssh_tty_parse_specchar(val);
5889 arg = ssh_tty_parse_boolean(val);
5892 ssh2_pkt_addbyte(pktout, mode->opcode);
5893 ssh2_pkt_addbyte(pktout, arg);
5896 int ssh_agent_forwarding_permitted(Ssh ssh)
5898 return conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists();
5901 static void do_ssh1_connection(Ssh ssh, const unsigned char *in, int inlen,
5902 struct Packet *pktin)
5904 crBegin(ssh->do_ssh1_connection_crstate);
5906 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5907 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5908 ssh1_smsg_stdout_stderr_data;
5910 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5911 ssh1_msg_channel_open_confirmation;
5912 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5913 ssh1_msg_channel_open_failure;
5914 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5915 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5916 ssh1_msg_channel_close;
5917 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5918 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5920 if (ssh_agent_forwarding_permitted(ssh)) {
5921 logevent("Requesting agent forwarding");
5922 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5926 if (pktin->type != SSH1_SMSG_SUCCESS
5927 && pktin->type != SSH1_SMSG_FAILURE) {
5928 bombout(("Protocol confusion"));
5930 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5931 logevent("Agent forwarding refused");
5933 logevent("Agent forwarding enabled");
5934 ssh->agentfwd_enabled = TRUE;
5935 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5939 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
5941 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5943 if (!ssh->x11disp) {
5944 /* FIXME: return an error message from x11_setup_display */
5945 logevent("X11 forwarding not enabled: unable to"
5946 " initialise X display");
5948 ssh->x11auth = x11_invent_fake_auth
5949 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
5950 ssh->x11auth->disp = ssh->x11disp;
5952 logevent("Requesting X11 forwarding");
5953 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5954 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5955 PKT_STR, ssh->x11auth->protoname,
5956 PKT_STR, ssh->x11auth->datastring,
5957 PKT_INT, ssh->x11disp->screennum,
5960 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5961 PKT_STR, ssh->x11auth->protoname,
5962 PKT_STR, ssh->x11auth->datastring,
5968 if (pktin->type != SSH1_SMSG_SUCCESS
5969 && pktin->type != SSH1_SMSG_FAILURE) {
5970 bombout(("Protocol confusion"));
5972 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5973 logevent("X11 forwarding refused");
5975 logevent("X11 forwarding enabled");
5976 ssh->X11_fwd_enabled = TRUE;
5977 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5982 ssh_setup_portfwd(ssh, ssh->conf);
5983 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5985 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5987 /* Unpick the terminal-speed string. */
5988 /* XXX perhaps we should allow no speeds to be sent. */
5989 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5990 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5991 /* Send the pty request. */
5992 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5993 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5994 ssh_pkt_adduint32(pkt, ssh->term_height);
5995 ssh_pkt_adduint32(pkt, ssh->term_width);
5996 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5997 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5998 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5999 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
6000 ssh_pkt_adduint32(pkt, ssh->ispeed);
6001 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
6002 ssh_pkt_adduint32(pkt, ssh->ospeed);
6003 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
6005 ssh->state = SSH_STATE_INTERMED;
6009 if (pktin->type != SSH1_SMSG_SUCCESS
6010 && pktin->type != SSH1_SMSG_FAILURE) {
6011 bombout(("Protocol confusion"));
6013 } else if (pktin->type == SSH1_SMSG_FAILURE) {
6014 c_write_str(ssh, "Server refused to allocate pty\r\n");
6015 ssh->editing = ssh->echoing = 1;
6017 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
6018 ssh->ospeed, ssh->ispeed);
6019 ssh->got_pty = TRUE;
6022 ssh->editing = ssh->echoing = 1;
6025 if (conf_get_int(ssh->conf, CONF_compression)) {
6026 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
6030 if (pktin->type != SSH1_SMSG_SUCCESS
6031 && pktin->type != SSH1_SMSG_FAILURE) {
6032 bombout(("Protocol confusion"));
6034 } else if (pktin->type == SSH1_SMSG_FAILURE) {
6035 c_write_str(ssh, "Server refused to compress\r\n");
6037 logevent("Started compression");
6038 ssh->v1_compressing = TRUE;
6039 ssh->cs_comp_ctx = zlib_compress_init();
6040 logevent("Initialised zlib (RFC1950) compression");
6041 ssh->sc_comp_ctx = zlib_decompress_init();
6042 logevent("Initialised zlib (RFC1950) decompression");
6046 * Start the shell or command.
6048 * Special case: if the first-choice command is an SSH-2
6049 * subsystem (hence not usable here) and the second choice
6050 * exists, we fall straight back to that.
6053 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
6055 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
6056 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
6057 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
6058 ssh->fallback_cmd = TRUE;
6061 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
6063 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
6064 logevent("Started session");
6067 ssh->state = SSH_STATE_SESSION;
6068 if (ssh->size_needed)
6069 ssh_size(ssh, ssh->term_width, ssh->term_height);
6070 if (ssh->eof_needed)
6071 ssh_special(ssh, TS_EOF);
6074 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
6076 ssh->channels = newtree234(ssh_channelcmp);
6080 * By this point, most incoming packets are already being
6081 * handled by the dispatch table, and we need only pay
6082 * attention to the unusual ones.
6087 if (pktin->type == SSH1_SMSG_SUCCESS) {
6088 /* may be from EXEC_SHELL on some servers */
6089 } else if (pktin->type == SSH1_SMSG_FAILURE) {
6090 /* may be from EXEC_SHELL on some servers
6091 * if no pty is available or in other odd cases. Ignore */
6093 bombout(("Strange packet received: type %d", pktin->type));
6098 int len = min(inlen, 512);
6099 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
6100 PKT_INT, len, PKT_DATA, in, len,
6112 * Handle the top-level SSH-2 protocol.
6114 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
6119 ssh_pkt_getstring(pktin, &msg, &msglen);
6120 logeventf(ssh, "Remote debug message: %.*s", msglen, NULLTOEMPTY(msg));
6123 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
6125 /* log reason code in disconnect message */
6129 ssh_pkt_getstring(pktin, &msg, &msglen);
6130 bombout(("Server sent disconnect message:\n\"%.*s\"",
6131 msglen, NULLTOEMPTY(msg)));
6134 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
6136 /* Do nothing, because we're ignoring it! Duhh. */
6139 static void ssh1_protocol_setup(Ssh ssh)
6144 * Most messages are handled by the coroutines.
6146 for (i = 0; i < 256; i++)
6147 ssh->packet_dispatch[i] = NULL;
6150 * These special message types we install handlers for.
6152 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
6153 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
6154 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
6157 static void ssh1_protocol(Ssh ssh, const void *vin, int inlen,
6158 struct Packet *pktin)
6160 const unsigned char *in = (const unsigned char *)vin;
6161 if (ssh->state == SSH_STATE_CLOSED)
6164 if (pktin && ssh->packet_dispatch[pktin->type]) {
6165 ssh->packet_dispatch[pktin->type](ssh, pktin);
6169 if (!ssh->protocol_initial_phase_done) {
6170 if (do_ssh1_login(ssh, in, inlen, pktin))
6171 ssh->protocol_initial_phase_done = TRUE;
6176 do_ssh1_connection(ssh, in, inlen, pktin);
6180 * Utility routines for decoding comma-separated strings in KEXINIT.
6182 static int first_in_commasep_string(char const *needle, char const *haystack,
6186 if (!needle || !haystack) /* protect against null pointers */
6188 needlen = strlen(needle);
6190 if (haylen >= needlen && /* haystack is long enough */
6191 !memcmp(needle, haystack, needlen) && /* initial match */
6192 (haylen == needlen || haystack[needlen] == ',')
6193 /* either , or EOS follows */
6199 static int in_commasep_string(char const *needle, char const *haystack,
6204 if (!needle || !haystack) /* protect against null pointers */
6207 * Is it at the start of the string?
6209 if (first_in_commasep_string(needle, haystack, haylen))
6212 * If not, search for the next comma and resume after that.
6213 * If no comma found, terminate.
6215 p = memchr(haystack, ',', haylen);
6217 /* + 1 to skip over comma */
6218 return in_commasep_string(needle, p + 1, haylen - (p + 1 - haystack));
6222 * Add a value to the comma-separated string at the end of the packet.
6224 static void ssh2_pkt_addstring_commasep(struct Packet *pkt, const char *data)
6226 if (pkt->length - pkt->savedpos > 0)
6227 ssh_pkt_addstring_str(pkt, ",");
6228 ssh_pkt_addstring_str(pkt, data);
6233 * SSH-2 key derivation (RFC 4253 section 7.2).
6235 static unsigned char *ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H,
6236 char chr, int keylen)
6238 const struct ssh_hash *h = ssh->kex->hash;
6246 /* Round up to the next multiple of hash length. */
6247 keylen_padded = ((keylen + h->hlen - 1) / h->hlen) * h->hlen;
6249 key = snewn(keylen_padded, unsigned char);
6251 /* First hlen bytes. */
6253 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6254 hash_mpint(h, s, K);
6255 h->bytes(s, H, h->hlen);
6256 h->bytes(s, &chr, 1);
6257 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
6260 /* Subsequent blocks of hlen bytes. */
6261 if (keylen_padded > h->hlen) {
6265 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6266 hash_mpint(h, s, K);
6267 h->bytes(s, H, h->hlen);
6269 for (offset = h->hlen; offset < keylen_padded; offset += h->hlen) {
6270 h->bytes(s, key + offset - h->hlen, h->hlen);
6272 h->final(s2, key + offset);
6278 /* Now clear any extra bytes of key material beyond the length
6279 * we're officially returning, because the caller won't know to
6281 if (keylen_padded > keylen)
6282 smemclr(key + keylen, keylen_padded - keylen);
6288 * Structure for constructing KEXINIT algorithm lists.
6290 #define MAXKEXLIST 16
6291 struct kexinit_algorithm {
6295 const struct ssh_kex *kex;
6299 const struct ssh_signkey *hostkey;
6303 const struct ssh2_cipher *cipher;
6307 const struct ssh_mac *mac;
6310 const struct ssh_compress *comp;
6315 * Find a slot in a KEXINIT algorithm list to use for a new algorithm.
6316 * If the algorithm is already in the list, return a pointer to its
6317 * entry, otherwise return an entry from the end of the list.
6318 * This assumes that every time a particular name is passed in, it
6319 * comes from the same string constant. If this isn't true, this
6320 * function may need to be rewritten to use strcmp() instead.
6322 static struct kexinit_algorithm *ssh2_kexinit_addalg(struct kexinit_algorithm
6323 *list, const char *name)
6327 for (i = 0; i < MAXKEXLIST; i++)
6328 if (list[i].name == NULL || list[i].name == name) {
6329 list[i].name = name;
6332 assert(!"No space in KEXINIT list");
6337 * Handle the SSH-2 transport layer.
6339 static void do_ssh2_transport(Ssh ssh, const void *vin, int inlen,
6340 struct Packet *pktin)
6342 const unsigned char *in = (const unsigned char *)vin;
6344 KEXLIST_KEX, KEXLIST_HOSTKEY, KEXLIST_CSCIPHER, KEXLIST_SCCIPHER,
6345 KEXLIST_CSMAC, KEXLIST_SCMAC, KEXLIST_CSCOMP, KEXLIST_SCCOMP,
6348 const char * kexlist_descr[NKEXLIST] = {
6349 "key exchange algorithm", "host key algorithm",
6350 "client-to-server cipher", "server-to-client cipher",
6351 "client-to-server MAC", "server-to-client MAC",
6352 "client-to-server compression method",
6353 "server-to-client compression method" };
6354 struct do_ssh2_transport_state {
6356 int nbits, pbits, warn_kex, warn_hk, warn_cscipher, warn_sccipher;
6357 Bignum p, g, e, f, K;
6360 int kex_init_value, kex_reply_value;
6361 const struct ssh_mac *const *maclist;
6363 const struct ssh2_cipher *cscipher_tobe;
6364 const struct ssh2_cipher *sccipher_tobe;
6365 const struct ssh_mac *csmac_tobe;
6366 const struct ssh_mac *scmac_tobe;
6367 int csmac_etm_tobe, scmac_etm_tobe;
6368 const struct ssh_compress *cscomp_tobe;
6369 const struct ssh_compress *sccomp_tobe;
6370 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
6371 int hostkeylen, siglen, rsakeylen;
6372 void *hkey; /* actual host key */
6373 void *rsakey; /* for RSA kex */
6374 void *eckey; /* for ECDH kex */
6375 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
6376 int n_preferred_kex;
6377 const struct ssh_kexes *preferred_kex[KEX_MAX];
6379 int preferred_hk[HK_MAX];
6380 int n_preferred_ciphers;
6381 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
6382 const struct ssh_compress *preferred_comp;
6383 int userauth_succeeded; /* for delayed compression */
6384 int pending_compression;
6385 int got_session_id, activated_authconn;
6386 struct Packet *pktout;
6390 struct kexinit_algorithm kexlists[NKEXLIST][MAXKEXLIST];
6392 crState(do_ssh2_transport_state);
6394 assert(!ssh->bare_connection);
6395 assert(ssh->version == 2);
6399 s->cscipher_tobe = s->sccipher_tobe = NULL;
6400 s->csmac_tobe = s->scmac_tobe = NULL;
6401 s->cscomp_tobe = s->sccomp_tobe = NULL;
6403 s->got_session_id = s->activated_authconn = FALSE;
6404 s->userauth_succeeded = FALSE;
6405 s->pending_compression = FALSE;
6408 * Be prepared to work around the buggy MAC problem.
6410 if (ssh->remote_bugs & BUG_SSH2_HMAC)
6411 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
6413 s->maclist = macs, s->nmacs = lenof(macs);
6416 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
6419 struct kexinit_algorithm *alg;
6422 * Set up the preferred key exchange. (NULL => warn below here)
6424 s->n_preferred_kex = 0;
6425 for (i = 0; i < KEX_MAX; i++) {
6426 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
6428 s->preferred_kex[s->n_preferred_kex++] =
6429 &ssh_diffiehellman_gex;
6432 s->preferred_kex[s->n_preferred_kex++] =
6433 &ssh_diffiehellman_group14;
6436 s->preferred_kex[s->n_preferred_kex++] =
6437 &ssh_diffiehellman_group1;
6440 s->preferred_kex[s->n_preferred_kex++] =
6444 s->preferred_kex[s->n_preferred_kex++] =
6448 /* Flag for later. Don't bother if it's the last in
6450 if (i < KEX_MAX - 1) {
6451 s->preferred_kex[s->n_preferred_kex++] = NULL;
6458 * Set up the preferred host key types. These are just the ids
6459 * in the enum in putty.h, so 'warn below here' is indicated
6462 s->n_preferred_hk = 0;
6463 for (i = 0; i < HK_MAX; i++) {
6464 int id = conf_get_int_int(ssh->conf, CONF_ssh_hklist, i);
6465 /* As above, don't bother with HK_WARN if it's last in the
6467 if (id != HK_WARN || i < HK_MAX - 1)
6468 s->preferred_hk[s->n_preferred_hk++] = id;
6472 * Set up the preferred ciphers. (NULL => warn below here)
6474 s->n_preferred_ciphers = 0;
6475 for (i = 0; i < CIPHER_MAX; i++) {
6476 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
6477 case CIPHER_BLOWFISH:
6478 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
6481 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
6482 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
6486 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
6489 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
6491 case CIPHER_ARCFOUR:
6492 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
6494 case CIPHER_CHACHA20:
6495 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_ccp;
6498 /* Flag for later. Don't bother if it's the last in
6500 if (i < CIPHER_MAX - 1) {
6501 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
6508 * Set up preferred compression.
6510 if (conf_get_int(ssh->conf, CONF_compression))
6511 s->preferred_comp = &ssh_zlib;
6513 s->preferred_comp = &ssh_comp_none;
6516 * Enable queueing of outgoing auth- or connection-layer
6517 * packets while we are in the middle of a key exchange.
6519 ssh->queueing = TRUE;
6522 * Flag that KEX is in progress.
6524 ssh->kex_in_progress = TRUE;
6526 for (i = 0; i < NKEXLIST; i++)
6527 for (j = 0; j < MAXKEXLIST; j++)
6528 s->kexlists[i][j].name = NULL;
6529 /* List key exchange algorithms. */
6531 for (i = 0; i < s->n_preferred_kex; i++) {
6532 const struct ssh_kexes *k = s->preferred_kex[i];
6533 if (!k) warn = TRUE;
6534 else for (j = 0; j < k->nkexes; j++) {
6535 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_KEX],
6537 alg->u.kex.kex = k->list[j];
6538 alg->u.kex.warn = warn;
6541 /* List server host key algorithms. */
6542 if (!s->got_session_id) {
6544 * In the first key exchange, we list all the algorithms
6545 * we're prepared to cope with, but prefer those algorithms
6546 * for which we have a host key for this host.
6548 * If the host key algorithm is below the warning
6549 * threshold, we warn even if we did already have a key
6550 * for it, on the basis that if the user has just
6551 * reconfigured that host key type to be warned about,
6552 * they surely _do_ want to be alerted that a server
6553 * they're actually connecting to is using it.
6556 for (i = 0; i < s->n_preferred_hk; i++) {
6557 if (s->preferred_hk[i] == HK_WARN)
6559 for (j = 0; j < lenof(hostkey_algs); j++) {
6560 if (hostkey_algs[j].id != s->preferred_hk[i])
6562 if (have_ssh_host_key(ssh->savedhost, ssh->savedport,
6563 hostkey_algs[j].alg->keytype)) {
6564 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6565 hostkey_algs[j].alg->name);
6566 alg->u.hk.hostkey = hostkey_algs[j].alg;
6567 alg->u.hk.warn = warn;
6572 for (i = 0; i < s->n_preferred_hk; i++) {
6573 if (s->preferred_hk[i] == HK_WARN)
6575 for (j = 0; j < lenof(hostkey_algs); j++) {
6576 if (hostkey_algs[j].id != s->preferred_hk[i])
6578 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6579 hostkey_algs[j].alg->name);
6580 alg->u.hk.hostkey = hostkey_algs[j].alg;
6581 alg->u.hk.warn = warn;
6586 * In subsequent key exchanges, we list only the kex
6587 * algorithm that was selected in the first key exchange,
6588 * so that we keep getting the same host key and hence
6589 * don't have to interrupt the user's session to ask for
6593 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6594 ssh->hostkey->name);
6595 alg->u.hk.hostkey = ssh->hostkey;
6596 alg->u.hk.warn = FALSE;
6598 /* List encryption algorithms (client->server then server->client). */
6599 for (k = KEXLIST_CSCIPHER; k <= KEXLIST_SCCIPHER; k++) {
6602 alg = ssh2_kexinit_addalg(s->kexlists[k], "none");
6603 alg->u.cipher.cipher = NULL;
6604 alg->u.cipher.warn = warn;
6605 #endif /* FUZZING */
6606 for (i = 0; i < s->n_preferred_ciphers; i++) {
6607 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6608 if (!c) warn = TRUE;
6609 else for (j = 0; j < c->nciphers; j++) {
6610 alg = ssh2_kexinit_addalg(s->kexlists[k],
6612 alg->u.cipher.cipher = c->list[j];
6613 alg->u.cipher.warn = warn;
6617 /* List MAC algorithms (client->server then server->client). */
6618 for (j = KEXLIST_CSMAC; j <= KEXLIST_SCMAC; j++) {
6620 alg = ssh2_kexinit_addalg(s->kexlists[j], "none");
6621 alg->u.mac.mac = NULL;
6622 alg->u.mac.etm = FALSE;
6623 #endif /* FUZZING */
6624 for (i = 0; i < s->nmacs; i++) {
6625 alg = ssh2_kexinit_addalg(s->kexlists[j], s->maclist[i]->name);
6626 alg->u.mac.mac = s->maclist[i];
6627 alg->u.mac.etm = FALSE;
6629 for (i = 0; i < s->nmacs; i++)
6630 /* For each MAC, there may also be an ETM version,
6631 * which we list second. */
6632 if (s->maclist[i]->etm_name) {
6633 alg = ssh2_kexinit_addalg(s->kexlists[j],
6634 s->maclist[i]->etm_name);
6635 alg->u.mac.mac = s->maclist[i];
6636 alg->u.mac.etm = TRUE;
6639 /* List client->server compression algorithms,
6640 * then server->client compression algorithms. (We use the
6641 * same set twice.) */
6642 for (j = KEXLIST_CSCOMP; j <= KEXLIST_SCCOMP; j++) {
6643 assert(lenof(compressions) > 1);
6644 /* Prefer non-delayed versions */
6645 alg = ssh2_kexinit_addalg(s->kexlists[j], s->preferred_comp->name);
6646 alg->u.comp = s->preferred_comp;
6647 /* We don't even list delayed versions of algorithms until
6648 * they're allowed to be used, to avoid a race. See the end of
6650 if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
6651 alg = ssh2_kexinit_addalg(s->kexlists[j],
6652 s->preferred_comp->delayed_name);
6653 alg->u.comp = s->preferred_comp;
6655 for (i = 0; i < lenof(compressions); i++) {
6656 const struct ssh_compress *c = compressions[i];
6657 alg = ssh2_kexinit_addalg(s->kexlists[j], c->name);
6659 if (s->userauth_succeeded && c->delayed_name) {
6660 alg = ssh2_kexinit_addalg(s->kexlists[j], c->delayed_name);
6666 * Construct and send our key exchange packet.
6668 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
6669 for (i = 0; i < 16; i++)
6670 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
6671 for (i = 0; i < NKEXLIST; i++) {
6672 ssh2_pkt_addstring_start(s->pktout);
6673 for (j = 0; j < MAXKEXLIST; j++) {
6674 if (s->kexlists[i][j].name == NULL) break;
6675 ssh2_pkt_addstring_commasep(s->pktout, s->kexlists[i][j].name);
6678 /* List client->server languages. Empty list. */
6679 ssh2_pkt_addstring_start(s->pktout);
6680 /* List server->client languages. Empty list. */
6681 ssh2_pkt_addstring_start(s->pktout);
6682 /* First KEX packet does _not_ follow, because we're not that brave. */
6683 ssh2_pkt_addbool(s->pktout, FALSE);
6685 ssh2_pkt_adduint32(s->pktout, 0);
6688 s->our_kexinitlen = s->pktout->length - 5;
6689 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
6690 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
6692 ssh2_pkt_send_noqueue(ssh, s->pktout);
6695 crWaitUntilV(pktin);
6698 * Now examine the other side's KEXINIT to see what we're up
6705 if (pktin->type != SSH2_MSG_KEXINIT) {
6706 bombout(("expected key exchange packet from server"));
6710 ssh->hostkey = NULL;
6711 s->cscipher_tobe = NULL;
6712 s->sccipher_tobe = NULL;
6713 s->csmac_tobe = NULL;
6714 s->scmac_tobe = NULL;
6715 s->cscomp_tobe = NULL;
6716 s->sccomp_tobe = NULL;
6717 s->warn_kex = s->warn_hk = FALSE;
6718 s->warn_cscipher = s->warn_sccipher = FALSE;
6720 pktin->savedpos += 16; /* skip garbage cookie */
6723 for (i = 0; i < NKEXLIST; i++) {
6724 ssh_pkt_getstring(pktin, &str, &len);
6726 bombout(("KEXINIT packet was incomplete"));
6730 /* If we've already selected a cipher which requires a
6731 * particular MAC, then just select that, and don't even
6732 * bother looking through the server's KEXINIT string for
6734 if (i == KEXLIST_CSMAC && s->cscipher_tobe &&
6735 s->cscipher_tobe->required_mac) {
6736 s->csmac_tobe = s->cscipher_tobe->required_mac;
6737 s->csmac_etm_tobe = !!(s->csmac_tobe->etm_name);
6740 if (i == KEXLIST_SCMAC && s->sccipher_tobe &&
6741 s->sccipher_tobe->required_mac) {
6742 s->scmac_tobe = s->sccipher_tobe->required_mac;
6743 s->scmac_etm_tobe = !!(s->scmac_tobe->etm_name);
6747 for (j = 0; j < MAXKEXLIST; j++) {
6748 struct kexinit_algorithm *alg = &s->kexlists[i][j];
6749 if (alg->name == NULL) break;
6750 if (in_commasep_string(alg->name, str, len)) {
6751 /* We've found a matching algorithm. */
6752 if (i == KEXLIST_KEX || i == KEXLIST_HOSTKEY) {
6753 /* Check if we might need to ignore first kex pkt */
6755 !first_in_commasep_string(alg->name, str, len))
6758 if (i == KEXLIST_KEX) {
6759 ssh->kex = alg->u.kex.kex;
6760 s->warn_kex = alg->u.kex.warn;
6761 } else if (i == KEXLIST_HOSTKEY) {
6762 ssh->hostkey = alg->u.hk.hostkey;
6763 s->warn_hk = alg->u.hk.warn;
6764 } else if (i == KEXLIST_CSCIPHER) {
6765 s->cscipher_tobe = alg->u.cipher.cipher;
6766 s->warn_cscipher = alg->u.cipher.warn;
6767 } else if (i == KEXLIST_SCCIPHER) {
6768 s->sccipher_tobe = alg->u.cipher.cipher;
6769 s->warn_sccipher = alg->u.cipher.warn;
6770 } else if (i == KEXLIST_CSMAC) {
6771 s->csmac_tobe = alg->u.mac.mac;
6772 s->csmac_etm_tobe = alg->u.mac.etm;
6773 } else if (i == KEXLIST_SCMAC) {
6774 s->scmac_tobe = alg->u.mac.mac;
6775 s->scmac_etm_tobe = alg->u.mac.etm;
6776 } else if (i == KEXLIST_CSCOMP) {
6777 s->cscomp_tobe = alg->u.comp;
6778 } else if (i == KEXLIST_SCCOMP) {
6779 s->sccomp_tobe = alg->u.comp;
6783 if ((i == KEXLIST_CSCOMP || i == KEXLIST_SCCOMP) &&
6784 in_commasep_string(alg->u.comp->delayed_name, str, len))
6785 s->pending_compression = TRUE; /* try this later */
6787 bombout(("Couldn't agree a %s (available: %.*s)",
6788 kexlist_descr[i], len, str));
6792 if (i == KEXLIST_HOSTKEY) {
6796 * In addition to deciding which host key we're
6797 * actually going to use, we should make a list of the
6798 * host keys offered by the server which we _don't_
6799 * have cached. These will be offered as cross-
6800 * certification options by ssh_get_specials.
6802 * We also count the key we're currently using for KEX
6803 * as one we've already got, because by the time this
6804 * menu becomes visible, it will be.
6806 ssh->n_uncert_hostkeys = 0;
6808 for (j = 0; j < lenof(hostkey_algs); j++) {
6809 if (hostkey_algs[j].alg != ssh->hostkey &&
6810 in_commasep_string(hostkey_algs[j].alg->name,
6812 !have_ssh_host_key(ssh->savedhost, ssh->savedport,
6813 hostkey_algs[j].alg->keytype)) {
6814 ssh->uncert_hostkeys[ssh->n_uncert_hostkeys++] = j;
6820 if (s->pending_compression) {
6821 logevent("Server supports delayed compression; "
6822 "will try this later");
6824 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
6825 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
6826 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
6828 ssh->exhash = ssh->kex->hash->init();
6829 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
6830 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
6831 hash_string(ssh->kex->hash, ssh->exhash,
6832 s->our_kexinit, s->our_kexinitlen);
6833 sfree(s->our_kexinit);
6834 /* Include the type byte in the hash of server's KEXINIT */
6835 hash_string(ssh->kex->hash, ssh->exhash,
6836 pktin->body - 1, pktin->length + 1);
6839 ssh_set_frozen(ssh, 1);
6840 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
6842 ssh_dialog_callback, ssh);
6843 if (s->dlgret < 0) {
6847 bombout(("Unexpected data from server while"
6848 " waiting for user response"));
6851 } while (pktin || inlen > 0);
6852 s->dlgret = ssh->user_response;
6854 ssh_set_frozen(ssh, 0);
6855 if (s->dlgret == 0) {
6856 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
6866 ssh_set_frozen(ssh, 1);
6869 * Change warning box wording depending on why we chose a
6870 * warning-level host key algorithm. If it's because
6871 * that's all we have *cached*, use the askhk mechanism,
6872 * and list the host keys we could usefully cross-certify.
6873 * Otherwise, use askalg for the standard wording.
6876 for (j = 0; j < ssh->n_uncert_hostkeys; j++) {
6877 const struct ssh_signkey_with_user_pref_id *hktype =
6878 &hostkey_algs[ssh->uncert_hostkeys[j]];
6880 for (k = 0; k < HK_MAX; k++) {
6881 int id = conf_get_int_int(ssh->conf, CONF_ssh_hklist, k);
6882 if (id == HK_WARN) {
6884 } else if (id == hktype->id) {
6891 char *old_ba = betteralgs;
6892 betteralgs = dupcat(betteralgs, ",",
6894 (const char *)NULL);
6897 betteralgs = dupstr(hktype->alg->name);
6902 s->dlgret = askhk(ssh->frontend, ssh->hostkey->name,
6903 betteralgs, ssh_dialog_callback, ssh);
6906 s->dlgret = askalg(ssh->frontend, "host key type",
6908 ssh_dialog_callback, ssh);
6910 if (s->dlgret < 0) {
6914 bombout(("Unexpected data from server while"
6915 " waiting for user response"));
6918 } while (pktin || inlen > 0);
6919 s->dlgret = ssh->user_response;
6921 ssh_set_frozen(ssh, 0);
6922 if (s->dlgret == 0) {
6923 ssh_disconnect(ssh, "User aborted at host key warning", NULL,
6929 if (s->warn_cscipher) {
6930 ssh_set_frozen(ssh, 1);
6931 s->dlgret = askalg(ssh->frontend,
6932 "client-to-server cipher",
6933 s->cscipher_tobe->name,
6934 ssh_dialog_callback, ssh);
6935 if (s->dlgret < 0) {
6939 bombout(("Unexpected data from server while"
6940 " waiting for user response"));
6943 } while (pktin || inlen > 0);
6944 s->dlgret = ssh->user_response;
6946 ssh_set_frozen(ssh, 0);
6947 if (s->dlgret == 0) {
6948 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6954 if (s->warn_sccipher) {
6955 ssh_set_frozen(ssh, 1);
6956 s->dlgret = askalg(ssh->frontend,
6957 "server-to-client cipher",
6958 s->sccipher_tobe->name,
6959 ssh_dialog_callback, ssh);
6960 if (s->dlgret < 0) {
6964 bombout(("Unexpected data from server while"
6965 " waiting for user response"));
6968 } while (pktin || inlen > 0);
6969 s->dlgret = ssh->user_response;
6971 ssh_set_frozen(ssh, 0);
6972 if (s->dlgret == 0) {
6973 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6979 if (s->ignorepkt) /* first_kex_packet_follows */
6980 crWaitUntilV(pktin); /* Ignore packet */
6983 if (ssh->kex->main_type == KEXTYPE_DH) {
6985 * Work out the number of bits of key we will need from the
6986 * key exchange. We start with the maximum key length of
6992 csbits = s->cscipher_tobe ? s->cscipher_tobe->real_keybits : 0;
6993 scbits = s->sccipher_tobe ? s->sccipher_tobe->real_keybits : 0;
6994 s->nbits = (csbits > scbits ? csbits : scbits);
6996 /* The keys only have hlen-bit entropy, since they're based on
6997 * a hash. So cap the key size at hlen bits. */
6998 if (s->nbits > ssh->kex->hash->hlen * 8)
6999 s->nbits = ssh->kex->hash->hlen * 8;
7002 * If we're doing Diffie-Hellman group exchange, start by
7003 * requesting a group.
7005 if (dh_is_gex(ssh->kex)) {
7006 logevent("Doing Diffie-Hellman group exchange");
7007 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
7009 * Work out how big a DH group we will need to allow that
7012 s->pbits = 512 << ((s->nbits - 1) / 64);
7013 if (s->pbits < DH_MIN_SIZE)
7014 s->pbits = DH_MIN_SIZE;
7015 if (s->pbits > DH_MAX_SIZE)
7016 s->pbits = DH_MAX_SIZE;
7017 if ((ssh->remote_bugs & BUG_SSH2_OLDGEX)) {
7018 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD);
7019 ssh2_pkt_adduint32(s->pktout, s->pbits);
7021 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
7022 ssh2_pkt_adduint32(s->pktout, DH_MIN_SIZE);
7023 ssh2_pkt_adduint32(s->pktout, s->pbits);
7024 ssh2_pkt_adduint32(s->pktout, DH_MAX_SIZE);
7026 ssh2_pkt_send_noqueue(ssh, s->pktout);
7028 crWaitUntilV(pktin);
7029 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
7030 bombout(("expected key exchange group packet from server"));
7033 s->p = ssh2_pkt_getmp(pktin);
7034 s->g = ssh2_pkt_getmp(pktin);
7035 if (!s->p || !s->g) {
7036 bombout(("unable to read mp-ints from incoming group packet"));
7039 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
7040 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
7041 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
7043 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
7044 ssh->kex_ctx = dh_setup_group(ssh->kex);
7045 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
7046 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
7047 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
7048 ssh->kex->groupname);
7051 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
7052 ssh->kex->hash->text_name);
7054 * Now generate and send e for Diffie-Hellman.
7056 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
7057 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
7058 s->pktout = ssh2_pkt_init(s->kex_init_value);
7059 ssh2_pkt_addmp(s->pktout, s->e);
7060 ssh2_pkt_send_noqueue(ssh, s->pktout);
7062 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
7063 crWaitUntilV(pktin);
7064 if (pktin->type != s->kex_reply_value) {
7065 bombout(("expected key exchange reply packet from server"));
7068 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
7069 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7070 if (!s->hostkeydata) {
7071 bombout(("unable to parse key exchange reply packet"));
7074 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7075 s->hostkeydata, s->hostkeylen);
7076 s->f = ssh2_pkt_getmp(pktin);
7078 bombout(("unable to parse key exchange reply packet"));
7081 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7083 bombout(("unable to parse key exchange reply packet"));
7088 const char *err = dh_validate_f(ssh->kex_ctx, s->f);
7090 bombout(("key exchange reply failed validation: %s", err));
7094 s->K = dh_find_K(ssh->kex_ctx, s->f);
7096 /* We assume everything from now on will be quick, and it might
7097 * involve user interaction. */
7098 set_busy_status(ssh->frontend, BUSY_NOT);
7100 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
7101 if (dh_is_gex(ssh->kex)) {
7102 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
7103 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MIN_SIZE);
7104 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
7105 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
7106 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MAX_SIZE);
7107 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
7108 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
7110 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
7111 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
7113 dh_cleanup(ssh->kex_ctx);
7115 if (dh_is_gex(ssh->kex)) {
7119 } else if (ssh->kex->main_type == KEXTYPE_ECDH) {
7121 logeventf(ssh, "Doing ECDH key exchange with curve %s and hash %s",
7122 ssh_ecdhkex_curve_textname(ssh->kex),
7123 ssh->kex->hash->text_name);
7124 ssh->pkt_kctx = SSH2_PKTCTX_ECDHKEX;
7126 s->eckey = ssh_ecdhkex_newkey(ssh->kex);
7128 bombout(("Unable to generate key for ECDH"));
7134 int publicPointLength;
7135 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
7137 ssh_ecdhkex_freekey(s->eckey);
7138 bombout(("Unable to encode public key for ECDH"));
7141 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_ECDH_INIT);
7142 ssh2_pkt_addstring_start(s->pktout);
7143 ssh2_pkt_addstring_data(s->pktout, publicPoint, publicPointLength);
7147 ssh2_pkt_send_noqueue(ssh, s->pktout);
7149 crWaitUntilV(pktin);
7150 if (pktin->type != SSH2_MSG_KEX_ECDH_REPLY) {
7151 ssh_ecdhkex_freekey(s->eckey);
7152 bombout(("expected ECDH reply packet from server"));
7156 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7157 if (!s->hostkeydata) {
7158 bombout(("unable to parse ECDH reply packet"));
7161 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
7162 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7163 s->hostkeydata, s->hostkeylen);
7167 int publicPointLength;
7168 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
7170 ssh_ecdhkex_freekey(s->eckey);
7171 bombout(("Unable to encode public key for ECDH hash"));
7174 hash_string(ssh->kex->hash, ssh->exhash,
7175 publicPoint, publicPointLength);
7182 ssh_pkt_getstring(pktin, &keydata, &keylen);
7184 bombout(("unable to parse ECDH reply packet"));
7187 hash_string(ssh->kex->hash, ssh->exhash, keydata, keylen);
7188 s->K = ssh_ecdhkex_getkey(s->eckey, keydata, keylen);
7190 ssh_ecdhkex_freekey(s->eckey);
7191 bombout(("point received in ECDH was not valid"));
7196 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7198 bombout(("unable to parse key exchange reply packet"));
7202 ssh_ecdhkex_freekey(s->eckey);
7204 logeventf(ssh, "Doing RSA key exchange with hash %s",
7205 ssh->kex->hash->text_name);
7206 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
7208 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
7211 crWaitUntilV(pktin);
7212 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
7213 bombout(("expected RSA public key packet from server"));
7217 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7218 if (!s->hostkeydata) {
7219 bombout(("unable to parse RSA public key packet"));
7222 hash_string(ssh->kex->hash, ssh->exhash,
7223 s->hostkeydata, s->hostkeylen);
7224 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7225 s->hostkeydata, s->hostkeylen);
7229 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
7231 bombout(("unable to parse RSA public key packet"));
7234 s->rsakeydata = snewn(s->rsakeylen, char);
7235 memcpy(s->rsakeydata, keydata, s->rsakeylen);
7238 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
7240 sfree(s->rsakeydata);
7241 bombout(("unable to parse RSA public key from server"));
7245 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
7248 * Next, set up a shared secret K, of precisely KLEN -
7249 * 2*HLEN - 49 bits, where KLEN is the bit length of the
7250 * RSA key modulus and HLEN is the bit length of the hash
7254 int klen = ssh_rsakex_klen(s->rsakey);
7255 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
7257 unsigned char *kstr1, *kstr2, *outstr;
7258 int kstr1len, kstr2len, outstrlen;
7260 s->K = bn_power_2(nbits - 1);
7262 for (i = 0; i < nbits; i++) {
7264 byte = random_byte();
7266 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
7270 * Encode this as an mpint.
7272 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
7273 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
7274 PUT_32BIT(kstr2, kstr1len);
7275 memcpy(kstr2 + 4, kstr1, kstr1len);
7278 * Encrypt it with the given RSA key.
7280 outstrlen = (klen + 7) / 8;
7281 outstr = snewn(outstrlen, unsigned char);
7282 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
7283 outstr, outstrlen, s->rsakey);
7286 * And send it off in a return packet.
7288 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
7289 ssh2_pkt_addstring_start(s->pktout);
7290 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
7291 ssh2_pkt_send_noqueue(ssh, s->pktout);
7293 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
7300 ssh_rsakex_freekey(s->rsakey);
7302 crWaitUntilV(pktin);
7303 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
7304 sfree(s->rsakeydata);
7305 bombout(("expected signature packet from server"));
7309 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7311 bombout(("unable to parse signature packet"));
7315 sfree(s->rsakeydata);
7318 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
7319 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
7320 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
7322 ssh->kex_ctx = NULL;
7325 debug(("Exchange hash is:\n"));
7326 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
7330 bombout(("Server's host key is invalid"));
7334 if (!ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
7335 (char *)s->exchange_hash,
7336 ssh->kex->hash->hlen)) {
7338 bombout(("Server's host key did not match the signature supplied"));
7343 s->keystr = ssh->hostkey->fmtkey(s->hkey);
7344 if (!s->got_session_id) {
7346 * Make a note of any other host key formats that are available.
7349 int i, j, nkeys = 0;
7351 for (i = 0; i < lenof(hostkey_algs); i++) {
7352 if (hostkey_algs[i].alg == ssh->hostkey)
7355 for (j = 0; j < ssh->n_uncert_hostkeys; j++)
7356 if (ssh->uncert_hostkeys[j] == i)
7359 if (j < ssh->n_uncert_hostkeys) {
7362 newlist = dupprintf("%s/%s", list,
7363 hostkey_algs[i].alg->name);
7365 newlist = dupprintf("%s", hostkey_algs[i].alg->name);
7373 "Server also has %s host key%s, but we "
7374 "don't know %s", list,
7375 nkeys > 1 ? "s" : "",
7376 nkeys > 1 ? "any of them" : "it");
7382 * Authenticate remote host: verify host key. (We've already
7383 * checked the signature of the exchange hash.)
7385 s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
7386 logevent("Host key fingerprint is:");
7387 logevent(s->fingerprint);
7388 /* First check against manually configured host keys. */
7389 s->dlgret = verify_ssh_manual_host_key(ssh, s->fingerprint,
7390 ssh->hostkey, s->hkey);
7391 if (s->dlgret == 0) { /* did not match */
7392 bombout(("Host key did not appear in manually configured list"));
7394 } else if (s->dlgret < 0) { /* none configured; use standard handling */
7395 ssh_set_frozen(ssh, 1);
7396 s->dlgret = verify_ssh_host_key(ssh->frontend,
7397 ssh->savedhost, ssh->savedport,
7398 ssh->hostkey->keytype, s->keystr,
7400 ssh_dialog_callback, ssh);
7404 if (s->dlgret < 0) {
7408 bombout(("Unexpected data from server while waiting"
7409 " for user host key response"));
7412 } while (pktin || inlen > 0);
7413 s->dlgret = ssh->user_response;
7415 ssh_set_frozen(ssh, 0);
7416 if (s->dlgret == 0) {
7417 ssh_disconnect(ssh, "Aborted at host key verification", NULL,
7422 sfree(s->fingerprint);
7424 * Save this host key, to check against the one presented in
7425 * subsequent rekeys.
7427 ssh->hostkey_str = s->keystr;
7428 } else if (ssh->cross_certifying) {
7429 s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
7430 logevent("Storing additional host key for this host:");
7431 logevent(s->fingerprint);
7432 sfree(s->fingerprint);
7433 store_host_key(ssh->savedhost, ssh->savedport,
7434 ssh->hostkey->keytype, s->keystr);
7435 ssh->cross_certifying = FALSE;
7437 * Don't forget to store the new key as the one we'll be
7438 * re-checking in future normal rekeys.
7440 ssh->hostkey_str = s->keystr;
7443 * In a rekey, we never present an interactive host key
7444 * verification request to the user. Instead, we simply
7445 * enforce that the key we're seeing this time is identical to
7446 * the one we saw before.
7448 if (strcmp(ssh->hostkey_str, s->keystr)) {
7450 bombout(("Host key was different in repeat key exchange"));
7456 ssh->hostkey->freekey(s->hkey);
7459 * The exchange hash from the very first key exchange is also
7460 * the session id, used in session key construction and
7463 if (!s->got_session_id) {
7464 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
7465 memcpy(ssh->v2_session_id, s->exchange_hash,
7466 sizeof(s->exchange_hash));
7467 ssh->v2_session_id_len = ssh->kex->hash->hlen;
7468 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
7469 s->got_session_id = TRUE;
7473 * Send SSH2_MSG_NEWKEYS.
7475 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
7476 ssh2_pkt_send_noqueue(ssh, s->pktout);
7477 ssh->outgoing_data_size = 0; /* start counting from here */
7480 * We've sent client NEWKEYS, so create and initialise
7481 * client-to-server session keys.
7483 if (ssh->cs_cipher_ctx)
7484 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
7485 ssh->cscipher = s->cscipher_tobe;
7486 if (ssh->cscipher) ssh->cs_cipher_ctx = ssh->cscipher->make_context();
7488 if (ssh->cs_mac_ctx)
7489 ssh->csmac->free_context(ssh->cs_mac_ctx);
7490 ssh->csmac = s->csmac_tobe;
7491 ssh->csmac_etm = s->csmac_etm_tobe;
7493 ssh->cs_mac_ctx = ssh->csmac->make_context(ssh->cs_cipher_ctx);
7495 if (ssh->cs_comp_ctx)
7496 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
7497 ssh->cscomp = s->cscomp_tobe;
7498 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
7501 * Set IVs on client-to-server keys. Here we use the exchange
7502 * hash from the _first_ key exchange.
7504 if (ssh->cscipher) {
7507 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'C',
7508 ssh->cscipher->padded_keybytes);
7509 ssh->cscipher->setkey(ssh->cs_cipher_ctx, key);
7510 smemclr(key, ssh->cscipher->padded_keybytes);
7513 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'A',
7514 ssh->cscipher->blksize);
7515 ssh->cscipher->setiv(ssh->cs_cipher_ctx, key);
7516 smemclr(key, ssh->cscipher->blksize);
7522 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'E',
7523 ssh->csmac->keylen);
7524 ssh->csmac->setkey(ssh->cs_mac_ctx, key);
7525 smemclr(key, ssh->csmac->keylen);
7530 logeventf(ssh, "Initialised %.200s client->server encryption",
7531 ssh->cscipher->text_name);
7533 logeventf(ssh, "Initialised %.200s client->server MAC algorithm%s%s",
7534 ssh->csmac->text_name,
7535 ssh->csmac_etm ? " (in ETM mode)" : "",
7536 ssh->cscipher->required_mac ? " (required by cipher)" : "");
7537 if (ssh->cscomp->text_name)
7538 logeventf(ssh, "Initialised %s compression",
7539 ssh->cscomp->text_name);
7542 * Now our end of the key exchange is complete, we can send all
7543 * our queued higher-layer packets.
7545 ssh->queueing = FALSE;
7546 ssh2_pkt_queuesend(ssh);
7549 * Expect SSH2_MSG_NEWKEYS from server.
7551 crWaitUntilV(pktin);
7552 if (pktin->type != SSH2_MSG_NEWKEYS) {
7553 bombout(("expected new-keys packet from server"));
7556 ssh->incoming_data_size = 0; /* start counting from here */
7559 * We've seen server NEWKEYS, so create and initialise
7560 * server-to-client session keys.
7562 if (ssh->sc_cipher_ctx)
7563 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
7564 if (s->sccipher_tobe) {
7565 ssh->sccipher = s->sccipher_tobe;
7566 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
7569 if (ssh->sc_mac_ctx)
7570 ssh->scmac->free_context(ssh->sc_mac_ctx);
7571 if (s->scmac_tobe) {
7572 ssh->scmac = s->scmac_tobe;
7573 ssh->scmac_etm = s->scmac_etm_tobe;
7574 ssh->sc_mac_ctx = ssh->scmac->make_context(ssh->sc_cipher_ctx);
7577 if (ssh->sc_comp_ctx)
7578 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
7579 ssh->sccomp = s->sccomp_tobe;
7580 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
7583 * Set IVs on server-to-client keys. Here we use the exchange
7584 * hash from the _first_ key exchange.
7586 if (ssh->sccipher) {
7589 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'D',
7590 ssh->sccipher->padded_keybytes);
7591 ssh->sccipher->setkey(ssh->sc_cipher_ctx, key);
7592 smemclr(key, ssh->sccipher->padded_keybytes);
7595 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'B',
7596 ssh->sccipher->blksize);
7597 ssh->sccipher->setiv(ssh->sc_cipher_ctx, key);
7598 smemclr(key, ssh->sccipher->blksize);
7604 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'F',
7605 ssh->scmac->keylen);
7606 ssh->scmac->setkey(ssh->sc_mac_ctx, key);
7607 smemclr(key, ssh->scmac->keylen);
7611 logeventf(ssh, "Initialised %.200s server->client encryption",
7612 ssh->sccipher->text_name);
7614 logeventf(ssh, "Initialised %.200s server->client MAC algorithm%s%s",
7615 ssh->scmac->text_name,
7616 ssh->scmac_etm ? " (in ETM mode)" : "",
7617 ssh->sccipher->required_mac ? " (required by cipher)" : "");
7618 if (ssh->sccomp->text_name)
7619 logeventf(ssh, "Initialised %s decompression",
7620 ssh->sccomp->text_name);
7623 * Free shared secret.
7628 * Update the specials menu to list the remaining uncertified host
7631 update_specials_menu(ssh->frontend);
7634 * Key exchange is over. Loop straight back round if we have a
7635 * deferred rekey reason.
7637 if (ssh->deferred_rekey_reason) {
7638 logevent(ssh->deferred_rekey_reason);
7640 ssh->deferred_rekey_reason = NULL;
7641 goto begin_key_exchange;
7645 * Otherwise, schedule a timer for our next rekey.
7647 ssh->kex_in_progress = FALSE;
7648 ssh->last_rekey = GETTICKCOUNT();
7649 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
7650 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7654 * Now we're encrypting. Begin returning 1 to the protocol main
7655 * function so that other things can run on top of the
7656 * transport. If we ever see a KEXINIT, we must go back to the
7659 * We _also_ go back to the start if we see pktin==NULL and
7660 * inlen negative, because this is a special signal meaning
7661 * `initiate client-driven rekey', and `in' contains a message
7662 * giving the reason for the rekey.
7664 * inlen==-1 means always initiate a rekey;
7665 * inlen==-2 means that userauth has completed successfully and
7666 * we should consider rekeying (for delayed compression).
7668 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
7669 (!pktin && inlen < 0))) {
7671 if (!ssh->protocol_initial_phase_done) {
7672 ssh->protocol_initial_phase_done = TRUE;
7674 * Allow authconn to initialise itself.
7676 do_ssh2_authconn(ssh, NULL, 0, NULL);
7681 logevent("Server initiated key re-exchange");
7685 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
7686 * delayed compression, if it's available.
7688 * draft-miller-secsh-compression-delayed-00 says that you
7689 * negotiate delayed compression in the first key exchange, and
7690 * both sides start compressing when the server has sent
7691 * USERAUTH_SUCCESS. This has a race condition -- the server
7692 * can't know when the client has seen it, and thus which incoming
7693 * packets it should treat as compressed.
7695 * Instead, we do the initial key exchange without offering the
7696 * delayed methods, but note if the server offers them; when we
7697 * get here, if a delayed method was available that was higher
7698 * on our list than what we got, we initiate a rekey in which we
7699 * _do_ list the delayed methods (and hopefully get it as a
7700 * result). Subsequent rekeys will do the same.
7702 assert(!s->userauth_succeeded); /* should only happen once */
7703 s->userauth_succeeded = TRUE;
7704 if (!s->pending_compression)
7705 /* Can't see any point rekeying. */
7706 goto wait_for_rekey; /* this is utterly horrid */
7707 /* else fall through to rekey... */
7708 s->pending_compression = FALSE;
7711 * Now we've decided to rekey.
7713 * Special case: if the server bug is set that doesn't
7714 * allow rekeying, we give a different log message and
7715 * continue waiting. (If such a server _initiates_ a rekey,
7716 * we process it anyway!)
7718 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
7719 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
7721 /* Reset the counters, so that at least this message doesn't
7722 * hit the event log _too_ often. */
7723 ssh->outgoing_data_size = 0;
7724 ssh->incoming_data_size = 0;
7725 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
7727 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7730 goto wait_for_rekey; /* this is still utterly horrid */
7732 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
7735 goto begin_key_exchange;
7741 * Send data on an SSH channel. In SSH-2, this involves buffering it
7744 static int ssh_send_channel_data(struct ssh_channel *c, const char *buf,
7747 if (c->ssh->version == 2) {
7748 bufchain_add(&c->v.v2.outbuffer, buf, len);
7749 return ssh2_try_send(c);
7751 send_packet(c->ssh, SSH1_MSG_CHANNEL_DATA,
7752 PKT_INT, c->remoteid,
7757 * In SSH-1 we can return 0 here - implying that channels are
7758 * never individually throttled - because the only
7759 * circumstance that can cause throttling will be the whole
7760 * SSH connection backing up, in which case _everything_ will
7761 * be throttled as a whole.
7768 * Attempt to send data on an SSH-2 channel.
7770 static int ssh2_try_send(struct ssh_channel *c)
7773 struct Packet *pktout;
7776 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
7779 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
7780 if ((unsigned)len > c->v.v2.remwindow)
7781 len = c->v.v2.remwindow;
7782 if ((unsigned)len > c->v.v2.remmaxpkt)
7783 len = c->v.v2.remmaxpkt;
7784 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
7785 ssh2_pkt_adduint32(pktout, c->remoteid);
7786 ssh2_pkt_addstring_start(pktout);
7787 ssh2_pkt_addstring_data(pktout, data, len);
7788 ssh2_pkt_send(ssh, pktout);
7789 bufchain_consume(&c->v.v2.outbuffer, len);
7790 c->v.v2.remwindow -= len;
7794 * After having sent as much data as we can, return the amount
7797 ret = bufchain_size(&c->v.v2.outbuffer);
7800 * And if there's no data pending but we need to send an EOF, send
7803 if (!ret && c->pending_eof)
7804 ssh_channel_try_eof(c);
7809 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
7812 if (c->closes & CLOSES_SENT_EOF)
7813 return; /* don't send on channels we've EOFed */
7814 bufsize = ssh2_try_send(c);
7817 case CHAN_MAINSESSION:
7818 /* stdin need not receive an unthrottle
7819 * notification since it will be polled */
7822 x11_unthrottle(c->u.x11.xconn);
7825 /* Now that we've successfully sent all the outgoing
7826 * replies we had, try to process more incoming data. */
7827 ssh_agentf_try_forward(c);
7830 pfd_unthrottle(c->u.pfd.pf);
7836 static int ssh_is_simple(Ssh ssh)
7839 * We use the 'simple' variant of the SSH protocol if we're asked
7840 * to, except not if we're also doing connection-sharing (either
7841 * tunnelling our packets over an upstream or expecting to be
7842 * tunnelled over ourselves), since then the assumption that we
7843 * have only one channel to worry about is not true after all.
7845 return (conf_get_int(ssh->conf, CONF_ssh_simple) &&
7846 !ssh->bare_connection && !ssh->connshare);
7850 * Set up most of a new ssh_channel.
7852 static void ssh_channel_init(struct ssh_channel *c)
7855 c->localid = alloc_channel_id(ssh);
7857 c->pending_eof = FALSE;
7858 c->throttling_conn = FALSE;
7859 if (ssh->version == 2) {
7860 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
7861 ssh_is_simple(ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
7862 c->v.v2.chanreq_head = NULL;
7863 c->v.v2.throttle_state = UNTHROTTLED;
7864 bufchain_init(&c->v.v2.outbuffer);
7866 add234(ssh->channels, c);
7870 * Construct the common parts of a CHANNEL_OPEN.
7872 static struct Packet *ssh2_chanopen_init(struct ssh_channel *c,
7875 struct Packet *pktout;
7877 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7878 ssh2_pkt_addstring(pktout, type);
7879 ssh2_pkt_adduint32(pktout, c->localid);
7880 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
7881 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7886 * CHANNEL_FAILURE doesn't come with any indication of what message
7887 * caused it, so we have to keep track of the outstanding
7888 * CHANNEL_REQUESTs ourselves.
7890 static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
7891 cchandler_fn_t handler, void *ctx)
7893 struct outstanding_channel_request *ocr =
7894 snew(struct outstanding_channel_request);
7896 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7897 ocr->handler = handler;
7900 if (!c->v.v2.chanreq_head)
7901 c->v.v2.chanreq_head = ocr;
7903 c->v.v2.chanreq_tail->next = ocr;
7904 c->v.v2.chanreq_tail = ocr;
7908 * Construct the common parts of a CHANNEL_REQUEST. If handler is not
7909 * NULL then a reply will be requested and the handler will be called
7910 * when it arrives. The returned packet is ready to have any
7911 * request-specific data added and be sent. Note that if a handler is
7912 * provided, it's essential that the request actually be sent.
7914 * The handler will usually be passed the response packet in pktin. If
7915 * pktin is NULL, this means that no reply will ever be forthcoming
7916 * (e.g. because the entire connection is being destroyed, or because
7917 * the server initiated channel closure before we saw the response)
7918 * and the handler should free any storage it's holding.
7920 static struct Packet *ssh2_chanreq_init(struct ssh_channel *c,
7922 cchandler_fn_t handler, void *ctx)
7924 struct Packet *pktout;
7926 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7927 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7928 ssh2_pkt_adduint32(pktout, c->remoteid);
7929 ssh2_pkt_addstring(pktout, type);
7930 ssh2_pkt_addbool(pktout, handler != NULL);
7931 if (handler != NULL)
7932 ssh2_queue_chanreq_handler(c, handler, ctx);
7936 static void ssh_channel_unthrottle(struct ssh_channel *c, int bufsize)
7941 if (ssh->version == 1) {
7942 buflimit = SSH1_BUFFER_LIMIT;
7944 if (ssh_is_simple(ssh))
7947 buflimit = c->v.v2.locmaxwin;
7948 if (bufsize < buflimit)
7949 ssh2_set_window(c, buflimit - bufsize);
7951 if (c->throttling_conn && bufsize <= buflimit) {
7952 c->throttling_conn = 0;
7953 ssh_throttle_conn(ssh, -1);
7958 * Potentially enlarge the window on an SSH-2 channel.
7960 static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
7962 static void ssh2_set_window(struct ssh_channel *c, int newwin)
7967 * Never send WINDOW_ADJUST for a channel that the remote side has
7968 * already sent EOF on; there's no point, since it won't be
7969 * sending any more data anyway. Ditto if _we've_ already sent
7972 if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
7976 * Also, never widen the window for an X11 channel when we're
7977 * still waiting to see its initial auth and may yet hand it off
7980 if (c->type == CHAN_X11 && c->u.x11.initial)
7984 * If the remote end has a habit of ignoring maxpkt, limit the
7985 * window so that it has no choice (assuming it doesn't ignore the
7988 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
7989 newwin = OUR_V2_MAXPKT;
7992 * Only send a WINDOW_ADJUST if there's significantly more window
7993 * available than the other end thinks there is. This saves us
7994 * sending a WINDOW_ADJUST for every character in a shell session.
7996 * "Significant" is arbitrarily defined as half the window size.
7998 if (newwin / 2 >= c->v.v2.locwindow) {
7999 struct Packet *pktout;
8003 * In order to keep track of how much window the client
8004 * actually has available, we'd like it to acknowledge each
8005 * WINDOW_ADJUST. We can't do that directly, so we accompany
8006 * it with a CHANNEL_REQUEST that has to be acknowledged.
8008 * This is only necessary if we're opening the window wide.
8009 * If we're not, then throughput is being constrained by
8010 * something other than the maximum window size anyway.
8012 if (newwin == c->v.v2.locmaxwin &&
8013 !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
8014 up = snew(unsigned);
8015 *up = newwin - c->v.v2.locwindow;
8016 pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org",
8017 ssh2_handle_winadj_response, up);
8018 ssh2_pkt_send(ssh, pktout);
8020 if (c->v.v2.throttle_state != UNTHROTTLED)
8021 c->v.v2.throttle_state = UNTHROTTLING;
8023 /* Pretend the WINDOW_ADJUST was acked immediately. */
8024 c->v.v2.remlocwin = newwin;
8025 c->v.v2.throttle_state = THROTTLED;
8027 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
8028 ssh2_pkt_adduint32(pktout, c->remoteid);
8029 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
8030 ssh2_pkt_send(ssh, pktout);
8031 c->v.v2.locwindow = newwin;
8036 * Find the channel associated with a message. If there's no channel,
8037 * or it's not properly open, make a noise about it and return NULL.
8038 * If the channel is shared, pass the message on to downstream and
8039 * also return NULL (meaning the caller should ignore this message).
8041 static struct ssh_channel *ssh_channel_msg(Ssh ssh, struct Packet *pktin)
8043 unsigned localid = ssh_pkt_getuint32(pktin);
8044 struct ssh_channel *c;
8047 /* Is this message OK on a half-open connection? */
8048 if (ssh->version == 1)
8049 halfopen_ok = (pktin->type == SSH1_MSG_CHANNEL_OPEN_CONFIRMATION ||
8050 pktin->type == SSH1_MSG_CHANNEL_OPEN_FAILURE);
8052 halfopen_ok = (pktin->type == SSH2_MSG_CHANNEL_OPEN_CONFIRMATION ||
8053 pktin->type == SSH2_MSG_CHANNEL_OPEN_FAILURE);
8054 c = find234(ssh->channels, &localid, ssh_channelfind);
8055 if (!c || (c->type != CHAN_SHARING && (c->halfopen != halfopen_ok))) {
8056 char *buf = dupprintf("Received %s for %s channel %u",
8057 ssh_pkt_type(ssh, pktin->type),
8058 !c ? "nonexistent" :
8059 c->halfopen ? "half-open" : "open",
8061 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
8065 if (c->type == CHAN_SHARING) {
8066 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8067 pktin->body, pktin->length);
8073 static void ssh2_handle_winadj_response(struct ssh_channel *c,
8074 struct Packet *pktin, void *ctx)
8076 unsigned *sizep = ctx;
8079 * Winadj responses should always be failures. However, at least
8080 * one server ("boks_sshd") is known to return SUCCESS for channel
8081 * requests it's never heard of, such as "winadj@putty". Raised
8082 * with foxt.com as bug 090916-090424, but for the sake of a quiet
8083 * life, we don't worry about what kind of response we got.
8086 c->v.v2.remlocwin += *sizep;
8089 * winadj messages are only sent when the window is fully open, so
8090 * if we get an ack of one, we know any pending unthrottle is
8093 if (c->v.v2.throttle_state == UNTHROTTLING)
8094 c->v.v2.throttle_state = UNTHROTTLED;
8097 static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
8099 struct ssh_channel *c = ssh_channel_msg(ssh, pktin);
8100 struct outstanding_channel_request *ocr;
8103 ocr = c->v.v2.chanreq_head;
8105 ssh2_msg_unexpected(ssh, pktin);
8108 ocr->handler(c, pktin, ocr->ctx);
8109 c->v.v2.chanreq_head = ocr->next;
8112 * We may now initiate channel-closing procedures, if that
8113 * CHANNEL_REQUEST was the last thing outstanding before we send
8116 ssh2_channel_check_close(c);
8119 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
8121 struct ssh_channel *c;
8122 c = ssh_channel_msg(ssh, pktin);
8125 if (!(c->closes & CLOSES_SENT_EOF)) {
8126 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
8127 ssh2_try_send_and_unthrottle(ssh, c);
8131 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
8135 unsigned ext_type = 0; /* 0 means not extended */
8136 struct ssh_channel *c;
8137 c = ssh_channel_msg(ssh, pktin);
8140 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
8141 ext_type = ssh_pkt_getuint32(pktin);
8142 ssh_pkt_getstring(pktin, &data, &length);
8145 c->v.v2.locwindow -= length;
8146 c->v.v2.remlocwin -= length;
8147 if (ext_type != 0 && ext_type != SSH2_EXTENDED_DATA_STDERR)
8148 length = 0; /* Don't do anything with unknown extended data. */
8149 bufsize = ssh_channel_data(c, ext_type == SSH2_EXTENDED_DATA_STDERR,
8152 * If it looks like the remote end hit the end of its window,
8153 * and we didn't want it to do that, think about using a
8156 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
8157 c->v.v2.locmaxwin < 0x40000000)
8158 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
8160 * If we are not buffering too much data,
8161 * enlarge the window again at the remote side.
8162 * If we are buffering too much, we may still
8163 * need to adjust the window if the server's
8166 if (bufsize < c->v.v2.locmaxwin)
8167 ssh2_set_window(c, c->v.v2.locmaxwin - bufsize);
8169 * If we're either buffering way too much data, or if we're
8170 * buffering anything at all and we're in "simple" mode,
8171 * throttle the whole channel.
8173 if ((bufsize > c->v.v2.locmaxwin || (ssh_is_simple(ssh) && bufsize>0))
8174 && !c->throttling_conn) {
8175 c->throttling_conn = 1;
8176 ssh_throttle_conn(ssh, +1);
8181 static void ssh_check_termination(Ssh ssh)
8183 if (ssh->version == 2 &&
8184 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
8185 (ssh->channels && count234(ssh->channels) == 0) &&
8186 !(ssh->connshare && share_ndownstreams(ssh->connshare) > 0)) {
8188 * We used to send SSH_MSG_DISCONNECT here, because I'd
8189 * believed that _every_ conforming SSH-2 connection had to
8190 * end with a disconnect being sent by at least one side;
8191 * apparently I was wrong and it's perfectly OK to
8192 * unceremoniously slam the connection shut when you're done,
8193 * and indeed OpenSSH feels this is more polite than sending a
8194 * DISCONNECT. So now we don't.
8196 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
8200 void ssh_sharing_downstream_connected(Ssh ssh, unsigned id,
8201 const char *peerinfo)
8204 logeventf(ssh, "Connection sharing downstream #%u connected from %s",
8207 logeventf(ssh, "Connection sharing downstream #%u connected", id);
8210 void ssh_sharing_downstream_disconnected(Ssh ssh, unsigned id)
8212 logeventf(ssh, "Connection sharing downstream #%u disconnected", id);
8213 ssh_check_termination(ssh);
8216 void ssh_sharing_logf(Ssh ssh, unsigned id, const char *logfmt, ...)
8221 va_start(ap, logfmt);
8222 buf = dupvprintf(logfmt, ap);
8225 logeventf(ssh, "Connection sharing downstream #%u: %s", id, buf);
8227 logeventf(ssh, "Connection sharing: %s", buf);
8232 * Close any local socket and free any local resources associated with
8233 * a channel. This converts the channel into a CHAN_ZOMBIE.
8235 static void ssh_channel_close_local(struct ssh_channel *c, char const *reason)
8238 char const *msg = NULL;
8241 case CHAN_MAINSESSION:
8242 ssh->mainchan = NULL;
8243 update_specials_menu(ssh->frontend);
8246 assert(c->u.x11.xconn != NULL);
8247 x11_close(c->u.x11.xconn);
8248 msg = "Forwarded X11 connection terminated";
8252 agent_cancel_query(c->u.a.pending);
8253 bufchain_clear(&c->u.a.inbuffer);
8254 msg = "Agent-forwarding connection closed";
8257 assert(c->u.pfd.pf != NULL);
8258 pfd_close(c->u.pfd.pf);
8259 msg = "Forwarded port closed";
8262 c->type = CHAN_ZOMBIE;
8265 logeventf(ssh, "%s %s", msg, reason);
8271 static void ssh_channel_destroy(struct ssh_channel *c)
8275 ssh_channel_close_local(c, NULL);
8277 del234(ssh->channels, c);
8278 if (ssh->version == 2) {
8279 bufchain_clear(&c->v.v2.outbuffer);
8280 assert(c->v.v2.chanreq_head == NULL);
8285 * If that was the last channel left open, we might need to
8288 ssh_check_termination(ssh);
8291 static void ssh2_channel_check_close(struct ssh_channel *c)
8294 struct Packet *pktout;
8296 assert(ssh->version == 2);
8299 * If we've sent out our own CHANNEL_OPEN but not yet seen
8300 * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
8301 * it's too early to be sending close messages of any kind.
8306 if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
8307 c->type == CHAN_ZOMBIE) &&
8308 !c->v.v2.chanreq_head &&
8309 !(c->closes & CLOSES_SENT_CLOSE)) {
8311 * We have both sent and received EOF (or the channel is a
8312 * zombie), and we have no outstanding channel requests, which
8313 * means the channel is in final wind-up. But we haven't sent
8314 * CLOSE, so let's do so now.
8316 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
8317 ssh2_pkt_adduint32(pktout, c->remoteid);
8318 ssh2_pkt_send(ssh, pktout);
8319 c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
8322 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
8323 assert(c->v.v2.chanreq_head == NULL);
8325 * We have both sent and received CLOSE, which means we're
8326 * completely done with the channel.
8328 ssh_channel_destroy(c);
8332 static void ssh_channel_got_eof(struct ssh_channel *c)
8334 if (c->closes & CLOSES_RCVD_EOF)
8335 return; /* already seen EOF */
8336 c->closes |= CLOSES_RCVD_EOF;
8338 if (c->type == CHAN_X11) {
8339 assert(c->u.x11.xconn != NULL);
8340 x11_send_eof(c->u.x11.xconn);
8341 } else if (c->type == CHAN_AGENT) {
8342 /* Just call try_forward, which will respond to the EOF now if
8343 * appropriate, or wait until the queue of outstanding
8344 * requests is dealt with if not */
8345 ssh_agentf_try_forward(c);
8346 } else if (c->type == CHAN_SOCKDATA) {
8347 assert(c->u.pfd.pf != NULL);
8348 pfd_send_eof(c->u.pfd.pf);
8349 } else if (c->type == CHAN_MAINSESSION) {
8352 if (!ssh->sent_console_eof &&
8353 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
8355 * Either from_backend_eof told us that the front end
8356 * wants us to close the outgoing side of the connection
8357 * as soon as we see EOF from the far end, or else we've
8358 * unilaterally decided to do that because we've allocated
8359 * a remote pty and hence EOF isn't a particularly
8360 * meaningful concept.
8362 sshfwd_write_eof(c);
8364 ssh->sent_console_eof = TRUE;
8368 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
8370 struct ssh_channel *c;
8372 c = ssh_channel_msg(ssh, pktin);
8375 ssh_channel_got_eof(c);
8376 ssh2_channel_check_close(c);
8379 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
8381 struct ssh_channel *c;
8383 c = ssh_channel_msg(ssh, pktin);
8388 * When we receive CLOSE on a channel, we assume it comes with an
8389 * implied EOF if we haven't seen EOF yet.
8391 ssh_channel_got_eof(c);
8393 if (!(ssh->remote_bugs & BUG_SENDS_LATE_REQUEST_REPLY)) {
8395 * It also means we stop expecting to see replies to any
8396 * outstanding channel requests, so clean those up too.
8397 * (ssh_chanreq_init will enforce by assertion that we don't
8398 * subsequently put anything back on this list.)
8400 while (c->v.v2.chanreq_head) {
8401 struct outstanding_channel_request *ocr = c->v.v2.chanreq_head;
8402 ocr->handler(c, NULL, ocr->ctx);
8403 c->v.v2.chanreq_head = ocr->next;
8409 * And we also send an outgoing EOF, if we haven't already, on the
8410 * assumption that CLOSE is a pretty forceful announcement that
8411 * the remote side is doing away with the entire channel. (If it
8412 * had wanted to send us EOF and continue receiving data from us,
8413 * it would have just sent CHANNEL_EOF.)
8415 if (!(c->closes & CLOSES_SENT_EOF)) {
8417 * Make sure we don't read any more from whatever our local
8418 * data source is for this channel.
8421 case CHAN_MAINSESSION:
8422 ssh->send_ok = 0; /* stop trying to read from stdin */
8425 x11_override_throttle(c->u.x11.xconn, 1);
8428 pfd_override_throttle(c->u.pfd.pf, 1);
8433 * Abandon any buffered data we still wanted to send to this
8434 * channel. Receiving a CHANNEL_CLOSE is an indication that
8435 * the server really wants to get on and _destroy_ this
8436 * channel, and it isn't going to send us any further
8437 * WINDOW_ADJUSTs to permit us to send pending stuff.
8439 bufchain_clear(&c->v.v2.outbuffer);
8442 * Send outgoing EOF.
8444 sshfwd_write_eof(c);
8448 * Now process the actual close.
8450 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
8451 c->closes |= CLOSES_RCVD_CLOSE;
8452 ssh2_channel_check_close(c);
8456 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
8458 struct ssh_channel *c;
8460 c = ssh_channel_msg(ssh, pktin);
8463 assert(c->halfopen); /* ssh_channel_msg will have enforced this */
8464 c->remoteid = ssh_pkt_getuint32(pktin);
8465 c->halfopen = FALSE;
8466 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8467 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8469 if (c->type == CHAN_SOCKDATA) {
8470 assert(c->u.pfd.pf != NULL);
8471 pfd_confirm(c->u.pfd.pf);
8472 } else if (c->type == CHAN_ZOMBIE) {
8474 * This case can occur if a local socket error occurred
8475 * between us sending out CHANNEL_OPEN and receiving
8476 * OPEN_CONFIRMATION. In this case, all we can do is
8477 * immediately initiate close proceedings now that we know the
8478 * server's id to put in the close message.
8480 ssh2_channel_check_close(c);
8483 * We never expect to receive OPEN_CONFIRMATION for any
8484 * *other* channel type (since only local-to-remote port
8485 * forwardings cause us to send CHANNEL_OPEN after the main
8486 * channel is live - all other auxiliary channel types are
8487 * initiated from the server end). It's safe to enforce this
8488 * by assertion rather than by ssh_disconnect, because the
8489 * real point is that we never constructed a half-open channel
8490 * structure in the first place with any type other than the
8493 assert(!"Funny channel type in ssh2_msg_channel_open_confirmation");
8497 ssh_channel_try_eof(c); /* in case we had a pending EOF */
8500 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
8502 static const char *const reasons[] = {
8503 "<unknown reason code>",
8504 "Administratively prohibited",
8506 "Unknown channel type",
8507 "Resource shortage",
8509 unsigned reason_code;
8510 char *reason_string;
8512 struct ssh_channel *c;
8514 c = ssh_channel_msg(ssh, pktin);
8517 assert(c->halfopen); /* ssh_channel_msg will have enforced this */
8519 if (c->type == CHAN_SOCKDATA) {
8520 reason_code = ssh_pkt_getuint32(pktin);
8521 if (reason_code >= lenof(reasons))
8522 reason_code = 0; /* ensure reasons[reason_code] in range */
8523 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
8524 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
8525 reasons[reason_code], reason_length,
8526 NULLTOEMPTY(reason_string));
8528 pfd_close(c->u.pfd.pf);
8529 } else if (c->type == CHAN_ZOMBIE) {
8531 * This case can occur if a local socket error occurred
8532 * between us sending out CHANNEL_OPEN and receiving
8533 * OPEN_FAILURE. In this case, we need do nothing except allow
8534 * the code below to throw the half-open channel away.
8538 * We never expect to receive OPEN_FAILURE for any *other*
8539 * channel type (since only local-to-remote port forwardings
8540 * cause us to send CHANNEL_OPEN after the main channel is
8541 * live - all other auxiliary channel types are initiated from
8542 * the server end). It's safe to enforce this by assertion
8543 * rather than by ssh_disconnect, because the real point is
8544 * that we never constructed a half-open channel structure in
8545 * the first place with any type other than the above.
8547 assert(!"Funny channel type in ssh2_msg_channel_open_failure");
8550 del234(ssh->channels, c);
8554 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
8557 int typelen, want_reply;
8558 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
8559 struct ssh_channel *c;
8560 struct Packet *pktout;
8562 c = ssh_channel_msg(ssh, pktin);
8565 ssh_pkt_getstring(pktin, &type, &typelen);
8566 want_reply = ssh2_pkt_getbool(pktin);
8568 if (c->closes & CLOSES_SENT_CLOSE) {
8570 * We don't reply to channel requests after we've sent
8571 * CHANNEL_CLOSE for the channel, because our reply might
8572 * cross in the network with the other side's CHANNEL_CLOSE
8573 * and arrive after they have wound the channel up completely.
8579 * Having got the channel number, we now look at
8580 * the request type string to see if it's something
8583 if (c == ssh->mainchan) {
8585 * We recognise "exit-status" and "exit-signal" on
8586 * the primary channel.
8588 if (typelen == 11 &&
8589 !memcmp(type, "exit-status", 11)) {
8591 ssh->exitcode = ssh_pkt_getuint32(pktin);
8592 logeventf(ssh, "Server sent command exit status %d",
8594 reply = SSH2_MSG_CHANNEL_SUCCESS;
8596 } else if (typelen == 11 &&
8597 !memcmp(type, "exit-signal", 11)) {
8599 int is_plausible = TRUE, is_int = FALSE;
8600 char *fmt_sig = NULL, *fmt_msg = NULL;
8602 int msglen = 0, core = FALSE;
8603 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
8604 * provide an `int' for the signal, despite its
8605 * having been a `string' in the drafts of RFC 4254 since at
8606 * least 2001. (Fixed in session.c 1.147.) Try to
8607 * infer which we can safely parse it as. */
8609 unsigned char *p = pktin->body +
8611 long len = pktin->length - pktin->savedpos;
8612 unsigned long num = GET_32BIT(p); /* what is it? */
8613 /* If it's 0, it hardly matters; assume string */
8617 int maybe_int = FALSE, maybe_str = FALSE;
8618 #define CHECK_HYPOTHESIS(offset, result) \
8621 int q = toint(offset); \
8622 if (q >= 0 && q+4 <= len) { \
8623 q = toint(q + 4 + GET_32BIT(p+q)); \
8624 if (q >= 0 && q+4 <= len && \
8625 ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
8630 CHECK_HYPOTHESIS(4+1, maybe_int);
8631 CHECK_HYPOTHESIS(4+num+1, maybe_str);
8632 #undef CHECK_HYPOTHESIS
8633 if (maybe_int && !maybe_str)
8635 else if (!maybe_int && maybe_str)
8638 /* Crikey. Either or neither. Panic. */
8639 is_plausible = FALSE;
8642 ssh->exitcode = 128; /* means `unknown signal' */
8645 /* Old non-standard OpenSSH. */
8646 int signum = ssh_pkt_getuint32(pktin);
8647 fmt_sig = dupprintf(" %d", signum);
8648 ssh->exitcode = 128 + signum;
8650 /* As per RFC 4254. */
8653 ssh_pkt_getstring(pktin, &sig, &siglen);
8654 /* Signal name isn't supposed to be blank, but
8655 * let's cope gracefully if it is. */
8657 fmt_sig = dupprintf(" \"%.*s\"",
8662 * Really hideous method of translating the
8663 * signal description back into a locally
8664 * meaningful number.
8669 #define TRANSLATE_SIGNAL(s) \
8670 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
8671 ssh->exitcode = 128 + SIG ## s
8673 TRANSLATE_SIGNAL(ABRT);
8676 TRANSLATE_SIGNAL(ALRM);
8679 TRANSLATE_SIGNAL(FPE);
8682 TRANSLATE_SIGNAL(HUP);
8685 TRANSLATE_SIGNAL(ILL);
8688 TRANSLATE_SIGNAL(INT);
8691 TRANSLATE_SIGNAL(KILL);
8694 TRANSLATE_SIGNAL(PIPE);
8697 TRANSLATE_SIGNAL(QUIT);
8700 TRANSLATE_SIGNAL(SEGV);
8703 TRANSLATE_SIGNAL(TERM);
8706 TRANSLATE_SIGNAL(USR1);
8709 TRANSLATE_SIGNAL(USR2);
8711 #undef TRANSLATE_SIGNAL
8713 ssh->exitcode = 128;
8715 core = ssh2_pkt_getbool(pktin);
8716 ssh_pkt_getstring(pktin, &msg, &msglen);
8718 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
8720 /* ignore lang tag */
8721 } /* else don't attempt to parse */
8722 logeventf(ssh, "Server exited on signal%s%s%s",
8723 fmt_sig ? fmt_sig : "",
8724 core ? " (core dumped)" : "",
8725 fmt_msg ? fmt_msg : "");
8728 reply = SSH2_MSG_CHANNEL_SUCCESS;
8733 * This is a channel request we don't know
8734 * about, so we now either ignore the request
8735 * or respond with CHANNEL_FAILURE, depending
8738 reply = SSH2_MSG_CHANNEL_FAILURE;
8741 pktout = ssh2_pkt_init(reply);
8742 ssh2_pkt_adduint32(pktout, c->remoteid);
8743 ssh2_pkt_send(ssh, pktout);
8747 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
8750 int typelen, want_reply;
8751 struct Packet *pktout;
8753 ssh_pkt_getstring(pktin, &type, &typelen);
8754 want_reply = ssh2_pkt_getbool(pktin);
8757 * We currently don't support any global requests
8758 * at all, so we either ignore the request or
8759 * respond with REQUEST_FAILURE, depending on
8763 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
8764 ssh2_pkt_send(ssh, pktout);
8768 struct X11FakeAuth *ssh_sharing_add_x11_display(Ssh ssh, int authtype,
8772 struct X11FakeAuth *auth;
8775 * Make up a new set of fake X11 auth data, and add it to the tree
8776 * of currently valid ones with an indication of the sharing
8777 * context that it's relevant to.
8779 auth = x11_invent_fake_auth(ssh->x11authtree, authtype);
8780 auth->share_cs = share_cs;
8781 auth->share_chan = share_chan;
8786 void ssh_sharing_remove_x11_display(Ssh ssh, struct X11FakeAuth *auth)
8788 del234(ssh->x11authtree, auth);
8789 x11_free_fake_auth(auth);
8792 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
8799 const char *error = NULL;
8800 struct ssh_channel *c;
8801 unsigned remid, winsize, pktsize;
8802 unsigned our_winsize_override = 0;
8803 struct Packet *pktout;
8805 ssh_pkt_getstring(pktin, &type, &typelen);
8806 c = snew(struct ssh_channel);
8809 remid = ssh_pkt_getuint32(pktin);
8810 winsize = ssh_pkt_getuint32(pktin);
8811 pktsize = ssh_pkt_getuint32(pktin);
8813 if (typelen == 3 && !memcmp(type, "x11", 3)) {
8816 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8817 addrstr = dupprintf("%.*s", peeraddrlen, NULLTOEMPTY(peeraddr));
8818 peerport = ssh_pkt_getuint32(pktin);
8820 logeventf(ssh, "Received X11 connect request from %s:%d",
8823 if (!ssh->X11_fwd_enabled && !ssh->connshare)
8824 error = "X11 forwarding is not enabled";
8826 c->u.x11.xconn = x11_init(ssh->x11authtree, c,
8829 c->u.x11.initial = TRUE;
8832 * If we are a connection-sharing upstream, then we should
8833 * initially present a very small window, adequate to take
8834 * the X11 initial authorisation packet but not much more.
8835 * Downstream will then present us a larger window (by
8836 * fiat of the connection-sharing protocol) and we can
8837 * guarantee to send a positive-valued WINDOW_ADJUST.
8840 our_winsize_override = 128;
8842 logevent("Opened X11 forward channel");
8846 } else if (typelen == 15 &&
8847 !memcmp(type, "forwarded-tcpip", 15)) {
8848 struct ssh_rportfwd pf, *realpf;
8851 ssh_pkt_getstring(pktin, &shost, &shostlen);/* skip address */
8852 pf.shost = dupprintf("%.*s", shostlen, NULLTOEMPTY(shost));
8853 pf.sport = ssh_pkt_getuint32(pktin);
8854 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8855 peerport = ssh_pkt_getuint32(pktin);
8856 realpf = find234(ssh->rportfwds, &pf, NULL);
8857 logeventf(ssh, "Received remote port %s:%d open request "
8858 "from %.*s:%d", pf.shost, pf.sport,
8859 peeraddrlen, NULLTOEMPTY(peeraddr), peerport);
8862 if (realpf == NULL) {
8863 error = "Remote port is not recognised";
8867 if (realpf->share_ctx) {
8869 * This port forwarding is on behalf of a
8870 * connection-sharing downstream, so abandon our own
8871 * channel-open procedure and just pass the message on
8874 share_got_pkt_from_server(realpf->share_ctx, pktin->type,
8875 pktin->body, pktin->length);
8880 err = pfd_connect(&c->u.pfd.pf, realpf->dhost, realpf->dport,
8881 c, ssh->conf, realpf->pfrec->addressfamily);
8882 logeventf(ssh, "Attempting to forward remote port to "
8883 "%s:%d", realpf->dhost, realpf->dport);
8885 logeventf(ssh, "Port open failed: %s", err);
8887 error = "Port open failed";
8889 logevent("Forwarded port opened successfully");
8890 c->type = CHAN_SOCKDATA;
8893 } else if (typelen == 22 &&
8894 !memcmp(type, "auth-agent@openssh.com", 22)) {
8895 if (!ssh->agentfwd_enabled)
8896 error = "Agent forwarding is not enabled";
8898 c->type = CHAN_AGENT; /* identify channel type */
8899 bufchain_init(&c->u.a.inbuffer);
8900 c->u.a.pending = NULL;
8903 error = "Unsupported channel type requested";
8906 c->remoteid = remid;
8907 c->halfopen = FALSE;
8909 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
8910 ssh2_pkt_adduint32(pktout, c->remoteid);
8911 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
8912 ssh2_pkt_addstring(pktout, error);
8913 ssh2_pkt_addstring(pktout, "en"); /* language tag */
8914 ssh2_pkt_send(ssh, pktout);
8915 logeventf(ssh, "Rejected channel open: %s", error);
8918 ssh_channel_init(c);
8919 c->v.v2.remwindow = winsize;
8920 c->v.v2.remmaxpkt = pktsize;
8921 if (our_winsize_override) {
8922 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
8923 our_winsize_override;
8925 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
8926 ssh2_pkt_adduint32(pktout, c->remoteid);
8927 ssh2_pkt_adduint32(pktout, c->localid);
8928 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
8929 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
8930 ssh2_pkt_send(ssh, pktout);
8934 void sshfwd_x11_sharing_handover(struct ssh_channel *c,
8935 void *share_cs, void *share_chan,
8936 const char *peer_addr, int peer_port,
8937 int endian, int protomajor, int protominor,
8938 const void *initial_data, int initial_len)
8941 * This function is called when we've just discovered that an X
8942 * forwarding channel on which we'd been handling the initial auth
8943 * ourselves turns out to be destined for a connection-sharing
8944 * downstream. So we turn the channel into a CHAN_SHARING, meaning
8945 * that we completely stop tracking windows and buffering data and
8946 * just pass more or less unmodified SSH messages back and forth.
8948 c->type = CHAN_SHARING;
8949 c->u.sharing.ctx = share_cs;
8950 share_setup_x11_channel(share_cs, share_chan,
8951 c->localid, c->remoteid, c->v.v2.remwindow,
8952 c->v.v2.remmaxpkt, c->v.v2.locwindow,
8953 peer_addr, peer_port, endian,
8954 protomajor, protominor,
8955 initial_data, initial_len);
8958 void sshfwd_x11_is_local(struct ssh_channel *c)
8961 * This function is called when we've just discovered that an X
8962 * forwarding channel is _not_ destined for a connection-sharing
8963 * downstream but we're going to handle it ourselves. We stop
8964 * presenting a cautiously small window and go into ordinary data
8967 c->u.x11.initial = FALSE;
8968 ssh2_set_window(c, ssh_is_simple(c->ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE);
8972 * Buffer banner messages for later display at some convenient point,
8973 * if we're going to display them.
8975 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
8977 /* Arbitrary limit to prevent unbounded inflation of buffer */
8978 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
8979 bufchain_size(&ssh->banner) <= 131072) {
8980 char *banner = NULL;
8982 ssh_pkt_getstring(pktin, &banner, &size);
8984 bufchain_add(&ssh->banner, banner, size);
8988 /* Helper function to deal with sending tty modes for "pty-req" */
8989 static void ssh2_send_ttymode(void *data,
8990 const struct ssh_ttymode *mode, char *val)
8992 struct Packet *pktout = (struct Packet *)data;
8993 unsigned int arg = 0;
8995 switch (mode->type) {
8997 arg = ssh_tty_parse_specchar(val);
9000 arg = ssh_tty_parse_boolean(val);
9003 ssh2_pkt_addbyte(pktout, mode->opcode);
9004 ssh2_pkt_adduint32(pktout, arg);
9007 static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
9010 struct ssh2_setup_x11_state {
9014 struct Packet *pktout;
9015 crStateP(ssh2_setup_x11_state, ctx);
9019 logevent("Requesting X11 forwarding");
9020 pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
9022 ssh2_pkt_addbool(pktout, 0); /* many connections */
9023 ssh2_pkt_addstring(pktout, ssh->x11auth->protoname);
9024 ssh2_pkt_addstring(pktout, ssh->x11auth->datastring);
9025 ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
9026 ssh2_pkt_send(ssh, pktout);
9028 /* Wait to be called back with either a response packet, or NULL
9029 * meaning clean up and free our data */
9033 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
9034 logevent("X11 forwarding enabled");
9035 ssh->X11_fwd_enabled = TRUE;
9037 logevent("X11 forwarding refused");
9043 static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
9046 struct ssh2_setup_agent_state {
9050 struct Packet *pktout;
9051 crStateP(ssh2_setup_agent_state, ctx);
9055 logevent("Requesting OpenSSH-style agent forwarding");
9056 pktout = ssh2_chanreq_init(ssh->mainchan, "auth-agent-req@openssh.com",
9057 ssh2_setup_agent, s);
9058 ssh2_pkt_send(ssh, pktout);
9060 /* Wait to be called back with either a response packet, or NULL
9061 * meaning clean up and free our data */
9065 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
9066 logevent("Agent forwarding enabled");
9067 ssh->agentfwd_enabled = TRUE;
9069 logevent("Agent forwarding refused");
9075 static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
9078 struct ssh2_setup_pty_state {
9082 struct Packet *pktout;
9083 crStateP(ssh2_setup_pty_state, ctx);
9087 /* Unpick the terminal-speed string. */
9088 /* XXX perhaps we should allow no speeds to be sent. */
9089 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
9090 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
9091 /* Build the pty request. */
9092 pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
9094 ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
9095 ssh2_pkt_adduint32(pktout, ssh->term_width);
9096 ssh2_pkt_adduint32(pktout, ssh->term_height);
9097 ssh2_pkt_adduint32(pktout, 0); /* pixel width */
9098 ssh2_pkt_adduint32(pktout, 0); /* pixel height */
9099 ssh2_pkt_addstring_start(pktout);
9100 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
9101 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
9102 ssh2_pkt_adduint32(pktout, ssh->ispeed);
9103 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
9104 ssh2_pkt_adduint32(pktout, ssh->ospeed);
9105 ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
9106 ssh2_pkt_send(ssh, pktout);
9107 ssh->state = SSH_STATE_INTERMED;
9109 /* Wait to be called back with either a response packet, or NULL
9110 * meaning clean up and free our data */
9114 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
9115 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
9116 ssh->ospeed, ssh->ispeed);
9117 ssh->got_pty = TRUE;
9119 c_write_str(ssh, "Server refused to allocate pty\r\n");
9120 ssh->editing = ssh->echoing = 1;
9127 static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
9130 struct ssh2_setup_env_state {
9132 int num_env, env_left, env_ok;
9135 struct Packet *pktout;
9136 crStateP(ssh2_setup_env_state, ctx);
9141 * Send environment variables.
9143 * Simplest thing here is to send all the requests at once, and
9144 * then wait for a whole bunch of successes or failures.
9150 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
9152 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
9153 pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
9154 ssh2_pkt_addstring(pktout, key);
9155 ssh2_pkt_addstring(pktout, val);
9156 ssh2_pkt_send(ssh, pktout);
9161 logeventf(ssh, "Sent %d environment variables", s->num_env);
9166 s->env_left = s->num_env;
9168 while (s->env_left > 0) {
9169 /* Wait to be called back with either a response packet,
9170 * or NULL meaning clean up and free our data */
9172 if (!pktin) goto out;
9173 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
9178 if (s->env_ok == s->num_env) {
9179 logevent("All environment variables successfully set");
9180 } else if (s->env_ok == 0) {
9181 logevent("All environment variables refused");
9182 c_write_str(ssh, "Server refused to set environment variables\r\n");
9184 logeventf(ssh, "%d environment variables refused",
9185 s->num_env - s->env_ok);
9186 c_write_str(ssh, "Server refused to set all environment variables\r\n");
9194 * Handle the SSH-2 userauth and connection layers.
9196 static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
9198 do_ssh2_authconn(ssh, NULL, 0, pktin);
9201 static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
9205 do_ssh2_authconn(c->ssh, NULL, 0, pktin);
9208 static void do_ssh2_authconn(Ssh ssh, const unsigned char *in, int inlen,
9209 struct Packet *pktin)
9211 struct do_ssh2_authconn_state {
9215 AUTH_TYPE_PUBLICKEY,
9216 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
9217 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
9219 AUTH_TYPE_GSSAPI, /* always QUIET */
9220 AUTH_TYPE_KEYBOARD_INTERACTIVE,
9221 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
9223 int done_service_req;
9224 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
9225 int tried_pubkey_config, done_agent;
9230 int kbd_inter_refused;
9231 int we_are_in, userauth_success;
9232 prompts_t *cur_prompt;
9237 void *publickey_blob;
9238 int publickey_bloblen;
9239 int privatekey_available, privatekey_encrypted;
9240 char *publickey_algorithm;
9241 char *publickey_comment;
9242 unsigned char agent_request[5], *agent_response, *agentp;
9243 int agent_responselen;
9244 unsigned char *pkblob_in_agent;
9246 char *pkblob, *alg, *commentp;
9247 int pklen, alglen, commentlen;
9248 int siglen, retlen, len;
9249 char *q, *agentreq, *ret;
9250 struct Packet *pktout;
9253 struct ssh_gss_library *gsslib;
9254 Ssh_gss_ctx gss_ctx;
9255 Ssh_gss_buf gss_buf;
9256 Ssh_gss_buf gss_rcvtok, gss_sndtok;
9257 Ssh_gss_name gss_srv_name;
9258 Ssh_gss_stat gss_stat;
9261 crState(do_ssh2_authconn_state);
9265 /* Register as a handler for all the messages this coroutine handles. */
9266 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
9267 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
9268 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
9269 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
9270 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
9271 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
9272 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
9273 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
9274 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
9275 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
9276 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
9277 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
9278 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
9279 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
9280 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
9281 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
9282 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
9283 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
9284 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
9285 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
9287 s->done_service_req = FALSE;
9288 s->we_are_in = s->userauth_success = FALSE;
9289 s->agent_response = NULL;
9291 s->tried_gssapi = FALSE;
9294 if (!ssh->bare_connection) {
9295 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
9297 * Request userauth protocol, and await a response to it.
9299 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
9300 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
9301 ssh2_pkt_send(ssh, s->pktout);
9302 crWaitUntilV(pktin);
9303 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
9304 s->done_service_req = TRUE;
9306 if (!s->done_service_req) {
9308 * Request connection protocol directly, without authentication.
9310 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
9311 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9312 ssh2_pkt_send(ssh, s->pktout);
9313 crWaitUntilV(pktin);
9314 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
9315 s->we_are_in = TRUE; /* no auth required */
9317 bombout(("Server refused service request"));
9322 s->we_are_in = TRUE;
9325 /* Arrange to be able to deal with any BANNERs that come in.
9326 * (We do this now as packets may come in during the next bit.) */
9327 bufchain_init(&ssh->banner);
9328 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
9329 ssh2_msg_userauth_banner;
9332 * Misc one-time setup for authentication.
9334 s->publickey_blob = NULL;
9335 if (!s->we_are_in) {
9338 * Load the public half of any configured public key file
9341 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9342 if (!filename_is_null(s->keyfile)) {
9344 logeventf(ssh, "Reading key file \"%.150s\"",
9345 filename_to_str(s->keyfile));
9346 keytype = key_type(s->keyfile);
9347 if (keytype == SSH_KEYTYPE_SSH2 ||
9348 keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 ||
9349 keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
9352 ssh2_userkey_loadpub(s->keyfile,
9353 &s->publickey_algorithm,
9354 &s->publickey_bloblen,
9355 &s->publickey_comment, &error);
9356 if (s->publickey_blob) {
9357 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH2);
9358 if (!s->privatekey_available)
9359 logeventf(ssh, "Key file contains public key only");
9360 s->privatekey_encrypted =
9361 ssh2_userkey_encrypted(s->keyfile, NULL);
9364 logeventf(ssh, "Unable to load key (%s)",
9366 msgbuf = dupprintf("Unable to load key file "
9367 "\"%.150s\" (%s)\r\n",
9368 filename_to_str(s->keyfile),
9370 c_write_str(ssh, msgbuf);
9375 logeventf(ssh, "Unable to use this key file (%s)",
9376 key_type_to_str(keytype));
9377 msgbuf = dupprintf("Unable to use key file \"%.150s\""
9379 filename_to_str(s->keyfile),
9380 key_type_to_str(keytype));
9381 c_write_str(ssh, msgbuf);
9383 s->publickey_blob = NULL;
9388 * Find out about any keys Pageant has (but if there's a
9389 * public key configured, filter out all others).
9392 s->agent_response = NULL;
9393 s->pkblob_in_agent = NULL;
9394 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
9398 logevent("Pageant is running. Requesting keys.");
9400 /* Request the keys held by the agent. */
9401 PUT_32BIT(s->agent_request, 1);
9402 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
9403 ssh->auth_agent_query = agent_query(
9404 s->agent_request, 5, &r, &s->agent_responselen,
9405 ssh_agent_callback, ssh);
9406 if (ssh->auth_agent_query) {
9410 bombout(("Unexpected data from server while"
9411 " waiting for agent response"));
9414 } while (pktin || inlen > 0);
9415 r = ssh->agent_response;
9416 s->agent_responselen = ssh->agent_response_len;
9418 s->agent_response = (unsigned char *) r;
9419 if (s->agent_response && s->agent_responselen >= 5 &&
9420 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
9423 p = s->agent_response + 5;
9424 s->nkeys = toint(GET_32BIT(p));
9427 * Vet the Pageant response to ensure that the key
9428 * count and blob lengths make sense.
9431 logeventf(ssh, "Pageant response contained a negative"
9432 " key count %d", s->nkeys);
9434 goto done_agent_query;
9436 unsigned char *q = p + 4;
9437 int lenleft = s->agent_responselen - 5 - 4;
9439 for (keyi = 0; keyi < s->nkeys; keyi++) {
9440 int bloblen, commentlen;
9442 logeventf(ssh, "Pageant response was truncated");
9444 goto done_agent_query;
9446 bloblen = toint(GET_32BIT(q));
9447 if (bloblen < 0 || bloblen > lenleft) {
9448 logeventf(ssh, "Pageant response was truncated");
9450 goto done_agent_query;
9452 lenleft -= 4 + bloblen;
9454 commentlen = toint(GET_32BIT(q));
9455 if (commentlen < 0 || commentlen > lenleft) {
9456 logeventf(ssh, "Pageant response was truncated");
9458 goto done_agent_query;
9460 lenleft -= 4 + commentlen;
9461 q += 4 + commentlen;
9466 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
9467 if (s->publickey_blob) {
9468 /* See if configured key is in agent. */
9469 for (keyi = 0; keyi < s->nkeys; keyi++) {
9470 s->pklen = toint(GET_32BIT(p));
9471 if (s->pklen == s->publickey_bloblen &&
9472 !memcmp(p+4, s->publickey_blob,
9473 s->publickey_bloblen)) {
9474 logeventf(ssh, "Pageant key #%d matches "
9475 "configured key file", keyi);
9477 s->pkblob_in_agent = p;
9481 p += toint(GET_32BIT(p)) + 4; /* comment */
9483 if (!s->pkblob_in_agent) {
9484 logevent("Configured key file not in Pageant");
9489 logevent("Failed to get reply from Pageant");
9497 * We repeat this whole loop, including the username prompt,
9498 * until we manage a successful authentication. If the user
9499 * types the wrong _password_, they can be sent back to the
9500 * beginning to try another username, if this is configured on.
9501 * (If they specify a username in the config, they are never
9502 * asked, even if they do give a wrong password.)
9504 * I think this best serves the needs of
9506 * - the people who have no configuration, no keys, and just
9507 * want to try repeated (username,password) pairs until they
9508 * type both correctly
9510 * - people who have keys and configuration but occasionally
9511 * need to fall back to passwords
9513 * - people with a key held in Pageant, who might not have
9514 * logged in to a particular machine before; so they want to
9515 * type a username, and then _either_ their key will be
9516 * accepted, _or_ they will type a password. If they mistype
9517 * the username they will want to be able to get back and
9520 s->got_username = FALSE;
9521 while (!s->we_are_in) {
9525 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
9527 * We got a username last time round this loop, and
9528 * with change_username turned off we don't try to get
9531 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
9532 int ret; /* need not be kept over crReturn */
9533 s->cur_prompt = new_prompts(ssh->frontend);
9534 s->cur_prompt->to_server = TRUE;
9535 s->cur_prompt->name = dupstr("SSH login name");
9536 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
9537 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9540 crWaitUntilV(!pktin);
9541 ret = get_userpass_input(s->cur_prompt, in, inlen);
9546 * get_userpass_input() failed to get a username.
9549 free_prompts(s->cur_prompt);
9550 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
9553 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
9554 free_prompts(s->cur_prompt);
9557 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
9558 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
9559 c_write_str(ssh, stuff);
9563 s->got_username = TRUE;
9566 * Send an authentication request using method "none": (a)
9567 * just in case it succeeds, and (b) so that we know what
9568 * authentication methods we can usefully try next.
9570 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9572 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9573 ssh2_pkt_addstring(s->pktout, ssh->username);
9574 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
9575 ssh2_pkt_addstring(s->pktout, "none"); /* method */
9576 ssh2_pkt_send(ssh, s->pktout);
9577 s->type = AUTH_TYPE_NONE;
9579 s->we_are_in = FALSE;
9581 s->tried_pubkey_config = FALSE;
9582 s->kbd_inter_refused = FALSE;
9584 /* Reset agent request state. */
9585 s->done_agent = FALSE;
9586 if (s->agent_response) {
9587 if (s->pkblob_in_agent) {
9588 s->agentp = s->pkblob_in_agent;
9590 s->agentp = s->agent_response + 5 + 4;
9596 char *methods = NULL;
9600 * Wait for the result of the last authentication request.
9603 crWaitUntilV(pktin);
9605 * Now is a convenient point to spew any banner material
9606 * that we've accumulated. (This should ensure that when
9607 * we exit the auth loop, we haven't any left to deal
9611 int size = bufchain_size(&ssh->banner);
9613 * Don't show the banner if we're operating in
9614 * non-verbose non-interactive mode. (It's probably
9615 * a script, which means nobody will read the
9616 * banner _anyway_, and moreover the printing of
9617 * the banner will screw up processing on the
9618 * output of (say) plink.)
9620 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
9621 char *banner = snewn(size, char);
9622 bufchain_fetch(&ssh->banner, banner, size);
9623 c_write_untrusted(ssh, banner, size);
9626 bufchain_clear(&ssh->banner);
9628 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
9629 logevent("Access granted");
9630 s->we_are_in = s->userauth_success = TRUE;
9634 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
9635 bombout(("Strange packet received during authentication: "
9636 "type %d", pktin->type));
9643 * OK, we're now sitting on a USERAUTH_FAILURE message, so
9644 * we can look at the string in it and know what we can
9645 * helpfully try next.
9647 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
9648 ssh_pkt_getstring(pktin, &methods, &methlen);
9649 if (!ssh2_pkt_getbool(pktin)) {
9651 * We have received an unequivocal Access
9652 * Denied. This can translate to a variety of
9653 * messages, or no message at all.
9655 * For forms of authentication which are attempted
9656 * implicitly, by which I mean without printing
9657 * anything in the window indicating that we're
9658 * trying them, we should never print 'Access
9661 * If we do print a message saying that we're
9662 * attempting some kind of authentication, it's OK
9663 * to print a followup message saying it failed -
9664 * but the message may sometimes be more specific
9665 * than simply 'Access denied'.
9667 * Additionally, if we'd just tried password
9668 * authentication, we should break out of this
9669 * whole loop so as to go back to the username
9670 * prompt (iff we're configured to allow
9671 * username change attempts).
9673 if (s->type == AUTH_TYPE_NONE) {
9675 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
9676 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
9677 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
9678 c_write_str(ssh, "Server refused our key\r\n");
9679 logevent("Server refused our key");
9680 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
9681 /* This _shouldn't_ happen except by a
9682 * protocol bug causing client and server to
9683 * disagree on what is a correct signature. */
9684 c_write_str(ssh, "Server refused public-key signature"
9685 " despite accepting key!\r\n");
9686 logevent("Server refused public-key signature"
9687 " despite accepting key!");
9688 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
9689 /* quiet, so no c_write */
9690 logevent("Server refused keyboard-interactive authentication");
9691 } else if (s->type==AUTH_TYPE_GSSAPI) {
9692 /* always quiet, so no c_write */
9693 /* also, the code down in the GSSAPI block has
9694 * already logged this in the Event Log */
9695 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
9696 logevent("Keyboard-interactive authentication failed");
9697 c_write_str(ssh, "Access denied\r\n");
9699 assert(s->type == AUTH_TYPE_PASSWORD);
9700 logevent("Password authentication failed");
9701 c_write_str(ssh, "Access denied\r\n");
9703 if (conf_get_int(ssh->conf, CONF_change_username)) {
9704 /* XXX perhaps we should allow
9705 * keyboard-interactive to do this too? */
9706 s->we_are_in = FALSE;
9711 c_write_str(ssh, "Further authentication required\r\n");
9712 logevent("Further authentication required");
9716 in_commasep_string("publickey", methods, methlen);
9718 in_commasep_string("password", methods, methlen);
9719 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
9720 in_commasep_string("keyboard-interactive", methods, methlen);
9722 if (conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
9723 in_commasep_string("gssapi-with-mic", methods, methlen)) {
9724 /* Try loading the GSS libraries and see if we
9727 ssh->gsslibs = ssh_gss_setup(ssh->conf);
9728 s->can_gssapi = (ssh->gsslibs->nlibraries > 0);
9730 /* No point in even bothering to try to load the
9731 * GSS libraries, if the user configuration and
9732 * server aren't both prepared to attempt GSSAPI
9733 * auth in the first place. */
9734 s->can_gssapi = FALSE;
9739 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9741 if (s->can_pubkey && !s->done_agent && s->nkeys) {
9744 * Attempt public-key authentication using a key from Pageant.
9747 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9749 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
9751 /* Unpack key from agent response */
9752 s->pklen = toint(GET_32BIT(s->agentp));
9754 s->pkblob = (char *)s->agentp;
9755 s->agentp += s->pklen;
9756 s->alglen = toint(GET_32BIT(s->pkblob));
9757 s->alg = s->pkblob + 4;
9758 s->commentlen = toint(GET_32BIT(s->agentp));
9760 s->commentp = (char *)s->agentp;
9761 s->agentp += s->commentlen;
9762 /* s->agentp now points at next key, if any */
9764 /* See if server will accept it */
9765 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9766 ssh2_pkt_addstring(s->pktout, ssh->username);
9767 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9768 /* service requested */
9769 ssh2_pkt_addstring(s->pktout, "publickey");
9771 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
9772 ssh2_pkt_addstring_start(s->pktout);
9773 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9774 ssh2_pkt_addstring_start(s->pktout);
9775 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9776 ssh2_pkt_send(ssh, s->pktout);
9777 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
9779 crWaitUntilV(pktin);
9780 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9782 /* Offer of key refused. */
9789 if (flags & FLAG_VERBOSE) {
9790 c_write_str(ssh, "Authenticating with "
9792 c_write(ssh, s->commentp, s->commentlen);
9793 c_write_str(ssh, "\" from agent\r\n");
9797 * Server is willing to accept the key.
9798 * Construct a SIGN_REQUEST.
9800 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9801 ssh2_pkt_addstring(s->pktout, ssh->username);
9802 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9803 /* service requested */
9804 ssh2_pkt_addstring(s->pktout, "publickey");
9806 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
9807 ssh2_pkt_addstring_start(s->pktout);
9808 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9809 ssh2_pkt_addstring_start(s->pktout);
9810 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9812 /* Ask agent for signature. */
9813 s->siglen = s->pktout->length - 5 + 4 +
9814 ssh->v2_session_id_len;
9815 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9817 s->len = 1; /* message type */
9818 s->len += 4 + s->pklen; /* key blob */
9819 s->len += 4 + s->siglen; /* data to sign */
9820 s->len += 4; /* flags */
9821 s->agentreq = snewn(4 + s->len, char);
9822 PUT_32BIT(s->agentreq, s->len);
9823 s->q = s->agentreq + 4;
9824 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
9825 PUT_32BIT(s->q, s->pklen);
9827 memcpy(s->q, s->pkblob, s->pklen);
9829 PUT_32BIT(s->q, s->siglen);
9831 /* Now the data to be signed... */
9832 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9833 PUT_32BIT(s->q, ssh->v2_session_id_len);
9836 memcpy(s->q, ssh->v2_session_id,
9837 ssh->v2_session_id_len);
9838 s->q += ssh->v2_session_id_len;
9839 memcpy(s->q, s->pktout->data + 5,
9840 s->pktout->length - 5);
9841 s->q += s->pktout->length - 5;
9842 /* And finally the (zero) flags word. */
9844 ssh->auth_agent_query = agent_query(
9845 s->agentreq, s->len + 4, &vret, &s->retlen,
9846 ssh_agent_callback, ssh);
9847 if (ssh->auth_agent_query) {
9851 bombout(("Unexpected data from server"
9852 " while waiting for agent"
9856 } while (pktin || inlen > 0);
9857 vret = ssh->agent_response;
9858 s->retlen = ssh->agent_response_len;
9863 if (s->retlen >= 9 &&
9864 s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
9865 GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
9866 logevent("Sending Pageant's response");
9867 ssh2_add_sigblob(ssh, s->pktout,
9868 s->pkblob, s->pklen,
9870 GET_32BIT(s->ret + 5));
9871 ssh2_pkt_send(ssh, s->pktout);
9872 s->type = AUTH_TYPE_PUBLICKEY;
9874 /* FIXME: less drastic response */
9875 bombout(("Pageant failed to answer challenge"));
9881 /* Do we have any keys left to try? */
9882 if (s->pkblob_in_agent) {
9883 s->done_agent = TRUE;
9884 s->tried_pubkey_config = TRUE;
9887 if (s->keyi >= s->nkeys)
9888 s->done_agent = TRUE;
9891 } else if (s->can_pubkey && s->publickey_blob &&
9892 s->privatekey_available && !s->tried_pubkey_config) {
9894 struct ssh2_userkey *key; /* not live over crReturn */
9895 char *passphrase; /* not live over crReturn */
9897 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9899 s->tried_pubkey_config = TRUE;
9902 * Try the public key supplied in the configuration.
9904 * First, offer the public blob to see if the server is
9905 * willing to accept it.
9907 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9908 ssh2_pkt_addstring(s->pktout, ssh->username);
9909 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9910 /* service requested */
9911 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
9912 ssh2_pkt_addbool(s->pktout, FALSE);
9913 /* no signature included */
9914 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
9915 ssh2_pkt_addstring_start(s->pktout);
9916 ssh2_pkt_addstring_data(s->pktout,
9917 (char *)s->publickey_blob,
9918 s->publickey_bloblen);
9919 ssh2_pkt_send(ssh, s->pktout);
9920 logevent("Offered public key");
9922 crWaitUntilV(pktin);
9923 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9924 /* Key refused. Give up. */
9925 s->gotit = TRUE; /* reconsider message next loop */
9926 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
9927 continue; /* process this new message */
9929 logevent("Offer of public key accepted");
9932 * Actually attempt a serious authentication using
9935 if (flags & FLAG_VERBOSE) {
9936 c_write_str(ssh, "Authenticating with public key \"");
9937 c_write_str(ssh, s->publickey_comment);
9938 c_write_str(ssh, "\"\r\n");
9942 const char *error; /* not live over crReturn */
9943 if (s->privatekey_encrypted) {
9945 * Get a passphrase from the user.
9947 int ret; /* need not be kept over crReturn */
9948 s->cur_prompt = new_prompts(ssh->frontend);
9949 s->cur_prompt->to_server = FALSE;
9950 s->cur_prompt->name = dupstr("SSH key passphrase");
9951 add_prompt(s->cur_prompt,
9952 dupprintf("Passphrase for key \"%.100s\": ",
9953 s->publickey_comment),
9955 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9958 crWaitUntilV(!pktin);
9959 ret = get_userpass_input(s->cur_prompt,
9964 /* Failed to get a passphrase. Terminate. */
9965 free_prompts(s->cur_prompt);
9966 ssh_disconnect(ssh, NULL,
9967 "Unable to authenticate",
9968 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9973 dupstr(s->cur_prompt->prompts[0]->result);
9974 free_prompts(s->cur_prompt);
9976 passphrase = NULL; /* no passphrase needed */
9980 * Try decrypting the key.
9982 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9983 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
9985 /* burn the evidence */
9986 smemclr(passphrase, strlen(passphrase));
9989 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
9991 (key == SSH2_WRONG_PASSPHRASE)) {
9992 c_write_str(ssh, "Wrong passphrase\r\n");
9994 /* and loop again */
9996 c_write_str(ssh, "Unable to load private key (");
9997 c_write_str(ssh, error);
9998 c_write_str(ssh, ")\r\n");
10000 break; /* try something else */
10006 unsigned char *pkblob, *sigblob, *sigdata;
10007 int pkblob_len, sigblob_len, sigdata_len;
10011 * We have loaded the private key and the server
10012 * has announced that it's willing to accept it.
10013 * Hallelujah. Generate a signature and send it.
10015 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10016 ssh2_pkt_addstring(s->pktout, ssh->username);
10017 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10018 /* service requested */
10019 ssh2_pkt_addstring(s->pktout, "publickey");
10021 ssh2_pkt_addbool(s->pktout, TRUE);
10022 /* signature follows */
10023 ssh2_pkt_addstring(s->pktout, key->alg->name);
10024 pkblob = key->alg->public_blob(key->data,
10026 ssh2_pkt_addstring_start(s->pktout);
10027 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
10031 * The data to be signed is:
10033 * string session-id
10035 * followed by everything so far placed in the
10038 sigdata_len = s->pktout->length - 5 + 4 +
10039 ssh->v2_session_id_len;
10040 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
10042 sigdata = snewn(sigdata_len, unsigned char);
10044 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
10045 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
10048 memcpy(sigdata+p, ssh->v2_session_id,
10049 ssh->v2_session_id_len);
10050 p += ssh->v2_session_id_len;
10051 memcpy(sigdata+p, s->pktout->data + 5,
10052 s->pktout->length - 5);
10053 p += s->pktout->length - 5;
10054 assert(p == sigdata_len);
10055 sigblob = key->alg->sign(key->data, (char *)sigdata,
10056 sigdata_len, &sigblob_len);
10057 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
10058 sigblob, sigblob_len);
10063 ssh2_pkt_send(ssh, s->pktout);
10064 logevent("Sent public key signature");
10065 s->type = AUTH_TYPE_PUBLICKEY;
10066 key->alg->freekey(key->data);
10067 sfree(key->comment);
10072 } else if (s->can_gssapi && !s->tried_gssapi) {
10074 /* GSSAPI Authentication */
10076 int micoffset, len;
10079 s->type = AUTH_TYPE_GSSAPI;
10080 s->tried_gssapi = TRUE;
10082 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
10085 * Pick the highest GSS library on the preference
10091 for (i = 0; i < ngsslibs; i++) {
10092 int want_id = conf_get_int_int(ssh->conf,
10093 CONF_ssh_gsslist, i);
10094 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
10095 if (ssh->gsslibs->libraries[j].id == want_id) {
10096 s->gsslib = &ssh->gsslibs->libraries[j];
10097 goto got_gsslib; /* double break */
10102 * We always expect to have found something in
10103 * the above loop: we only came here if there
10104 * was at least one viable GSS library, and the
10105 * preference list should always mention
10106 * everything and only change the order.
10111 if (s->gsslib->gsslogmsg)
10112 logevent(s->gsslib->gsslogmsg);
10114 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
10115 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10116 ssh2_pkt_addstring(s->pktout, ssh->username);
10117 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10118 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
10119 logevent("Attempting GSSAPI authentication");
10121 /* add mechanism info */
10122 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
10124 /* number of GSSAPI mechanisms */
10125 ssh2_pkt_adduint32(s->pktout,1);
10127 /* length of OID + 2 */
10128 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
10129 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
10131 /* length of OID */
10132 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
10134 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
10135 s->gss_buf.length);
10136 ssh2_pkt_send(ssh, s->pktout);
10137 crWaitUntilV(pktin);
10138 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
10139 logevent("GSSAPI authentication request refused");
10143 /* check returned packet ... */
10145 ssh_pkt_getstring(pktin, &data, &len);
10146 s->gss_rcvtok.value = data;
10147 s->gss_rcvtok.length = len;
10148 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
10149 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
10150 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
10151 memcmp((char *)s->gss_rcvtok.value + 2,
10152 s->gss_buf.value,s->gss_buf.length) ) {
10153 logevent("GSSAPI authentication - wrong response from server");
10157 /* now start running */
10158 s->gss_stat = s->gsslib->import_name(s->gsslib,
10161 if (s->gss_stat != SSH_GSS_OK) {
10162 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
10163 logevent("GSSAPI import name failed - Bad service name");
10165 logevent("GSSAPI import name failed");
10169 /* fetch TGT into GSS engine */
10170 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
10172 if (s->gss_stat != SSH_GSS_OK) {
10173 logevent("GSSAPI authentication failed to get credentials");
10174 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10178 /* initial tokens are empty */
10179 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
10180 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
10182 /* now enter the loop */
10184 s->gss_stat = s->gsslib->init_sec_context
10188 conf_get_int(ssh->conf, CONF_gssapifwd),
10192 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
10193 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
10194 logevent("GSSAPI authentication initialisation failed");
10196 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
10197 &s->gss_buf) == SSH_GSS_OK) {
10198 logevent(s->gss_buf.value);
10199 sfree(s->gss_buf.value);
10204 logevent("GSSAPI authentication initialised");
10206 /* Client and server now exchange tokens until GSSAPI
10207 * no longer says CONTINUE_NEEDED */
10209 if (s->gss_sndtok.length != 0) {
10210 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
10211 ssh_pkt_addstring_start(s->pktout);
10212 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
10213 ssh2_pkt_send(ssh, s->pktout);
10214 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
10217 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
10218 crWaitUntilV(pktin);
10219 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
10220 logevent("GSSAPI authentication - bad server response");
10221 s->gss_stat = SSH_GSS_FAILURE;
10224 ssh_pkt_getstring(pktin, &data, &len);
10225 s->gss_rcvtok.value = data;
10226 s->gss_rcvtok.length = len;
10228 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
10230 if (s->gss_stat != SSH_GSS_OK) {
10231 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10232 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
10235 logevent("GSSAPI authentication loop finished OK");
10237 /* Now send the MIC */
10239 s->pktout = ssh2_pkt_init(0);
10240 micoffset = s->pktout->length;
10241 ssh_pkt_addstring_start(s->pktout);
10242 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
10243 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
10244 ssh_pkt_addstring(s->pktout, ssh->username);
10245 ssh_pkt_addstring(s->pktout, "ssh-connection");
10246 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
10248 s->gss_buf.value = (char *)s->pktout->data + micoffset;
10249 s->gss_buf.length = s->pktout->length - micoffset;
10251 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
10252 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
10253 ssh_pkt_addstring_start(s->pktout);
10254 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
10255 ssh2_pkt_send(ssh, s->pktout);
10256 s->gsslib->free_mic(s->gsslib, &mic);
10260 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10261 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
10264 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
10267 * Keyboard-interactive authentication.
10270 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
10272 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
10274 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10275 ssh2_pkt_addstring(s->pktout, ssh->username);
10276 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10277 /* service requested */
10278 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
10280 ssh2_pkt_addstring(s->pktout, ""); /* lang */
10281 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
10282 ssh2_pkt_send(ssh, s->pktout);
10284 logevent("Attempting keyboard-interactive authentication");
10286 crWaitUntilV(pktin);
10287 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
10288 /* Server is not willing to do keyboard-interactive
10289 * at all (or, bizarrely but legally, accepts the
10290 * user without actually issuing any prompts).
10291 * Give up on it entirely. */
10293 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
10294 s->kbd_inter_refused = TRUE; /* don't try it again */
10299 * Loop while the server continues to send INFO_REQUESTs.
10301 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
10303 char *name, *inst, *lang;
10304 int name_len, inst_len, lang_len;
10308 * We've got a fresh USERAUTH_INFO_REQUEST.
10309 * Get the preamble and start building a prompt.
10311 ssh_pkt_getstring(pktin, &name, &name_len);
10312 ssh_pkt_getstring(pktin, &inst, &inst_len);
10313 ssh_pkt_getstring(pktin, &lang, &lang_len);
10314 s->cur_prompt = new_prompts(ssh->frontend);
10315 s->cur_prompt->to_server = TRUE;
10318 * Get any prompt(s) from the packet.
10320 s->num_prompts = ssh_pkt_getuint32(pktin);
10321 for (i = 0; i < s->num_prompts; i++) {
10325 static char noprompt[] =
10326 "<server failed to send prompt>: ";
10328 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10329 echo = ssh2_pkt_getbool(pktin);
10332 prompt_len = lenof(noprompt)-1;
10334 add_prompt(s->cur_prompt,
10335 dupprintf("%.*s", prompt_len, prompt),
10340 /* FIXME: better prefix to distinguish from
10341 * local prompts? */
10342 s->cur_prompt->name =
10343 dupprintf("SSH server: %.*s", name_len, name);
10344 s->cur_prompt->name_reqd = TRUE;
10346 s->cur_prompt->name =
10347 dupstr("SSH server authentication");
10348 s->cur_prompt->name_reqd = FALSE;
10350 /* We add a prefix to try to make it clear that a prompt
10351 * has come from the server.
10352 * FIXME: ugly to print "Using..." in prompt _every_
10353 * time round. Can this be done more subtly? */
10354 /* Special case: for reasons best known to themselves,
10355 * some servers send k-i requests with no prompts and
10356 * nothing to display. Keep quiet in this case. */
10357 if (s->num_prompts || name_len || inst_len) {
10358 s->cur_prompt->instruction =
10359 dupprintf("Using keyboard-interactive authentication.%s%.*s",
10360 inst_len ? "\n" : "", inst_len, inst);
10361 s->cur_prompt->instr_reqd = TRUE;
10363 s->cur_prompt->instr_reqd = FALSE;
10367 * Display any instructions, and get the user's
10371 int ret; /* not live over crReturn */
10372 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10375 crWaitUntilV(!pktin);
10376 ret = get_userpass_input(s->cur_prompt, in, inlen);
10381 * Failed to get responses. Terminate.
10383 free_prompts(s->cur_prompt);
10384 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10385 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10392 * Send the response(s) to the server.
10394 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
10395 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
10396 for (i=0; i < s->num_prompts; i++) {
10397 ssh2_pkt_addstring(s->pktout,
10398 s->cur_prompt->prompts[i]->result);
10400 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10403 * Free the prompts structure from this iteration.
10404 * If there's another, a new one will be allocated
10405 * when we return to the top of this while loop.
10407 free_prompts(s->cur_prompt);
10410 * Get the next packet in case it's another
10413 crWaitUntilV(pktin);
10418 * We should have SUCCESS or FAILURE now.
10422 } else if (s->can_passwd) {
10425 * Plain old password authentication.
10427 int ret; /* not live over crReturn */
10428 int changereq_first_time; /* not live over crReturn */
10430 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
10432 s->cur_prompt = new_prompts(ssh->frontend);
10433 s->cur_prompt->to_server = TRUE;
10434 s->cur_prompt->name = dupstr("SSH password");
10435 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
10440 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10443 crWaitUntilV(!pktin);
10444 ret = get_userpass_input(s->cur_prompt, in, inlen);
10449 * Failed to get responses. Terminate.
10451 free_prompts(s->cur_prompt);
10452 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10453 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10458 * Squirrel away the password. (We may need it later if
10459 * asked to change it.)
10461 s->password = dupstr(s->cur_prompt->prompts[0]->result);
10462 free_prompts(s->cur_prompt);
10465 * Send the password packet.
10467 * We pad out the password packet to 256 bytes to make
10468 * it harder for an attacker to find the length of the
10471 * Anyone using a password longer than 256 bytes
10472 * probably doesn't have much to worry about from
10473 * people who find out how long their password is!
10475 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10476 ssh2_pkt_addstring(s->pktout, ssh->username);
10477 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10478 /* service requested */
10479 ssh2_pkt_addstring(s->pktout, "password");
10480 ssh2_pkt_addbool(s->pktout, FALSE);
10481 ssh2_pkt_addstring(s->pktout, s->password);
10482 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10483 logevent("Sent password");
10484 s->type = AUTH_TYPE_PASSWORD;
10487 * Wait for next packet, in case it's a password change
10490 crWaitUntilV(pktin);
10491 changereq_first_time = TRUE;
10493 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
10496 * We're being asked for a new password
10497 * (perhaps not for the first time).
10498 * Loop until the server accepts it.
10501 int got_new = FALSE; /* not live over crReturn */
10502 char *prompt; /* not live over crReturn */
10503 int prompt_len; /* not live over crReturn */
10507 if (changereq_first_time)
10508 msg = "Server requested password change";
10510 msg = "Server rejected new password";
10512 c_write_str(ssh, msg);
10513 c_write_str(ssh, "\r\n");
10516 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10518 s->cur_prompt = new_prompts(ssh->frontend);
10519 s->cur_prompt->to_server = TRUE;
10520 s->cur_prompt->name = dupstr("New SSH password");
10521 s->cur_prompt->instruction =
10522 dupprintf("%.*s", prompt_len, NULLTOEMPTY(prompt));
10523 s->cur_prompt->instr_reqd = TRUE;
10525 * There's no explicit requirement in the protocol
10526 * for the "old" passwords in the original and
10527 * password-change messages to be the same, and
10528 * apparently some Cisco kit supports password change
10529 * by the user entering a blank password originally
10530 * and the real password subsequently, so,
10531 * reluctantly, we prompt for the old password again.
10533 * (On the other hand, some servers don't even bother
10534 * to check this field.)
10536 add_prompt(s->cur_prompt,
10537 dupstr("Current password (blank for previously entered password): "),
10539 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
10541 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
10545 * Loop until the user manages to enter the same
10550 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10553 crWaitUntilV(!pktin);
10554 ret = get_userpass_input(s->cur_prompt, in, inlen);
10559 * Failed to get responses. Terminate.
10561 /* burn the evidence */
10562 free_prompts(s->cur_prompt);
10563 smemclr(s->password, strlen(s->password));
10564 sfree(s->password);
10565 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10566 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10572 * If the user specified a new original password
10573 * (IYSWIM), overwrite any previously specified
10575 * (A side effect is that the user doesn't have to
10576 * re-enter it if they louse up the new password.)
10578 if (s->cur_prompt->prompts[0]->result[0]) {
10579 smemclr(s->password, strlen(s->password));
10580 /* burn the evidence */
10581 sfree(s->password);
10583 dupstr(s->cur_prompt->prompts[0]->result);
10587 * Check the two new passwords match.
10589 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
10590 s->cur_prompt->prompts[2]->result)
10593 /* They don't. Silly user. */
10594 c_write_str(ssh, "Passwords do not match\r\n");
10599 * Send the new password (along with the old one).
10600 * (see above for padding rationale)
10602 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10603 ssh2_pkt_addstring(s->pktout, ssh->username);
10604 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10605 /* service requested */
10606 ssh2_pkt_addstring(s->pktout, "password");
10607 ssh2_pkt_addbool(s->pktout, TRUE);
10608 ssh2_pkt_addstring(s->pktout, s->password);
10609 ssh2_pkt_addstring(s->pktout,
10610 s->cur_prompt->prompts[1]->result);
10611 free_prompts(s->cur_prompt);
10612 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10613 logevent("Sent new password");
10616 * Now see what the server has to say about it.
10617 * (If it's CHANGEREQ again, it's not happy with the
10620 crWaitUntilV(pktin);
10621 changereq_first_time = FALSE;
10626 * We need to reexamine the current pktin at the top
10627 * of the loop. Either:
10628 * - we weren't asked to change password at all, in
10629 * which case it's a SUCCESS or FAILURE with the
10631 * - we sent a new password, and the server was
10632 * either OK with it (SUCCESS or FAILURE w/partial
10633 * success) or unhappy with the _old_ password
10634 * (FAILURE w/o partial success)
10635 * In any of these cases, we go back to the top of
10636 * the loop and start again.
10641 * We don't need the old password any more, in any
10642 * case. Burn the evidence.
10644 smemclr(s->password, strlen(s->password));
10645 sfree(s->password);
10648 char *str = dupprintf("No supported authentication methods available"
10649 " (server sent: %.*s)",
10652 ssh_disconnect(ssh, str,
10653 "No supported authentication methods available",
10654 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
10664 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
10666 /* Clear up various bits and pieces from authentication. */
10667 if (s->publickey_blob) {
10668 sfree(s->publickey_algorithm);
10669 sfree(s->publickey_blob);
10670 sfree(s->publickey_comment);
10672 if (s->agent_response)
10673 sfree(s->agent_response);
10675 if (s->userauth_success && !ssh->bare_connection) {
10677 * We've just received USERAUTH_SUCCESS, and we haven't sent any
10678 * packets since. Signal the transport layer to consider enacting
10679 * delayed compression.
10681 * (Relying on we_are_in is not sufficient, as
10682 * draft-miller-secsh-compression-delayed is quite clear that it
10683 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
10684 * become set for other reasons.)
10686 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
10689 ssh->channels = newtree234(ssh_channelcmp);
10692 * Set up handlers for some connection protocol messages, so we
10693 * don't have to handle them repeatedly in this coroutine.
10695 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
10696 ssh2_msg_channel_window_adjust;
10697 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
10698 ssh2_msg_global_request;
10701 * Create the main session channel.
10703 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
10704 ssh->mainchan = NULL;
10706 ssh->mainchan = snew(struct ssh_channel);
10707 ssh->mainchan->ssh = ssh;
10708 ssh_channel_init(ssh->mainchan);
10710 if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
10712 * Just start a direct-tcpip channel and use it as the main
10715 ssh_send_port_open(ssh->mainchan,
10716 conf_get_str(ssh->conf, CONF_ssh_nc_host),
10717 conf_get_int(ssh->conf, CONF_ssh_nc_port),
10719 ssh->ncmode = TRUE;
10721 s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
10722 logevent("Opening session as main channel");
10723 ssh2_pkt_send(ssh, s->pktout);
10724 ssh->ncmode = FALSE;
10726 crWaitUntilV(pktin);
10727 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
10728 bombout(("Server refused to open channel"));
10730 /* FIXME: error data comes back in FAILURE packet */
10732 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
10733 bombout(("Server's channel confirmation cited wrong channel"));
10736 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
10737 ssh->mainchan->halfopen = FALSE;
10738 ssh->mainchan->type = CHAN_MAINSESSION;
10739 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
10740 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
10741 update_specials_menu(ssh->frontend);
10742 logevent("Opened main channel");
10746 * Now we have a channel, make dispatch table entries for
10747 * general channel-based messages.
10749 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
10750 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
10751 ssh2_msg_channel_data;
10752 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
10753 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
10754 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
10755 ssh2_msg_channel_open_confirmation;
10756 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
10757 ssh2_msg_channel_open_failure;
10758 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
10759 ssh2_msg_channel_request;
10760 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
10761 ssh2_msg_channel_open;
10762 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
10763 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
10766 * Now the connection protocol is properly up and running, with
10767 * all those dispatch table entries, so it's safe to let
10768 * downstreams start trying to open extra channels through us.
10770 if (ssh->connshare)
10771 share_activate(ssh->connshare, ssh->v_s);
10773 if (ssh->mainchan && ssh_is_simple(ssh)) {
10775 * This message indicates to the server that we promise
10776 * not to try to run any other channel in parallel with
10777 * this one, so it's safe for it to advertise a very large
10778 * window and leave the flow control to TCP.
10780 s->pktout = ssh2_chanreq_init(ssh->mainchan,
10781 "simple@putty.projects.tartarus.org",
10783 ssh2_pkt_send(ssh, s->pktout);
10787 * Enable port forwardings.
10789 ssh_setup_portfwd(ssh, ssh->conf);
10791 if (ssh->mainchan && !ssh->ncmode) {
10793 * Send the CHANNEL_REQUESTS for the main session channel.
10794 * Each one is handled by its own little asynchronous
10798 /* Potentially enable X11 forwarding. */
10799 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
10801 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
10803 if (!ssh->x11disp) {
10804 /* FIXME: return an error message from x11_setup_display */
10805 logevent("X11 forwarding not enabled: unable to"
10806 " initialise X display");
10808 ssh->x11auth = x11_invent_fake_auth
10809 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
10810 ssh->x11auth->disp = ssh->x11disp;
10812 ssh2_setup_x11(ssh->mainchan, NULL, NULL);
10816 /* Potentially enable agent forwarding. */
10817 if (ssh_agent_forwarding_permitted(ssh))
10818 ssh2_setup_agent(ssh->mainchan, NULL, NULL);
10820 /* Now allocate a pty for the session. */
10821 if (!conf_get_int(ssh->conf, CONF_nopty))
10822 ssh2_setup_pty(ssh->mainchan, NULL, NULL);
10824 /* Send environment variables. */
10825 ssh2_setup_env(ssh->mainchan, NULL, NULL);
10828 * Start a shell or a remote command. We may have to attempt
10829 * this twice if the config data has provided a second choice
10836 if (ssh->fallback_cmd) {
10837 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
10838 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
10840 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
10841 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
10845 s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
10846 ssh2_response_authconn, NULL);
10847 ssh2_pkt_addstring(s->pktout, cmd);
10849 s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
10850 ssh2_response_authconn, NULL);
10851 ssh2_pkt_addstring(s->pktout, cmd);
10853 s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
10854 ssh2_response_authconn, NULL);
10856 ssh2_pkt_send(ssh, s->pktout);
10858 crWaitUntilV(pktin);
10860 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
10861 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
10862 bombout(("Unexpected response to shell/command request:"
10863 " packet type %d", pktin->type));
10867 * We failed to start the command. If this is the
10868 * fallback command, we really are finished; if it's
10869 * not, and if the fallback command exists, try falling
10870 * back to it before complaining.
10872 if (!ssh->fallback_cmd &&
10873 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
10874 logevent("Primary command failed; attempting fallback");
10875 ssh->fallback_cmd = TRUE;
10878 bombout(("Server refused to start a shell/command"));
10881 logevent("Started a shell/command");
10886 ssh->editing = ssh->echoing = TRUE;
10889 ssh->state = SSH_STATE_SESSION;
10890 if (ssh->size_needed)
10891 ssh_size(ssh, ssh->term_width, ssh->term_height);
10892 if (ssh->eof_needed)
10893 ssh_special(ssh, TS_EOF);
10899 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
10907 * _All_ the connection-layer packets we expect to
10908 * receive are now handled by the dispatch table.
10909 * Anything that reaches here must be bogus.
10912 bombout(("Strange packet received: type %d", pktin->type));
10914 } else if (ssh->mainchan) {
10916 * We have spare data. Add it to the channel buffer.
10918 ssh_send_channel_data(ssh->mainchan, (char *)in, inlen);
10926 * Handlers for SSH-2 messages that might arrive at any moment.
10928 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
10930 /* log reason code in disconnect message */
10932 int reason, msglen;
10934 reason = ssh_pkt_getuint32(pktin);
10935 ssh_pkt_getstring(pktin, &msg, &msglen);
10937 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
10938 buf = dupprintf("Received disconnect message (%s)",
10939 ssh2_disconnect_reasons[reason]);
10941 buf = dupprintf("Received disconnect message (unknown"
10942 " type %d)", reason);
10946 buf = dupprintf("Disconnection message text: %.*s",
10947 msglen, NULLTOEMPTY(msg));
10949 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
10951 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
10952 ssh2_disconnect_reasons[reason] : "unknown",
10953 msglen, NULLTOEMPTY(msg)));
10957 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
10959 /* log the debug message */
10963 /* XXX maybe we should actually take notice of the return value */
10964 ssh2_pkt_getbool(pktin);
10965 ssh_pkt_getstring(pktin, &msg, &msglen);
10967 logeventf(ssh, "Remote debug message: %.*s", msglen, NULLTOEMPTY(msg));
10970 static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
10972 do_ssh2_transport(ssh, NULL, 0, pktin);
10976 * Called if we receive a packet that isn't allowed by the protocol.
10977 * This only applies to packets whose meaning PuTTY understands.
10978 * Entirely unknown packets are handled below.
10980 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
10982 char *buf = dupprintf("Server protocol violation: unexpected %s packet",
10983 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
10985 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
10989 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
10991 struct Packet *pktout;
10992 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
10993 ssh2_pkt_adduint32(pktout, pktin->sequence);
10995 * UNIMPLEMENTED messages MUST appear in the same order as the
10996 * messages they respond to. Hence, never queue them.
10998 ssh2_pkt_send_noqueue(ssh, pktout);
11002 * Handle the top-level SSH-2 protocol.
11004 static void ssh2_protocol_setup(Ssh ssh)
11009 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
11011 for (i = 0; i < 256; i++)
11012 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
11015 * Initially, we only accept transport messages (and a few generic
11016 * ones). do_ssh2_authconn will add more when it starts.
11017 * Messages that are understood but not currently acceptable go to
11018 * ssh2_msg_unexpected.
11020 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
11021 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
11022 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
11023 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
11024 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
11025 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
11026 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
11027 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
11028 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
11029 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
11030 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
11031 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
11032 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
11033 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
11034 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
11035 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
11036 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
11037 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
11038 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
11039 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
11040 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
11041 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
11042 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
11043 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
11044 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
11045 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
11046 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
11047 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
11048 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
11049 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
11050 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
11051 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
11052 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
11055 * These messages have a special handler from the start.
11057 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
11058 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
11059 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
11062 static void ssh2_bare_connection_protocol_setup(Ssh ssh)
11067 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
11069 for (i = 0; i < 256; i++)
11070 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
11073 * Initially, we set all ssh-connection messages to 'unexpected';
11074 * do_ssh2_authconn will fill things in properly. We also handle a
11075 * couple of messages from the transport protocol which aren't
11076 * related to key exchange (UNIMPLEMENTED, IGNORE, DEBUG,
11079 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
11080 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
11081 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
11082 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
11083 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
11084 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
11085 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
11086 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
11087 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
11088 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
11089 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
11090 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
11091 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
11092 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
11094 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
11097 * These messages have a special handler from the start.
11099 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
11100 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore;
11101 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
11104 static void ssh2_timer(void *ctx, unsigned long now)
11106 Ssh ssh = (Ssh)ctx;
11108 if (ssh->state == SSH_STATE_CLOSED)
11111 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11112 conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
11113 now == ssh->next_rekey) {
11114 do_ssh2_transport(ssh, "timeout", -1, NULL);
11118 static void ssh2_protocol(Ssh ssh, const void *vin, int inlen,
11119 struct Packet *pktin)
11121 const unsigned char *in = (const unsigned char *)vin;
11122 if (ssh->state == SSH_STATE_CLOSED)
11126 ssh->incoming_data_size += pktin->encrypted_len;
11127 if (!ssh->kex_in_progress &&
11128 ssh->max_data_size != 0 &&
11129 ssh->incoming_data_size > ssh->max_data_size)
11130 do_ssh2_transport(ssh, "too much data received", -1, NULL);
11134 ssh->packet_dispatch[pktin->type](ssh, pktin);
11135 else if (!ssh->protocol_initial_phase_done)
11136 do_ssh2_transport(ssh, in, inlen, pktin);
11138 do_ssh2_authconn(ssh, in, inlen, pktin);
11141 static void ssh2_bare_connection_protocol(Ssh ssh, const void *vin, int inlen,
11142 struct Packet *pktin)
11144 const unsigned char *in = (const unsigned char *)vin;
11145 if (ssh->state == SSH_STATE_CLOSED)
11149 ssh->packet_dispatch[pktin->type](ssh, pktin);
11151 do_ssh2_authconn(ssh, in, inlen, pktin);
11154 static void ssh_cache_conf_values(Ssh ssh)
11156 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
11160 * Called to set up the connection.
11162 * Returns an error message, or NULL on success.
11164 static const char *ssh_init(void *frontend_handle, void **backend_handle,
11166 const char *host, int port, char **realhost,
11167 int nodelay, int keepalive)
11172 ssh = snew(struct ssh_tag);
11173 ssh->conf = conf_copy(conf);
11174 ssh_cache_conf_values(ssh);
11175 ssh->version = 0; /* when not ready yet */
11177 ssh->cipher = NULL;
11178 ssh->v1_cipher_ctx = NULL;
11179 ssh->crcda_ctx = NULL;
11180 ssh->cscipher = NULL;
11181 ssh->cs_cipher_ctx = NULL;
11182 ssh->sccipher = NULL;
11183 ssh->sc_cipher_ctx = NULL;
11185 ssh->cs_mac_ctx = NULL;
11187 ssh->sc_mac_ctx = NULL;
11188 ssh->cscomp = NULL;
11189 ssh->cs_comp_ctx = NULL;
11190 ssh->sccomp = NULL;
11191 ssh->sc_comp_ctx = NULL;
11193 ssh->kex_ctx = NULL;
11194 ssh->hostkey = NULL;
11195 ssh->hostkey_str = NULL;
11196 ssh->exitcode = -1;
11197 ssh->close_expected = FALSE;
11198 ssh->clean_exit = FALSE;
11199 ssh->state = SSH_STATE_PREPACKET;
11200 ssh->size_needed = FALSE;
11201 ssh->eof_needed = FALSE;
11203 ssh->logctx = NULL;
11204 ssh->deferred_send_data = NULL;
11205 ssh->deferred_len = 0;
11206 ssh->deferred_size = 0;
11207 ssh->fallback_cmd = 0;
11208 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
11209 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
11210 ssh->x11disp = NULL;
11211 ssh->x11auth = NULL;
11212 ssh->x11authtree = newtree234(x11_authcmp);
11213 ssh->v1_compressing = FALSE;
11214 ssh->v2_outgoing_sequence = 0;
11215 ssh->ssh1_rdpkt_crstate = 0;
11216 ssh->ssh2_rdpkt_crstate = 0;
11217 ssh->ssh2_bare_rdpkt_crstate = 0;
11218 ssh->ssh_gotdata_crstate = 0;
11219 ssh->do_ssh1_connection_crstate = 0;
11220 ssh->do_ssh_init_state = NULL;
11221 ssh->do_ssh_connection_init_state = NULL;
11222 ssh->do_ssh1_login_state = NULL;
11223 ssh->do_ssh2_transport_state = NULL;
11224 ssh->do_ssh2_authconn_state = NULL;
11227 ssh->mainchan = NULL;
11228 ssh->throttled_all = 0;
11229 ssh->v1_stdout_throttling = 0;
11231 ssh->queuelen = ssh->queuesize = 0;
11232 ssh->queueing = FALSE;
11233 ssh->qhead = ssh->qtail = NULL;
11234 ssh->deferred_rekey_reason = NULL;
11235 bufchain_init(&ssh->queued_incoming_data);
11236 ssh->frozen = FALSE;
11237 ssh->username = NULL;
11238 ssh->sent_console_eof = FALSE;
11239 ssh->got_pty = FALSE;
11240 ssh->bare_connection = FALSE;
11241 ssh->X11_fwd_enabled = FALSE;
11242 ssh->connshare = NULL;
11243 ssh->attempting_connshare = FALSE;
11244 ssh->session_started = FALSE;
11245 ssh->specials = NULL;
11246 ssh->n_uncert_hostkeys = 0;
11247 ssh->cross_certifying = FALSE;
11249 *backend_handle = ssh;
11252 if (crypto_startup() == 0)
11253 return "Microsoft high encryption pack not installed!";
11256 ssh->frontend = frontend_handle;
11257 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
11258 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
11260 ssh->channels = NULL;
11261 ssh->rportfwds = NULL;
11262 ssh->portfwds = NULL;
11267 ssh->conn_throttle_count = 0;
11268 ssh->overall_bufsize = 0;
11269 ssh->fallback_cmd = 0;
11271 ssh->protocol = NULL;
11273 ssh->protocol_initial_phase_done = FALSE;
11275 ssh->pinger = NULL;
11277 ssh->incoming_data_size = ssh->outgoing_data_size =
11278 ssh->deferred_data_size = 0L;
11279 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11280 CONF_ssh_rekey_data));
11281 ssh->kex_in_progress = FALSE;
11283 ssh->auth_agent_query = NULL;
11286 ssh->gsslibs = NULL;
11289 random_ref(); /* do this now - may be needed by sharing setup code */
11291 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
11300 static void ssh_free(void *handle)
11302 Ssh ssh = (Ssh) handle;
11303 struct ssh_channel *c;
11304 struct ssh_rportfwd *pf;
11305 struct X11FakeAuth *auth;
11307 if (ssh->v1_cipher_ctx)
11308 ssh->cipher->free_context(ssh->v1_cipher_ctx);
11309 if (ssh->cs_cipher_ctx)
11310 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
11311 if (ssh->sc_cipher_ctx)
11312 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
11313 if (ssh->cs_mac_ctx)
11314 ssh->csmac->free_context(ssh->cs_mac_ctx);
11315 if (ssh->sc_mac_ctx)
11316 ssh->scmac->free_context(ssh->sc_mac_ctx);
11317 if (ssh->cs_comp_ctx) {
11319 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
11321 zlib_compress_cleanup(ssh->cs_comp_ctx);
11323 if (ssh->sc_comp_ctx) {
11325 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
11327 zlib_decompress_cleanup(ssh->sc_comp_ctx);
11330 dh_cleanup(ssh->kex_ctx);
11331 sfree(ssh->savedhost);
11333 while (ssh->queuelen-- > 0)
11334 ssh_free_packet(ssh->queue[ssh->queuelen]);
11337 while (ssh->qhead) {
11338 struct queued_handler *qh = ssh->qhead;
11339 ssh->qhead = qh->next;
11342 ssh->qhead = ssh->qtail = NULL;
11344 if (ssh->channels) {
11345 while ((c = delpos234(ssh->channels, 0)) != NULL) {
11346 ssh_channel_close_local(c, NULL);
11347 if (ssh->version == 2) {
11348 struct outstanding_channel_request *ocr, *nocr;
11349 ocr = c->v.v2.chanreq_head;
11351 ocr->handler(c, NULL, ocr->ctx);
11356 bufchain_clear(&c->v.v2.outbuffer);
11360 freetree234(ssh->channels);
11361 ssh->channels = NULL;
11364 if (ssh->connshare)
11365 sharestate_free(ssh->connshare);
11367 if (ssh->rportfwds) {
11368 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
11370 freetree234(ssh->rportfwds);
11371 ssh->rportfwds = NULL;
11373 sfree(ssh->deferred_send_data);
11375 x11_free_display(ssh->x11disp);
11376 while ((auth = delpos234(ssh->x11authtree, 0)) != NULL)
11377 x11_free_fake_auth(auth);
11378 freetree234(ssh->x11authtree);
11379 sfree(ssh->do_ssh_init_state);
11380 sfree(ssh->do_ssh1_login_state);
11381 sfree(ssh->do_ssh2_transport_state);
11382 sfree(ssh->do_ssh2_authconn_state);
11385 sfree(ssh->fullhostname);
11386 sfree(ssh->hostkey_str);
11387 sfree(ssh->specials);
11388 if (ssh->crcda_ctx) {
11389 crcda_free_context(ssh->crcda_ctx);
11390 ssh->crcda_ctx = NULL;
11393 ssh_do_close(ssh, TRUE);
11394 expire_timer_context(ssh);
11396 pinger_free(ssh->pinger);
11397 bufchain_clear(&ssh->queued_incoming_data);
11398 sfree(ssh->username);
11399 conf_free(ssh->conf);
11401 if (ssh->auth_agent_query)
11402 agent_cancel_query(ssh->auth_agent_query);
11406 ssh_gss_cleanup(ssh->gsslibs);
11414 * Reconfigure the SSH backend.
11416 static void ssh_reconfig(void *handle, Conf *conf)
11418 Ssh ssh = (Ssh) handle;
11419 const char *rekeying = NULL;
11420 int rekey_mandatory = FALSE;
11421 unsigned long old_max_data_size;
11424 pinger_reconfig(ssh->pinger, ssh->conf, conf);
11426 ssh_setup_portfwd(ssh, conf);
11428 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
11429 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
11431 unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
11432 unsigned long now = GETTICKCOUNT();
11434 if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
11435 rekeying = "timeout shortened";
11437 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
11441 old_max_data_size = ssh->max_data_size;
11442 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11443 CONF_ssh_rekey_data));
11444 if (old_max_data_size != ssh->max_data_size &&
11445 ssh->max_data_size != 0) {
11446 if (ssh->outgoing_data_size > ssh->max_data_size ||
11447 ssh->incoming_data_size > ssh->max_data_size)
11448 rekeying = "data limit lowered";
11451 if (conf_get_int(ssh->conf, CONF_compression) !=
11452 conf_get_int(conf, CONF_compression)) {
11453 rekeying = "compression setting changed";
11454 rekey_mandatory = TRUE;
11457 for (i = 0; i < CIPHER_MAX; i++)
11458 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
11459 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
11460 rekeying = "cipher settings changed";
11461 rekey_mandatory = TRUE;
11463 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
11464 conf_get_int(conf, CONF_ssh2_des_cbc)) {
11465 rekeying = "cipher settings changed";
11466 rekey_mandatory = TRUE;
11469 conf_free(ssh->conf);
11470 ssh->conf = conf_copy(conf);
11471 ssh_cache_conf_values(ssh);
11473 if (!ssh->bare_connection && rekeying) {
11474 if (!ssh->kex_in_progress) {
11475 do_ssh2_transport(ssh, rekeying, -1, NULL);
11476 } else if (rekey_mandatory) {
11477 ssh->deferred_rekey_reason = rekeying;
11483 * Called to send data down the SSH connection.
11485 static int ssh_send(void *handle, const char *buf, int len)
11487 Ssh ssh = (Ssh) handle;
11489 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11492 ssh->protocol(ssh, (const unsigned char *)buf, len, 0);
11494 return ssh_sendbuffer(ssh);
11498 * Called to query the current amount of buffered stdin data.
11500 static int ssh_sendbuffer(void *handle)
11502 Ssh ssh = (Ssh) handle;
11503 int override_value;
11505 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11509 * If the SSH socket itself has backed up, add the total backup
11510 * size on that to any individual buffer on the stdin channel.
11512 override_value = 0;
11513 if (ssh->throttled_all)
11514 override_value = ssh->overall_bufsize;
11516 if (ssh->version == 1) {
11517 return override_value;
11518 } else if (ssh->version == 2) {
11519 if (!ssh->mainchan)
11520 return override_value;
11522 return (override_value +
11523 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
11530 * Called to set the size of the window from SSH's POV.
11532 static void ssh_size(void *handle, int width, int height)
11534 Ssh ssh = (Ssh) handle;
11535 struct Packet *pktout;
11537 ssh->term_width = width;
11538 ssh->term_height = height;
11540 switch (ssh->state) {
11541 case SSH_STATE_BEFORE_SIZE:
11542 case SSH_STATE_PREPACKET:
11543 case SSH_STATE_CLOSED:
11544 break; /* do nothing */
11545 case SSH_STATE_INTERMED:
11546 ssh->size_needed = TRUE; /* buffer for later */
11548 case SSH_STATE_SESSION:
11549 if (!conf_get_int(ssh->conf, CONF_nopty)) {
11550 if (ssh->version == 1) {
11551 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
11552 PKT_INT, ssh->term_height,
11553 PKT_INT, ssh->term_width,
11554 PKT_INT, 0, PKT_INT, 0, PKT_END);
11555 } else if (ssh->mainchan) {
11556 pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
11558 ssh2_pkt_adduint32(pktout, ssh->term_width);
11559 ssh2_pkt_adduint32(pktout, ssh->term_height);
11560 ssh2_pkt_adduint32(pktout, 0);
11561 ssh2_pkt_adduint32(pktout, 0);
11562 ssh2_pkt_send(ssh, pktout);
11570 * Return a list of the special codes that make sense in this
11573 static const struct telnet_special *ssh_get_specials(void *handle)
11575 static const struct telnet_special ssh1_ignore_special[] = {
11576 {"IGNORE message", TS_NOP}
11578 static const struct telnet_special ssh2_ignore_special[] = {
11579 {"IGNORE message", TS_NOP},
11581 static const struct telnet_special ssh2_rekey_special[] = {
11582 {"Repeat key exchange", TS_REKEY},
11584 static const struct telnet_special ssh2_session_specials[] = {
11587 /* These are the signal names defined by RFC 4254.
11588 * They include all the ISO C signals, but are a subset of the POSIX
11589 * required signals. */
11590 {"SIGINT (Interrupt)", TS_SIGINT},
11591 {"SIGTERM (Terminate)", TS_SIGTERM},
11592 {"SIGKILL (Kill)", TS_SIGKILL},
11593 {"SIGQUIT (Quit)", TS_SIGQUIT},
11594 {"SIGHUP (Hangup)", TS_SIGHUP},
11595 {"More signals", TS_SUBMENU},
11596 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
11597 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
11598 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
11599 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
11600 {NULL, TS_EXITMENU}
11602 static const struct telnet_special specials_end[] = {
11603 {NULL, TS_EXITMENU}
11606 struct telnet_special *specials = NULL;
11607 int nspecials = 0, specialsize = 0;
11609 Ssh ssh = (Ssh) handle;
11611 sfree(ssh->specials);
11613 #define ADD_SPECIALS(name) do \
11615 int len = lenof(name); \
11616 if (nspecials + len > specialsize) { \
11617 specialsize = (nspecials + len) * 5 / 4 + 32; \
11618 specials = sresize(specials, specialsize, struct telnet_special); \
11620 memcpy(specials+nspecials, name, len*sizeof(struct telnet_special)); \
11621 nspecials += len; \
11624 if (ssh->version == 1) {
11625 /* Don't bother offering IGNORE if we've decided the remote
11626 * won't cope with it, since we wouldn't bother sending it if
11628 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11629 ADD_SPECIALS(ssh1_ignore_special);
11630 } else if (ssh->version == 2) {
11631 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
11632 ADD_SPECIALS(ssh2_ignore_special);
11633 if (!(ssh->remote_bugs & BUG_SSH2_REKEY) && !ssh->bare_connection)
11634 ADD_SPECIALS(ssh2_rekey_special);
11636 ADD_SPECIALS(ssh2_session_specials);
11638 if (ssh->n_uncert_hostkeys) {
11639 static const struct telnet_special uncert_start[] = {
11641 {"Cache new host key type", TS_SUBMENU},
11643 static const struct telnet_special uncert_end[] = {
11644 {NULL, TS_EXITMENU},
11648 ADD_SPECIALS(uncert_start);
11649 for (i = 0; i < ssh->n_uncert_hostkeys; i++) {
11650 struct telnet_special uncert[1];
11651 const struct ssh_signkey *alg =
11652 hostkey_algs[ssh->uncert_hostkeys[i]].alg;
11653 uncert[0].name = alg->name;
11654 uncert[0].code = TS_LOCALSTART + ssh->uncert_hostkeys[i];
11655 ADD_SPECIALS(uncert);
11657 ADD_SPECIALS(uncert_end);
11659 } /* else we're not ready yet */
11662 ADD_SPECIALS(specials_end);
11664 ssh->specials = specials;
11671 #undef ADD_SPECIALS
11675 * Send special codes. TS_EOF is useful for `plink', so you
11676 * can send an EOF and collect resulting output (e.g. `plink
11679 static void ssh_special(void *handle, Telnet_Special code)
11681 Ssh ssh = (Ssh) handle;
11682 struct Packet *pktout;
11684 if (code == TS_EOF) {
11685 if (ssh->state != SSH_STATE_SESSION) {
11687 * Buffer the EOF in case we are pre-SESSION, so we can
11688 * send it as soon as we reach SESSION.
11690 if (code == TS_EOF)
11691 ssh->eof_needed = TRUE;
11694 if (ssh->version == 1) {
11695 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
11696 } else if (ssh->mainchan) {
11697 sshfwd_write_eof(ssh->mainchan);
11698 ssh->send_ok = 0; /* now stop trying to read from stdin */
11700 logevent("Sent EOF message");
11701 } else if (code == TS_PING || code == TS_NOP) {
11702 if (ssh->state == SSH_STATE_CLOSED
11703 || ssh->state == SSH_STATE_PREPACKET) return;
11704 if (ssh->version == 1) {
11705 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11706 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
11708 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
11709 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
11710 ssh2_pkt_addstring_start(pktout);
11711 ssh2_pkt_send_noqueue(ssh, pktout);
11714 } else if (code == TS_REKEY) {
11715 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11716 ssh->version == 2) {
11717 do_ssh2_transport(ssh, "at user request", -1, NULL);
11719 } else if (code >= TS_LOCALSTART) {
11720 ssh->hostkey = hostkey_algs[code - TS_LOCALSTART].alg;
11721 ssh->cross_certifying = TRUE;
11722 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11723 ssh->version == 2) {
11724 do_ssh2_transport(ssh, "cross-certifying new host key", -1, NULL);
11726 } else if (code == TS_BRK) {
11727 if (ssh->state == SSH_STATE_CLOSED
11728 || ssh->state == SSH_STATE_PREPACKET) return;
11729 if (ssh->version == 1) {
11730 logevent("Unable to send BREAK signal in SSH-1");
11731 } else if (ssh->mainchan) {
11732 pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
11733 ssh2_pkt_adduint32(pktout, 0); /* default break length */
11734 ssh2_pkt_send(ssh, pktout);
11737 /* Is is a POSIX signal? */
11738 const char *signame = NULL;
11739 if (code == TS_SIGABRT) signame = "ABRT";
11740 if (code == TS_SIGALRM) signame = "ALRM";
11741 if (code == TS_SIGFPE) signame = "FPE";
11742 if (code == TS_SIGHUP) signame = "HUP";
11743 if (code == TS_SIGILL) signame = "ILL";
11744 if (code == TS_SIGINT) signame = "INT";
11745 if (code == TS_SIGKILL) signame = "KILL";
11746 if (code == TS_SIGPIPE) signame = "PIPE";
11747 if (code == TS_SIGQUIT) signame = "QUIT";
11748 if (code == TS_SIGSEGV) signame = "SEGV";
11749 if (code == TS_SIGTERM) signame = "TERM";
11750 if (code == TS_SIGUSR1) signame = "USR1";
11751 if (code == TS_SIGUSR2) signame = "USR2";
11752 /* The SSH-2 protocol does in principle support arbitrary named
11753 * signals, including signame@domain, but we don't support those. */
11755 /* It's a signal. */
11756 if (ssh->version == 2 && ssh->mainchan) {
11757 pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
11758 ssh2_pkt_addstring(pktout, signame);
11759 ssh2_pkt_send(ssh, pktout);
11760 logeventf(ssh, "Sent signal SIG%s", signame);
11763 /* Never heard of it. Do nothing */
11768 void *new_sock_channel(void *handle, struct PortForwarding *pf)
11770 Ssh ssh = (Ssh) handle;
11771 struct ssh_channel *c;
11772 c = snew(struct ssh_channel);
11775 ssh_channel_init(c);
11776 c->halfopen = TRUE;
11777 c->type = CHAN_SOCKDATA;/* identify channel type */
11782 unsigned ssh_alloc_sharing_channel(Ssh ssh, void *sharing_ctx)
11784 struct ssh_channel *c;
11785 c = snew(struct ssh_channel);
11788 ssh_channel_init(c);
11789 c->type = CHAN_SHARING;
11790 c->u.sharing.ctx = sharing_ctx;
11794 void ssh_delete_sharing_channel(Ssh ssh, unsigned localid)
11796 struct ssh_channel *c;
11798 c = find234(ssh->channels, &localid, ssh_channelfind);
11800 ssh_channel_destroy(c);
11803 void ssh_send_packet_from_downstream(Ssh ssh, unsigned id, int type,
11804 const void *data, int datalen,
11805 const char *additional_log_text)
11807 struct Packet *pkt;
11809 pkt = ssh2_pkt_init(type);
11810 pkt->downstream_id = id;
11811 pkt->additional_log_text = additional_log_text;
11812 ssh2_pkt_adddata(pkt, data, datalen);
11813 ssh2_pkt_send(ssh, pkt);
11817 * This is called when stdout/stderr (the entity to which
11818 * from_backend sends data) manages to clear some backlog.
11820 static void ssh_unthrottle(void *handle, int bufsize)
11822 Ssh ssh = (Ssh) handle;
11824 if (ssh->version == 1) {
11825 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
11826 ssh->v1_stdout_throttling = 0;
11827 ssh_throttle_conn(ssh, -1);
11831 ssh_channel_unthrottle(ssh->mainchan, bufsize);
11835 * Now process any SSH connection data that was stashed in our
11836 * queue while we were frozen.
11838 ssh_process_queued_incoming_data(ssh);
11841 void ssh_send_port_open(void *channel, const char *hostname, int port,
11844 struct ssh_channel *c = (struct ssh_channel *)channel;
11846 struct Packet *pktout;
11848 logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
11850 if (ssh->version == 1) {
11851 send_packet(ssh, SSH1_MSG_PORT_OPEN,
11852 PKT_INT, c->localid,
11855 /* PKT_STR, <org:orgport>, */
11858 pktout = ssh2_chanopen_init(c, "direct-tcpip");
11860 char *trimmed_host = host_strduptrim(hostname);
11861 ssh2_pkt_addstring(pktout, trimmed_host);
11862 sfree(trimmed_host);
11864 ssh2_pkt_adduint32(pktout, port);
11866 * We make up values for the originator data; partly it's
11867 * too much hassle to keep track, and partly I'm not
11868 * convinced the server should be told details like that
11869 * about my local network configuration.
11870 * The "originator IP address" is syntactically a numeric
11871 * IP address, and some servers (e.g., Tectia) get upset
11872 * if it doesn't match this syntax.
11874 ssh2_pkt_addstring(pktout, "0.0.0.0");
11875 ssh2_pkt_adduint32(pktout, 0);
11876 ssh2_pkt_send(ssh, pktout);
11880 static int ssh_connected(void *handle)
11882 Ssh ssh = (Ssh) handle;
11883 return ssh->s != NULL;
11886 static int ssh_sendok(void *handle)
11888 Ssh ssh = (Ssh) handle;
11889 return ssh->send_ok;
11892 static int ssh_ldisc(void *handle, int option)
11894 Ssh ssh = (Ssh) handle;
11895 if (option == LD_ECHO)
11896 return ssh->echoing;
11897 if (option == LD_EDIT)
11898 return ssh->editing;
11902 static void ssh_provide_ldisc(void *handle, void *ldisc)
11904 Ssh ssh = (Ssh) handle;
11905 ssh->ldisc = ldisc;
11908 static void ssh_provide_logctx(void *handle, void *logctx)
11910 Ssh ssh = (Ssh) handle;
11911 ssh->logctx = logctx;
11914 static int ssh_return_exitcode(void *handle)
11916 Ssh ssh = (Ssh) handle;
11917 if (ssh->s != NULL)
11920 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
11924 * cfg_info for SSH is the protocol running in this session.
11925 * (1 or 2 for the full SSH-1 or SSH-2 protocol; -1 for the bare
11926 * SSH-2 connection protocol, i.e. a downstream; 0 for not-decided-yet.)
11928 static int ssh_cfg_info(void *handle)
11930 Ssh ssh = (Ssh) handle;
11931 if (ssh->version == 0)
11932 return 0; /* don't know yet */
11933 else if (ssh->bare_connection)
11936 return ssh->version;
11940 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
11941 * that fails. This variable is the means by which scp.c can reach
11942 * into the SSH code and find out which one it got.
11944 extern int ssh_fallback_cmd(void *handle)
11946 Ssh ssh = (Ssh) handle;
11947 return ssh->fallback_cmd;
11950 Backend ssh_backend = {
11960 ssh_return_exitcode,
11964 ssh_provide_logctx,
11967 ssh_test_for_upstream,