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);
3961 * If we get here (i.e. we left the above while loop via 'break'
3962 * rather than 'return'), that means we've determined that the
3963 * input buffer for the agent forwarding connection doesn't
3964 * contain a complete request.
3966 * So if there's potentially more data to come, we can return now,
3967 * and wait for the remote client to send it. But if the remote
3968 * has sent EOF, it would be a mistake to do that, because we'd be
3969 * waiting a long time. So this is the moment to check for EOF,
3970 * and respond appropriately.
3972 if (c->closes & CLOSES_RCVD_EOF)
3973 sshfwd_write_eof(c);
3976 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3978 struct ssh_channel *c = (struct ssh_channel *)cv;
3980 ssh_agentf_got_response(c, reply, replylen);
3984 * Now try to extract and send further messages from the channel's
3985 * input-side buffer.
3987 ssh_agentf_try_forward(c);
3991 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3992 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3993 * => log `wire_reason'.
3995 static void ssh_disconnect(Ssh ssh, const char *client_reason,
3996 const char *wire_reason,
3997 int code, int clean_exit)
4001 client_reason = wire_reason;
4003 error = dupprintf("Disconnected: %s", client_reason);
4005 error = dupstr("Disconnected");
4007 if (ssh->version == 1) {
4008 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
4010 } else if (ssh->version == 2) {
4011 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
4012 ssh2_pkt_adduint32(pktout, code);
4013 ssh2_pkt_addstring(pktout, wire_reason);
4014 ssh2_pkt_addstring(pktout, "en"); /* language tag */
4015 ssh2_pkt_send_noqueue(ssh, pktout);
4018 ssh->close_expected = TRUE;
4019 ssh->clean_exit = clean_exit;
4020 ssh_closing((Plug)ssh, error, 0, 0);
4024 int verify_ssh_manual_host_key(Ssh ssh, const char *fingerprint,
4025 const struct ssh_signkey *ssh2keytype,
4028 if (!conf_get_str_nthstrkey(ssh->conf, CONF_ssh_manual_hostkeys, 0)) {
4029 return -1; /* no manual keys configured */
4034 * The fingerprint string we've been given will have things
4035 * like 'ssh-rsa 2048' at the front of it. Strip those off and
4036 * narrow down to just the colon-separated hex block at the
4037 * end of the string.
4039 const char *p = strrchr(fingerprint, ' ');
4040 fingerprint = p ? p+1 : fingerprint;
4041 /* Quick sanity checks, including making sure it's in lowercase */
4042 assert(strlen(fingerprint) == 16*3 - 1);
4043 assert(fingerprint[2] == ':');
4044 assert(fingerprint[strspn(fingerprint, "0123456789abcdef:")] == 0);
4046 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
4048 return 1; /* success */
4053 * Construct the base64-encoded public key blob and see if
4056 unsigned char *binblob;
4058 int binlen, atoms, i;
4059 binblob = ssh2keytype->public_blob(ssh2keydata, &binlen);
4060 atoms = (binlen + 2) / 3;
4061 base64blob = snewn(atoms * 4 + 1, char);
4062 for (i = 0; i < atoms; i++)
4063 base64_encode_atom(binblob + 3*i, binlen - 3*i, base64blob + 4*i);
4064 base64blob[atoms * 4] = '\0';
4066 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
4069 return 1; /* success */
4078 * Handle the key exchange and user authentication phases.
4080 static int do_ssh1_login(Ssh ssh, const unsigned char *in, int inlen,
4081 struct Packet *pktin)
4084 unsigned char cookie[8], *ptr;
4085 struct MD5Context md5c;
4086 struct do_ssh1_login_state {
4089 unsigned char *rsabuf;
4090 const unsigned char *keystr1, *keystr2;
4091 unsigned long supported_ciphers_mask, supported_auths_mask;
4092 int tried_publickey, tried_agent;
4093 int tis_auth_refused, ccard_auth_refused;
4094 unsigned char session_id[16];
4096 void *publickey_blob;
4097 int publickey_bloblen;
4098 char *publickey_comment;
4099 int privatekey_available, privatekey_encrypted;
4100 prompts_t *cur_prompt;
4103 unsigned char request[5], *response, *p;
4113 struct RSAKey servkey, hostkey;
4115 crState(do_ssh1_login_state);
4122 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
4123 bombout(("Public key packet not received"));
4127 logevent("Received public keys");
4129 ptr = ssh_pkt_getdata(pktin, 8);
4131 bombout(("SSH-1 public key packet stopped before random cookie"));
4134 memcpy(cookie, ptr, 8);
4136 if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
4137 !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) {
4138 bombout(("Failed to read SSH-1 public keys from public key packet"));
4143 * Log the host key fingerprint.
4147 logevent("Host key fingerprint is:");
4148 strcpy(logmsg, " ");
4149 s->hostkey.comment = NULL;
4150 rsa_fingerprint(logmsg + strlen(logmsg),
4151 sizeof(logmsg) - strlen(logmsg), &s->hostkey);
4155 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
4156 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
4157 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
4158 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
4159 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
4161 ssh->v1_local_protoflags =
4162 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
4163 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
4166 MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
4167 MD5Update(&md5c, s->keystr1, s->servkey.bytes);
4168 MD5Update(&md5c, cookie, 8);
4169 MD5Final(s->session_id, &md5c);
4171 for (i = 0; i < 32; i++)
4172 ssh->session_key[i] = random_byte();
4175 * Verify that the `bits' and `bytes' parameters match.
4177 if (s->hostkey.bits > s->hostkey.bytes * 8 ||
4178 s->servkey.bits > s->servkey.bytes * 8) {
4179 bombout(("SSH-1 public keys were badly formatted"));
4183 s->len = (s->hostkey.bytes > s->servkey.bytes ?
4184 s->hostkey.bytes : s->servkey.bytes);
4186 s->rsabuf = snewn(s->len, unsigned char);
4189 * Verify the host key.
4193 * First format the key into a string.
4195 int len = rsastr_len(&s->hostkey);
4196 char fingerprint[100];
4197 char *keystr = snewn(len, char);
4198 rsastr_fmt(keystr, &s->hostkey);
4199 rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
4201 /* First check against manually configured host keys. */
4202 s->dlgret = verify_ssh_manual_host_key(ssh, fingerprint, NULL, NULL);
4203 if (s->dlgret == 0) { /* did not match */
4204 bombout(("Host key did not appear in manually configured list"));
4207 } else if (s->dlgret < 0) { /* none configured; use standard handling */
4208 ssh_set_frozen(ssh, 1);
4209 s->dlgret = verify_ssh_host_key(ssh->frontend,
4210 ssh->savedhost, ssh->savedport,
4211 "rsa", keystr, fingerprint,
4212 ssh_dialog_callback, ssh);
4217 if (s->dlgret < 0) {
4221 bombout(("Unexpected data from server while waiting"
4222 " for user host key response"));
4225 } while (pktin || inlen > 0);
4226 s->dlgret = ssh->user_response;
4228 ssh_set_frozen(ssh, 0);
4230 if (s->dlgret == 0) {
4231 ssh_disconnect(ssh, "User aborted at host key verification",
4240 for (i = 0; i < 32; i++) {
4241 s->rsabuf[i] = ssh->session_key[i];
4243 s->rsabuf[i] ^= s->session_id[i];
4246 if (s->hostkey.bytes > s->servkey.bytes) {
4247 ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
4249 ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
4251 ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
4253 ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
4256 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
4260 logevent("Encrypted session key");
4263 int cipher_chosen = 0, warn = 0;
4264 const char *cipher_string = NULL;
4266 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
4267 int next_cipher = conf_get_int_int(ssh->conf,
4268 CONF_ssh_cipherlist, i);
4269 if (next_cipher == CIPHER_WARN) {
4270 /* If/when we choose a cipher, warn about it */
4272 } else if (next_cipher == CIPHER_AES) {
4273 /* XXX Probably don't need to mention this. */
4274 logevent("AES not supported in SSH-1, skipping");
4276 switch (next_cipher) {
4277 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
4278 cipher_string = "3DES"; break;
4279 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
4280 cipher_string = "Blowfish"; break;
4281 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
4282 cipher_string = "single-DES"; break;
4284 if (s->supported_ciphers_mask & (1 << s->cipher_type))
4288 if (!cipher_chosen) {
4289 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
4290 bombout(("Server violates SSH-1 protocol by not "
4291 "supporting 3DES encryption"));
4293 /* shouldn't happen */
4294 bombout(("No supported ciphers found"));
4298 /* Warn about chosen cipher if necessary. */
4300 ssh_set_frozen(ssh, 1);
4301 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
4302 ssh_dialog_callback, ssh);
4303 if (s->dlgret < 0) {
4307 bombout(("Unexpected data from server while waiting"
4308 " for user response"));
4311 } while (pktin || inlen > 0);
4312 s->dlgret = ssh->user_response;
4314 ssh_set_frozen(ssh, 0);
4315 if (s->dlgret == 0) {
4316 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
4323 switch (s->cipher_type) {
4324 case SSH_CIPHER_3DES:
4325 logevent("Using 3DES encryption");
4327 case SSH_CIPHER_DES:
4328 logevent("Using single-DES encryption");
4330 case SSH_CIPHER_BLOWFISH:
4331 logevent("Using Blowfish encryption");
4335 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
4336 PKT_CHAR, s->cipher_type,
4337 PKT_DATA, cookie, 8,
4338 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
4339 PKT_DATA, s->rsabuf, s->len,
4340 PKT_INT, ssh->v1_local_protoflags, PKT_END);
4342 logevent("Trying to enable encryption...");
4346 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
4347 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
4349 ssh->v1_cipher_ctx = ssh->cipher->make_context();
4350 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
4351 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
4353 ssh->crcda_ctx = crcda_make_context();
4354 logevent("Installing CRC compensation attack detector");
4356 if (s->servkey.modulus) {
4357 sfree(s->servkey.modulus);
4358 s->servkey.modulus = NULL;
4360 if (s->servkey.exponent) {
4361 sfree(s->servkey.exponent);
4362 s->servkey.exponent = NULL;
4364 if (s->hostkey.modulus) {
4365 sfree(s->hostkey.modulus);
4366 s->hostkey.modulus = NULL;
4368 if (s->hostkey.exponent) {
4369 sfree(s->hostkey.exponent);
4370 s->hostkey.exponent = NULL;
4374 if (pktin->type != SSH1_SMSG_SUCCESS) {
4375 bombout(("Encryption not successfully enabled"));
4379 logevent("Successfully started encryption");
4381 fflush(stdout); /* FIXME eh? */
4383 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
4384 int ret; /* need not be kept over crReturn */
4385 s->cur_prompt = new_prompts(ssh->frontend);
4386 s->cur_prompt->to_server = TRUE;
4387 s->cur_prompt->name = dupstr("SSH login name");
4388 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
4389 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4392 crWaitUntil(!pktin);
4393 ret = get_userpass_input(s->cur_prompt, in, inlen);
4398 * Failed to get a username. Terminate.
4400 free_prompts(s->cur_prompt);
4401 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
4404 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
4405 free_prompts(s->cur_prompt);
4408 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
4410 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
4412 if (flags & FLAG_INTERACTIVE &&
4413 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
4414 c_write_str(ssh, userlog);
4415 c_write_str(ssh, "\r\n");
4423 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
4424 /* We must not attempt PK auth. Pretend we've already tried it. */
4425 s->tried_publickey = s->tried_agent = 1;
4427 s->tried_publickey = s->tried_agent = 0;
4429 s->tis_auth_refused = s->ccard_auth_refused = 0;
4431 * Load the public half of any configured keyfile for later use.
4433 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4434 if (!filename_is_null(s->keyfile)) {
4436 logeventf(ssh, "Reading key file \"%.150s\"",
4437 filename_to_str(s->keyfile));
4438 keytype = key_type(s->keyfile);
4439 if (keytype == SSH_KEYTYPE_SSH1 ||
4440 keytype == SSH_KEYTYPE_SSH1_PUBLIC) {
4442 if (rsakey_pubblob(s->keyfile,
4443 &s->publickey_blob, &s->publickey_bloblen,
4444 &s->publickey_comment, &error)) {
4445 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH1);
4446 if (!s->privatekey_available)
4447 logeventf(ssh, "Key file contains public key only");
4448 s->privatekey_encrypted = rsakey_encrypted(s->keyfile,
4452 logeventf(ssh, "Unable to load key (%s)", error);
4453 msgbuf = dupprintf("Unable to load key file "
4454 "\"%.150s\" (%s)\r\n",
4455 filename_to_str(s->keyfile),
4457 c_write_str(ssh, msgbuf);
4459 s->publickey_blob = NULL;
4463 logeventf(ssh, "Unable to use this key file (%s)",
4464 key_type_to_str(keytype));
4465 msgbuf = dupprintf("Unable to use key file \"%.150s\""
4467 filename_to_str(s->keyfile),
4468 key_type_to_str(keytype));
4469 c_write_str(ssh, msgbuf);
4471 s->publickey_blob = NULL;
4474 s->publickey_blob = NULL;
4476 while (pktin->type == SSH1_SMSG_FAILURE) {
4477 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
4479 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
4481 * Attempt RSA authentication using Pageant.
4487 logevent("Pageant is running. Requesting keys.");
4489 /* Request the keys held by the agent. */
4490 PUT_32BIT(s->request, 1);
4491 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
4492 ssh->auth_agent_query = agent_query(
4493 s->request, 5, &r, &s->responselen, ssh_agent_callback, ssh);
4494 if (ssh->auth_agent_query) {
4498 bombout(("Unexpected data from server while waiting"
4499 " for agent response"));
4502 } while (pktin || inlen > 0);
4503 r = ssh->agent_response;
4504 s->responselen = ssh->agent_response_len;
4506 s->response = (unsigned char *) r;
4507 if (s->response && s->responselen >= 5 &&
4508 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
4509 s->p = s->response + 5;
4510 s->nkeys = toint(GET_32BIT(s->p));
4512 logeventf(ssh, "Pageant reported negative key count %d",
4517 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
4518 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
4519 unsigned char *pkblob = s->p;
4523 do { /* do while (0) to make breaking easy */
4524 n = ssh1_read_bignum
4525 (s->p, toint(s->responselen-(s->p-s->response)),
4530 n = ssh1_read_bignum
4531 (s->p, toint(s->responselen-(s->p-s->response)),
4536 if (s->responselen - (s->p-s->response) < 4)
4538 s->commentlen = toint(GET_32BIT(s->p));
4540 if (s->commentlen < 0 ||
4541 toint(s->responselen - (s->p-s->response)) <
4544 s->commentp = (char *)s->p;
4545 s->p += s->commentlen;
4549 logevent("Pageant key list packet was truncated");
4553 if (s->publickey_blob) {
4554 if (!memcmp(pkblob, s->publickey_blob,
4555 s->publickey_bloblen)) {
4556 logeventf(ssh, "Pageant key #%d matches "
4557 "configured key file", s->keyi);
4558 s->tried_publickey = 1;
4560 /* Skip non-configured key */
4563 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
4564 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4565 PKT_BIGNUM, s->key.modulus, PKT_END);
4567 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4568 logevent("Key refused");
4571 logevent("Received RSA challenge");
4572 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4573 bombout(("Server's RSA challenge was badly formatted"));
4578 char *agentreq, *q, *ret;
4581 len = 1 + 4; /* message type, bit count */
4582 len += ssh1_bignum_length(s->key.exponent);
4583 len += ssh1_bignum_length(s->key.modulus);
4584 len += ssh1_bignum_length(s->challenge);
4585 len += 16; /* session id */
4586 len += 4; /* response format */
4587 agentreq = snewn(4 + len, char);
4588 PUT_32BIT(agentreq, len);
4590 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
4591 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
4593 q += ssh1_write_bignum(q, s->key.exponent);
4594 q += ssh1_write_bignum(q, s->key.modulus);
4595 q += ssh1_write_bignum(q, s->challenge);
4596 memcpy(q, s->session_id, 16);
4598 PUT_32BIT(q, 1); /* response format */
4599 ssh->auth_agent_query = agent_query(
4600 agentreq, len + 4, &vret, &retlen,
4601 ssh_agent_callback, ssh);
4602 if (ssh->auth_agent_query) {
4607 bombout(("Unexpected data from server"
4608 " while waiting for agent"
4612 } while (pktin || inlen > 0);
4613 vret = ssh->agent_response;
4614 retlen = ssh->agent_response_len;
4619 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
4620 logevent("Sending Pageant's response");
4621 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4622 PKT_DATA, ret + 5, 16,
4626 if (pktin->type == SSH1_SMSG_SUCCESS) {
4628 ("Pageant's response accepted");
4629 if (flags & FLAG_VERBOSE) {
4630 c_write_str(ssh, "Authenticated using"
4632 c_write(ssh, s->commentp,
4634 c_write_str(ssh, "\" from agent\r\n");
4639 ("Pageant's response not accepted");
4642 ("Pageant failed to answer challenge");
4646 logevent("No reply received from Pageant");
4649 freebn(s->key.exponent);
4650 freebn(s->key.modulus);
4651 freebn(s->challenge);
4656 if (s->publickey_blob && !s->tried_publickey)
4657 logevent("Configured key file not in Pageant");
4659 logevent("Failed to get reply from Pageant");
4664 if (s->publickey_blob && s->privatekey_available &&
4665 !s->tried_publickey) {
4667 * Try public key authentication with the specified
4670 int got_passphrase; /* need not be kept over crReturn */
4671 if (flags & FLAG_VERBOSE)
4672 c_write_str(ssh, "Trying public key authentication.\r\n");
4673 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4674 logeventf(ssh, "Trying public key \"%s\"",
4675 filename_to_str(s->keyfile));
4676 s->tried_publickey = 1;
4677 got_passphrase = FALSE;
4678 while (!got_passphrase) {
4680 * Get a passphrase, if necessary.
4682 char *passphrase = NULL; /* only written after crReturn */
4684 if (!s->privatekey_encrypted) {
4685 if (flags & FLAG_VERBOSE)
4686 c_write_str(ssh, "No passphrase required.\r\n");
4689 int ret; /* need not be kept over crReturn */
4690 s->cur_prompt = new_prompts(ssh->frontend);
4691 s->cur_prompt->to_server = FALSE;
4692 s->cur_prompt->name = dupstr("SSH key passphrase");
4693 add_prompt(s->cur_prompt,
4694 dupprintf("Passphrase for key \"%.100s\": ",
4695 s->publickey_comment), FALSE);
4696 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4699 crWaitUntil(!pktin);
4700 ret = get_userpass_input(s->cur_prompt, in, inlen);
4704 /* Failed to get a passphrase. Terminate. */
4705 free_prompts(s->cur_prompt);
4706 ssh_disconnect(ssh, NULL, "Unable to authenticate",
4710 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
4711 free_prompts(s->cur_prompt);
4714 * Try decrypting key with passphrase.
4716 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4717 ret = loadrsakey(s->keyfile, &s->key, passphrase,
4720 smemclr(passphrase, strlen(passphrase));
4724 /* Correct passphrase. */
4725 got_passphrase = TRUE;
4726 } else if (ret == 0) {
4727 c_write_str(ssh, "Couldn't load private key from ");
4728 c_write_str(ssh, filename_to_str(s->keyfile));
4729 c_write_str(ssh, " (");
4730 c_write_str(ssh, error);
4731 c_write_str(ssh, ").\r\n");
4732 got_passphrase = FALSE;
4733 break; /* go and try something else */
4734 } else if (ret == -1) {
4735 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
4736 got_passphrase = FALSE;
4739 assert(0 && "unexpected return from loadrsakey()");
4740 got_passphrase = FALSE; /* placate optimisers */
4744 if (got_passphrase) {
4747 * Send a public key attempt.
4749 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4750 PKT_BIGNUM, s->key.modulus, PKT_END);
4753 if (pktin->type == SSH1_SMSG_FAILURE) {
4754 c_write_str(ssh, "Server refused our public key.\r\n");
4755 continue; /* go and try something else */
4757 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4758 bombout(("Bizarre response to offer of public key"));
4764 unsigned char buffer[32];
4765 Bignum challenge, response;
4767 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4768 bombout(("Server's RSA challenge was badly formatted"));
4771 response = rsadecrypt(challenge, &s->key);
4772 freebn(s->key.private_exponent);/* burn the evidence */
4774 for (i = 0; i < 32; i++) {
4775 buffer[i] = bignum_byte(response, 31 - i);
4779 MD5Update(&md5c, buffer, 32);
4780 MD5Update(&md5c, s->session_id, 16);
4781 MD5Final(buffer, &md5c);
4783 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4784 PKT_DATA, buffer, 16, PKT_END);
4791 if (pktin->type == SSH1_SMSG_FAILURE) {
4792 if (flags & FLAG_VERBOSE)
4793 c_write_str(ssh, "Failed to authenticate with"
4794 " our public key.\r\n");
4795 continue; /* go and try something else */
4796 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4797 bombout(("Bizarre response to RSA authentication response"));
4801 break; /* we're through! */
4807 * Otherwise, try various forms of password-like authentication.
4809 s->cur_prompt = new_prompts(ssh->frontend);
4811 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4812 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
4813 !s->tis_auth_refused) {
4814 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
4815 logevent("Requested TIS authentication");
4816 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
4818 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
4819 logevent("TIS authentication declined");
4820 if (flags & FLAG_INTERACTIVE)
4821 c_write_str(ssh, "TIS authentication refused.\r\n");
4822 s->tis_auth_refused = 1;
4827 char *instr_suf, *prompt;
4829 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4831 bombout(("TIS challenge packet was badly formed"));
4834 logevent("Received TIS challenge");
4835 s->cur_prompt->to_server = TRUE;
4836 s->cur_prompt->name = dupstr("SSH TIS authentication");
4837 /* Prompt heuristic comes from OpenSSH */
4838 if (memchr(challenge, '\n', challengelen)) {
4839 instr_suf = dupstr("");
4840 prompt = dupprintf("%.*s", challengelen, challenge);
4842 instr_suf = dupprintf("%.*s", challengelen, challenge);
4843 prompt = dupstr("Response: ");
4845 s->cur_prompt->instruction =
4846 dupprintf("Using TIS authentication.%s%s",
4847 (*instr_suf) ? "\n" : "",
4849 s->cur_prompt->instr_reqd = TRUE;
4850 add_prompt(s->cur_prompt, prompt, FALSE);
4854 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4855 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
4856 !s->ccard_auth_refused) {
4857 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
4858 logevent("Requested CryptoCard authentication");
4859 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
4861 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
4862 logevent("CryptoCard authentication declined");
4863 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
4864 s->ccard_auth_refused = 1;
4869 char *instr_suf, *prompt;
4871 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4873 bombout(("CryptoCard challenge packet was badly formed"));
4876 logevent("Received CryptoCard challenge");
4877 s->cur_prompt->to_server = TRUE;
4878 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4879 s->cur_prompt->name_reqd = FALSE;
4880 /* Prompt heuristic comes from OpenSSH */
4881 if (memchr(challenge, '\n', challengelen)) {
4882 instr_suf = dupstr("");
4883 prompt = dupprintf("%.*s", challengelen, challenge);
4885 instr_suf = dupprintf("%.*s", challengelen, challenge);
4886 prompt = dupstr("Response: ");
4888 s->cur_prompt->instruction =
4889 dupprintf("Using CryptoCard authentication.%s%s",
4890 (*instr_suf) ? "\n" : "",
4892 s->cur_prompt->instr_reqd = TRUE;
4893 add_prompt(s->cur_prompt, prompt, FALSE);
4897 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4898 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4899 bombout(("No supported authentication methods available"));
4902 s->cur_prompt->to_server = TRUE;
4903 s->cur_prompt->name = dupstr("SSH password");
4904 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4905 ssh->username, ssh->savedhost),
4910 * Show password prompt, having first obtained it via a TIS
4911 * or CryptoCard exchange if we're doing TIS or CryptoCard
4915 int ret; /* need not be kept over crReturn */
4916 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4919 crWaitUntil(!pktin);
4920 ret = get_userpass_input(s->cur_prompt, in, inlen);
4925 * Failed to get a password (for example
4926 * because one was supplied on the command line
4927 * which has already failed to work). Terminate.
4929 free_prompts(s->cur_prompt);
4930 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4935 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4937 * Defence against traffic analysis: we send a
4938 * whole bunch of packets containing strings of
4939 * different lengths. One of these strings is the
4940 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4941 * The others are all random data in
4942 * SSH1_MSG_IGNORE packets. This way a passive
4943 * listener can't tell which is the password, and
4944 * hence can't deduce the password length.
4946 * Anybody with a password length greater than 16
4947 * bytes is going to have enough entropy in their
4948 * password that a listener won't find it _that_
4949 * much help to know how long it is. So what we'll
4952 * - if password length < 16, we send 15 packets
4953 * containing string lengths 1 through 15
4955 * - otherwise, we let N be the nearest multiple
4956 * of 8 below the password length, and send 8
4957 * packets containing string lengths N through
4958 * N+7. This won't obscure the order of
4959 * magnitude of the password length, but it will
4960 * introduce a bit of extra uncertainty.
4962 * A few servers can't deal with SSH1_MSG_IGNORE, at
4963 * least in this context. For these servers, we need
4964 * an alternative defence. We make use of the fact
4965 * that the password is interpreted as a C string:
4966 * so we can append a NUL, then some random data.
4968 * A few servers can deal with neither SSH1_MSG_IGNORE
4969 * here _nor_ a padded password string.
4970 * For these servers we are left with no defences
4971 * against password length sniffing.
4973 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4974 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4976 * The server can deal with SSH1_MSG_IGNORE, so
4977 * we can use the primary defence.
4979 int bottom, top, pwlen, i;
4982 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4984 bottom = 0; /* zero length passwords are OK! :-) */
4987 bottom = pwlen & ~7;
4991 assert(pwlen >= bottom && pwlen <= top);
4993 randomstr = snewn(top + 1, char);
4995 for (i = bottom; i <= top; i++) {
4997 defer_packet(ssh, s->pwpkt_type,
4998 PKT_STR,s->cur_prompt->prompts[0]->result,
5001 for (j = 0; j < i; j++) {
5003 randomstr[j] = random_byte();
5004 } while (randomstr[j] == '\0');
5006 randomstr[i] = '\0';
5007 defer_packet(ssh, SSH1_MSG_IGNORE,
5008 PKT_STR, randomstr, PKT_END);
5011 logevent("Sending password with camouflage packets");
5012 ssh_pkt_defersend(ssh);
5015 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
5017 * The server can't deal with SSH1_MSG_IGNORE
5018 * but can deal with padded passwords, so we
5019 * can use the secondary defence.
5025 len = strlen(s->cur_prompt->prompts[0]->result);
5026 if (len < sizeof(string)) {
5028 strcpy(string, s->cur_prompt->prompts[0]->result);
5029 len++; /* cover the zero byte */
5030 while (len < sizeof(string)) {
5031 string[len++] = (char) random_byte();
5034 ss = s->cur_prompt->prompts[0]->result;
5036 logevent("Sending length-padded password");
5037 send_packet(ssh, s->pwpkt_type,
5038 PKT_INT, len, PKT_DATA, ss, len,
5042 * The server is believed unable to cope with
5043 * any of our password camouflage methods.
5046 len = strlen(s->cur_prompt->prompts[0]->result);
5047 logevent("Sending unpadded password");
5048 send_packet(ssh, s->pwpkt_type,
5050 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
5054 send_packet(ssh, s->pwpkt_type,
5055 PKT_STR, s->cur_prompt->prompts[0]->result,
5058 logevent("Sent password");
5059 free_prompts(s->cur_prompt);
5061 if (pktin->type == SSH1_SMSG_FAILURE) {
5062 if (flags & FLAG_VERBOSE)
5063 c_write_str(ssh, "Access denied\r\n");
5064 logevent("Authentication refused");
5065 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
5066 bombout(("Strange packet received, type %d", pktin->type));
5072 if (s->publickey_blob) {
5073 sfree(s->publickey_blob);
5074 sfree(s->publickey_comment);
5077 logevent("Authentication successful");
5082 static void ssh_channel_try_eof(struct ssh_channel *c)
5085 assert(c->pending_eof); /* precondition for calling us */
5087 return; /* can't close: not even opened yet */
5088 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
5089 return; /* can't send EOF: pending outgoing data */
5091 c->pending_eof = FALSE; /* we're about to send it */
5092 if (ssh->version == 1) {
5093 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
5095 c->closes |= CLOSES_SENT_EOF;
5097 struct Packet *pktout;
5098 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
5099 ssh2_pkt_adduint32(pktout, c->remoteid);
5100 ssh2_pkt_send(ssh, pktout);
5101 c->closes |= CLOSES_SENT_EOF;
5102 ssh2_channel_check_close(c);
5106 Conf *sshfwd_get_conf(struct ssh_channel *c)
5112 void sshfwd_write_eof(struct ssh_channel *c)
5116 if (ssh->state == SSH_STATE_CLOSED)
5119 if (c->closes & CLOSES_SENT_EOF)
5122 c->pending_eof = TRUE;
5123 ssh_channel_try_eof(c);
5126 void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
5131 if (ssh->state == SSH_STATE_CLOSED)
5134 reason = dupprintf("due to local error: %s", err);
5135 ssh_channel_close_local(c, reason);
5137 c->pending_eof = FALSE; /* this will confuse a zombie channel */
5139 ssh2_channel_check_close(c);
5142 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
5146 if (ssh->state == SSH_STATE_CLOSED)
5149 return ssh_send_channel_data(c, buf, len);
5152 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
5156 if (ssh->state == SSH_STATE_CLOSED)
5159 ssh_channel_unthrottle(c, bufsize);
5162 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
5164 struct queued_handler *qh = ssh->qhead;
5168 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
5171 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
5172 ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
5175 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
5176 ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
5180 ssh->qhead = qh->next;
5182 if (ssh->qhead->msg1 > 0) {
5183 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5184 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
5186 if (ssh->qhead->msg2 > 0) {
5187 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5188 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
5191 ssh->qhead = ssh->qtail = NULL;
5194 qh->handler(ssh, pktin, qh->ctx);
5199 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
5200 chandler_fn_t handler, void *ctx)
5202 struct queued_handler *qh;
5204 qh = snew(struct queued_handler);
5207 qh->handler = handler;
5211 if (ssh->qtail == NULL) {
5215 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5216 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
5219 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5220 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
5223 ssh->qtail->next = qh;
5228 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
5230 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
5232 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
5233 SSH2_MSG_REQUEST_SUCCESS)) {
5234 logeventf(ssh, "Remote port forwarding from %s enabled",
5237 logeventf(ssh, "Remote port forwarding from %s refused",
5240 rpf = del234(ssh->rportfwds, pf);
5242 pf->pfrec->remote = NULL;
5247 int ssh_alloc_sharing_rportfwd(Ssh ssh, const char *shost, int sport,
5250 struct ssh_rportfwd *pf = snew(struct ssh_rportfwd);
5253 pf->share_ctx = share_ctx;
5254 pf->shost = dupstr(shost);
5256 pf->sportdesc = NULL;
5257 if (!ssh->rportfwds) {
5258 assert(ssh->version == 2);
5259 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5261 if (add234(ssh->rportfwds, pf) != pf) {
5269 static void ssh_sharing_global_request_response(Ssh ssh, struct Packet *pktin,
5272 share_got_pkt_from_server(ctx, pktin->type,
5273 pktin->body, pktin->length);
5276 void ssh_sharing_queue_global_request(Ssh ssh, void *share_ctx)
5278 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE,
5279 ssh_sharing_global_request_response, share_ctx);
5282 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
5284 struct ssh_portfwd *epf;
5288 if (!ssh->portfwds) {
5289 ssh->portfwds = newtree234(ssh_portcmp);
5292 * Go through the existing port forwardings and tag them
5293 * with status==DESTROY. Any that we want to keep will be
5294 * re-enabled (status==KEEP) as we go through the
5295 * configuration and find out which bits are the same as
5298 struct ssh_portfwd *epf;
5300 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5301 epf->status = DESTROY;
5304 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
5306 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
5307 char *kp, *kp2, *vp, *vp2;
5308 char address_family, type;
5309 int sport,dport,sserv,dserv;
5310 char *sports, *dports, *saddr, *host;
5314 address_family = 'A';
5316 if (*kp == 'A' || *kp == '4' || *kp == '6')
5317 address_family = *kp++;
5318 if (*kp == 'L' || *kp == 'R')
5321 if ((kp2 = host_strchr(kp, ':')) != NULL) {
5323 * There's a colon in the middle of the source port
5324 * string, which means that the part before it is
5325 * actually a source address.
5327 char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp);
5328 saddr = host_strduptrim(saddr_tmp);
5335 sport = atoi(sports);
5339 sport = net_service_lookup(sports);
5341 logeventf(ssh, "Service lookup failed for source"
5342 " port \"%s\"", sports);
5346 if (type == 'L' && !strcmp(val, "D")) {
5347 /* dynamic forwarding */
5354 /* ordinary forwarding */
5356 vp2 = vp + host_strcspn(vp, ":");
5357 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
5361 dport = atoi(dports);
5365 dport = net_service_lookup(dports);
5367 logeventf(ssh, "Service lookup failed for destination"
5368 " port \"%s\"", dports);
5373 if (sport && dport) {
5374 /* Set up a description of the source port. */
5375 struct ssh_portfwd *pfrec, *epfrec;
5377 pfrec = snew(struct ssh_portfwd);
5379 pfrec->saddr = saddr;
5380 pfrec->sserv = sserv ? dupstr(sports) : NULL;
5381 pfrec->sport = sport;
5382 pfrec->daddr = host;
5383 pfrec->dserv = dserv ? dupstr(dports) : NULL;
5384 pfrec->dport = dport;
5385 pfrec->local = NULL;
5386 pfrec->remote = NULL;
5387 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
5388 address_family == '6' ? ADDRTYPE_IPV6 :
5391 epfrec = add234(ssh->portfwds, pfrec);
5392 if (epfrec != pfrec) {
5393 if (epfrec->status == DESTROY) {
5395 * We already have a port forwarding up and running
5396 * with precisely these parameters. Hence, no need
5397 * to do anything; simply re-tag the existing one
5400 epfrec->status = KEEP;
5403 * Anything else indicates that there was a duplicate
5404 * in our input, which we'll silently ignore.
5406 free_portfwd(pfrec);
5408 pfrec->status = CREATE;
5417 * Now go through and destroy any port forwardings which were
5420 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5421 if (epf->status == DESTROY) {
5424 message = dupprintf("%s port forwarding from %s%s%d",
5425 epf->type == 'L' ? "local" :
5426 epf->type == 'R' ? "remote" : "dynamic",
5427 epf->saddr ? epf->saddr : "",
5428 epf->saddr ? ":" : "",
5431 if (epf->type != 'D') {
5432 char *msg2 = dupprintf("%s to %s:%d", message,
5433 epf->daddr, epf->dport);
5438 logeventf(ssh, "Cancelling %s", message);
5441 /* epf->remote or epf->local may be NULL if setting up a
5442 * forwarding failed. */
5444 struct ssh_rportfwd *rpf = epf->remote;
5445 struct Packet *pktout;
5448 * Cancel the port forwarding at the server
5451 if (ssh->version == 1) {
5453 * We cannot cancel listening ports on the
5454 * server side in SSH-1! There's no message
5455 * to support it. Instead, we simply remove
5456 * the rportfwd record from the local end
5457 * so that any connections the server tries
5458 * to make on it are rejected.
5461 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5462 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
5463 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
5465 ssh2_pkt_addstring(pktout, epf->saddr);
5466 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5467 /* XXX: rport_acceptall may not represent
5468 * what was used to open the original connection,
5469 * since it's reconfigurable. */
5470 ssh2_pkt_addstring(pktout, "");
5472 ssh2_pkt_addstring(pktout, "localhost");
5474 ssh2_pkt_adduint32(pktout, epf->sport);
5475 ssh2_pkt_send(ssh, pktout);
5478 del234(ssh->rportfwds, rpf);
5480 } else if (epf->local) {
5481 pfl_terminate(epf->local);
5484 delpos234(ssh->portfwds, i);
5486 i--; /* so we don't skip one in the list */
5490 * And finally, set up any new port forwardings (status==CREATE).
5492 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5493 if (epf->status == CREATE) {
5494 char *sportdesc, *dportdesc;
5495 sportdesc = dupprintf("%s%s%s%s%d%s",
5496 epf->saddr ? epf->saddr : "",
5497 epf->saddr ? ":" : "",
5498 epf->sserv ? epf->sserv : "",
5499 epf->sserv ? "(" : "",
5501 epf->sserv ? ")" : "");
5502 if (epf->type == 'D') {
5505 dportdesc = dupprintf("%s:%s%s%d%s",
5507 epf->dserv ? epf->dserv : "",
5508 epf->dserv ? "(" : "",
5510 epf->dserv ? ")" : "");
5513 if (epf->type == 'L') {
5514 char *err = pfl_listen(epf->daddr, epf->dport,
5515 epf->saddr, epf->sport,
5516 ssh, conf, &epf->local,
5517 epf->addressfamily);
5519 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
5520 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5521 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5522 sportdesc, dportdesc,
5523 err ? " failed: " : "", err ? err : "");
5526 } else if (epf->type == 'D') {
5527 char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport,
5528 ssh, conf, &epf->local,
5529 epf->addressfamily);
5531 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
5532 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5533 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5535 err ? " failed: " : "", err ? err : "");
5540 struct ssh_rportfwd *pf;
5543 * Ensure the remote port forwardings tree exists.
5545 if (!ssh->rportfwds) {
5546 if (ssh->version == 1)
5547 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
5549 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5552 pf = snew(struct ssh_rportfwd);
5553 pf->share_ctx = NULL;
5554 pf->dhost = dupstr(epf->daddr);
5555 pf->dport = epf->dport;
5557 pf->shost = dupstr(epf->saddr);
5558 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5559 pf->shost = dupstr("");
5561 pf->shost = dupstr("localhost");
5563 pf->sport = epf->sport;
5564 if (add234(ssh->rportfwds, pf) != pf) {
5565 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
5566 epf->daddr, epf->dport);
5569 logeventf(ssh, "Requesting remote port %s"
5570 " forward to %s", sportdesc, dportdesc);
5572 pf->sportdesc = sportdesc;
5577 if (ssh->version == 1) {
5578 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
5579 PKT_INT, epf->sport,
5580 PKT_STR, epf->daddr,
5581 PKT_INT, epf->dport,
5583 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
5585 ssh_rportfwd_succfail, pf);
5587 struct Packet *pktout;
5588 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5589 ssh2_pkt_addstring(pktout, "tcpip-forward");
5590 ssh2_pkt_addbool(pktout, 1);/* want reply */
5591 ssh2_pkt_addstring(pktout, pf->shost);
5592 ssh2_pkt_adduint32(pktout, pf->sport);
5593 ssh2_pkt_send(ssh, pktout);
5595 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
5596 SSH2_MSG_REQUEST_FAILURE,
5597 ssh_rportfwd_succfail, pf);
5606 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
5609 int stringlen, bufsize;
5611 ssh_pkt_getstring(pktin, &string, &stringlen);
5612 if (string == NULL) {
5613 bombout(("Incoming terminal data packet was badly formed"));
5617 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
5619 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
5620 ssh->v1_stdout_throttling = 1;
5621 ssh_throttle_conn(ssh, +1);
5625 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
5627 /* Remote side is trying to open a channel to talk to our
5628 * X-Server. Give them back a local channel number. */
5629 struct ssh_channel *c;
5630 int remoteid = ssh_pkt_getuint32(pktin);
5632 logevent("Received X11 connect request");
5633 /* Refuse if X11 forwarding is disabled. */
5634 if (!ssh->X11_fwd_enabled) {
5635 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5636 PKT_INT, remoteid, PKT_END);
5637 logevent("Rejected X11 connect request");
5639 c = snew(struct ssh_channel);
5642 ssh_channel_init(c);
5643 c->u.x11.xconn = x11_init(ssh->x11authtree, c, NULL, -1);
5644 c->remoteid = remoteid;
5645 c->halfopen = FALSE;
5646 c->type = CHAN_X11; /* identify channel type */
5647 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5648 PKT_INT, c->remoteid, PKT_INT,
5649 c->localid, PKT_END);
5650 logevent("Opened X11 forward channel");
5654 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
5656 /* Remote side is trying to open a channel to talk to our
5657 * agent. Give them back a local channel number. */
5658 struct ssh_channel *c;
5659 int remoteid = ssh_pkt_getuint32(pktin);
5661 /* Refuse if agent forwarding is disabled. */
5662 if (!ssh->agentfwd_enabled) {
5663 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5664 PKT_INT, remoteid, PKT_END);
5666 c = snew(struct ssh_channel);
5668 ssh_channel_init(c);
5669 c->remoteid = remoteid;
5670 c->halfopen = FALSE;
5671 c->type = CHAN_AGENT; /* identify channel type */
5672 c->u.a.pending = NULL;
5673 bufchain_init(&c->u.a.inbuffer);
5674 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5675 PKT_INT, c->remoteid, PKT_INT, c->localid,
5680 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
5682 /* Remote side is trying to open a channel to talk to a
5683 * forwarded port. Give them back a local channel number. */
5684 struct ssh_rportfwd pf, *pfp;
5690 remoteid = ssh_pkt_getuint32(pktin);
5691 ssh_pkt_getstring(pktin, &host, &hostsize);
5692 port = ssh_pkt_getuint32(pktin);
5694 pf.dhost = dupprintf("%.*s", hostsize, NULLTOEMPTY(host));
5696 pfp = find234(ssh->rportfwds, &pf, NULL);
5699 logeventf(ssh, "Rejected remote port open request for %s:%d",
5701 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5702 PKT_INT, remoteid, PKT_END);
5704 struct ssh_channel *c = snew(struct ssh_channel);
5707 logeventf(ssh, "Received remote port open request for %s:%d",
5709 err = pfd_connect(&c->u.pfd.pf, pf.dhost, port,
5710 c, ssh->conf, pfp->pfrec->addressfamily);
5712 logeventf(ssh, "Port open failed: %s", err);
5715 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5716 PKT_INT, remoteid, PKT_END);
5718 ssh_channel_init(c);
5719 c->remoteid = remoteid;
5720 c->halfopen = FALSE;
5721 c->type = CHAN_SOCKDATA; /* identify channel type */
5722 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5723 PKT_INT, c->remoteid, PKT_INT,
5724 c->localid, PKT_END);
5725 logevent("Forwarded port opened successfully");
5732 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
5734 struct ssh_channel *c;
5736 c = ssh_channel_msg(ssh, pktin);
5737 if (c && c->type == CHAN_SOCKDATA) {
5738 c->remoteid = ssh_pkt_getuint32(pktin);
5739 c->halfopen = FALSE;
5740 c->throttling_conn = 0;
5741 pfd_confirm(c->u.pfd.pf);
5744 if (c && c->pending_eof) {
5746 * We have a pending close on this channel,
5747 * which we decided on before the server acked
5748 * the channel open. So now we know the
5749 * remoteid, we can close it again.
5751 ssh_channel_try_eof(c);
5755 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
5757 struct ssh_channel *c;
5759 c = ssh_channel_msg(ssh, pktin);
5760 if (c && c->type == CHAN_SOCKDATA) {
5761 logevent("Forwarded connection refused by server");
5762 pfd_close(c->u.pfd.pf);
5763 del234(ssh->channels, c);
5768 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
5770 /* Remote side closes a channel. */
5771 struct ssh_channel *c;
5773 c = ssh_channel_msg(ssh, pktin);
5776 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE) {
5778 * Received CHANNEL_CLOSE, which we translate into
5781 ssh_channel_got_eof(c);
5784 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
5785 !(c->closes & CLOSES_RCVD_CLOSE)) {
5787 if (!(c->closes & CLOSES_SENT_EOF)) {
5788 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %u"
5789 " for which we never sent CHANNEL_CLOSE\n",
5793 c->closes |= CLOSES_RCVD_CLOSE;
5796 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
5797 !(c->closes & CLOSES_SENT_CLOSE)) {
5798 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
5799 PKT_INT, c->remoteid, PKT_END);
5800 c->closes |= CLOSES_SENT_CLOSE;
5803 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
5804 ssh_channel_destroy(c);
5809 * Handle incoming data on an SSH-1 or SSH-2 agent-forwarding channel.
5811 static int ssh_agent_channel_data(struct ssh_channel *c, char *data,
5814 bufchain_add(&c->u.a.inbuffer, data, length);
5815 ssh_agentf_try_forward(c);
5818 * We exert back-pressure on an agent forwarding client if and
5819 * only if we're waiting for the response to an asynchronous agent
5820 * request. This prevents the client running out of window while
5821 * receiving the _first_ message, but means that if any message
5822 * takes time to process, the client will be discouraged from
5823 * sending an endless stream of further ones after it.
5825 return (c->u.a.pending ? bufchain_size(&c->u.a.inbuffer) : 0);
5828 static int ssh_channel_data(struct ssh_channel *c, int is_stderr,
5829 char *data, int length)
5832 case CHAN_MAINSESSION:
5833 return from_backend(c->ssh->frontend, is_stderr, data, length);
5835 return x11_send(c->u.x11.xconn, data, length);
5837 return pfd_send(c->u.pfd.pf, data, length);
5839 return ssh_agent_channel_data(c, data, length);
5844 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
5846 /* Data sent down one of our channels. */
5849 struct ssh_channel *c;
5851 c = ssh_channel_msg(ssh, pktin);
5852 ssh_pkt_getstring(pktin, &p, &len);
5855 int bufsize = ssh_channel_data(c, FALSE, p, len);
5856 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5857 c->throttling_conn = 1;
5858 ssh_throttle_conn(ssh, +1);
5863 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5865 ssh->exitcode = ssh_pkt_getuint32(pktin);
5866 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5867 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5869 * In case `helpful' firewalls or proxies tack
5870 * extra human-readable text on the end of the
5871 * session which we might mistake for another
5872 * encrypted packet, we close the session once
5873 * we've sent EXIT_CONFIRMATION.
5875 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5878 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5879 static void ssh1_send_ttymode(void *data,
5880 const struct ssh_ttymode *mode, char *val)
5882 struct Packet *pktout = (struct Packet *)data;
5883 unsigned int arg = 0;
5885 switch (mode->type) {
5887 arg = ssh_tty_parse_specchar(val);
5890 arg = ssh_tty_parse_boolean(val);
5893 ssh2_pkt_addbyte(pktout, mode->opcode);
5894 ssh2_pkt_addbyte(pktout, arg);
5897 int ssh_agent_forwarding_permitted(Ssh ssh)
5899 return conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists();
5902 static void do_ssh1_connection(Ssh ssh, const unsigned char *in, int inlen,
5903 struct Packet *pktin)
5905 crBegin(ssh->do_ssh1_connection_crstate);
5907 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5908 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5909 ssh1_smsg_stdout_stderr_data;
5911 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5912 ssh1_msg_channel_open_confirmation;
5913 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5914 ssh1_msg_channel_open_failure;
5915 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5916 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5917 ssh1_msg_channel_close;
5918 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5919 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5921 if (ssh_agent_forwarding_permitted(ssh)) {
5922 logevent("Requesting agent forwarding");
5923 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5927 if (pktin->type != SSH1_SMSG_SUCCESS
5928 && pktin->type != SSH1_SMSG_FAILURE) {
5929 bombout(("Protocol confusion"));
5931 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5932 logevent("Agent forwarding refused");
5934 logevent("Agent forwarding enabled");
5935 ssh->agentfwd_enabled = TRUE;
5936 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5940 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
5942 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5944 if (!ssh->x11disp) {
5945 /* FIXME: return an error message from x11_setup_display */
5946 logevent("X11 forwarding not enabled: unable to"
5947 " initialise X display");
5949 ssh->x11auth = x11_invent_fake_auth
5950 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
5951 ssh->x11auth->disp = ssh->x11disp;
5953 logevent("Requesting X11 forwarding");
5954 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5955 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5956 PKT_STR, ssh->x11auth->protoname,
5957 PKT_STR, ssh->x11auth->datastring,
5958 PKT_INT, ssh->x11disp->screennum,
5961 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5962 PKT_STR, ssh->x11auth->protoname,
5963 PKT_STR, ssh->x11auth->datastring,
5969 if (pktin->type != SSH1_SMSG_SUCCESS
5970 && pktin->type != SSH1_SMSG_FAILURE) {
5971 bombout(("Protocol confusion"));
5973 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5974 logevent("X11 forwarding refused");
5976 logevent("X11 forwarding enabled");
5977 ssh->X11_fwd_enabled = TRUE;
5978 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5983 ssh_setup_portfwd(ssh, ssh->conf);
5984 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5986 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5988 /* Unpick the terminal-speed string. */
5989 /* XXX perhaps we should allow no speeds to be sent. */
5990 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5991 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5992 /* Send the pty request. */
5993 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5994 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5995 ssh_pkt_adduint32(pkt, ssh->term_height);
5996 ssh_pkt_adduint32(pkt, ssh->term_width);
5997 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5998 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5999 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
6000 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
6001 ssh_pkt_adduint32(pkt, ssh->ispeed);
6002 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
6003 ssh_pkt_adduint32(pkt, ssh->ospeed);
6004 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
6006 ssh->state = SSH_STATE_INTERMED;
6010 if (pktin->type != SSH1_SMSG_SUCCESS
6011 && pktin->type != SSH1_SMSG_FAILURE) {
6012 bombout(("Protocol confusion"));
6014 } else if (pktin->type == SSH1_SMSG_FAILURE) {
6015 c_write_str(ssh, "Server refused to allocate pty\r\n");
6016 ssh->editing = ssh->echoing = 1;
6018 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
6019 ssh->ospeed, ssh->ispeed);
6020 ssh->got_pty = TRUE;
6023 ssh->editing = ssh->echoing = 1;
6026 if (conf_get_int(ssh->conf, CONF_compression)) {
6027 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
6031 if (pktin->type != SSH1_SMSG_SUCCESS
6032 && pktin->type != SSH1_SMSG_FAILURE) {
6033 bombout(("Protocol confusion"));
6035 } else if (pktin->type == SSH1_SMSG_FAILURE) {
6036 c_write_str(ssh, "Server refused to compress\r\n");
6038 logevent("Started compression");
6039 ssh->v1_compressing = TRUE;
6040 ssh->cs_comp_ctx = zlib_compress_init();
6041 logevent("Initialised zlib (RFC1950) compression");
6042 ssh->sc_comp_ctx = zlib_decompress_init();
6043 logevent("Initialised zlib (RFC1950) decompression");
6047 * Start the shell or command.
6049 * Special case: if the first-choice command is an SSH-2
6050 * subsystem (hence not usable here) and the second choice
6051 * exists, we fall straight back to that.
6054 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
6056 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
6057 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
6058 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
6059 ssh->fallback_cmd = TRUE;
6062 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
6064 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
6065 logevent("Started session");
6068 ssh->state = SSH_STATE_SESSION;
6069 if (ssh->size_needed)
6070 ssh_size(ssh, ssh->term_width, ssh->term_height);
6071 if (ssh->eof_needed)
6072 ssh_special(ssh, TS_EOF);
6075 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
6077 ssh->channels = newtree234(ssh_channelcmp);
6081 * By this point, most incoming packets are already being
6082 * handled by the dispatch table, and we need only pay
6083 * attention to the unusual ones.
6088 if (pktin->type == SSH1_SMSG_SUCCESS) {
6089 /* may be from EXEC_SHELL on some servers */
6090 } else if (pktin->type == SSH1_SMSG_FAILURE) {
6091 /* may be from EXEC_SHELL on some servers
6092 * if no pty is available or in other odd cases. Ignore */
6094 bombout(("Strange packet received: type %d", pktin->type));
6099 int len = min(inlen, 512);
6100 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
6101 PKT_INT, len, PKT_DATA, in, len,
6113 * Handle the top-level SSH-2 protocol.
6115 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
6120 ssh_pkt_getstring(pktin, &msg, &msglen);
6121 logeventf(ssh, "Remote debug message: %.*s", msglen, NULLTOEMPTY(msg));
6124 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
6126 /* log reason code in disconnect message */
6130 ssh_pkt_getstring(pktin, &msg, &msglen);
6131 bombout(("Server sent disconnect message:\n\"%.*s\"",
6132 msglen, NULLTOEMPTY(msg)));
6135 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
6137 /* Do nothing, because we're ignoring it! Duhh. */
6140 static void ssh1_protocol_setup(Ssh ssh)
6145 * Most messages are handled by the coroutines.
6147 for (i = 0; i < 256; i++)
6148 ssh->packet_dispatch[i] = NULL;
6151 * These special message types we install handlers for.
6153 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
6154 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
6155 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
6158 static void ssh1_protocol(Ssh ssh, const void *vin, int inlen,
6159 struct Packet *pktin)
6161 const unsigned char *in = (const unsigned char *)vin;
6162 if (ssh->state == SSH_STATE_CLOSED)
6165 if (pktin && ssh->packet_dispatch[pktin->type]) {
6166 ssh->packet_dispatch[pktin->type](ssh, pktin);
6170 if (!ssh->protocol_initial_phase_done) {
6171 if (do_ssh1_login(ssh, in, inlen, pktin))
6172 ssh->protocol_initial_phase_done = TRUE;
6177 do_ssh1_connection(ssh, in, inlen, pktin);
6181 * Utility routines for decoding comma-separated strings in KEXINIT.
6183 static int first_in_commasep_string(char const *needle, char const *haystack,
6187 if (!needle || !haystack) /* protect against null pointers */
6189 needlen = strlen(needle);
6191 if (haylen >= needlen && /* haystack is long enough */
6192 !memcmp(needle, haystack, needlen) && /* initial match */
6193 (haylen == needlen || haystack[needlen] == ',')
6194 /* either , or EOS follows */
6200 static int in_commasep_string(char const *needle, char const *haystack,
6205 if (!needle || !haystack) /* protect against null pointers */
6208 * Is it at the start of the string?
6210 if (first_in_commasep_string(needle, haystack, haylen))
6213 * If not, search for the next comma and resume after that.
6214 * If no comma found, terminate.
6216 p = memchr(haystack, ',', haylen);
6218 /* + 1 to skip over comma */
6219 return in_commasep_string(needle, p + 1, haylen - (p + 1 - haystack));
6223 * Add a value to the comma-separated string at the end of the packet.
6225 static void ssh2_pkt_addstring_commasep(struct Packet *pkt, const char *data)
6227 if (pkt->length - pkt->savedpos > 0)
6228 ssh_pkt_addstring_str(pkt, ",");
6229 ssh_pkt_addstring_str(pkt, data);
6234 * SSH-2 key derivation (RFC 4253 section 7.2).
6236 static unsigned char *ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H,
6237 char chr, int keylen)
6239 const struct ssh_hash *h = ssh->kex->hash;
6247 /* Round up to the next multiple of hash length. */
6248 keylen_padded = ((keylen + h->hlen - 1) / h->hlen) * h->hlen;
6250 key = snewn(keylen_padded, unsigned char);
6252 /* First hlen bytes. */
6254 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6255 hash_mpint(h, s, K);
6256 h->bytes(s, H, h->hlen);
6257 h->bytes(s, &chr, 1);
6258 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
6261 /* Subsequent blocks of hlen bytes. */
6262 if (keylen_padded > h->hlen) {
6266 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6267 hash_mpint(h, s, K);
6268 h->bytes(s, H, h->hlen);
6270 for (offset = h->hlen; offset < keylen_padded; offset += h->hlen) {
6271 h->bytes(s, key + offset - h->hlen, h->hlen);
6273 h->final(s2, key + offset);
6279 /* Now clear any extra bytes of key material beyond the length
6280 * we're officially returning, because the caller won't know to
6282 if (keylen_padded > keylen)
6283 smemclr(key + keylen, keylen_padded - keylen);
6289 * Structure for constructing KEXINIT algorithm lists.
6291 #define MAXKEXLIST 16
6292 struct kexinit_algorithm {
6296 const struct ssh_kex *kex;
6300 const struct ssh_signkey *hostkey;
6304 const struct ssh2_cipher *cipher;
6308 const struct ssh_mac *mac;
6311 const struct ssh_compress *comp;
6316 * Find a slot in a KEXINIT algorithm list to use for a new algorithm.
6317 * If the algorithm is already in the list, return a pointer to its
6318 * entry, otherwise return an entry from the end of the list.
6319 * This assumes that every time a particular name is passed in, it
6320 * comes from the same string constant. If this isn't true, this
6321 * function may need to be rewritten to use strcmp() instead.
6323 static struct kexinit_algorithm *ssh2_kexinit_addalg(struct kexinit_algorithm
6324 *list, const char *name)
6328 for (i = 0; i < MAXKEXLIST; i++)
6329 if (list[i].name == NULL || list[i].name == name) {
6330 list[i].name = name;
6333 assert(!"No space in KEXINIT list");
6338 * Handle the SSH-2 transport layer.
6340 static void do_ssh2_transport(Ssh ssh, const void *vin, int inlen,
6341 struct Packet *pktin)
6343 const unsigned char *in = (const unsigned char *)vin;
6345 KEXLIST_KEX, KEXLIST_HOSTKEY, KEXLIST_CSCIPHER, KEXLIST_SCCIPHER,
6346 KEXLIST_CSMAC, KEXLIST_SCMAC, KEXLIST_CSCOMP, KEXLIST_SCCOMP,
6349 const char * kexlist_descr[NKEXLIST] = {
6350 "key exchange algorithm", "host key algorithm",
6351 "client-to-server cipher", "server-to-client cipher",
6352 "client-to-server MAC", "server-to-client MAC",
6353 "client-to-server compression method",
6354 "server-to-client compression method" };
6355 struct do_ssh2_transport_state {
6357 int nbits, pbits, warn_kex, warn_hk, warn_cscipher, warn_sccipher;
6358 Bignum p, g, e, f, K;
6361 int kex_init_value, kex_reply_value;
6362 const struct ssh_mac *const *maclist;
6364 const struct ssh2_cipher *cscipher_tobe;
6365 const struct ssh2_cipher *sccipher_tobe;
6366 const struct ssh_mac *csmac_tobe;
6367 const struct ssh_mac *scmac_tobe;
6368 int csmac_etm_tobe, scmac_etm_tobe;
6369 const struct ssh_compress *cscomp_tobe;
6370 const struct ssh_compress *sccomp_tobe;
6371 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
6372 int hostkeylen, siglen, rsakeylen;
6373 void *hkey; /* actual host key */
6374 void *rsakey; /* for RSA kex */
6375 void *eckey; /* for ECDH kex */
6376 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
6377 int n_preferred_kex;
6378 const struct ssh_kexes *preferred_kex[KEX_MAX];
6380 int preferred_hk[HK_MAX];
6381 int n_preferred_ciphers;
6382 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
6383 const struct ssh_compress *preferred_comp;
6384 int userauth_succeeded; /* for delayed compression */
6385 int pending_compression;
6386 int got_session_id, activated_authconn;
6387 struct Packet *pktout;
6391 struct kexinit_algorithm kexlists[NKEXLIST][MAXKEXLIST];
6393 crState(do_ssh2_transport_state);
6395 assert(!ssh->bare_connection);
6396 assert(ssh->version == 2);
6400 s->cscipher_tobe = s->sccipher_tobe = NULL;
6401 s->csmac_tobe = s->scmac_tobe = NULL;
6402 s->cscomp_tobe = s->sccomp_tobe = NULL;
6404 s->got_session_id = s->activated_authconn = FALSE;
6405 s->userauth_succeeded = FALSE;
6406 s->pending_compression = FALSE;
6409 * Be prepared to work around the buggy MAC problem.
6411 if (ssh->remote_bugs & BUG_SSH2_HMAC)
6412 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
6414 s->maclist = macs, s->nmacs = lenof(macs);
6417 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
6420 struct kexinit_algorithm *alg;
6423 * Set up the preferred key exchange. (NULL => warn below here)
6425 s->n_preferred_kex = 0;
6426 for (i = 0; i < KEX_MAX; i++) {
6427 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
6429 s->preferred_kex[s->n_preferred_kex++] =
6430 &ssh_diffiehellman_gex;
6433 s->preferred_kex[s->n_preferred_kex++] =
6434 &ssh_diffiehellman_group14;
6437 s->preferred_kex[s->n_preferred_kex++] =
6438 &ssh_diffiehellman_group1;
6441 s->preferred_kex[s->n_preferred_kex++] =
6445 s->preferred_kex[s->n_preferred_kex++] =
6449 /* Flag for later. Don't bother if it's the last in
6451 if (i < KEX_MAX - 1) {
6452 s->preferred_kex[s->n_preferred_kex++] = NULL;
6459 * Set up the preferred host key types. These are just the ids
6460 * in the enum in putty.h, so 'warn below here' is indicated
6463 s->n_preferred_hk = 0;
6464 for (i = 0; i < HK_MAX; i++) {
6465 int id = conf_get_int_int(ssh->conf, CONF_ssh_hklist, i);
6466 /* As above, don't bother with HK_WARN if it's last in the
6468 if (id != HK_WARN || i < HK_MAX - 1)
6469 s->preferred_hk[s->n_preferred_hk++] = id;
6473 * Set up the preferred ciphers. (NULL => warn below here)
6475 s->n_preferred_ciphers = 0;
6476 for (i = 0; i < CIPHER_MAX; i++) {
6477 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
6478 case CIPHER_BLOWFISH:
6479 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
6482 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
6483 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
6487 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
6490 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
6492 case CIPHER_ARCFOUR:
6493 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
6495 case CIPHER_CHACHA20:
6496 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_ccp;
6499 /* Flag for later. Don't bother if it's the last in
6501 if (i < CIPHER_MAX - 1) {
6502 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
6509 * Set up preferred compression.
6511 if (conf_get_int(ssh->conf, CONF_compression))
6512 s->preferred_comp = &ssh_zlib;
6514 s->preferred_comp = &ssh_comp_none;
6517 * Enable queueing of outgoing auth- or connection-layer
6518 * packets while we are in the middle of a key exchange.
6520 ssh->queueing = TRUE;
6523 * Flag that KEX is in progress.
6525 ssh->kex_in_progress = TRUE;
6527 for (i = 0; i < NKEXLIST; i++)
6528 for (j = 0; j < MAXKEXLIST; j++)
6529 s->kexlists[i][j].name = NULL;
6530 /* List key exchange algorithms. */
6532 for (i = 0; i < s->n_preferred_kex; i++) {
6533 const struct ssh_kexes *k = s->preferred_kex[i];
6534 if (!k) warn = TRUE;
6535 else for (j = 0; j < k->nkexes; j++) {
6536 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_KEX],
6538 alg->u.kex.kex = k->list[j];
6539 alg->u.kex.warn = warn;
6542 /* List server host key algorithms. */
6543 if (!s->got_session_id) {
6545 * In the first key exchange, we list all the algorithms
6546 * we're prepared to cope with, but prefer those algorithms
6547 * for which we have a host key for this host.
6549 * If the host key algorithm is below the warning
6550 * threshold, we warn even if we did already have a key
6551 * for it, on the basis that if the user has just
6552 * reconfigured that host key type to be warned about,
6553 * they surely _do_ want to be alerted that a server
6554 * they're actually connecting to is using it.
6557 for (i = 0; i < s->n_preferred_hk; i++) {
6558 if (s->preferred_hk[i] == HK_WARN)
6560 for (j = 0; j < lenof(hostkey_algs); j++) {
6561 if (hostkey_algs[j].id != s->preferred_hk[i])
6563 if (have_ssh_host_key(ssh->savedhost, ssh->savedport,
6564 hostkey_algs[j].alg->keytype)) {
6565 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6566 hostkey_algs[j].alg->name);
6567 alg->u.hk.hostkey = hostkey_algs[j].alg;
6568 alg->u.hk.warn = warn;
6573 for (i = 0; i < s->n_preferred_hk; i++) {
6574 if (s->preferred_hk[i] == HK_WARN)
6576 for (j = 0; j < lenof(hostkey_algs); j++) {
6577 if (hostkey_algs[j].id != s->preferred_hk[i])
6579 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6580 hostkey_algs[j].alg->name);
6581 alg->u.hk.hostkey = hostkey_algs[j].alg;
6582 alg->u.hk.warn = warn;
6587 * In subsequent key exchanges, we list only the kex
6588 * algorithm that was selected in the first key exchange,
6589 * so that we keep getting the same host key and hence
6590 * don't have to interrupt the user's session to ask for
6594 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6595 ssh->hostkey->name);
6596 alg->u.hk.hostkey = ssh->hostkey;
6597 alg->u.hk.warn = FALSE;
6599 /* List encryption algorithms (client->server then server->client). */
6600 for (k = KEXLIST_CSCIPHER; k <= KEXLIST_SCCIPHER; k++) {
6603 alg = ssh2_kexinit_addalg(s->kexlists[k], "none");
6604 alg->u.cipher.cipher = NULL;
6605 alg->u.cipher.warn = warn;
6606 #endif /* FUZZING */
6607 for (i = 0; i < s->n_preferred_ciphers; i++) {
6608 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6609 if (!c) warn = TRUE;
6610 else for (j = 0; j < c->nciphers; j++) {
6611 alg = ssh2_kexinit_addalg(s->kexlists[k],
6613 alg->u.cipher.cipher = c->list[j];
6614 alg->u.cipher.warn = warn;
6618 /* List MAC algorithms (client->server then server->client). */
6619 for (j = KEXLIST_CSMAC; j <= KEXLIST_SCMAC; j++) {
6621 alg = ssh2_kexinit_addalg(s->kexlists[j], "none");
6622 alg->u.mac.mac = NULL;
6623 alg->u.mac.etm = FALSE;
6624 #endif /* FUZZING */
6625 for (i = 0; i < s->nmacs; i++) {
6626 alg = ssh2_kexinit_addalg(s->kexlists[j], s->maclist[i]->name);
6627 alg->u.mac.mac = s->maclist[i];
6628 alg->u.mac.etm = FALSE;
6630 for (i = 0; i < s->nmacs; i++)
6631 /* For each MAC, there may also be an ETM version,
6632 * which we list second. */
6633 if (s->maclist[i]->etm_name) {
6634 alg = ssh2_kexinit_addalg(s->kexlists[j],
6635 s->maclist[i]->etm_name);
6636 alg->u.mac.mac = s->maclist[i];
6637 alg->u.mac.etm = TRUE;
6640 /* List client->server compression algorithms,
6641 * then server->client compression algorithms. (We use the
6642 * same set twice.) */
6643 for (j = KEXLIST_CSCOMP; j <= KEXLIST_SCCOMP; j++) {
6644 assert(lenof(compressions) > 1);
6645 /* Prefer non-delayed versions */
6646 alg = ssh2_kexinit_addalg(s->kexlists[j], s->preferred_comp->name);
6647 alg->u.comp = s->preferred_comp;
6648 /* We don't even list delayed versions of algorithms until
6649 * they're allowed to be used, to avoid a race. See the end of
6651 if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
6652 alg = ssh2_kexinit_addalg(s->kexlists[j],
6653 s->preferred_comp->delayed_name);
6654 alg->u.comp = s->preferred_comp;
6656 for (i = 0; i < lenof(compressions); i++) {
6657 const struct ssh_compress *c = compressions[i];
6658 alg = ssh2_kexinit_addalg(s->kexlists[j], c->name);
6660 if (s->userauth_succeeded && c->delayed_name) {
6661 alg = ssh2_kexinit_addalg(s->kexlists[j], c->delayed_name);
6667 * Construct and send our key exchange packet.
6669 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
6670 for (i = 0; i < 16; i++)
6671 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
6672 for (i = 0; i < NKEXLIST; i++) {
6673 ssh2_pkt_addstring_start(s->pktout);
6674 for (j = 0; j < MAXKEXLIST; j++) {
6675 if (s->kexlists[i][j].name == NULL) break;
6676 ssh2_pkt_addstring_commasep(s->pktout, s->kexlists[i][j].name);
6679 /* List client->server languages. Empty list. */
6680 ssh2_pkt_addstring_start(s->pktout);
6681 /* List server->client languages. Empty list. */
6682 ssh2_pkt_addstring_start(s->pktout);
6683 /* First KEX packet does _not_ follow, because we're not that brave. */
6684 ssh2_pkt_addbool(s->pktout, FALSE);
6686 ssh2_pkt_adduint32(s->pktout, 0);
6689 s->our_kexinitlen = s->pktout->length - 5;
6690 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
6691 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
6693 ssh2_pkt_send_noqueue(ssh, s->pktout);
6696 crWaitUntilV(pktin);
6699 * Now examine the other side's KEXINIT to see what we're up
6706 if (pktin->type != SSH2_MSG_KEXINIT) {
6707 bombout(("expected key exchange packet from server"));
6711 ssh->hostkey = NULL;
6712 s->cscipher_tobe = NULL;
6713 s->sccipher_tobe = NULL;
6714 s->csmac_tobe = NULL;
6715 s->scmac_tobe = NULL;
6716 s->cscomp_tobe = NULL;
6717 s->sccomp_tobe = NULL;
6718 s->warn_kex = s->warn_hk = FALSE;
6719 s->warn_cscipher = s->warn_sccipher = FALSE;
6721 pktin->savedpos += 16; /* skip garbage cookie */
6724 for (i = 0; i < NKEXLIST; i++) {
6725 ssh_pkt_getstring(pktin, &str, &len);
6727 bombout(("KEXINIT packet was incomplete"));
6731 /* If we've already selected a cipher which requires a
6732 * particular MAC, then just select that, and don't even
6733 * bother looking through the server's KEXINIT string for
6735 if (i == KEXLIST_CSMAC && s->cscipher_tobe &&
6736 s->cscipher_tobe->required_mac) {
6737 s->csmac_tobe = s->cscipher_tobe->required_mac;
6738 s->csmac_etm_tobe = !!(s->csmac_tobe->etm_name);
6741 if (i == KEXLIST_SCMAC && s->sccipher_tobe &&
6742 s->sccipher_tobe->required_mac) {
6743 s->scmac_tobe = s->sccipher_tobe->required_mac;
6744 s->scmac_etm_tobe = !!(s->scmac_tobe->etm_name);
6748 for (j = 0; j < MAXKEXLIST; j++) {
6749 struct kexinit_algorithm *alg = &s->kexlists[i][j];
6750 if (alg->name == NULL) break;
6751 if (in_commasep_string(alg->name, str, len)) {
6752 /* We've found a matching algorithm. */
6753 if (i == KEXLIST_KEX || i == KEXLIST_HOSTKEY) {
6754 /* Check if we might need to ignore first kex pkt */
6756 !first_in_commasep_string(alg->name, str, len))
6759 if (i == KEXLIST_KEX) {
6760 ssh->kex = alg->u.kex.kex;
6761 s->warn_kex = alg->u.kex.warn;
6762 } else if (i == KEXLIST_HOSTKEY) {
6763 ssh->hostkey = alg->u.hk.hostkey;
6764 s->warn_hk = alg->u.hk.warn;
6765 } else if (i == KEXLIST_CSCIPHER) {
6766 s->cscipher_tobe = alg->u.cipher.cipher;
6767 s->warn_cscipher = alg->u.cipher.warn;
6768 } else if (i == KEXLIST_SCCIPHER) {
6769 s->sccipher_tobe = alg->u.cipher.cipher;
6770 s->warn_sccipher = alg->u.cipher.warn;
6771 } else if (i == KEXLIST_CSMAC) {
6772 s->csmac_tobe = alg->u.mac.mac;
6773 s->csmac_etm_tobe = alg->u.mac.etm;
6774 } else if (i == KEXLIST_SCMAC) {
6775 s->scmac_tobe = alg->u.mac.mac;
6776 s->scmac_etm_tobe = alg->u.mac.etm;
6777 } else if (i == KEXLIST_CSCOMP) {
6778 s->cscomp_tobe = alg->u.comp;
6779 } else if (i == KEXLIST_SCCOMP) {
6780 s->sccomp_tobe = alg->u.comp;
6784 if ((i == KEXLIST_CSCOMP || i == KEXLIST_SCCOMP) &&
6785 in_commasep_string(alg->u.comp->delayed_name, str, len))
6786 s->pending_compression = TRUE; /* try this later */
6788 bombout(("Couldn't agree a %s (available: %.*s)",
6789 kexlist_descr[i], len, str));
6793 if (i == KEXLIST_HOSTKEY) {
6797 * In addition to deciding which host key we're
6798 * actually going to use, we should make a list of the
6799 * host keys offered by the server which we _don't_
6800 * have cached. These will be offered as cross-
6801 * certification options by ssh_get_specials.
6803 * We also count the key we're currently using for KEX
6804 * as one we've already got, because by the time this
6805 * menu becomes visible, it will be.
6807 ssh->n_uncert_hostkeys = 0;
6809 for (j = 0; j < lenof(hostkey_algs); j++) {
6810 if (hostkey_algs[j].alg != ssh->hostkey &&
6811 in_commasep_string(hostkey_algs[j].alg->name,
6813 !have_ssh_host_key(ssh->savedhost, ssh->savedport,
6814 hostkey_algs[j].alg->keytype)) {
6815 ssh->uncert_hostkeys[ssh->n_uncert_hostkeys++] = j;
6821 if (s->pending_compression) {
6822 logevent("Server supports delayed compression; "
6823 "will try this later");
6825 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
6826 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
6827 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
6829 ssh->exhash = ssh->kex->hash->init();
6830 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
6831 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
6832 hash_string(ssh->kex->hash, ssh->exhash,
6833 s->our_kexinit, s->our_kexinitlen);
6834 sfree(s->our_kexinit);
6835 /* Include the type byte in the hash of server's KEXINIT */
6836 hash_string(ssh->kex->hash, ssh->exhash,
6837 pktin->body - 1, pktin->length + 1);
6840 ssh_set_frozen(ssh, 1);
6841 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
6843 ssh_dialog_callback, ssh);
6844 if (s->dlgret < 0) {
6848 bombout(("Unexpected data from server while"
6849 " waiting for user response"));
6852 } while (pktin || inlen > 0);
6853 s->dlgret = ssh->user_response;
6855 ssh_set_frozen(ssh, 0);
6856 if (s->dlgret == 0) {
6857 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
6867 ssh_set_frozen(ssh, 1);
6870 * Change warning box wording depending on why we chose a
6871 * warning-level host key algorithm. If it's because
6872 * that's all we have *cached*, use the askhk mechanism,
6873 * and list the host keys we could usefully cross-certify.
6874 * Otherwise, use askalg for the standard wording.
6877 for (j = 0; j < ssh->n_uncert_hostkeys; j++) {
6878 const struct ssh_signkey_with_user_pref_id *hktype =
6879 &hostkey_algs[ssh->uncert_hostkeys[j]];
6881 for (k = 0; k < HK_MAX; k++) {
6882 int id = conf_get_int_int(ssh->conf, CONF_ssh_hklist, k);
6883 if (id == HK_WARN) {
6885 } else if (id == hktype->id) {
6892 char *old_ba = betteralgs;
6893 betteralgs = dupcat(betteralgs, ",",
6895 (const char *)NULL);
6898 betteralgs = dupstr(hktype->alg->name);
6903 s->dlgret = askhk(ssh->frontend, ssh->hostkey->name,
6904 betteralgs, ssh_dialog_callback, ssh);
6907 s->dlgret = askalg(ssh->frontend, "host key type",
6909 ssh_dialog_callback, ssh);
6911 if (s->dlgret < 0) {
6915 bombout(("Unexpected data from server while"
6916 " waiting for user response"));
6919 } while (pktin || inlen > 0);
6920 s->dlgret = ssh->user_response;
6922 ssh_set_frozen(ssh, 0);
6923 if (s->dlgret == 0) {
6924 ssh_disconnect(ssh, "User aborted at host key warning", NULL,
6930 if (s->warn_cscipher) {
6931 ssh_set_frozen(ssh, 1);
6932 s->dlgret = askalg(ssh->frontend,
6933 "client-to-server cipher",
6934 s->cscipher_tobe->name,
6935 ssh_dialog_callback, ssh);
6936 if (s->dlgret < 0) {
6940 bombout(("Unexpected data from server while"
6941 " waiting for user response"));
6944 } while (pktin || inlen > 0);
6945 s->dlgret = ssh->user_response;
6947 ssh_set_frozen(ssh, 0);
6948 if (s->dlgret == 0) {
6949 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6955 if (s->warn_sccipher) {
6956 ssh_set_frozen(ssh, 1);
6957 s->dlgret = askalg(ssh->frontend,
6958 "server-to-client cipher",
6959 s->sccipher_tobe->name,
6960 ssh_dialog_callback, ssh);
6961 if (s->dlgret < 0) {
6965 bombout(("Unexpected data from server while"
6966 " waiting for user response"));
6969 } while (pktin || inlen > 0);
6970 s->dlgret = ssh->user_response;
6972 ssh_set_frozen(ssh, 0);
6973 if (s->dlgret == 0) {
6974 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6980 if (s->ignorepkt) /* first_kex_packet_follows */
6981 crWaitUntilV(pktin); /* Ignore packet */
6984 if (ssh->kex->main_type == KEXTYPE_DH) {
6986 * Work out the number of bits of key we will need from the
6987 * key exchange. We start with the maximum key length of
6993 csbits = s->cscipher_tobe ? s->cscipher_tobe->real_keybits : 0;
6994 scbits = s->sccipher_tobe ? s->sccipher_tobe->real_keybits : 0;
6995 s->nbits = (csbits > scbits ? csbits : scbits);
6997 /* The keys only have hlen-bit entropy, since they're based on
6998 * a hash. So cap the key size at hlen bits. */
6999 if (s->nbits > ssh->kex->hash->hlen * 8)
7000 s->nbits = ssh->kex->hash->hlen * 8;
7003 * If we're doing Diffie-Hellman group exchange, start by
7004 * requesting a group.
7006 if (dh_is_gex(ssh->kex)) {
7007 logevent("Doing Diffie-Hellman group exchange");
7008 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
7010 * Work out how big a DH group we will need to allow that
7013 s->pbits = 512 << ((s->nbits - 1) / 64);
7014 if (s->pbits < DH_MIN_SIZE)
7015 s->pbits = DH_MIN_SIZE;
7016 if (s->pbits > DH_MAX_SIZE)
7017 s->pbits = DH_MAX_SIZE;
7018 if ((ssh->remote_bugs & BUG_SSH2_OLDGEX)) {
7019 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD);
7020 ssh2_pkt_adduint32(s->pktout, s->pbits);
7022 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
7023 ssh2_pkt_adduint32(s->pktout, DH_MIN_SIZE);
7024 ssh2_pkt_adduint32(s->pktout, s->pbits);
7025 ssh2_pkt_adduint32(s->pktout, DH_MAX_SIZE);
7027 ssh2_pkt_send_noqueue(ssh, s->pktout);
7029 crWaitUntilV(pktin);
7030 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
7031 bombout(("expected key exchange group packet from server"));
7034 s->p = ssh2_pkt_getmp(pktin);
7035 s->g = ssh2_pkt_getmp(pktin);
7036 if (!s->p || !s->g) {
7037 bombout(("unable to read mp-ints from incoming group packet"));
7040 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
7041 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
7042 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
7044 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
7045 ssh->kex_ctx = dh_setup_group(ssh->kex);
7046 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
7047 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
7048 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
7049 ssh->kex->groupname);
7052 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
7053 ssh->kex->hash->text_name);
7055 * Now generate and send e for Diffie-Hellman.
7057 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
7058 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
7059 s->pktout = ssh2_pkt_init(s->kex_init_value);
7060 ssh2_pkt_addmp(s->pktout, s->e);
7061 ssh2_pkt_send_noqueue(ssh, s->pktout);
7063 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
7064 crWaitUntilV(pktin);
7065 if (pktin->type != s->kex_reply_value) {
7066 bombout(("expected key exchange reply packet from server"));
7069 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
7070 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7071 if (!s->hostkeydata) {
7072 bombout(("unable to parse key exchange reply packet"));
7075 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7076 s->hostkeydata, s->hostkeylen);
7077 s->f = ssh2_pkt_getmp(pktin);
7079 bombout(("unable to parse key exchange reply packet"));
7082 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7084 bombout(("unable to parse key exchange reply packet"));
7089 const char *err = dh_validate_f(ssh->kex_ctx, s->f);
7091 bombout(("key exchange reply failed validation: %s", err));
7095 s->K = dh_find_K(ssh->kex_ctx, s->f);
7097 /* We assume everything from now on will be quick, and it might
7098 * involve user interaction. */
7099 set_busy_status(ssh->frontend, BUSY_NOT);
7101 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
7102 if (dh_is_gex(ssh->kex)) {
7103 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
7104 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MIN_SIZE);
7105 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
7106 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
7107 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MAX_SIZE);
7108 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
7109 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
7111 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
7112 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
7114 dh_cleanup(ssh->kex_ctx);
7116 if (dh_is_gex(ssh->kex)) {
7120 } else if (ssh->kex->main_type == KEXTYPE_ECDH) {
7122 logeventf(ssh, "Doing ECDH key exchange with curve %s and hash %s",
7123 ssh_ecdhkex_curve_textname(ssh->kex),
7124 ssh->kex->hash->text_name);
7125 ssh->pkt_kctx = SSH2_PKTCTX_ECDHKEX;
7127 s->eckey = ssh_ecdhkex_newkey(ssh->kex);
7129 bombout(("Unable to generate key for ECDH"));
7135 int publicPointLength;
7136 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
7138 ssh_ecdhkex_freekey(s->eckey);
7139 bombout(("Unable to encode public key for ECDH"));
7142 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_ECDH_INIT);
7143 ssh2_pkt_addstring_start(s->pktout);
7144 ssh2_pkt_addstring_data(s->pktout, publicPoint, publicPointLength);
7148 ssh2_pkt_send_noqueue(ssh, s->pktout);
7150 crWaitUntilV(pktin);
7151 if (pktin->type != SSH2_MSG_KEX_ECDH_REPLY) {
7152 ssh_ecdhkex_freekey(s->eckey);
7153 bombout(("expected ECDH reply packet from server"));
7157 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7158 if (!s->hostkeydata) {
7159 bombout(("unable to parse ECDH reply packet"));
7162 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
7163 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7164 s->hostkeydata, s->hostkeylen);
7168 int publicPointLength;
7169 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
7171 ssh_ecdhkex_freekey(s->eckey);
7172 bombout(("Unable to encode public key for ECDH hash"));
7175 hash_string(ssh->kex->hash, ssh->exhash,
7176 publicPoint, publicPointLength);
7183 ssh_pkt_getstring(pktin, &keydata, &keylen);
7185 bombout(("unable to parse ECDH reply packet"));
7188 hash_string(ssh->kex->hash, ssh->exhash, keydata, keylen);
7189 s->K = ssh_ecdhkex_getkey(s->eckey, keydata, keylen);
7191 ssh_ecdhkex_freekey(s->eckey);
7192 bombout(("point received in ECDH was not valid"));
7197 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7199 bombout(("unable to parse key exchange reply packet"));
7203 ssh_ecdhkex_freekey(s->eckey);
7205 logeventf(ssh, "Doing RSA key exchange with hash %s",
7206 ssh->kex->hash->text_name);
7207 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
7209 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
7212 crWaitUntilV(pktin);
7213 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
7214 bombout(("expected RSA public key packet from server"));
7218 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7219 if (!s->hostkeydata) {
7220 bombout(("unable to parse RSA public key packet"));
7223 hash_string(ssh->kex->hash, ssh->exhash,
7224 s->hostkeydata, s->hostkeylen);
7225 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7226 s->hostkeydata, s->hostkeylen);
7230 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
7232 bombout(("unable to parse RSA public key packet"));
7235 s->rsakeydata = snewn(s->rsakeylen, char);
7236 memcpy(s->rsakeydata, keydata, s->rsakeylen);
7239 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
7241 sfree(s->rsakeydata);
7242 bombout(("unable to parse RSA public key from server"));
7246 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
7249 * Next, set up a shared secret K, of precisely KLEN -
7250 * 2*HLEN - 49 bits, where KLEN is the bit length of the
7251 * RSA key modulus and HLEN is the bit length of the hash
7255 int klen = ssh_rsakex_klen(s->rsakey);
7256 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
7258 unsigned char *kstr1, *kstr2, *outstr;
7259 int kstr1len, kstr2len, outstrlen;
7261 s->K = bn_power_2(nbits - 1);
7263 for (i = 0; i < nbits; i++) {
7265 byte = random_byte();
7267 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
7271 * Encode this as an mpint.
7273 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
7274 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
7275 PUT_32BIT(kstr2, kstr1len);
7276 memcpy(kstr2 + 4, kstr1, kstr1len);
7279 * Encrypt it with the given RSA key.
7281 outstrlen = (klen + 7) / 8;
7282 outstr = snewn(outstrlen, unsigned char);
7283 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
7284 outstr, outstrlen, s->rsakey);
7287 * And send it off in a return packet.
7289 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
7290 ssh2_pkt_addstring_start(s->pktout);
7291 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
7292 ssh2_pkt_send_noqueue(ssh, s->pktout);
7294 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
7301 ssh_rsakex_freekey(s->rsakey);
7303 crWaitUntilV(pktin);
7304 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
7305 sfree(s->rsakeydata);
7306 bombout(("expected signature packet from server"));
7310 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7312 bombout(("unable to parse signature packet"));
7316 sfree(s->rsakeydata);
7319 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
7320 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
7321 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
7323 ssh->kex_ctx = NULL;
7326 debug(("Exchange hash is:\n"));
7327 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
7331 bombout(("Server's host key is invalid"));
7335 if (!ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
7336 (char *)s->exchange_hash,
7337 ssh->kex->hash->hlen)) {
7339 bombout(("Server's host key did not match the signature supplied"));
7344 s->keystr = ssh->hostkey->fmtkey(s->hkey);
7345 if (!s->got_session_id) {
7347 * Make a note of any other host key formats that are available.
7350 int i, j, nkeys = 0;
7352 for (i = 0; i < lenof(hostkey_algs); i++) {
7353 if (hostkey_algs[i].alg == ssh->hostkey)
7356 for (j = 0; j < ssh->n_uncert_hostkeys; j++)
7357 if (ssh->uncert_hostkeys[j] == i)
7360 if (j < ssh->n_uncert_hostkeys) {
7363 newlist = dupprintf("%s/%s", list,
7364 hostkey_algs[i].alg->name);
7366 newlist = dupprintf("%s", hostkey_algs[i].alg->name);
7374 "Server also has %s host key%s, but we "
7375 "don't know %s", list,
7376 nkeys > 1 ? "s" : "",
7377 nkeys > 1 ? "any of them" : "it");
7383 * Authenticate remote host: verify host key. (We've already
7384 * checked the signature of the exchange hash.)
7386 s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
7387 logevent("Host key fingerprint is:");
7388 logevent(s->fingerprint);
7389 /* First check against manually configured host keys. */
7390 s->dlgret = verify_ssh_manual_host_key(ssh, s->fingerprint,
7391 ssh->hostkey, s->hkey);
7392 if (s->dlgret == 0) { /* did not match */
7393 bombout(("Host key did not appear in manually configured list"));
7395 } else if (s->dlgret < 0) { /* none configured; use standard handling */
7396 ssh_set_frozen(ssh, 1);
7397 s->dlgret = verify_ssh_host_key(ssh->frontend,
7398 ssh->savedhost, ssh->savedport,
7399 ssh->hostkey->keytype, s->keystr,
7401 ssh_dialog_callback, ssh);
7405 if (s->dlgret < 0) {
7409 bombout(("Unexpected data from server while waiting"
7410 " for user host key response"));
7413 } while (pktin || inlen > 0);
7414 s->dlgret = ssh->user_response;
7416 ssh_set_frozen(ssh, 0);
7417 if (s->dlgret == 0) {
7418 ssh_disconnect(ssh, "Aborted at host key verification", NULL,
7423 sfree(s->fingerprint);
7425 * Save this host key, to check against the one presented in
7426 * subsequent rekeys.
7428 ssh->hostkey_str = s->keystr;
7429 } else if (ssh->cross_certifying) {
7430 s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
7431 logevent("Storing additional host key for this host:");
7432 logevent(s->fingerprint);
7433 sfree(s->fingerprint);
7434 store_host_key(ssh->savedhost, ssh->savedport,
7435 ssh->hostkey->keytype, s->keystr);
7436 ssh->cross_certifying = FALSE;
7438 * Don't forget to store the new key as the one we'll be
7439 * re-checking in future normal rekeys.
7441 ssh->hostkey_str = s->keystr;
7444 * In a rekey, we never present an interactive host key
7445 * verification request to the user. Instead, we simply
7446 * enforce that the key we're seeing this time is identical to
7447 * the one we saw before.
7449 if (strcmp(ssh->hostkey_str, s->keystr)) {
7451 bombout(("Host key was different in repeat key exchange"));
7457 ssh->hostkey->freekey(s->hkey);
7460 * The exchange hash from the very first key exchange is also
7461 * the session id, used in session key construction and
7464 if (!s->got_session_id) {
7465 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
7466 memcpy(ssh->v2_session_id, s->exchange_hash,
7467 sizeof(s->exchange_hash));
7468 ssh->v2_session_id_len = ssh->kex->hash->hlen;
7469 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
7470 s->got_session_id = TRUE;
7474 * Send SSH2_MSG_NEWKEYS.
7476 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
7477 ssh2_pkt_send_noqueue(ssh, s->pktout);
7478 ssh->outgoing_data_size = 0; /* start counting from here */
7481 * We've sent client NEWKEYS, so create and initialise
7482 * client-to-server session keys.
7484 if (ssh->cs_cipher_ctx)
7485 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
7486 ssh->cscipher = s->cscipher_tobe;
7487 if (ssh->cscipher) ssh->cs_cipher_ctx = ssh->cscipher->make_context();
7489 if (ssh->cs_mac_ctx)
7490 ssh->csmac->free_context(ssh->cs_mac_ctx);
7491 ssh->csmac = s->csmac_tobe;
7492 ssh->csmac_etm = s->csmac_etm_tobe;
7494 ssh->cs_mac_ctx = ssh->csmac->make_context(ssh->cs_cipher_ctx);
7496 if (ssh->cs_comp_ctx)
7497 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
7498 ssh->cscomp = s->cscomp_tobe;
7499 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
7502 * Set IVs on client-to-server keys. Here we use the exchange
7503 * hash from the _first_ key exchange.
7505 if (ssh->cscipher) {
7508 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'C',
7509 ssh->cscipher->padded_keybytes);
7510 ssh->cscipher->setkey(ssh->cs_cipher_ctx, key);
7511 smemclr(key, ssh->cscipher->padded_keybytes);
7514 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'A',
7515 ssh->cscipher->blksize);
7516 ssh->cscipher->setiv(ssh->cs_cipher_ctx, key);
7517 smemclr(key, ssh->cscipher->blksize);
7523 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'E',
7524 ssh->csmac->keylen);
7525 ssh->csmac->setkey(ssh->cs_mac_ctx, key);
7526 smemclr(key, ssh->csmac->keylen);
7531 logeventf(ssh, "Initialised %.200s client->server encryption",
7532 ssh->cscipher->text_name);
7534 logeventf(ssh, "Initialised %.200s client->server MAC algorithm%s%s",
7535 ssh->csmac->text_name,
7536 ssh->csmac_etm ? " (in ETM mode)" : "",
7537 ssh->cscipher->required_mac ? " (required by cipher)" : "");
7538 if (ssh->cscomp->text_name)
7539 logeventf(ssh, "Initialised %s compression",
7540 ssh->cscomp->text_name);
7543 * Now our end of the key exchange is complete, we can send all
7544 * our queued higher-layer packets.
7546 ssh->queueing = FALSE;
7547 ssh2_pkt_queuesend(ssh);
7550 * Expect SSH2_MSG_NEWKEYS from server.
7552 crWaitUntilV(pktin);
7553 if (pktin->type != SSH2_MSG_NEWKEYS) {
7554 bombout(("expected new-keys packet from server"));
7557 ssh->incoming_data_size = 0; /* start counting from here */
7560 * We've seen server NEWKEYS, so create and initialise
7561 * server-to-client session keys.
7563 if (ssh->sc_cipher_ctx)
7564 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
7565 if (s->sccipher_tobe) {
7566 ssh->sccipher = s->sccipher_tobe;
7567 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
7570 if (ssh->sc_mac_ctx)
7571 ssh->scmac->free_context(ssh->sc_mac_ctx);
7572 if (s->scmac_tobe) {
7573 ssh->scmac = s->scmac_tobe;
7574 ssh->scmac_etm = s->scmac_etm_tobe;
7575 ssh->sc_mac_ctx = ssh->scmac->make_context(ssh->sc_cipher_ctx);
7578 if (ssh->sc_comp_ctx)
7579 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
7580 ssh->sccomp = s->sccomp_tobe;
7581 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
7584 * Set IVs on server-to-client keys. Here we use the exchange
7585 * hash from the _first_ key exchange.
7587 if (ssh->sccipher) {
7590 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'D',
7591 ssh->sccipher->padded_keybytes);
7592 ssh->sccipher->setkey(ssh->sc_cipher_ctx, key);
7593 smemclr(key, ssh->sccipher->padded_keybytes);
7596 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'B',
7597 ssh->sccipher->blksize);
7598 ssh->sccipher->setiv(ssh->sc_cipher_ctx, key);
7599 smemclr(key, ssh->sccipher->blksize);
7605 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'F',
7606 ssh->scmac->keylen);
7607 ssh->scmac->setkey(ssh->sc_mac_ctx, key);
7608 smemclr(key, ssh->scmac->keylen);
7612 logeventf(ssh, "Initialised %.200s server->client encryption",
7613 ssh->sccipher->text_name);
7615 logeventf(ssh, "Initialised %.200s server->client MAC algorithm%s%s",
7616 ssh->scmac->text_name,
7617 ssh->scmac_etm ? " (in ETM mode)" : "",
7618 ssh->sccipher->required_mac ? " (required by cipher)" : "");
7619 if (ssh->sccomp->text_name)
7620 logeventf(ssh, "Initialised %s decompression",
7621 ssh->sccomp->text_name);
7624 * Free shared secret.
7629 * Update the specials menu to list the remaining uncertified host
7632 update_specials_menu(ssh->frontend);
7635 * Key exchange is over. Loop straight back round if we have a
7636 * deferred rekey reason.
7638 if (ssh->deferred_rekey_reason) {
7639 logevent(ssh->deferred_rekey_reason);
7641 ssh->deferred_rekey_reason = NULL;
7642 goto begin_key_exchange;
7646 * Otherwise, schedule a timer for our next rekey.
7648 ssh->kex_in_progress = FALSE;
7649 ssh->last_rekey = GETTICKCOUNT();
7650 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
7651 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7655 * Now we're encrypting. Begin returning 1 to the protocol main
7656 * function so that other things can run on top of the
7657 * transport. If we ever see a KEXINIT, we must go back to the
7660 * We _also_ go back to the start if we see pktin==NULL and
7661 * inlen negative, because this is a special signal meaning
7662 * `initiate client-driven rekey', and `in' contains a message
7663 * giving the reason for the rekey.
7665 * inlen==-1 means always initiate a rekey;
7666 * inlen==-2 means that userauth has completed successfully and
7667 * we should consider rekeying (for delayed compression).
7669 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
7670 (!pktin && inlen < 0))) {
7672 if (!ssh->protocol_initial_phase_done) {
7673 ssh->protocol_initial_phase_done = TRUE;
7675 * Allow authconn to initialise itself.
7677 do_ssh2_authconn(ssh, NULL, 0, NULL);
7682 logevent("Server initiated key re-exchange");
7686 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
7687 * delayed compression, if it's available.
7689 * draft-miller-secsh-compression-delayed-00 says that you
7690 * negotiate delayed compression in the first key exchange, and
7691 * both sides start compressing when the server has sent
7692 * USERAUTH_SUCCESS. This has a race condition -- the server
7693 * can't know when the client has seen it, and thus which incoming
7694 * packets it should treat as compressed.
7696 * Instead, we do the initial key exchange without offering the
7697 * delayed methods, but note if the server offers them; when we
7698 * get here, if a delayed method was available that was higher
7699 * on our list than what we got, we initiate a rekey in which we
7700 * _do_ list the delayed methods (and hopefully get it as a
7701 * result). Subsequent rekeys will do the same.
7703 assert(!s->userauth_succeeded); /* should only happen once */
7704 s->userauth_succeeded = TRUE;
7705 if (!s->pending_compression)
7706 /* Can't see any point rekeying. */
7707 goto wait_for_rekey; /* this is utterly horrid */
7708 /* else fall through to rekey... */
7709 s->pending_compression = FALSE;
7712 * Now we've decided to rekey.
7714 * Special case: if the server bug is set that doesn't
7715 * allow rekeying, we give a different log message and
7716 * continue waiting. (If such a server _initiates_ a rekey,
7717 * we process it anyway!)
7719 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
7720 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
7722 /* Reset the counters, so that at least this message doesn't
7723 * hit the event log _too_ often. */
7724 ssh->outgoing_data_size = 0;
7725 ssh->incoming_data_size = 0;
7726 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
7728 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7731 goto wait_for_rekey; /* this is still utterly horrid */
7733 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
7736 goto begin_key_exchange;
7742 * Send data on an SSH channel. In SSH-2, this involves buffering it
7745 static int ssh_send_channel_data(struct ssh_channel *c, const char *buf,
7748 if (c->ssh->version == 2) {
7749 bufchain_add(&c->v.v2.outbuffer, buf, len);
7750 return ssh2_try_send(c);
7752 send_packet(c->ssh, SSH1_MSG_CHANNEL_DATA,
7753 PKT_INT, c->remoteid,
7758 * In SSH-1 we can return 0 here - implying that channels are
7759 * never individually throttled - because the only
7760 * circumstance that can cause throttling will be the whole
7761 * SSH connection backing up, in which case _everything_ will
7762 * be throttled as a whole.
7769 * Attempt to send data on an SSH-2 channel.
7771 static int ssh2_try_send(struct ssh_channel *c)
7774 struct Packet *pktout;
7777 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
7780 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
7781 if ((unsigned)len > c->v.v2.remwindow)
7782 len = c->v.v2.remwindow;
7783 if ((unsigned)len > c->v.v2.remmaxpkt)
7784 len = c->v.v2.remmaxpkt;
7785 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
7786 ssh2_pkt_adduint32(pktout, c->remoteid);
7787 ssh2_pkt_addstring_start(pktout);
7788 ssh2_pkt_addstring_data(pktout, data, len);
7789 ssh2_pkt_send(ssh, pktout);
7790 bufchain_consume(&c->v.v2.outbuffer, len);
7791 c->v.v2.remwindow -= len;
7795 * After having sent as much data as we can, return the amount
7798 ret = bufchain_size(&c->v.v2.outbuffer);
7801 * And if there's no data pending but we need to send an EOF, send
7804 if (!ret && c->pending_eof)
7805 ssh_channel_try_eof(c);
7810 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
7813 if (c->closes & CLOSES_SENT_EOF)
7814 return; /* don't send on channels we've EOFed */
7815 bufsize = ssh2_try_send(c);
7818 case CHAN_MAINSESSION:
7819 /* stdin need not receive an unthrottle
7820 * notification since it will be polled */
7823 x11_unthrottle(c->u.x11.xconn);
7826 /* Now that we've successfully sent all the outgoing
7827 * replies we had, try to process more incoming data. */
7828 ssh_agentf_try_forward(c);
7831 pfd_unthrottle(c->u.pfd.pf);
7837 static int ssh_is_simple(Ssh ssh)
7840 * We use the 'simple' variant of the SSH protocol if we're asked
7841 * to, except not if we're also doing connection-sharing (either
7842 * tunnelling our packets over an upstream or expecting to be
7843 * tunnelled over ourselves), since then the assumption that we
7844 * have only one channel to worry about is not true after all.
7846 return (conf_get_int(ssh->conf, CONF_ssh_simple) &&
7847 !ssh->bare_connection && !ssh->connshare);
7851 * Set up most of a new ssh_channel.
7853 static void ssh_channel_init(struct ssh_channel *c)
7856 c->localid = alloc_channel_id(ssh);
7858 c->pending_eof = FALSE;
7859 c->throttling_conn = FALSE;
7860 if (ssh->version == 2) {
7861 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
7862 ssh_is_simple(ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
7863 c->v.v2.chanreq_head = NULL;
7864 c->v.v2.throttle_state = UNTHROTTLED;
7865 bufchain_init(&c->v.v2.outbuffer);
7867 add234(ssh->channels, c);
7871 * Construct the common parts of a CHANNEL_OPEN.
7873 static struct Packet *ssh2_chanopen_init(struct ssh_channel *c,
7876 struct Packet *pktout;
7878 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7879 ssh2_pkt_addstring(pktout, type);
7880 ssh2_pkt_adduint32(pktout, c->localid);
7881 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
7882 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7887 * CHANNEL_FAILURE doesn't come with any indication of what message
7888 * caused it, so we have to keep track of the outstanding
7889 * CHANNEL_REQUESTs ourselves.
7891 static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
7892 cchandler_fn_t handler, void *ctx)
7894 struct outstanding_channel_request *ocr =
7895 snew(struct outstanding_channel_request);
7897 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7898 ocr->handler = handler;
7901 if (!c->v.v2.chanreq_head)
7902 c->v.v2.chanreq_head = ocr;
7904 c->v.v2.chanreq_tail->next = ocr;
7905 c->v.v2.chanreq_tail = ocr;
7909 * Construct the common parts of a CHANNEL_REQUEST. If handler is not
7910 * NULL then a reply will be requested and the handler will be called
7911 * when it arrives. The returned packet is ready to have any
7912 * request-specific data added and be sent. Note that if a handler is
7913 * provided, it's essential that the request actually be sent.
7915 * The handler will usually be passed the response packet in pktin. If
7916 * pktin is NULL, this means that no reply will ever be forthcoming
7917 * (e.g. because the entire connection is being destroyed, or because
7918 * the server initiated channel closure before we saw the response)
7919 * and the handler should free any storage it's holding.
7921 static struct Packet *ssh2_chanreq_init(struct ssh_channel *c,
7923 cchandler_fn_t handler, void *ctx)
7925 struct Packet *pktout;
7927 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7928 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7929 ssh2_pkt_adduint32(pktout, c->remoteid);
7930 ssh2_pkt_addstring(pktout, type);
7931 ssh2_pkt_addbool(pktout, handler != NULL);
7932 if (handler != NULL)
7933 ssh2_queue_chanreq_handler(c, handler, ctx);
7937 static void ssh_channel_unthrottle(struct ssh_channel *c, int bufsize)
7942 if (ssh->version == 1) {
7943 buflimit = SSH1_BUFFER_LIMIT;
7945 if (ssh_is_simple(ssh))
7948 buflimit = c->v.v2.locmaxwin;
7949 if (bufsize < buflimit)
7950 ssh2_set_window(c, buflimit - bufsize);
7952 if (c->throttling_conn && bufsize <= buflimit) {
7953 c->throttling_conn = 0;
7954 ssh_throttle_conn(ssh, -1);
7959 * Potentially enlarge the window on an SSH-2 channel.
7961 static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
7963 static void ssh2_set_window(struct ssh_channel *c, int newwin)
7968 * Never send WINDOW_ADJUST for a channel that the remote side has
7969 * already sent EOF on; there's no point, since it won't be
7970 * sending any more data anyway. Ditto if _we've_ already sent
7973 if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
7977 * Also, never widen the window for an X11 channel when we're
7978 * still waiting to see its initial auth and may yet hand it off
7981 if (c->type == CHAN_X11 && c->u.x11.initial)
7985 * If the remote end has a habit of ignoring maxpkt, limit the
7986 * window so that it has no choice (assuming it doesn't ignore the
7989 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
7990 newwin = OUR_V2_MAXPKT;
7993 * Only send a WINDOW_ADJUST if there's significantly more window
7994 * available than the other end thinks there is. This saves us
7995 * sending a WINDOW_ADJUST for every character in a shell session.
7997 * "Significant" is arbitrarily defined as half the window size.
7999 if (newwin / 2 >= c->v.v2.locwindow) {
8000 struct Packet *pktout;
8004 * In order to keep track of how much window the client
8005 * actually has available, we'd like it to acknowledge each
8006 * WINDOW_ADJUST. We can't do that directly, so we accompany
8007 * it with a CHANNEL_REQUEST that has to be acknowledged.
8009 * This is only necessary if we're opening the window wide.
8010 * If we're not, then throughput is being constrained by
8011 * something other than the maximum window size anyway.
8013 if (newwin == c->v.v2.locmaxwin &&
8014 !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
8015 up = snew(unsigned);
8016 *up = newwin - c->v.v2.locwindow;
8017 pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org",
8018 ssh2_handle_winadj_response, up);
8019 ssh2_pkt_send(ssh, pktout);
8021 if (c->v.v2.throttle_state != UNTHROTTLED)
8022 c->v.v2.throttle_state = UNTHROTTLING;
8024 /* Pretend the WINDOW_ADJUST was acked immediately. */
8025 c->v.v2.remlocwin = newwin;
8026 c->v.v2.throttle_state = THROTTLED;
8028 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
8029 ssh2_pkt_adduint32(pktout, c->remoteid);
8030 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
8031 ssh2_pkt_send(ssh, pktout);
8032 c->v.v2.locwindow = newwin;
8037 * Find the channel associated with a message. If there's no channel,
8038 * or it's not properly open, make a noise about it and return NULL.
8039 * If the channel is shared, pass the message on to downstream and
8040 * also return NULL (meaning the caller should ignore this message).
8042 static struct ssh_channel *ssh_channel_msg(Ssh ssh, struct Packet *pktin)
8044 unsigned localid = ssh_pkt_getuint32(pktin);
8045 struct ssh_channel *c;
8048 /* Is this message OK on a half-open connection? */
8049 if (ssh->version == 1)
8050 halfopen_ok = (pktin->type == SSH1_MSG_CHANNEL_OPEN_CONFIRMATION ||
8051 pktin->type == SSH1_MSG_CHANNEL_OPEN_FAILURE);
8053 halfopen_ok = (pktin->type == SSH2_MSG_CHANNEL_OPEN_CONFIRMATION ||
8054 pktin->type == SSH2_MSG_CHANNEL_OPEN_FAILURE);
8055 c = find234(ssh->channels, &localid, ssh_channelfind);
8056 if (!c || (c->type != CHAN_SHARING && (c->halfopen != halfopen_ok))) {
8057 char *buf = dupprintf("Received %s for %s channel %u",
8058 ssh_pkt_type(ssh, pktin->type),
8059 !c ? "nonexistent" :
8060 c->halfopen ? "half-open" : "open",
8062 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
8066 if (c->type == CHAN_SHARING) {
8067 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8068 pktin->body, pktin->length);
8074 static void ssh2_handle_winadj_response(struct ssh_channel *c,
8075 struct Packet *pktin, void *ctx)
8077 unsigned *sizep = ctx;
8080 * Winadj responses should always be failures. However, at least
8081 * one server ("boks_sshd") is known to return SUCCESS for channel
8082 * requests it's never heard of, such as "winadj@putty". Raised
8083 * with foxt.com as bug 090916-090424, but for the sake of a quiet
8084 * life, we don't worry about what kind of response we got.
8087 c->v.v2.remlocwin += *sizep;
8090 * winadj messages are only sent when the window is fully open, so
8091 * if we get an ack of one, we know any pending unthrottle is
8094 if (c->v.v2.throttle_state == UNTHROTTLING)
8095 c->v.v2.throttle_state = UNTHROTTLED;
8098 static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
8100 struct ssh_channel *c = ssh_channel_msg(ssh, pktin);
8101 struct outstanding_channel_request *ocr;
8104 ocr = c->v.v2.chanreq_head;
8106 ssh2_msg_unexpected(ssh, pktin);
8109 ocr->handler(c, pktin, ocr->ctx);
8110 c->v.v2.chanreq_head = ocr->next;
8113 * We may now initiate channel-closing procedures, if that
8114 * CHANNEL_REQUEST was the last thing outstanding before we send
8117 ssh2_channel_check_close(c);
8120 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
8122 struct ssh_channel *c;
8123 c = ssh_channel_msg(ssh, pktin);
8126 if (!(c->closes & CLOSES_SENT_EOF)) {
8127 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
8128 ssh2_try_send_and_unthrottle(ssh, c);
8132 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
8136 unsigned ext_type = 0; /* 0 means not extended */
8137 struct ssh_channel *c;
8138 c = ssh_channel_msg(ssh, pktin);
8141 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
8142 ext_type = ssh_pkt_getuint32(pktin);
8143 ssh_pkt_getstring(pktin, &data, &length);
8146 c->v.v2.locwindow -= length;
8147 c->v.v2.remlocwin -= length;
8148 if (ext_type != 0 && ext_type != SSH2_EXTENDED_DATA_STDERR)
8149 length = 0; /* Don't do anything with unknown extended data. */
8150 bufsize = ssh_channel_data(c, ext_type == SSH2_EXTENDED_DATA_STDERR,
8153 * If it looks like the remote end hit the end of its window,
8154 * and we didn't want it to do that, think about using a
8157 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
8158 c->v.v2.locmaxwin < 0x40000000)
8159 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
8161 * If we are not buffering too much data,
8162 * enlarge the window again at the remote side.
8163 * If we are buffering too much, we may still
8164 * need to adjust the window if the server's
8167 if (bufsize < c->v.v2.locmaxwin)
8168 ssh2_set_window(c, c->v.v2.locmaxwin - bufsize);
8170 * If we're either buffering way too much data, or if we're
8171 * buffering anything at all and we're in "simple" mode,
8172 * throttle the whole channel.
8174 if ((bufsize > c->v.v2.locmaxwin || (ssh_is_simple(ssh) && bufsize>0))
8175 && !c->throttling_conn) {
8176 c->throttling_conn = 1;
8177 ssh_throttle_conn(ssh, +1);
8182 static void ssh_check_termination(Ssh ssh)
8184 if (ssh->version == 2 &&
8185 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
8186 (ssh->channels && count234(ssh->channels) == 0) &&
8187 !(ssh->connshare && share_ndownstreams(ssh->connshare) > 0)) {
8189 * We used to send SSH_MSG_DISCONNECT here, because I'd
8190 * believed that _every_ conforming SSH-2 connection had to
8191 * end with a disconnect being sent by at least one side;
8192 * apparently I was wrong and it's perfectly OK to
8193 * unceremoniously slam the connection shut when you're done,
8194 * and indeed OpenSSH feels this is more polite than sending a
8195 * DISCONNECT. So now we don't.
8197 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
8201 void ssh_sharing_downstream_connected(Ssh ssh, unsigned id,
8202 const char *peerinfo)
8205 logeventf(ssh, "Connection sharing downstream #%u connected from %s",
8208 logeventf(ssh, "Connection sharing downstream #%u connected", id);
8211 void ssh_sharing_downstream_disconnected(Ssh ssh, unsigned id)
8213 logeventf(ssh, "Connection sharing downstream #%u disconnected", id);
8214 ssh_check_termination(ssh);
8217 void ssh_sharing_logf(Ssh ssh, unsigned id, const char *logfmt, ...)
8222 va_start(ap, logfmt);
8223 buf = dupvprintf(logfmt, ap);
8226 logeventf(ssh, "Connection sharing downstream #%u: %s", id, buf);
8228 logeventf(ssh, "Connection sharing: %s", buf);
8233 * Close any local socket and free any local resources associated with
8234 * a channel. This converts the channel into a CHAN_ZOMBIE.
8236 static void ssh_channel_close_local(struct ssh_channel *c, char const *reason)
8239 char const *msg = NULL;
8242 case CHAN_MAINSESSION:
8243 ssh->mainchan = NULL;
8244 update_specials_menu(ssh->frontend);
8247 assert(c->u.x11.xconn != NULL);
8248 x11_close(c->u.x11.xconn);
8249 msg = "Forwarded X11 connection terminated";
8253 agent_cancel_query(c->u.a.pending);
8254 bufchain_clear(&c->u.a.inbuffer);
8255 msg = "Agent-forwarding connection closed";
8258 assert(c->u.pfd.pf != NULL);
8259 pfd_close(c->u.pfd.pf);
8260 msg = "Forwarded port closed";
8263 c->type = CHAN_ZOMBIE;
8266 logeventf(ssh, "%s %s", msg, reason);
8272 static void ssh_channel_destroy(struct ssh_channel *c)
8276 ssh_channel_close_local(c, NULL);
8278 del234(ssh->channels, c);
8279 if (ssh->version == 2) {
8280 bufchain_clear(&c->v.v2.outbuffer);
8281 assert(c->v.v2.chanreq_head == NULL);
8286 * If that was the last channel left open, we might need to
8289 ssh_check_termination(ssh);
8292 static void ssh2_channel_check_close(struct ssh_channel *c)
8295 struct Packet *pktout;
8297 assert(ssh->version == 2);
8300 * If we've sent out our own CHANNEL_OPEN but not yet seen
8301 * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
8302 * it's too early to be sending close messages of any kind.
8307 if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
8308 c->type == CHAN_ZOMBIE) &&
8309 !c->v.v2.chanreq_head &&
8310 !(c->closes & CLOSES_SENT_CLOSE)) {
8312 * We have both sent and received EOF (or the channel is a
8313 * zombie), and we have no outstanding channel requests, which
8314 * means the channel is in final wind-up. But we haven't sent
8315 * CLOSE, so let's do so now.
8317 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
8318 ssh2_pkt_adduint32(pktout, c->remoteid);
8319 ssh2_pkt_send(ssh, pktout);
8320 c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
8323 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
8324 assert(c->v.v2.chanreq_head == NULL);
8326 * We have both sent and received CLOSE, which means we're
8327 * completely done with the channel.
8329 ssh_channel_destroy(c);
8333 static void ssh_channel_got_eof(struct ssh_channel *c)
8335 if (c->closes & CLOSES_RCVD_EOF)
8336 return; /* already seen EOF */
8337 c->closes |= CLOSES_RCVD_EOF;
8339 if (c->type == CHAN_X11) {
8340 assert(c->u.x11.xconn != NULL);
8341 x11_send_eof(c->u.x11.xconn);
8342 } else if (c->type == CHAN_AGENT) {
8343 /* Just call try_forward, which will respond to the EOF now if
8344 * appropriate, or wait until the queue of outstanding
8345 * requests is dealt with if not */
8346 ssh_agentf_try_forward(c);
8347 } else if (c->type == CHAN_SOCKDATA) {
8348 assert(c->u.pfd.pf != NULL);
8349 pfd_send_eof(c->u.pfd.pf);
8350 } else if (c->type == CHAN_MAINSESSION) {
8353 if (!ssh->sent_console_eof &&
8354 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
8356 * Either from_backend_eof told us that the front end
8357 * wants us to close the outgoing side of the connection
8358 * as soon as we see EOF from the far end, or else we've
8359 * unilaterally decided to do that because we've allocated
8360 * a remote pty and hence EOF isn't a particularly
8361 * meaningful concept.
8363 sshfwd_write_eof(c);
8365 ssh->sent_console_eof = TRUE;
8369 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
8371 struct ssh_channel *c;
8373 c = ssh_channel_msg(ssh, pktin);
8376 ssh_channel_got_eof(c);
8377 ssh2_channel_check_close(c);
8380 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
8382 struct ssh_channel *c;
8384 c = ssh_channel_msg(ssh, pktin);
8389 * When we receive CLOSE on a channel, we assume it comes with an
8390 * implied EOF if we haven't seen EOF yet.
8392 ssh_channel_got_eof(c);
8394 if (!(ssh->remote_bugs & BUG_SENDS_LATE_REQUEST_REPLY)) {
8396 * It also means we stop expecting to see replies to any
8397 * outstanding channel requests, so clean those up too.
8398 * (ssh_chanreq_init will enforce by assertion that we don't
8399 * subsequently put anything back on this list.)
8401 while (c->v.v2.chanreq_head) {
8402 struct outstanding_channel_request *ocr = c->v.v2.chanreq_head;
8403 ocr->handler(c, NULL, ocr->ctx);
8404 c->v.v2.chanreq_head = ocr->next;
8410 * And we also send an outgoing EOF, if we haven't already, on the
8411 * assumption that CLOSE is a pretty forceful announcement that
8412 * the remote side is doing away with the entire channel. (If it
8413 * had wanted to send us EOF and continue receiving data from us,
8414 * it would have just sent CHANNEL_EOF.)
8416 if (!(c->closes & CLOSES_SENT_EOF)) {
8418 * Make sure we don't read any more from whatever our local
8419 * data source is for this channel.
8422 case CHAN_MAINSESSION:
8423 ssh->send_ok = 0; /* stop trying to read from stdin */
8426 x11_override_throttle(c->u.x11.xconn, 1);
8429 pfd_override_throttle(c->u.pfd.pf, 1);
8434 * Abandon any buffered data we still wanted to send to this
8435 * channel. Receiving a CHANNEL_CLOSE is an indication that
8436 * the server really wants to get on and _destroy_ this
8437 * channel, and it isn't going to send us any further
8438 * WINDOW_ADJUSTs to permit us to send pending stuff.
8440 bufchain_clear(&c->v.v2.outbuffer);
8443 * Send outgoing EOF.
8445 sshfwd_write_eof(c);
8449 * Now process the actual close.
8451 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
8452 c->closes |= CLOSES_RCVD_CLOSE;
8453 ssh2_channel_check_close(c);
8457 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
8459 struct ssh_channel *c;
8461 c = ssh_channel_msg(ssh, pktin);
8464 assert(c->halfopen); /* ssh_channel_msg will have enforced this */
8465 c->remoteid = ssh_pkt_getuint32(pktin);
8466 c->halfopen = FALSE;
8467 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8468 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8470 if (c->type == CHAN_SOCKDATA) {
8471 assert(c->u.pfd.pf != NULL);
8472 pfd_confirm(c->u.pfd.pf);
8473 } else if (c->type == CHAN_ZOMBIE) {
8475 * This case can occur if a local socket error occurred
8476 * between us sending out CHANNEL_OPEN and receiving
8477 * OPEN_CONFIRMATION. In this case, all we can do is
8478 * immediately initiate close proceedings now that we know the
8479 * server's id to put in the close message.
8481 ssh2_channel_check_close(c);
8484 * We never expect to receive OPEN_CONFIRMATION for any
8485 * *other* channel type (since only local-to-remote port
8486 * forwardings cause us to send CHANNEL_OPEN after the main
8487 * channel is live - all other auxiliary channel types are
8488 * initiated from the server end). It's safe to enforce this
8489 * by assertion rather than by ssh_disconnect, because the
8490 * real point is that we never constructed a half-open channel
8491 * structure in the first place with any type other than the
8494 assert(!"Funny channel type in ssh2_msg_channel_open_confirmation");
8498 ssh_channel_try_eof(c); /* in case we had a pending EOF */
8501 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
8503 static const char *const reasons[] = {
8504 "<unknown reason code>",
8505 "Administratively prohibited",
8507 "Unknown channel type",
8508 "Resource shortage",
8510 unsigned reason_code;
8511 char *reason_string;
8513 struct ssh_channel *c;
8515 c = ssh_channel_msg(ssh, pktin);
8518 assert(c->halfopen); /* ssh_channel_msg will have enforced this */
8520 if (c->type == CHAN_SOCKDATA) {
8521 reason_code = ssh_pkt_getuint32(pktin);
8522 if (reason_code >= lenof(reasons))
8523 reason_code = 0; /* ensure reasons[reason_code] in range */
8524 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
8525 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
8526 reasons[reason_code], reason_length,
8527 NULLTOEMPTY(reason_string));
8529 pfd_close(c->u.pfd.pf);
8530 } else if (c->type == CHAN_ZOMBIE) {
8532 * This case can occur if a local socket error occurred
8533 * between us sending out CHANNEL_OPEN and receiving
8534 * OPEN_FAILURE. In this case, we need do nothing except allow
8535 * the code below to throw the half-open channel away.
8539 * We never expect to receive OPEN_FAILURE for any *other*
8540 * channel type (since only local-to-remote port forwardings
8541 * cause us to send CHANNEL_OPEN after the main channel is
8542 * live - all other auxiliary channel types are initiated from
8543 * the server end). It's safe to enforce this by assertion
8544 * rather than by ssh_disconnect, because the real point is
8545 * that we never constructed a half-open channel structure in
8546 * the first place with any type other than the above.
8548 assert(!"Funny channel type in ssh2_msg_channel_open_failure");
8551 del234(ssh->channels, c);
8555 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
8558 int typelen, want_reply;
8559 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
8560 struct ssh_channel *c;
8561 struct Packet *pktout;
8563 c = ssh_channel_msg(ssh, pktin);
8566 ssh_pkt_getstring(pktin, &type, &typelen);
8567 want_reply = ssh2_pkt_getbool(pktin);
8569 if (c->closes & CLOSES_SENT_CLOSE) {
8571 * We don't reply to channel requests after we've sent
8572 * CHANNEL_CLOSE for the channel, because our reply might
8573 * cross in the network with the other side's CHANNEL_CLOSE
8574 * and arrive after they have wound the channel up completely.
8580 * Having got the channel number, we now look at
8581 * the request type string to see if it's something
8584 if (c == ssh->mainchan) {
8586 * We recognise "exit-status" and "exit-signal" on
8587 * the primary channel.
8589 if (typelen == 11 &&
8590 !memcmp(type, "exit-status", 11)) {
8592 ssh->exitcode = ssh_pkt_getuint32(pktin);
8593 logeventf(ssh, "Server sent command exit status %d",
8595 reply = SSH2_MSG_CHANNEL_SUCCESS;
8597 } else if (typelen == 11 &&
8598 !memcmp(type, "exit-signal", 11)) {
8600 int is_plausible = TRUE, is_int = FALSE;
8601 char *fmt_sig = NULL, *fmt_msg = NULL;
8603 int msglen = 0, core = FALSE;
8604 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
8605 * provide an `int' for the signal, despite its
8606 * having been a `string' in the drafts of RFC 4254 since at
8607 * least 2001. (Fixed in session.c 1.147.) Try to
8608 * infer which we can safely parse it as. */
8610 unsigned char *p = pktin->body +
8612 long len = pktin->length - pktin->savedpos;
8613 unsigned long num = GET_32BIT(p); /* what is it? */
8614 /* If it's 0, it hardly matters; assume string */
8618 int maybe_int = FALSE, maybe_str = FALSE;
8619 #define CHECK_HYPOTHESIS(offset, result) \
8622 int q = toint(offset); \
8623 if (q >= 0 && q+4 <= len) { \
8624 q = toint(q + 4 + GET_32BIT(p+q)); \
8625 if (q >= 0 && q+4 <= len && \
8626 ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
8631 CHECK_HYPOTHESIS(4+1, maybe_int);
8632 CHECK_HYPOTHESIS(4+num+1, maybe_str);
8633 #undef CHECK_HYPOTHESIS
8634 if (maybe_int && !maybe_str)
8636 else if (!maybe_int && maybe_str)
8639 /* Crikey. Either or neither. Panic. */
8640 is_plausible = FALSE;
8643 ssh->exitcode = 128; /* means `unknown signal' */
8646 /* Old non-standard OpenSSH. */
8647 int signum = ssh_pkt_getuint32(pktin);
8648 fmt_sig = dupprintf(" %d", signum);
8649 ssh->exitcode = 128 + signum;
8651 /* As per RFC 4254. */
8654 ssh_pkt_getstring(pktin, &sig, &siglen);
8655 /* Signal name isn't supposed to be blank, but
8656 * let's cope gracefully if it is. */
8658 fmt_sig = dupprintf(" \"%.*s\"",
8663 * Really hideous method of translating the
8664 * signal description back into a locally
8665 * meaningful number.
8670 #define TRANSLATE_SIGNAL(s) \
8671 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
8672 ssh->exitcode = 128 + SIG ## s
8674 TRANSLATE_SIGNAL(ABRT);
8677 TRANSLATE_SIGNAL(ALRM);
8680 TRANSLATE_SIGNAL(FPE);
8683 TRANSLATE_SIGNAL(HUP);
8686 TRANSLATE_SIGNAL(ILL);
8689 TRANSLATE_SIGNAL(INT);
8692 TRANSLATE_SIGNAL(KILL);
8695 TRANSLATE_SIGNAL(PIPE);
8698 TRANSLATE_SIGNAL(QUIT);
8701 TRANSLATE_SIGNAL(SEGV);
8704 TRANSLATE_SIGNAL(TERM);
8707 TRANSLATE_SIGNAL(USR1);
8710 TRANSLATE_SIGNAL(USR2);
8712 #undef TRANSLATE_SIGNAL
8714 ssh->exitcode = 128;
8716 core = ssh2_pkt_getbool(pktin);
8717 ssh_pkt_getstring(pktin, &msg, &msglen);
8719 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
8721 /* ignore lang tag */
8722 } /* else don't attempt to parse */
8723 logeventf(ssh, "Server exited on signal%s%s%s",
8724 fmt_sig ? fmt_sig : "",
8725 core ? " (core dumped)" : "",
8726 fmt_msg ? fmt_msg : "");
8729 reply = SSH2_MSG_CHANNEL_SUCCESS;
8734 * This is a channel request we don't know
8735 * about, so we now either ignore the request
8736 * or respond with CHANNEL_FAILURE, depending
8739 reply = SSH2_MSG_CHANNEL_FAILURE;
8742 pktout = ssh2_pkt_init(reply);
8743 ssh2_pkt_adduint32(pktout, c->remoteid);
8744 ssh2_pkt_send(ssh, pktout);
8748 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
8751 int typelen, want_reply;
8752 struct Packet *pktout;
8754 ssh_pkt_getstring(pktin, &type, &typelen);
8755 want_reply = ssh2_pkt_getbool(pktin);
8758 * We currently don't support any global requests
8759 * at all, so we either ignore the request or
8760 * respond with REQUEST_FAILURE, depending on
8764 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
8765 ssh2_pkt_send(ssh, pktout);
8769 struct X11FakeAuth *ssh_sharing_add_x11_display(Ssh ssh, int authtype,
8773 struct X11FakeAuth *auth;
8776 * Make up a new set of fake X11 auth data, and add it to the tree
8777 * of currently valid ones with an indication of the sharing
8778 * context that it's relevant to.
8780 auth = x11_invent_fake_auth(ssh->x11authtree, authtype);
8781 auth->share_cs = share_cs;
8782 auth->share_chan = share_chan;
8787 void ssh_sharing_remove_x11_display(Ssh ssh, struct X11FakeAuth *auth)
8789 del234(ssh->x11authtree, auth);
8790 x11_free_fake_auth(auth);
8793 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
8800 const char *error = NULL;
8801 struct ssh_channel *c;
8802 unsigned remid, winsize, pktsize;
8803 unsigned our_winsize_override = 0;
8804 struct Packet *pktout;
8806 ssh_pkt_getstring(pktin, &type, &typelen);
8807 c = snew(struct ssh_channel);
8810 remid = ssh_pkt_getuint32(pktin);
8811 winsize = ssh_pkt_getuint32(pktin);
8812 pktsize = ssh_pkt_getuint32(pktin);
8814 if (typelen == 3 && !memcmp(type, "x11", 3)) {
8817 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8818 addrstr = dupprintf("%.*s", peeraddrlen, NULLTOEMPTY(peeraddr));
8819 peerport = ssh_pkt_getuint32(pktin);
8821 logeventf(ssh, "Received X11 connect request from %s:%d",
8824 if (!ssh->X11_fwd_enabled && !ssh->connshare)
8825 error = "X11 forwarding is not enabled";
8827 c->u.x11.xconn = x11_init(ssh->x11authtree, c,
8830 c->u.x11.initial = TRUE;
8833 * If we are a connection-sharing upstream, then we should
8834 * initially present a very small window, adequate to take
8835 * the X11 initial authorisation packet but not much more.
8836 * Downstream will then present us a larger window (by
8837 * fiat of the connection-sharing protocol) and we can
8838 * guarantee to send a positive-valued WINDOW_ADJUST.
8841 our_winsize_override = 128;
8843 logevent("Opened X11 forward channel");
8847 } else if (typelen == 15 &&
8848 !memcmp(type, "forwarded-tcpip", 15)) {
8849 struct ssh_rportfwd pf, *realpf;
8852 ssh_pkt_getstring(pktin, &shost, &shostlen);/* skip address */
8853 pf.shost = dupprintf("%.*s", shostlen, NULLTOEMPTY(shost));
8854 pf.sport = ssh_pkt_getuint32(pktin);
8855 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8856 peerport = ssh_pkt_getuint32(pktin);
8857 realpf = find234(ssh->rportfwds, &pf, NULL);
8858 logeventf(ssh, "Received remote port %s:%d open request "
8859 "from %.*s:%d", pf.shost, pf.sport,
8860 peeraddrlen, NULLTOEMPTY(peeraddr), peerport);
8863 if (realpf == NULL) {
8864 error = "Remote port is not recognised";
8868 if (realpf->share_ctx) {
8870 * This port forwarding is on behalf of a
8871 * connection-sharing downstream, so abandon our own
8872 * channel-open procedure and just pass the message on
8875 share_got_pkt_from_server(realpf->share_ctx, pktin->type,
8876 pktin->body, pktin->length);
8881 err = pfd_connect(&c->u.pfd.pf, realpf->dhost, realpf->dport,
8882 c, ssh->conf, realpf->pfrec->addressfamily);
8883 logeventf(ssh, "Attempting to forward remote port to "
8884 "%s:%d", realpf->dhost, realpf->dport);
8886 logeventf(ssh, "Port open failed: %s", err);
8888 error = "Port open failed";
8890 logevent("Forwarded port opened successfully");
8891 c->type = CHAN_SOCKDATA;
8894 } else if (typelen == 22 &&
8895 !memcmp(type, "auth-agent@openssh.com", 22)) {
8896 if (!ssh->agentfwd_enabled)
8897 error = "Agent forwarding is not enabled";
8899 c->type = CHAN_AGENT; /* identify channel type */
8900 bufchain_init(&c->u.a.inbuffer);
8901 c->u.a.pending = NULL;
8904 error = "Unsupported channel type requested";
8907 c->remoteid = remid;
8908 c->halfopen = FALSE;
8910 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
8911 ssh2_pkt_adduint32(pktout, c->remoteid);
8912 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
8913 ssh2_pkt_addstring(pktout, error);
8914 ssh2_pkt_addstring(pktout, "en"); /* language tag */
8915 ssh2_pkt_send(ssh, pktout);
8916 logeventf(ssh, "Rejected channel open: %s", error);
8919 ssh_channel_init(c);
8920 c->v.v2.remwindow = winsize;
8921 c->v.v2.remmaxpkt = pktsize;
8922 if (our_winsize_override) {
8923 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
8924 our_winsize_override;
8926 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
8927 ssh2_pkt_adduint32(pktout, c->remoteid);
8928 ssh2_pkt_adduint32(pktout, c->localid);
8929 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
8930 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
8931 ssh2_pkt_send(ssh, pktout);
8935 void sshfwd_x11_sharing_handover(struct ssh_channel *c,
8936 void *share_cs, void *share_chan,
8937 const char *peer_addr, int peer_port,
8938 int endian, int protomajor, int protominor,
8939 const void *initial_data, int initial_len)
8942 * This function is called when we've just discovered that an X
8943 * forwarding channel on which we'd been handling the initial auth
8944 * ourselves turns out to be destined for a connection-sharing
8945 * downstream. So we turn the channel into a CHAN_SHARING, meaning
8946 * that we completely stop tracking windows and buffering data and
8947 * just pass more or less unmodified SSH messages back and forth.
8949 c->type = CHAN_SHARING;
8950 c->u.sharing.ctx = share_cs;
8951 share_setup_x11_channel(share_cs, share_chan,
8952 c->localid, c->remoteid, c->v.v2.remwindow,
8953 c->v.v2.remmaxpkt, c->v.v2.locwindow,
8954 peer_addr, peer_port, endian,
8955 protomajor, protominor,
8956 initial_data, initial_len);
8959 void sshfwd_x11_is_local(struct ssh_channel *c)
8962 * This function is called when we've just discovered that an X
8963 * forwarding channel is _not_ destined for a connection-sharing
8964 * downstream but we're going to handle it ourselves. We stop
8965 * presenting a cautiously small window and go into ordinary data
8968 c->u.x11.initial = FALSE;
8969 ssh2_set_window(c, ssh_is_simple(c->ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE);
8973 * Buffer banner messages for later display at some convenient point,
8974 * if we're going to display them.
8976 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
8978 /* Arbitrary limit to prevent unbounded inflation of buffer */
8979 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
8980 bufchain_size(&ssh->banner) <= 131072) {
8981 char *banner = NULL;
8983 ssh_pkt_getstring(pktin, &banner, &size);
8985 bufchain_add(&ssh->banner, banner, size);
8989 /* Helper function to deal with sending tty modes for "pty-req" */
8990 static void ssh2_send_ttymode(void *data,
8991 const struct ssh_ttymode *mode, char *val)
8993 struct Packet *pktout = (struct Packet *)data;
8994 unsigned int arg = 0;
8996 switch (mode->type) {
8998 arg = ssh_tty_parse_specchar(val);
9001 arg = ssh_tty_parse_boolean(val);
9004 ssh2_pkt_addbyte(pktout, mode->opcode);
9005 ssh2_pkt_adduint32(pktout, arg);
9008 static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
9011 struct ssh2_setup_x11_state {
9015 struct Packet *pktout;
9016 crStateP(ssh2_setup_x11_state, ctx);
9020 logevent("Requesting X11 forwarding");
9021 pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
9023 ssh2_pkt_addbool(pktout, 0); /* many connections */
9024 ssh2_pkt_addstring(pktout, ssh->x11auth->protoname);
9025 ssh2_pkt_addstring(pktout, ssh->x11auth->datastring);
9026 ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
9027 ssh2_pkt_send(ssh, pktout);
9029 /* Wait to be called back with either a response packet, or NULL
9030 * meaning clean up and free our data */
9034 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
9035 logevent("X11 forwarding enabled");
9036 ssh->X11_fwd_enabled = TRUE;
9038 logevent("X11 forwarding refused");
9044 static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
9047 struct ssh2_setup_agent_state {
9051 struct Packet *pktout;
9052 crStateP(ssh2_setup_agent_state, ctx);
9056 logevent("Requesting OpenSSH-style agent forwarding");
9057 pktout = ssh2_chanreq_init(ssh->mainchan, "auth-agent-req@openssh.com",
9058 ssh2_setup_agent, s);
9059 ssh2_pkt_send(ssh, pktout);
9061 /* Wait to be called back with either a response packet, or NULL
9062 * meaning clean up and free our data */
9066 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
9067 logevent("Agent forwarding enabled");
9068 ssh->agentfwd_enabled = TRUE;
9070 logevent("Agent forwarding refused");
9076 static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
9079 struct ssh2_setup_pty_state {
9083 struct Packet *pktout;
9084 crStateP(ssh2_setup_pty_state, ctx);
9088 /* Unpick the terminal-speed string. */
9089 /* XXX perhaps we should allow no speeds to be sent. */
9090 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
9091 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
9092 /* Build the pty request. */
9093 pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
9095 ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
9096 ssh2_pkt_adduint32(pktout, ssh->term_width);
9097 ssh2_pkt_adduint32(pktout, ssh->term_height);
9098 ssh2_pkt_adduint32(pktout, 0); /* pixel width */
9099 ssh2_pkt_adduint32(pktout, 0); /* pixel height */
9100 ssh2_pkt_addstring_start(pktout);
9101 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
9102 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
9103 ssh2_pkt_adduint32(pktout, ssh->ispeed);
9104 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
9105 ssh2_pkt_adduint32(pktout, ssh->ospeed);
9106 ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
9107 ssh2_pkt_send(ssh, pktout);
9108 ssh->state = SSH_STATE_INTERMED;
9110 /* Wait to be called back with either a response packet, or NULL
9111 * meaning clean up and free our data */
9115 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
9116 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
9117 ssh->ospeed, ssh->ispeed);
9118 ssh->got_pty = TRUE;
9120 c_write_str(ssh, "Server refused to allocate pty\r\n");
9121 ssh->editing = ssh->echoing = 1;
9128 static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
9131 struct ssh2_setup_env_state {
9133 int num_env, env_left, env_ok;
9136 struct Packet *pktout;
9137 crStateP(ssh2_setup_env_state, ctx);
9142 * Send environment variables.
9144 * Simplest thing here is to send all the requests at once, and
9145 * then wait for a whole bunch of successes or failures.
9151 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
9153 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
9154 pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
9155 ssh2_pkt_addstring(pktout, key);
9156 ssh2_pkt_addstring(pktout, val);
9157 ssh2_pkt_send(ssh, pktout);
9162 logeventf(ssh, "Sent %d environment variables", s->num_env);
9167 s->env_left = s->num_env;
9169 while (s->env_left > 0) {
9170 /* Wait to be called back with either a response packet,
9171 * or NULL meaning clean up and free our data */
9173 if (!pktin) goto out;
9174 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
9179 if (s->env_ok == s->num_env) {
9180 logevent("All environment variables successfully set");
9181 } else if (s->env_ok == 0) {
9182 logevent("All environment variables refused");
9183 c_write_str(ssh, "Server refused to set environment variables\r\n");
9185 logeventf(ssh, "%d environment variables refused",
9186 s->num_env - s->env_ok);
9187 c_write_str(ssh, "Server refused to set all environment variables\r\n");
9195 * Handle the SSH-2 userauth and connection layers.
9197 static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
9199 do_ssh2_authconn(ssh, NULL, 0, pktin);
9202 static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
9206 do_ssh2_authconn(c->ssh, NULL, 0, pktin);
9209 static void do_ssh2_authconn(Ssh ssh, const unsigned char *in, int inlen,
9210 struct Packet *pktin)
9212 struct do_ssh2_authconn_state {
9216 AUTH_TYPE_PUBLICKEY,
9217 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
9218 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
9220 AUTH_TYPE_GSSAPI, /* always QUIET */
9221 AUTH_TYPE_KEYBOARD_INTERACTIVE,
9222 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
9224 int done_service_req;
9225 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
9226 int tried_pubkey_config, done_agent;
9231 int kbd_inter_refused;
9232 int we_are_in, userauth_success;
9233 prompts_t *cur_prompt;
9238 void *publickey_blob;
9239 int publickey_bloblen;
9240 int privatekey_available, privatekey_encrypted;
9241 char *publickey_algorithm;
9242 char *publickey_comment;
9243 unsigned char agent_request[5], *agent_response, *agentp;
9244 int agent_responselen;
9245 unsigned char *pkblob_in_agent;
9247 char *pkblob, *alg, *commentp;
9248 int pklen, alglen, commentlen;
9249 int siglen, retlen, len;
9250 char *q, *agentreq, *ret;
9251 struct Packet *pktout;
9254 struct ssh_gss_library *gsslib;
9255 Ssh_gss_ctx gss_ctx;
9256 Ssh_gss_buf gss_buf;
9257 Ssh_gss_buf gss_rcvtok, gss_sndtok;
9258 Ssh_gss_name gss_srv_name;
9259 Ssh_gss_stat gss_stat;
9262 crState(do_ssh2_authconn_state);
9266 /* Register as a handler for all the messages this coroutine handles. */
9267 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
9268 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
9269 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
9270 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
9271 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
9272 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
9273 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
9274 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
9275 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
9276 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
9277 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
9278 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
9279 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
9280 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
9281 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
9282 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
9283 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
9284 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
9285 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
9286 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
9288 s->done_service_req = FALSE;
9289 s->we_are_in = s->userauth_success = FALSE;
9290 s->agent_response = NULL;
9292 s->tried_gssapi = FALSE;
9295 if (!ssh->bare_connection) {
9296 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
9298 * Request userauth protocol, and await a response to it.
9300 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
9301 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
9302 ssh2_pkt_send(ssh, s->pktout);
9303 crWaitUntilV(pktin);
9304 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
9305 s->done_service_req = TRUE;
9307 if (!s->done_service_req) {
9309 * Request connection protocol directly, without authentication.
9311 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
9312 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9313 ssh2_pkt_send(ssh, s->pktout);
9314 crWaitUntilV(pktin);
9315 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
9316 s->we_are_in = TRUE; /* no auth required */
9318 bombout(("Server refused service request"));
9323 s->we_are_in = TRUE;
9326 /* Arrange to be able to deal with any BANNERs that come in.
9327 * (We do this now as packets may come in during the next bit.) */
9328 bufchain_init(&ssh->banner);
9329 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
9330 ssh2_msg_userauth_banner;
9333 * Misc one-time setup for authentication.
9335 s->publickey_blob = NULL;
9336 if (!s->we_are_in) {
9339 * Load the public half of any configured public key file
9342 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9343 if (!filename_is_null(s->keyfile)) {
9345 logeventf(ssh, "Reading key file \"%.150s\"",
9346 filename_to_str(s->keyfile));
9347 keytype = key_type(s->keyfile);
9348 if (keytype == SSH_KEYTYPE_SSH2 ||
9349 keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 ||
9350 keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
9353 ssh2_userkey_loadpub(s->keyfile,
9354 &s->publickey_algorithm,
9355 &s->publickey_bloblen,
9356 &s->publickey_comment, &error);
9357 if (s->publickey_blob) {
9358 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH2);
9359 if (!s->privatekey_available)
9360 logeventf(ssh, "Key file contains public key only");
9361 s->privatekey_encrypted =
9362 ssh2_userkey_encrypted(s->keyfile, NULL);
9365 logeventf(ssh, "Unable to load key (%s)",
9367 msgbuf = dupprintf("Unable to load key file "
9368 "\"%.150s\" (%s)\r\n",
9369 filename_to_str(s->keyfile),
9371 c_write_str(ssh, msgbuf);
9376 logeventf(ssh, "Unable to use this key file (%s)",
9377 key_type_to_str(keytype));
9378 msgbuf = dupprintf("Unable to use key file \"%.150s\""
9380 filename_to_str(s->keyfile),
9381 key_type_to_str(keytype));
9382 c_write_str(ssh, msgbuf);
9384 s->publickey_blob = NULL;
9389 * Find out about any keys Pageant has (but if there's a
9390 * public key configured, filter out all others).
9393 s->agent_response = NULL;
9394 s->pkblob_in_agent = NULL;
9395 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
9399 logevent("Pageant is running. Requesting keys.");
9401 /* Request the keys held by the agent. */
9402 PUT_32BIT(s->agent_request, 1);
9403 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
9404 ssh->auth_agent_query = agent_query(
9405 s->agent_request, 5, &r, &s->agent_responselen,
9406 ssh_agent_callback, ssh);
9407 if (ssh->auth_agent_query) {
9411 bombout(("Unexpected data from server while"
9412 " waiting for agent response"));
9415 } while (pktin || inlen > 0);
9416 r = ssh->agent_response;
9417 s->agent_responselen = ssh->agent_response_len;
9419 s->agent_response = (unsigned char *) r;
9420 if (s->agent_response && s->agent_responselen >= 5 &&
9421 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
9424 p = s->agent_response + 5;
9425 s->nkeys = toint(GET_32BIT(p));
9428 * Vet the Pageant response to ensure that the key
9429 * count and blob lengths make sense.
9432 logeventf(ssh, "Pageant response contained a negative"
9433 " key count %d", s->nkeys);
9435 goto done_agent_query;
9437 unsigned char *q = p + 4;
9438 int lenleft = s->agent_responselen - 5 - 4;
9440 for (keyi = 0; keyi < s->nkeys; keyi++) {
9441 int bloblen, commentlen;
9443 logeventf(ssh, "Pageant response was truncated");
9445 goto done_agent_query;
9447 bloblen = toint(GET_32BIT(q));
9450 if (bloblen < 0 || bloblen > lenleft) {
9451 logeventf(ssh, "Pageant response was truncated");
9453 goto done_agent_query;
9457 commentlen = toint(GET_32BIT(q));
9460 if (commentlen < 0 || commentlen > lenleft) {
9461 logeventf(ssh, "Pageant response was truncated");
9463 goto done_agent_query;
9465 lenleft -= commentlen;
9471 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
9472 if (s->publickey_blob) {
9473 /* See if configured key is in agent. */
9474 for (keyi = 0; keyi < s->nkeys; keyi++) {
9475 s->pklen = toint(GET_32BIT(p));
9476 if (s->pklen == s->publickey_bloblen &&
9477 !memcmp(p+4, s->publickey_blob,
9478 s->publickey_bloblen)) {
9479 logeventf(ssh, "Pageant key #%d matches "
9480 "configured key file", keyi);
9482 s->pkblob_in_agent = p;
9486 p += toint(GET_32BIT(p)) + 4; /* comment */
9488 if (!s->pkblob_in_agent) {
9489 logevent("Configured key file not in Pageant");
9494 logevent("Failed to get reply from Pageant");
9502 * We repeat this whole loop, including the username prompt,
9503 * until we manage a successful authentication. If the user
9504 * types the wrong _password_, they can be sent back to the
9505 * beginning to try another username, if this is configured on.
9506 * (If they specify a username in the config, they are never
9507 * asked, even if they do give a wrong password.)
9509 * I think this best serves the needs of
9511 * - the people who have no configuration, no keys, and just
9512 * want to try repeated (username,password) pairs until they
9513 * type both correctly
9515 * - people who have keys and configuration but occasionally
9516 * need to fall back to passwords
9518 * - people with a key held in Pageant, who might not have
9519 * logged in to a particular machine before; so they want to
9520 * type a username, and then _either_ their key will be
9521 * accepted, _or_ they will type a password. If they mistype
9522 * the username they will want to be able to get back and
9525 s->got_username = FALSE;
9526 while (!s->we_are_in) {
9530 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
9532 * We got a username last time round this loop, and
9533 * with change_username turned off we don't try to get
9536 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
9537 int ret; /* need not be kept over crReturn */
9538 s->cur_prompt = new_prompts(ssh->frontend);
9539 s->cur_prompt->to_server = TRUE;
9540 s->cur_prompt->name = dupstr("SSH login name");
9541 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
9542 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9545 crWaitUntilV(!pktin);
9546 ret = get_userpass_input(s->cur_prompt, in, inlen);
9551 * get_userpass_input() failed to get a username.
9554 free_prompts(s->cur_prompt);
9555 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
9558 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
9559 free_prompts(s->cur_prompt);
9562 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
9563 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
9564 c_write_str(ssh, stuff);
9568 s->got_username = TRUE;
9571 * Send an authentication request using method "none": (a)
9572 * just in case it succeeds, and (b) so that we know what
9573 * authentication methods we can usefully try next.
9575 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9577 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9578 ssh2_pkt_addstring(s->pktout, ssh->username);
9579 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
9580 ssh2_pkt_addstring(s->pktout, "none"); /* method */
9581 ssh2_pkt_send(ssh, s->pktout);
9582 s->type = AUTH_TYPE_NONE;
9584 s->we_are_in = FALSE;
9586 s->tried_pubkey_config = FALSE;
9587 s->kbd_inter_refused = FALSE;
9589 /* Reset agent request state. */
9590 s->done_agent = FALSE;
9591 if (s->agent_response) {
9592 if (s->pkblob_in_agent) {
9593 s->agentp = s->pkblob_in_agent;
9595 s->agentp = s->agent_response + 5 + 4;
9601 char *methods = NULL;
9605 * Wait for the result of the last authentication request.
9608 crWaitUntilV(pktin);
9610 * Now is a convenient point to spew any banner material
9611 * that we've accumulated. (This should ensure that when
9612 * we exit the auth loop, we haven't any left to deal
9616 int size = bufchain_size(&ssh->banner);
9618 * Don't show the banner if we're operating in
9619 * non-verbose non-interactive mode. (It's probably
9620 * a script, which means nobody will read the
9621 * banner _anyway_, and moreover the printing of
9622 * the banner will screw up processing on the
9623 * output of (say) plink.)
9625 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
9626 char *banner = snewn(size, char);
9627 bufchain_fetch(&ssh->banner, banner, size);
9628 c_write_untrusted(ssh, banner, size);
9631 bufchain_clear(&ssh->banner);
9633 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
9634 logevent("Access granted");
9635 s->we_are_in = s->userauth_success = TRUE;
9639 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
9640 bombout(("Strange packet received during authentication: "
9641 "type %d", pktin->type));
9648 * OK, we're now sitting on a USERAUTH_FAILURE message, so
9649 * we can look at the string in it and know what we can
9650 * helpfully try next.
9652 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
9653 ssh_pkt_getstring(pktin, &methods, &methlen);
9654 if (!ssh2_pkt_getbool(pktin)) {
9656 * We have received an unequivocal Access
9657 * Denied. This can translate to a variety of
9658 * messages, or no message at all.
9660 * For forms of authentication which are attempted
9661 * implicitly, by which I mean without printing
9662 * anything in the window indicating that we're
9663 * trying them, we should never print 'Access
9666 * If we do print a message saying that we're
9667 * attempting some kind of authentication, it's OK
9668 * to print a followup message saying it failed -
9669 * but the message may sometimes be more specific
9670 * than simply 'Access denied'.
9672 * Additionally, if we'd just tried password
9673 * authentication, we should break out of this
9674 * whole loop so as to go back to the username
9675 * prompt (iff we're configured to allow
9676 * username change attempts).
9678 if (s->type == AUTH_TYPE_NONE) {
9680 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
9681 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
9682 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
9683 c_write_str(ssh, "Server refused our key\r\n");
9684 logevent("Server refused our key");
9685 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
9686 /* This _shouldn't_ happen except by a
9687 * protocol bug causing client and server to
9688 * disagree on what is a correct signature. */
9689 c_write_str(ssh, "Server refused public-key signature"
9690 " despite accepting key!\r\n");
9691 logevent("Server refused public-key signature"
9692 " despite accepting key!");
9693 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
9694 /* quiet, so no c_write */
9695 logevent("Server refused keyboard-interactive authentication");
9696 } else if (s->type==AUTH_TYPE_GSSAPI) {
9697 /* always quiet, so no c_write */
9698 /* also, the code down in the GSSAPI block has
9699 * already logged this in the Event Log */
9700 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
9701 logevent("Keyboard-interactive authentication failed");
9702 c_write_str(ssh, "Access denied\r\n");
9704 assert(s->type == AUTH_TYPE_PASSWORD);
9705 logevent("Password authentication failed");
9706 c_write_str(ssh, "Access denied\r\n");
9708 if (conf_get_int(ssh->conf, CONF_change_username)) {
9709 /* XXX perhaps we should allow
9710 * keyboard-interactive to do this too? */
9711 s->we_are_in = FALSE;
9716 c_write_str(ssh, "Further authentication required\r\n");
9717 logevent("Further authentication required");
9721 in_commasep_string("publickey", methods, methlen);
9723 in_commasep_string("password", methods, methlen);
9724 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
9725 in_commasep_string("keyboard-interactive", methods, methlen);
9727 if (conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
9728 in_commasep_string("gssapi-with-mic", methods, methlen)) {
9729 /* Try loading the GSS libraries and see if we
9732 ssh->gsslibs = ssh_gss_setup(ssh->conf);
9733 s->can_gssapi = (ssh->gsslibs->nlibraries > 0);
9735 /* No point in even bothering to try to load the
9736 * GSS libraries, if the user configuration and
9737 * server aren't both prepared to attempt GSSAPI
9738 * auth in the first place. */
9739 s->can_gssapi = FALSE;
9744 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9746 if (s->can_pubkey && !s->done_agent && s->nkeys) {
9749 * Attempt public-key authentication using a key from Pageant.
9752 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9754 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
9756 /* Unpack key from agent response */
9757 s->pklen = toint(GET_32BIT(s->agentp));
9759 s->pkblob = (char *)s->agentp;
9760 s->agentp += s->pklen;
9761 s->alglen = toint(GET_32BIT(s->pkblob));
9762 s->alg = s->pkblob + 4;
9763 s->commentlen = toint(GET_32BIT(s->agentp));
9765 s->commentp = (char *)s->agentp;
9766 s->agentp += s->commentlen;
9767 /* s->agentp now points at next key, if any */
9769 /* See if server will accept it */
9770 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9771 ssh2_pkt_addstring(s->pktout, ssh->username);
9772 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9773 /* service requested */
9774 ssh2_pkt_addstring(s->pktout, "publickey");
9776 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
9777 ssh2_pkt_addstring_start(s->pktout);
9778 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9779 ssh2_pkt_addstring_start(s->pktout);
9780 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9781 ssh2_pkt_send(ssh, s->pktout);
9782 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
9784 crWaitUntilV(pktin);
9785 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9787 /* Offer of key refused. */
9794 if (flags & FLAG_VERBOSE) {
9795 c_write_str(ssh, "Authenticating with "
9797 c_write(ssh, s->commentp, s->commentlen);
9798 c_write_str(ssh, "\" from agent\r\n");
9802 * Server is willing to accept the key.
9803 * Construct a SIGN_REQUEST.
9805 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9806 ssh2_pkt_addstring(s->pktout, ssh->username);
9807 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9808 /* service requested */
9809 ssh2_pkt_addstring(s->pktout, "publickey");
9811 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
9812 ssh2_pkt_addstring_start(s->pktout);
9813 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9814 ssh2_pkt_addstring_start(s->pktout);
9815 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9817 /* Ask agent for signature. */
9818 s->siglen = s->pktout->length - 5 + 4 +
9819 ssh->v2_session_id_len;
9820 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9822 s->len = 1; /* message type */
9823 s->len += 4 + s->pklen; /* key blob */
9824 s->len += 4 + s->siglen; /* data to sign */
9825 s->len += 4; /* flags */
9826 s->agentreq = snewn(4 + s->len, char);
9827 PUT_32BIT(s->agentreq, s->len);
9828 s->q = s->agentreq + 4;
9829 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
9830 PUT_32BIT(s->q, s->pklen);
9832 memcpy(s->q, s->pkblob, s->pklen);
9834 PUT_32BIT(s->q, s->siglen);
9836 /* Now the data to be signed... */
9837 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9838 PUT_32BIT(s->q, ssh->v2_session_id_len);
9841 memcpy(s->q, ssh->v2_session_id,
9842 ssh->v2_session_id_len);
9843 s->q += ssh->v2_session_id_len;
9844 memcpy(s->q, s->pktout->data + 5,
9845 s->pktout->length - 5);
9846 s->q += s->pktout->length - 5;
9847 /* And finally the (zero) flags word. */
9849 ssh->auth_agent_query = agent_query(
9850 s->agentreq, s->len + 4, &vret, &s->retlen,
9851 ssh_agent_callback, ssh);
9852 if (ssh->auth_agent_query) {
9856 bombout(("Unexpected data from server"
9857 " while waiting for agent"
9861 } while (pktin || inlen > 0);
9862 vret = ssh->agent_response;
9863 s->retlen = ssh->agent_response_len;
9868 if (s->retlen >= 9 &&
9869 s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
9870 GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
9871 logevent("Sending Pageant's response");
9872 ssh2_add_sigblob(ssh, s->pktout,
9873 s->pkblob, s->pklen,
9875 GET_32BIT(s->ret + 5));
9876 ssh2_pkt_send(ssh, s->pktout);
9877 s->type = AUTH_TYPE_PUBLICKEY;
9879 /* FIXME: less drastic response */
9880 bombout(("Pageant failed to answer challenge"));
9886 /* Do we have any keys left to try? */
9887 if (s->pkblob_in_agent) {
9888 s->done_agent = TRUE;
9889 s->tried_pubkey_config = TRUE;
9892 if (s->keyi >= s->nkeys)
9893 s->done_agent = TRUE;
9896 } else if (s->can_pubkey && s->publickey_blob &&
9897 s->privatekey_available && !s->tried_pubkey_config) {
9899 struct ssh2_userkey *key; /* not live over crReturn */
9900 char *passphrase; /* not live over crReturn */
9902 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9904 s->tried_pubkey_config = TRUE;
9907 * Try the public key supplied in the configuration.
9909 * First, offer the public blob to see if the server is
9910 * willing to accept it.
9912 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9913 ssh2_pkt_addstring(s->pktout, ssh->username);
9914 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9915 /* service requested */
9916 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
9917 ssh2_pkt_addbool(s->pktout, FALSE);
9918 /* no signature included */
9919 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
9920 ssh2_pkt_addstring_start(s->pktout);
9921 ssh2_pkt_addstring_data(s->pktout,
9922 (char *)s->publickey_blob,
9923 s->publickey_bloblen);
9924 ssh2_pkt_send(ssh, s->pktout);
9925 logevent("Offered public key");
9927 crWaitUntilV(pktin);
9928 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9929 /* Key refused. Give up. */
9930 s->gotit = TRUE; /* reconsider message next loop */
9931 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
9932 continue; /* process this new message */
9934 logevent("Offer of public key accepted");
9937 * Actually attempt a serious authentication using
9940 if (flags & FLAG_VERBOSE) {
9941 c_write_str(ssh, "Authenticating with public key \"");
9942 c_write_str(ssh, s->publickey_comment);
9943 c_write_str(ssh, "\"\r\n");
9947 const char *error; /* not live over crReturn */
9948 if (s->privatekey_encrypted) {
9950 * Get a passphrase from the user.
9952 int ret; /* need not be kept over crReturn */
9953 s->cur_prompt = new_prompts(ssh->frontend);
9954 s->cur_prompt->to_server = FALSE;
9955 s->cur_prompt->name = dupstr("SSH key passphrase");
9956 add_prompt(s->cur_prompt,
9957 dupprintf("Passphrase for key \"%.100s\": ",
9958 s->publickey_comment),
9960 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9963 crWaitUntilV(!pktin);
9964 ret = get_userpass_input(s->cur_prompt,
9969 /* Failed to get a passphrase. Terminate. */
9970 free_prompts(s->cur_prompt);
9971 ssh_disconnect(ssh, NULL,
9972 "Unable to authenticate",
9973 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9978 dupstr(s->cur_prompt->prompts[0]->result);
9979 free_prompts(s->cur_prompt);
9981 passphrase = NULL; /* no passphrase needed */
9985 * Try decrypting the key.
9987 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9988 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
9990 /* burn the evidence */
9991 smemclr(passphrase, strlen(passphrase));
9994 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
9996 (key == SSH2_WRONG_PASSPHRASE)) {
9997 c_write_str(ssh, "Wrong passphrase\r\n");
9999 /* and loop again */
10001 c_write_str(ssh, "Unable to load private key (");
10002 c_write_str(ssh, error);
10003 c_write_str(ssh, ")\r\n");
10005 break; /* try something else */
10011 unsigned char *pkblob, *sigblob, *sigdata;
10012 int pkblob_len, sigblob_len, sigdata_len;
10016 * We have loaded the private key and the server
10017 * has announced that it's willing to accept it.
10018 * Hallelujah. Generate a signature and send it.
10020 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10021 ssh2_pkt_addstring(s->pktout, ssh->username);
10022 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10023 /* service requested */
10024 ssh2_pkt_addstring(s->pktout, "publickey");
10026 ssh2_pkt_addbool(s->pktout, TRUE);
10027 /* signature follows */
10028 ssh2_pkt_addstring(s->pktout, key->alg->name);
10029 pkblob = key->alg->public_blob(key->data,
10031 ssh2_pkt_addstring_start(s->pktout);
10032 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
10036 * The data to be signed is:
10038 * string session-id
10040 * followed by everything so far placed in the
10043 sigdata_len = s->pktout->length - 5 + 4 +
10044 ssh->v2_session_id_len;
10045 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
10047 sigdata = snewn(sigdata_len, unsigned char);
10049 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
10050 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
10053 memcpy(sigdata+p, ssh->v2_session_id,
10054 ssh->v2_session_id_len);
10055 p += ssh->v2_session_id_len;
10056 memcpy(sigdata+p, s->pktout->data + 5,
10057 s->pktout->length - 5);
10058 p += s->pktout->length - 5;
10059 assert(p == sigdata_len);
10060 sigblob = key->alg->sign(key->data, (char *)sigdata,
10061 sigdata_len, &sigblob_len);
10062 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
10063 sigblob, sigblob_len);
10068 ssh2_pkt_send(ssh, s->pktout);
10069 logevent("Sent public key signature");
10070 s->type = AUTH_TYPE_PUBLICKEY;
10071 key->alg->freekey(key->data);
10072 sfree(key->comment);
10077 } else if (s->can_gssapi && !s->tried_gssapi) {
10079 /* GSSAPI Authentication */
10081 int micoffset, len;
10084 s->type = AUTH_TYPE_GSSAPI;
10085 s->tried_gssapi = TRUE;
10087 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
10090 * Pick the highest GSS library on the preference
10096 for (i = 0; i < ngsslibs; i++) {
10097 int want_id = conf_get_int_int(ssh->conf,
10098 CONF_ssh_gsslist, i);
10099 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
10100 if (ssh->gsslibs->libraries[j].id == want_id) {
10101 s->gsslib = &ssh->gsslibs->libraries[j];
10102 goto got_gsslib; /* double break */
10107 * We always expect to have found something in
10108 * the above loop: we only came here if there
10109 * was at least one viable GSS library, and the
10110 * preference list should always mention
10111 * everything and only change the order.
10116 if (s->gsslib->gsslogmsg)
10117 logevent(s->gsslib->gsslogmsg);
10119 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
10120 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10121 ssh2_pkt_addstring(s->pktout, ssh->username);
10122 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10123 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
10124 logevent("Attempting GSSAPI authentication");
10126 /* add mechanism info */
10127 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
10129 /* number of GSSAPI mechanisms */
10130 ssh2_pkt_adduint32(s->pktout,1);
10132 /* length of OID + 2 */
10133 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
10134 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
10136 /* length of OID */
10137 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
10139 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
10140 s->gss_buf.length);
10141 ssh2_pkt_send(ssh, s->pktout);
10142 crWaitUntilV(pktin);
10143 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
10144 logevent("GSSAPI authentication request refused");
10148 /* check returned packet ... */
10150 ssh_pkt_getstring(pktin, &data, &len);
10151 s->gss_rcvtok.value = data;
10152 s->gss_rcvtok.length = len;
10153 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
10154 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
10155 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
10156 memcmp((char *)s->gss_rcvtok.value + 2,
10157 s->gss_buf.value,s->gss_buf.length) ) {
10158 logevent("GSSAPI authentication - wrong response from server");
10162 /* now start running */
10163 s->gss_stat = s->gsslib->import_name(s->gsslib,
10166 if (s->gss_stat != SSH_GSS_OK) {
10167 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
10168 logevent("GSSAPI import name failed - Bad service name");
10170 logevent("GSSAPI import name failed");
10174 /* fetch TGT into GSS engine */
10175 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
10177 if (s->gss_stat != SSH_GSS_OK) {
10178 logevent("GSSAPI authentication failed to get credentials");
10179 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10183 /* initial tokens are empty */
10184 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
10185 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
10187 /* now enter the loop */
10189 s->gss_stat = s->gsslib->init_sec_context
10193 conf_get_int(ssh->conf, CONF_gssapifwd),
10197 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
10198 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
10199 logevent("GSSAPI authentication initialisation failed");
10201 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
10202 &s->gss_buf) == SSH_GSS_OK) {
10203 logevent(s->gss_buf.value);
10204 sfree(s->gss_buf.value);
10209 logevent("GSSAPI authentication initialised");
10211 /* Client and server now exchange tokens until GSSAPI
10212 * no longer says CONTINUE_NEEDED */
10214 if (s->gss_sndtok.length != 0) {
10215 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
10216 ssh_pkt_addstring_start(s->pktout);
10217 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
10218 ssh2_pkt_send(ssh, s->pktout);
10219 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
10222 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
10223 crWaitUntilV(pktin);
10224 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
10225 logevent("GSSAPI authentication - bad server response");
10226 s->gss_stat = SSH_GSS_FAILURE;
10229 ssh_pkt_getstring(pktin, &data, &len);
10230 s->gss_rcvtok.value = data;
10231 s->gss_rcvtok.length = len;
10233 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
10235 if (s->gss_stat != SSH_GSS_OK) {
10236 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10237 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
10240 logevent("GSSAPI authentication loop finished OK");
10242 /* Now send the MIC */
10244 s->pktout = ssh2_pkt_init(0);
10245 micoffset = s->pktout->length;
10246 ssh_pkt_addstring_start(s->pktout);
10247 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
10248 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
10249 ssh_pkt_addstring(s->pktout, ssh->username);
10250 ssh_pkt_addstring(s->pktout, "ssh-connection");
10251 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
10253 s->gss_buf.value = (char *)s->pktout->data + micoffset;
10254 s->gss_buf.length = s->pktout->length - micoffset;
10256 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
10257 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
10258 ssh_pkt_addstring_start(s->pktout);
10259 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
10260 ssh2_pkt_send(ssh, s->pktout);
10261 s->gsslib->free_mic(s->gsslib, &mic);
10265 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10266 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
10269 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
10272 * Keyboard-interactive authentication.
10275 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
10277 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
10279 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10280 ssh2_pkt_addstring(s->pktout, ssh->username);
10281 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10282 /* service requested */
10283 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
10285 ssh2_pkt_addstring(s->pktout, ""); /* lang */
10286 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
10287 ssh2_pkt_send(ssh, s->pktout);
10289 logevent("Attempting keyboard-interactive authentication");
10291 crWaitUntilV(pktin);
10292 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
10293 /* Server is not willing to do keyboard-interactive
10294 * at all (or, bizarrely but legally, accepts the
10295 * user without actually issuing any prompts).
10296 * Give up on it entirely. */
10298 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
10299 s->kbd_inter_refused = TRUE; /* don't try it again */
10304 * Loop while the server continues to send INFO_REQUESTs.
10306 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
10308 char *name, *inst, *lang;
10309 int name_len, inst_len, lang_len;
10313 * We've got a fresh USERAUTH_INFO_REQUEST.
10314 * Get the preamble and start building a prompt.
10316 ssh_pkt_getstring(pktin, &name, &name_len);
10317 ssh_pkt_getstring(pktin, &inst, &inst_len);
10318 ssh_pkt_getstring(pktin, &lang, &lang_len);
10319 s->cur_prompt = new_prompts(ssh->frontend);
10320 s->cur_prompt->to_server = TRUE;
10323 * Get any prompt(s) from the packet.
10325 s->num_prompts = ssh_pkt_getuint32(pktin);
10326 for (i = 0; i < s->num_prompts; i++) {
10330 static char noprompt[] =
10331 "<server failed to send prompt>: ";
10333 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10334 echo = ssh2_pkt_getbool(pktin);
10337 prompt_len = lenof(noprompt)-1;
10339 add_prompt(s->cur_prompt,
10340 dupprintf("%.*s", prompt_len, prompt),
10345 /* FIXME: better prefix to distinguish from
10346 * local prompts? */
10347 s->cur_prompt->name =
10348 dupprintf("SSH server: %.*s", name_len, name);
10349 s->cur_prompt->name_reqd = TRUE;
10351 s->cur_prompt->name =
10352 dupstr("SSH server authentication");
10353 s->cur_prompt->name_reqd = FALSE;
10355 /* We add a prefix to try to make it clear that a prompt
10356 * has come from the server.
10357 * FIXME: ugly to print "Using..." in prompt _every_
10358 * time round. Can this be done more subtly? */
10359 /* Special case: for reasons best known to themselves,
10360 * some servers send k-i requests with no prompts and
10361 * nothing to display. Keep quiet in this case. */
10362 if (s->num_prompts || name_len || inst_len) {
10363 s->cur_prompt->instruction =
10364 dupprintf("Using keyboard-interactive authentication.%s%.*s",
10365 inst_len ? "\n" : "", inst_len, inst);
10366 s->cur_prompt->instr_reqd = TRUE;
10368 s->cur_prompt->instr_reqd = FALSE;
10372 * Display any instructions, and get the user's
10376 int ret; /* not live over crReturn */
10377 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10380 crWaitUntilV(!pktin);
10381 ret = get_userpass_input(s->cur_prompt, in, inlen);
10386 * Failed to get responses. Terminate.
10388 free_prompts(s->cur_prompt);
10389 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10390 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10397 * Send the response(s) to the server.
10399 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
10400 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
10401 for (i=0; i < s->num_prompts; i++) {
10402 ssh2_pkt_addstring(s->pktout,
10403 s->cur_prompt->prompts[i]->result);
10405 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10408 * Free the prompts structure from this iteration.
10409 * If there's another, a new one will be allocated
10410 * when we return to the top of this while loop.
10412 free_prompts(s->cur_prompt);
10415 * Get the next packet in case it's another
10418 crWaitUntilV(pktin);
10423 * We should have SUCCESS or FAILURE now.
10427 } else if (s->can_passwd) {
10430 * Plain old password authentication.
10432 int ret; /* not live over crReturn */
10433 int changereq_first_time; /* not live over crReturn */
10435 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
10437 s->cur_prompt = new_prompts(ssh->frontend);
10438 s->cur_prompt->to_server = TRUE;
10439 s->cur_prompt->name = dupstr("SSH password");
10440 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
10445 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10448 crWaitUntilV(!pktin);
10449 ret = get_userpass_input(s->cur_prompt, in, inlen);
10454 * Failed to get responses. Terminate.
10456 free_prompts(s->cur_prompt);
10457 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10458 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10463 * Squirrel away the password. (We may need it later if
10464 * asked to change it.)
10466 s->password = dupstr(s->cur_prompt->prompts[0]->result);
10467 free_prompts(s->cur_prompt);
10470 * Send the password packet.
10472 * We pad out the password packet to 256 bytes to make
10473 * it harder for an attacker to find the length of the
10476 * Anyone using a password longer than 256 bytes
10477 * probably doesn't have much to worry about from
10478 * people who find out how long their password is!
10480 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10481 ssh2_pkt_addstring(s->pktout, ssh->username);
10482 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10483 /* service requested */
10484 ssh2_pkt_addstring(s->pktout, "password");
10485 ssh2_pkt_addbool(s->pktout, FALSE);
10486 ssh2_pkt_addstring(s->pktout, s->password);
10487 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10488 logevent("Sent password");
10489 s->type = AUTH_TYPE_PASSWORD;
10492 * Wait for next packet, in case it's a password change
10495 crWaitUntilV(pktin);
10496 changereq_first_time = TRUE;
10498 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
10501 * We're being asked for a new password
10502 * (perhaps not for the first time).
10503 * Loop until the server accepts it.
10506 int got_new = FALSE; /* not live over crReturn */
10507 char *prompt; /* not live over crReturn */
10508 int prompt_len; /* not live over crReturn */
10512 if (changereq_first_time)
10513 msg = "Server requested password change";
10515 msg = "Server rejected new password";
10517 c_write_str(ssh, msg);
10518 c_write_str(ssh, "\r\n");
10521 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10523 s->cur_prompt = new_prompts(ssh->frontend);
10524 s->cur_prompt->to_server = TRUE;
10525 s->cur_prompt->name = dupstr("New SSH password");
10526 s->cur_prompt->instruction =
10527 dupprintf("%.*s", prompt_len, NULLTOEMPTY(prompt));
10528 s->cur_prompt->instr_reqd = TRUE;
10530 * There's no explicit requirement in the protocol
10531 * for the "old" passwords in the original and
10532 * password-change messages to be the same, and
10533 * apparently some Cisco kit supports password change
10534 * by the user entering a blank password originally
10535 * and the real password subsequently, so,
10536 * reluctantly, we prompt for the old password again.
10538 * (On the other hand, some servers don't even bother
10539 * to check this field.)
10541 add_prompt(s->cur_prompt,
10542 dupstr("Current password (blank for previously entered password): "),
10544 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
10546 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
10550 * Loop until the user manages to enter the same
10555 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10558 crWaitUntilV(!pktin);
10559 ret = get_userpass_input(s->cur_prompt, in, inlen);
10564 * Failed to get responses. Terminate.
10566 /* burn the evidence */
10567 free_prompts(s->cur_prompt);
10568 smemclr(s->password, strlen(s->password));
10569 sfree(s->password);
10570 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10571 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10577 * If the user specified a new original password
10578 * (IYSWIM), overwrite any previously specified
10580 * (A side effect is that the user doesn't have to
10581 * re-enter it if they louse up the new password.)
10583 if (s->cur_prompt->prompts[0]->result[0]) {
10584 smemclr(s->password, strlen(s->password));
10585 /* burn the evidence */
10586 sfree(s->password);
10588 dupstr(s->cur_prompt->prompts[0]->result);
10592 * Check the two new passwords match.
10594 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
10595 s->cur_prompt->prompts[2]->result)
10598 /* They don't. Silly user. */
10599 c_write_str(ssh, "Passwords do not match\r\n");
10604 * Send the new password (along with the old one).
10605 * (see above for padding rationale)
10607 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10608 ssh2_pkt_addstring(s->pktout, ssh->username);
10609 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10610 /* service requested */
10611 ssh2_pkt_addstring(s->pktout, "password");
10612 ssh2_pkt_addbool(s->pktout, TRUE);
10613 ssh2_pkt_addstring(s->pktout, s->password);
10614 ssh2_pkt_addstring(s->pktout,
10615 s->cur_prompt->prompts[1]->result);
10616 free_prompts(s->cur_prompt);
10617 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10618 logevent("Sent new password");
10621 * Now see what the server has to say about it.
10622 * (If it's CHANGEREQ again, it's not happy with the
10625 crWaitUntilV(pktin);
10626 changereq_first_time = FALSE;
10631 * We need to reexamine the current pktin at the top
10632 * of the loop. Either:
10633 * - we weren't asked to change password at all, in
10634 * which case it's a SUCCESS or FAILURE with the
10636 * - we sent a new password, and the server was
10637 * either OK with it (SUCCESS or FAILURE w/partial
10638 * success) or unhappy with the _old_ password
10639 * (FAILURE w/o partial success)
10640 * In any of these cases, we go back to the top of
10641 * the loop and start again.
10646 * We don't need the old password any more, in any
10647 * case. Burn the evidence.
10649 smemclr(s->password, strlen(s->password));
10650 sfree(s->password);
10653 char *str = dupprintf("No supported authentication methods available"
10654 " (server sent: %.*s)",
10657 ssh_disconnect(ssh, str,
10658 "No supported authentication methods available",
10659 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
10669 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
10671 /* Clear up various bits and pieces from authentication. */
10672 if (s->publickey_blob) {
10673 sfree(s->publickey_algorithm);
10674 sfree(s->publickey_blob);
10675 sfree(s->publickey_comment);
10677 if (s->agent_response)
10678 sfree(s->agent_response);
10680 if (s->userauth_success && !ssh->bare_connection) {
10682 * We've just received USERAUTH_SUCCESS, and we haven't sent any
10683 * packets since. Signal the transport layer to consider enacting
10684 * delayed compression.
10686 * (Relying on we_are_in is not sufficient, as
10687 * draft-miller-secsh-compression-delayed is quite clear that it
10688 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
10689 * become set for other reasons.)
10691 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
10694 ssh->channels = newtree234(ssh_channelcmp);
10697 * Set up handlers for some connection protocol messages, so we
10698 * don't have to handle them repeatedly in this coroutine.
10700 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
10701 ssh2_msg_channel_window_adjust;
10702 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
10703 ssh2_msg_global_request;
10706 * Create the main session channel.
10708 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
10709 ssh->mainchan = NULL;
10711 ssh->mainchan = snew(struct ssh_channel);
10712 ssh->mainchan->ssh = ssh;
10713 ssh_channel_init(ssh->mainchan);
10715 if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
10717 * Just start a direct-tcpip channel and use it as the main
10720 ssh_send_port_open(ssh->mainchan,
10721 conf_get_str(ssh->conf, CONF_ssh_nc_host),
10722 conf_get_int(ssh->conf, CONF_ssh_nc_port),
10724 ssh->ncmode = TRUE;
10726 s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
10727 logevent("Opening session as main channel");
10728 ssh2_pkt_send(ssh, s->pktout);
10729 ssh->ncmode = FALSE;
10731 crWaitUntilV(pktin);
10732 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
10733 bombout(("Server refused to open channel"));
10735 /* FIXME: error data comes back in FAILURE packet */
10737 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
10738 bombout(("Server's channel confirmation cited wrong channel"));
10741 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
10742 ssh->mainchan->halfopen = FALSE;
10743 ssh->mainchan->type = CHAN_MAINSESSION;
10744 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
10745 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
10746 update_specials_menu(ssh->frontend);
10747 logevent("Opened main channel");
10751 * Now we have a channel, make dispatch table entries for
10752 * general channel-based messages.
10754 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
10755 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
10756 ssh2_msg_channel_data;
10757 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
10758 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
10759 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
10760 ssh2_msg_channel_open_confirmation;
10761 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
10762 ssh2_msg_channel_open_failure;
10763 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
10764 ssh2_msg_channel_request;
10765 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
10766 ssh2_msg_channel_open;
10767 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
10768 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
10771 * Now the connection protocol is properly up and running, with
10772 * all those dispatch table entries, so it's safe to let
10773 * downstreams start trying to open extra channels through us.
10775 if (ssh->connshare)
10776 share_activate(ssh->connshare, ssh->v_s);
10778 if (ssh->mainchan && ssh_is_simple(ssh)) {
10780 * This message indicates to the server that we promise
10781 * not to try to run any other channel in parallel with
10782 * this one, so it's safe for it to advertise a very large
10783 * window and leave the flow control to TCP.
10785 s->pktout = ssh2_chanreq_init(ssh->mainchan,
10786 "simple@putty.projects.tartarus.org",
10788 ssh2_pkt_send(ssh, s->pktout);
10792 * Enable port forwardings.
10794 ssh_setup_portfwd(ssh, ssh->conf);
10796 if (ssh->mainchan && !ssh->ncmode) {
10798 * Send the CHANNEL_REQUESTS for the main session channel.
10799 * Each one is handled by its own little asynchronous
10803 /* Potentially enable X11 forwarding. */
10804 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
10806 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
10808 if (!ssh->x11disp) {
10809 /* FIXME: return an error message from x11_setup_display */
10810 logevent("X11 forwarding not enabled: unable to"
10811 " initialise X display");
10813 ssh->x11auth = x11_invent_fake_auth
10814 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
10815 ssh->x11auth->disp = ssh->x11disp;
10817 ssh2_setup_x11(ssh->mainchan, NULL, NULL);
10821 /* Potentially enable agent forwarding. */
10822 if (ssh_agent_forwarding_permitted(ssh))
10823 ssh2_setup_agent(ssh->mainchan, NULL, NULL);
10825 /* Now allocate a pty for the session. */
10826 if (!conf_get_int(ssh->conf, CONF_nopty))
10827 ssh2_setup_pty(ssh->mainchan, NULL, NULL);
10829 /* Send environment variables. */
10830 ssh2_setup_env(ssh->mainchan, NULL, NULL);
10833 * Start a shell or a remote command. We may have to attempt
10834 * this twice if the config data has provided a second choice
10841 if (ssh->fallback_cmd) {
10842 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
10843 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
10845 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
10846 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
10850 s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
10851 ssh2_response_authconn, NULL);
10852 ssh2_pkt_addstring(s->pktout, cmd);
10854 s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
10855 ssh2_response_authconn, NULL);
10856 ssh2_pkt_addstring(s->pktout, cmd);
10858 s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
10859 ssh2_response_authconn, NULL);
10861 ssh2_pkt_send(ssh, s->pktout);
10863 crWaitUntilV(pktin);
10865 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
10866 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
10867 bombout(("Unexpected response to shell/command request:"
10868 " packet type %d", pktin->type));
10872 * We failed to start the command. If this is the
10873 * fallback command, we really are finished; if it's
10874 * not, and if the fallback command exists, try falling
10875 * back to it before complaining.
10877 if (!ssh->fallback_cmd &&
10878 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
10879 logevent("Primary command failed; attempting fallback");
10880 ssh->fallback_cmd = TRUE;
10883 bombout(("Server refused to start a shell/command"));
10886 logevent("Started a shell/command");
10891 ssh->editing = ssh->echoing = TRUE;
10894 ssh->state = SSH_STATE_SESSION;
10895 if (ssh->size_needed)
10896 ssh_size(ssh, ssh->term_width, ssh->term_height);
10897 if (ssh->eof_needed)
10898 ssh_special(ssh, TS_EOF);
10904 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
10912 * _All_ the connection-layer packets we expect to
10913 * receive are now handled by the dispatch table.
10914 * Anything that reaches here must be bogus.
10917 bombout(("Strange packet received: type %d", pktin->type));
10919 } else if (ssh->mainchan) {
10921 * We have spare data. Add it to the channel buffer.
10923 ssh_send_channel_data(ssh->mainchan, (char *)in, inlen);
10931 * Handlers for SSH-2 messages that might arrive at any moment.
10933 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
10935 /* log reason code in disconnect message */
10937 int reason, msglen;
10939 reason = ssh_pkt_getuint32(pktin);
10940 ssh_pkt_getstring(pktin, &msg, &msglen);
10942 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
10943 buf = dupprintf("Received disconnect message (%s)",
10944 ssh2_disconnect_reasons[reason]);
10946 buf = dupprintf("Received disconnect message (unknown"
10947 " type %d)", reason);
10951 buf = dupprintf("Disconnection message text: %.*s",
10952 msglen, NULLTOEMPTY(msg));
10954 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
10956 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
10957 ssh2_disconnect_reasons[reason] : "unknown",
10958 msglen, NULLTOEMPTY(msg)));
10962 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
10964 /* log the debug message */
10968 /* XXX maybe we should actually take notice of the return value */
10969 ssh2_pkt_getbool(pktin);
10970 ssh_pkt_getstring(pktin, &msg, &msglen);
10972 logeventf(ssh, "Remote debug message: %.*s", msglen, NULLTOEMPTY(msg));
10975 static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
10977 do_ssh2_transport(ssh, NULL, 0, pktin);
10981 * Called if we receive a packet that isn't allowed by the protocol.
10982 * This only applies to packets whose meaning PuTTY understands.
10983 * Entirely unknown packets are handled below.
10985 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
10987 char *buf = dupprintf("Server protocol violation: unexpected %s packet",
10988 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
10990 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
10994 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
10996 struct Packet *pktout;
10997 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
10998 ssh2_pkt_adduint32(pktout, pktin->sequence);
11000 * UNIMPLEMENTED messages MUST appear in the same order as the
11001 * messages they respond to. Hence, never queue them.
11003 ssh2_pkt_send_noqueue(ssh, pktout);
11007 * Handle the top-level SSH-2 protocol.
11009 static void ssh2_protocol_setup(Ssh ssh)
11014 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
11016 for (i = 0; i < 256; i++)
11017 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
11020 * Initially, we only accept transport messages (and a few generic
11021 * ones). do_ssh2_authconn will add more when it starts.
11022 * Messages that are understood but not currently acceptable go to
11023 * ssh2_msg_unexpected.
11025 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
11026 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
11027 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
11028 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
11029 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
11030 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
11031 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
11032 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
11033 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
11034 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
11035 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
11036 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
11037 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
11038 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
11039 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
11040 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
11041 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
11042 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
11043 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
11044 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
11045 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
11046 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
11047 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
11048 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
11049 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
11050 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
11051 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
11052 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
11053 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
11054 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
11055 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
11056 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
11057 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
11060 * These messages have a special handler from the start.
11062 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
11063 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
11064 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
11067 static void ssh2_bare_connection_protocol_setup(Ssh ssh)
11072 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
11074 for (i = 0; i < 256; i++)
11075 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
11078 * Initially, we set all ssh-connection messages to 'unexpected';
11079 * do_ssh2_authconn will fill things in properly. We also handle a
11080 * couple of messages from the transport protocol which aren't
11081 * related to key exchange (UNIMPLEMENTED, IGNORE, DEBUG,
11084 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
11085 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
11086 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
11087 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
11088 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
11089 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
11090 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
11091 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
11092 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
11093 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
11094 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
11095 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
11096 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
11097 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
11099 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
11102 * These messages have a special handler from the start.
11104 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
11105 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore;
11106 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
11109 static void ssh2_timer(void *ctx, unsigned long now)
11111 Ssh ssh = (Ssh)ctx;
11113 if (ssh->state == SSH_STATE_CLOSED)
11116 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11117 conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
11118 now == ssh->next_rekey) {
11119 do_ssh2_transport(ssh, "timeout", -1, NULL);
11123 static void ssh2_protocol(Ssh ssh, const void *vin, int inlen,
11124 struct Packet *pktin)
11126 const unsigned char *in = (const unsigned char *)vin;
11127 if (ssh->state == SSH_STATE_CLOSED)
11131 ssh->incoming_data_size += pktin->encrypted_len;
11132 if (!ssh->kex_in_progress &&
11133 ssh->max_data_size != 0 &&
11134 ssh->incoming_data_size > ssh->max_data_size)
11135 do_ssh2_transport(ssh, "too much data received", -1, NULL);
11139 ssh->packet_dispatch[pktin->type](ssh, pktin);
11140 else if (!ssh->protocol_initial_phase_done)
11141 do_ssh2_transport(ssh, in, inlen, pktin);
11143 do_ssh2_authconn(ssh, in, inlen, pktin);
11146 static void ssh2_bare_connection_protocol(Ssh ssh, const void *vin, int inlen,
11147 struct Packet *pktin)
11149 const unsigned char *in = (const unsigned char *)vin;
11150 if (ssh->state == SSH_STATE_CLOSED)
11154 ssh->packet_dispatch[pktin->type](ssh, pktin);
11156 do_ssh2_authconn(ssh, in, inlen, pktin);
11159 static void ssh_cache_conf_values(Ssh ssh)
11161 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
11165 * Called to set up the connection.
11167 * Returns an error message, or NULL on success.
11169 static const char *ssh_init(void *frontend_handle, void **backend_handle,
11171 const char *host, int port, char **realhost,
11172 int nodelay, int keepalive)
11177 ssh = snew(struct ssh_tag);
11178 ssh->conf = conf_copy(conf);
11179 ssh_cache_conf_values(ssh);
11180 ssh->version = 0; /* when not ready yet */
11182 ssh->cipher = NULL;
11183 ssh->v1_cipher_ctx = NULL;
11184 ssh->crcda_ctx = NULL;
11185 ssh->cscipher = NULL;
11186 ssh->cs_cipher_ctx = NULL;
11187 ssh->sccipher = NULL;
11188 ssh->sc_cipher_ctx = NULL;
11190 ssh->cs_mac_ctx = NULL;
11192 ssh->sc_mac_ctx = NULL;
11193 ssh->cscomp = NULL;
11194 ssh->cs_comp_ctx = NULL;
11195 ssh->sccomp = NULL;
11196 ssh->sc_comp_ctx = NULL;
11198 ssh->kex_ctx = NULL;
11199 ssh->hostkey = NULL;
11200 ssh->hostkey_str = NULL;
11201 ssh->exitcode = -1;
11202 ssh->close_expected = FALSE;
11203 ssh->clean_exit = FALSE;
11204 ssh->state = SSH_STATE_PREPACKET;
11205 ssh->size_needed = FALSE;
11206 ssh->eof_needed = FALSE;
11208 ssh->logctx = NULL;
11209 ssh->deferred_send_data = NULL;
11210 ssh->deferred_len = 0;
11211 ssh->deferred_size = 0;
11212 ssh->fallback_cmd = 0;
11213 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
11214 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
11215 ssh->x11disp = NULL;
11216 ssh->x11auth = NULL;
11217 ssh->x11authtree = newtree234(x11_authcmp);
11218 ssh->v1_compressing = FALSE;
11219 ssh->v2_outgoing_sequence = 0;
11220 ssh->ssh1_rdpkt_crstate = 0;
11221 ssh->ssh2_rdpkt_crstate = 0;
11222 ssh->ssh2_bare_rdpkt_crstate = 0;
11223 ssh->ssh_gotdata_crstate = 0;
11224 ssh->do_ssh1_connection_crstate = 0;
11225 ssh->do_ssh_init_state = NULL;
11226 ssh->do_ssh_connection_init_state = NULL;
11227 ssh->do_ssh1_login_state = NULL;
11228 ssh->do_ssh2_transport_state = NULL;
11229 ssh->do_ssh2_authconn_state = NULL;
11232 ssh->mainchan = NULL;
11233 ssh->throttled_all = 0;
11234 ssh->v1_stdout_throttling = 0;
11236 ssh->queuelen = ssh->queuesize = 0;
11237 ssh->queueing = FALSE;
11238 ssh->qhead = ssh->qtail = NULL;
11239 ssh->deferred_rekey_reason = NULL;
11240 bufchain_init(&ssh->queued_incoming_data);
11241 ssh->frozen = FALSE;
11242 ssh->username = NULL;
11243 ssh->sent_console_eof = FALSE;
11244 ssh->got_pty = FALSE;
11245 ssh->bare_connection = FALSE;
11246 ssh->X11_fwd_enabled = FALSE;
11247 ssh->connshare = NULL;
11248 ssh->attempting_connshare = FALSE;
11249 ssh->session_started = FALSE;
11250 ssh->specials = NULL;
11251 ssh->n_uncert_hostkeys = 0;
11252 ssh->cross_certifying = FALSE;
11254 *backend_handle = ssh;
11257 if (crypto_startup() == 0)
11258 return "Microsoft high encryption pack not installed!";
11261 ssh->frontend = frontend_handle;
11262 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
11263 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
11265 ssh->channels = NULL;
11266 ssh->rportfwds = NULL;
11267 ssh->portfwds = NULL;
11272 ssh->conn_throttle_count = 0;
11273 ssh->overall_bufsize = 0;
11274 ssh->fallback_cmd = 0;
11276 ssh->protocol = NULL;
11278 ssh->protocol_initial_phase_done = FALSE;
11280 ssh->pinger = NULL;
11282 ssh->incoming_data_size = ssh->outgoing_data_size =
11283 ssh->deferred_data_size = 0L;
11284 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11285 CONF_ssh_rekey_data));
11286 ssh->kex_in_progress = FALSE;
11288 ssh->auth_agent_query = NULL;
11291 ssh->gsslibs = NULL;
11294 random_ref(); /* do this now - may be needed by sharing setup code */
11296 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
11305 static void ssh_free(void *handle)
11307 Ssh ssh = (Ssh) handle;
11308 struct ssh_channel *c;
11309 struct ssh_rportfwd *pf;
11310 struct X11FakeAuth *auth;
11312 if (ssh->v1_cipher_ctx)
11313 ssh->cipher->free_context(ssh->v1_cipher_ctx);
11314 if (ssh->cs_cipher_ctx)
11315 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
11316 if (ssh->sc_cipher_ctx)
11317 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
11318 if (ssh->cs_mac_ctx)
11319 ssh->csmac->free_context(ssh->cs_mac_ctx);
11320 if (ssh->sc_mac_ctx)
11321 ssh->scmac->free_context(ssh->sc_mac_ctx);
11322 if (ssh->cs_comp_ctx) {
11324 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
11326 zlib_compress_cleanup(ssh->cs_comp_ctx);
11328 if (ssh->sc_comp_ctx) {
11330 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
11332 zlib_decompress_cleanup(ssh->sc_comp_ctx);
11335 dh_cleanup(ssh->kex_ctx);
11336 sfree(ssh->savedhost);
11338 while (ssh->queuelen-- > 0)
11339 ssh_free_packet(ssh->queue[ssh->queuelen]);
11342 while (ssh->qhead) {
11343 struct queued_handler *qh = ssh->qhead;
11344 ssh->qhead = qh->next;
11347 ssh->qhead = ssh->qtail = NULL;
11349 if (ssh->channels) {
11350 while ((c = delpos234(ssh->channels, 0)) != NULL) {
11351 ssh_channel_close_local(c, NULL);
11352 if (ssh->version == 2) {
11353 struct outstanding_channel_request *ocr, *nocr;
11354 ocr = c->v.v2.chanreq_head;
11356 ocr->handler(c, NULL, ocr->ctx);
11361 bufchain_clear(&c->v.v2.outbuffer);
11365 freetree234(ssh->channels);
11366 ssh->channels = NULL;
11369 if (ssh->connshare)
11370 sharestate_free(ssh->connshare);
11372 if (ssh->rportfwds) {
11373 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
11375 freetree234(ssh->rportfwds);
11376 ssh->rportfwds = NULL;
11378 sfree(ssh->deferred_send_data);
11380 x11_free_display(ssh->x11disp);
11381 while ((auth = delpos234(ssh->x11authtree, 0)) != NULL)
11382 x11_free_fake_auth(auth);
11383 freetree234(ssh->x11authtree);
11384 sfree(ssh->do_ssh_init_state);
11385 sfree(ssh->do_ssh1_login_state);
11386 sfree(ssh->do_ssh2_transport_state);
11387 sfree(ssh->do_ssh2_authconn_state);
11390 sfree(ssh->fullhostname);
11391 sfree(ssh->hostkey_str);
11392 sfree(ssh->specials);
11393 if (ssh->crcda_ctx) {
11394 crcda_free_context(ssh->crcda_ctx);
11395 ssh->crcda_ctx = NULL;
11398 ssh_do_close(ssh, TRUE);
11399 expire_timer_context(ssh);
11401 pinger_free(ssh->pinger);
11402 bufchain_clear(&ssh->queued_incoming_data);
11403 sfree(ssh->username);
11404 conf_free(ssh->conf);
11406 if (ssh->auth_agent_query)
11407 agent_cancel_query(ssh->auth_agent_query);
11411 ssh_gss_cleanup(ssh->gsslibs);
11419 * Reconfigure the SSH backend.
11421 static void ssh_reconfig(void *handle, Conf *conf)
11423 Ssh ssh = (Ssh) handle;
11424 const char *rekeying = NULL;
11425 int rekey_mandatory = FALSE;
11426 unsigned long old_max_data_size;
11429 pinger_reconfig(ssh->pinger, ssh->conf, conf);
11431 ssh_setup_portfwd(ssh, conf);
11433 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
11434 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
11436 unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
11437 unsigned long now = GETTICKCOUNT();
11439 if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
11440 rekeying = "timeout shortened";
11442 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
11446 old_max_data_size = ssh->max_data_size;
11447 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11448 CONF_ssh_rekey_data));
11449 if (old_max_data_size != ssh->max_data_size &&
11450 ssh->max_data_size != 0) {
11451 if (ssh->outgoing_data_size > ssh->max_data_size ||
11452 ssh->incoming_data_size > ssh->max_data_size)
11453 rekeying = "data limit lowered";
11456 if (conf_get_int(ssh->conf, CONF_compression) !=
11457 conf_get_int(conf, CONF_compression)) {
11458 rekeying = "compression setting changed";
11459 rekey_mandatory = TRUE;
11462 for (i = 0; i < CIPHER_MAX; i++)
11463 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
11464 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
11465 rekeying = "cipher settings changed";
11466 rekey_mandatory = TRUE;
11468 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
11469 conf_get_int(conf, CONF_ssh2_des_cbc)) {
11470 rekeying = "cipher settings changed";
11471 rekey_mandatory = TRUE;
11474 conf_free(ssh->conf);
11475 ssh->conf = conf_copy(conf);
11476 ssh_cache_conf_values(ssh);
11478 if (!ssh->bare_connection && rekeying) {
11479 if (!ssh->kex_in_progress) {
11480 do_ssh2_transport(ssh, rekeying, -1, NULL);
11481 } else if (rekey_mandatory) {
11482 ssh->deferred_rekey_reason = rekeying;
11488 * Called to send data down the SSH connection.
11490 static int ssh_send(void *handle, const char *buf, int len)
11492 Ssh ssh = (Ssh) handle;
11494 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11497 ssh->protocol(ssh, (const unsigned char *)buf, len, 0);
11499 return ssh_sendbuffer(ssh);
11503 * Called to query the current amount of buffered stdin data.
11505 static int ssh_sendbuffer(void *handle)
11507 Ssh ssh = (Ssh) handle;
11508 int override_value;
11510 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11514 * If the SSH socket itself has backed up, add the total backup
11515 * size on that to any individual buffer on the stdin channel.
11517 override_value = 0;
11518 if (ssh->throttled_all)
11519 override_value = ssh->overall_bufsize;
11521 if (ssh->version == 1) {
11522 return override_value;
11523 } else if (ssh->version == 2) {
11524 if (!ssh->mainchan)
11525 return override_value;
11527 return (override_value +
11528 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
11535 * Called to set the size of the window from SSH's POV.
11537 static void ssh_size(void *handle, int width, int height)
11539 Ssh ssh = (Ssh) handle;
11540 struct Packet *pktout;
11542 ssh->term_width = width;
11543 ssh->term_height = height;
11545 switch (ssh->state) {
11546 case SSH_STATE_BEFORE_SIZE:
11547 case SSH_STATE_PREPACKET:
11548 case SSH_STATE_CLOSED:
11549 break; /* do nothing */
11550 case SSH_STATE_INTERMED:
11551 ssh->size_needed = TRUE; /* buffer for later */
11553 case SSH_STATE_SESSION:
11554 if (!conf_get_int(ssh->conf, CONF_nopty)) {
11555 if (ssh->version == 1) {
11556 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
11557 PKT_INT, ssh->term_height,
11558 PKT_INT, ssh->term_width,
11559 PKT_INT, 0, PKT_INT, 0, PKT_END);
11560 } else if (ssh->mainchan) {
11561 pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
11563 ssh2_pkt_adduint32(pktout, ssh->term_width);
11564 ssh2_pkt_adduint32(pktout, ssh->term_height);
11565 ssh2_pkt_adduint32(pktout, 0);
11566 ssh2_pkt_adduint32(pktout, 0);
11567 ssh2_pkt_send(ssh, pktout);
11575 * Return a list of the special codes that make sense in this
11578 static const struct telnet_special *ssh_get_specials(void *handle)
11580 static const struct telnet_special ssh1_ignore_special[] = {
11581 {"IGNORE message", TS_NOP}
11583 static const struct telnet_special ssh2_ignore_special[] = {
11584 {"IGNORE message", TS_NOP},
11586 static const struct telnet_special ssh2_rekey_special[] = {
11587 {"Repeat key exchange", TS_REKEY},
11589 static const struct telnet_special ssh2_session_specials[] = {
11592 /* These are the signal names defined by RFC 4254.
11593 * They include all the ISO C signals, but are a subset of the POSIX
11594 * required signals. */
11595 {"SIGINT (Interrupt)", TS_SIGINT},
11596 {"SIGTERM (Terminate)", TS_SIGTERM},
11597 {"SIGKILL (Kill)", TS_SIGKILL},
11598 {"SIGQUIT (Quit)", TS_SIGQUIT},
11599 {"SIGHUP (Hangup)", TS_SIGHUP},
11600 {"More signals", TS_SUBMENU},
11601 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
11602 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
11603 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
11604 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
11605 {NULL, TS_EXITMENU}
11607 static const struct telnet_special specials_end[] = {
11608 {NULL, TS_EXITMENU}
11611 struct telnet_special *specials = NULL;
11612 int nspecials = 0, specialsize = 0;
11614 Ssh ssh = (Ssh) handle;
11616 sfree(ssh->specials);
11618 #define ADD_SPECIALS(name) do \
11620 int len = lenof(name); \
11621 if (nspecials + len > specialsize) { \
11622 specialsize = (nspecials + len) * 5 / 4 + 32; \
11623 specials = sresize(specials, specialsize, struct telnet_special); \
11625 memcpy(specials+nspecials, name, len*sizeof(struct telnet_special)); \
11626 nspecials += len; \
11629 if (ssh->version == 1) {
11630 /* Don't bother offering IGNORE if we've decided the remote
11631 * won't cope with it, since we wouldn't bother sending it if
11633 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11634 ADD_SPECIALS(ssh1_ignore_special);
11635 } else if (ssh->version == 2) {
11636 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
11637 ADD_SPECIALS(ssh2_ignore_special);
11638 if (!(ssh->remote_bugs & BUG_SSH2_REKEY) && !ssh->bare_connection)
11639 ADD_SPECIALS(ssh2_rekey_special);
11641 ADD_SPECIALS(ssh2_session_specials);
11643 if (ssh->n_uncert_hostkeys) {
11644 static const struct telnet_special uncert_start[] = {
11646 {"Cache new host key type", TS_SUBMENU},
11648 static const struct telnet_special uncert_end[] = {
11649 {NULL, TS_EXITMENU},
11653 ADD_SPECIALS(uncert_start);
11654 for (i = 0; i < ssh->n_uncert_hostkeys; i++) {
11655 struct telnet_special uncert[1];
11656 const struct ssh_signkey *alg =
11657 hostkey_algs[ssh->uncert_hostkeys[i]].alg;
11658 uncert[0].name = alg->name;
11659 uncert[0].code = TS_LOCALSTART + ssh->uncert_hostkeys[i];
11660 ADD_SPECIALS(uncert);
11662 ADD_SPECIALS(uncert_end);
11664 } /* else we're not ready yet */
11667 ADD_SPECIALS(specials_end);
11669 ssh->specials = specials;
11676 #undef ADD_SPECIALS
11680 * Send special codes. TS_EOF is useful for `plink', so you
11681 * can send an EOF and collect resulting output (e.g. `plink
11684 static void ssh_special(void *handle, Telnet_Special code)
11686 Ssh ssh = (Ssh) handle;
11687 struct Packet *pktout;
11689 if (code == TS_EOF) {
11690 if (ssh->state != SSH_STATE_SESSION) {
11692 * Buffer the EOF in case we are pre-SESSION, so we can
11693 * send it as soon as we reach SESSION.
11695 if (code == TS_EOF)
11696 ssh->eof_needed = TRUE;
11699 if (ssh->version == 1) {
11700 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
11701 } else if (ssh->mainchan) {
11702 sshfwd_write_eof(ssh->mainchan);
11703 ssh->send_ok = 0; /* now stop trying to read from stdin */
11705 logevent("Sent EOF message");
11706 } else if (code == TS_PING || code == TS_NOP) {
11707 if (ssh->state == SSH_STATE_CLOSED
11708 || ssh->state == SSH_STATE_PREPACKET) return;
11709 if (ssh->version == 1) {
11710 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11711 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
11713 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
11714 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
11715 ssh2_pkt_addstring_start(pktout);
11716 ssh2_pkt_send_noqueue(ssh, pktout);
11719 } else if (code == TS_REKEY) {
11720 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11721 ssh->version == 2) {
11722 do_ssh2_transport(ssh, "at user request", -1, NULL);
11724 } else if (code >= TS_LOCALSTART) {
11725 ssh->hostkey = hostkey_algs[code - TS_LOCALSTART].alg;
11726 ssh->cross_certifying = TRUE;
11727 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11728 ssh->version == 2) {
11729 do_ssh2_transport(ssh, "cross-certifying new host key", -1, NULL);
11731 } else if (code == TS_BRK) {
11732 if (ssh->state == SSH_STATE_CLOSED
11733 || ssh->state == SSH_STATE_PREPACKET) return;
11734 if (ssh->version == 1) {
11735 logevent("Unable to send BREAK signal in SSH-1");
11736 } else if (ssh->mainchan) {
11737 pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
11738 ssh2_pkt_adduint32(pktout, 0); /* default break length */
11739 ssh2_pkt_send(ssh, pktout);
11742 /* Is is a POSIX signal? */
11743 const char *signame = NULL;
11744 if (code == TS_SIGABRT) signame = "ABRT";
11745 if (code == TS_SIGALRM) signame = "ALRM";
11746 if (code == TS_SIGFPE) signame = "FPE";
11747 if (code == TS_SIGHUP) signame = "HUP";
11748 if (code == TS_SIGILL) signame = "ILL";
11749 if (code == TS_SIGINT) signame = "INT";
11750 if (code == TS_SIGKILL) signame = "KILL";
11751 if (code == TS_SIGPIPE) signame = "PIPE";
11752 if (code == TS_SIGQUIT) signame = "QUIT";
11753 if (code == TS_SIGSEGV) signame = "SEGV";
11754 if (code == TS_SIGTERM) signame = "TERM";
11755 if (code == TS_SIGUSR1) signame = "USR1";
11756 if (code == TS_SIGUSR2) signame = "USR2";
11757 /* The SSH-2 protocol does in principle support arbitrary named
11758 * signals, including signame@domain, but we don't support those. */
11760 /* It's a signal. */
11761 if (ssh->version == 2 && ssh->mainchan) {
11762 pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
11763 ssh2_pkt_addstring(pktout, signame);
11764 ssh2_pkt_send(ssh, pktout);
11765 logeventf(ssh, "Sent signal SIG%s", signame);
11768 /* Never heard of it. Do nothing */
11773 void *new_sock_channel(void *handle, struct PortForwarding *pf)
11775 Ssh ssh = (Ssh) handle;
11776 struct ssh_channel *c;
11777 c = snew(struct ssh_channel);
11780 ssh_channel_init(c);
11781 c->halfopen = TRUE;
11782 c->type = CHAN_SOCKDATA;/* identify channel type */
11787 unsigned ssh_alloc_sharing_channel(Ssh ssh, void *sharing_ctx)
11789 struct ssh_channel *c;
11790 c = snew(struct ssh_channel);
11793 ssh_channel_init(c);
11794 c->type = CHAN_SHARING;
11795 c->u.sharing.ctx = sharing_ctx;
11799 void ssh_delete_sharing_channel(Ssh ssh, unsigned localid)
11801 struct ssh_channel *c;
11803 c = find234(ssh->channels, &localid, ssh_channelfind);
11805 ssh_channel_destroy(c);
11808 void ssh_send_packet_from_downstream(Ssh ssh, unsigned id, int type,
11809 const void *data, int datalen,
11810 const char *additional_log_text)
11812 struct Packet *pkt;
11814 pkt = ssh2_pkt_init(type);
11815 pkt->downstream_id = id;
11816 pkt->additional_log_text = additional_log_text;
11817 ssh2_pkt_adddata(pkt, data, datalen);
11818 ssh2_pkt_send(ssh, pkt);
11822 * This is called when stdout/stderr (the entity to which
11823 * from_backend sends data) manages to clear some backlog.
11825 static void ssh_unthrottle(void *handle, int bufsize)
11827 Ssh ssh = (Ssh) handle;
11829 if (ssh->version == 1) {
11830 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
11831 ssh->v1_stdout_throttling = 0;
11832 ssh_throttle_conn(ssh, -1);
11836 ssh_channel_unthrottle(ssh->mainchan, bufsize);
11840 * Now process any SSH connection data that was stashed in our
11841 * queue while we were frozen.
11843 ssh_process_queued_incoming_data(ssh);
11846 void ssh_send_port_open(void *channel, const char *hostname, int port,
11849 struct ssh_channel *c = (struct ssh_channel *)channel;
11851 struct Packet *pktout;
11853 logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
11855 if (ssh->version == 1) {
11856 send_packet(ssh, SSH1_MSG_PORT_OPEN,
11857 PKT_INT, c->localid,
11860 /* PKT_STR, <org:orgport>, */
11863 pktout = ssh2_chanopen_init(c, "direct-tcpip");
11865 char *trimmed_host = host_strduptrim(hostname);
11866 ssh2_pkt_addstring(pktout, trimmed_host);
11867 sfree(trimmed_host);
11869 ssh2_pkt_adduint32(pktout, port);
11871 * We make up values for the originator data; partly it's
11872 * too much hassle to keep track, and partly I'm not
11873 * convinced the server should be told details like that
11874 * about my local network configuration.
11875 * The "originator IP address" is syntactically a numeric
11876 * IP address, and some servers (e.g., Tectia) get upset
11877 * if it doesn't match this syntax.
11879 ssh2_pkt_addstring(pktout, "0.0.0.0");
11880 ssh2_pkt_adduint32(pktout, 0);
11881 ssh2_pkt_send(ssh, pktout);
11885 static int ssh_connected(void *handle)
11887 Ssh ssh = (Ssh) handle;
11888 return ssh->s != NULL;
11891 static int ssh_sendok(void *handle)
11893 Ssh ssh = (Ssh) handle;
11894 return ssh->send_ok;
11897 static int ssh_ldisc(void *handle, int option)
11899 Ssh ssh = (Ssh) handle;
11900 if (option == LD_ECHO)
11901 return ssh->echoing;
11902 if (option == LD_EDIT)
11903 return ssh->editing;
11907 static void ssh_provide_ldisc(void *handle, void *ldisc)
11909 Ssh ssh = (Ssh) handle;
11910 ssh->ldisc = ldisc;
11913 static void ssh_provide_logctx(void *handle, void *logctx)
11915 Ssh ssh = (Ssh) handle;
11916 ssh->logctx = logctx;
11919 static int ssh_return_exitcode(void *handle)
11921 Ssh ssh = (Ssh) handle;
11922 if (ssh->s != NULL)
11925 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
11929 * cfg_info for SSH is the protocol running in this session.
11930 * (1 or 2 for the full SSH-1 or SSH-2 protocol; -1 for the bare
11931 * SSH-2 connection protocol, i.e. a downstream; 0 for not-decided-yet.)
11933 static int ssh_cfg_info(void *handle)
11935 Ssh ssh = (Ssh) handle;
11936 if (ssh->version == 0)
11937 return 0; /* don't know yet */
11938 else if (ssh->bare_connection)
11941 return ssh->version;
11945 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
11946 * that fails. This variable is the means by which scp.c can reach
11947 * into the SSH code and find out which one it got.
11949 extern int ssh_fallback_cmd(void *handle)
11951 Ssh ssh = (Ssh) handle;
11952 return ssh->fallback_cmd;
11955 Backend ssh_backend = {
11965 ssh_return_exitcode,
11969 ssh_provide_logctx,
11972 ssh_test_for_upstream,