29 * Packet type contexts, so that ssh2_pkt_type can correctly decode
30 * the ambiguous type numbers back into the correct type strings.
41 SSH2_PKTCTX_PUBLICKEY,
47 static const char *const ssh2_disconnect_reasons[] = {
49 "host not allowed to connect",
51 "key exchange failed",
52 "host authentication failed",
55 "service not available",
56 "protocol version not supported",
57 "host key not verifiable",
60 "too many connections",
61 "auth cancelled by user",
62 "no more auth methods available",
67 * Various remote-bug flags.
69 #define BUG_CHOKES_ON_SSH1_IGNORE 1
70 #define BUG_SSH2_HMAC 2
71 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
72 #define BUG_CHOKES_ON_RSA 8
73 #define BUG_SSH2_RSA_PADDING 16
74 #define BUG_SSH2_DERIVEKEY 32
75 #define BUG_SSH2_REKEY 64
76 #define BUG_SSH2_PK_SESSIONID 128
77 #define BUG_SSH2_MAXPKT 256
78 #define BUG_CHOKES_ON_SSH2_IGNORE 512
79 #define BUG_CHOKES_ON_WINADJ 1024
80 #define BUG_SENDS_LATE_REQUEST_REPLY 2048
81 #define BUG_SSH2_OLDGEX 4096
83 #define DH_MIN_SIZE 1024
84 #define DH_MAX_SIZE 8192
87 * Codes for terminal modes.
88 * Most of these are the same in SSH-1 and SSH-2.
89 * This list is derived from RFC 4254 and
93 const char* const mode;
95 enum { TTY_OP_CHAR, TTY_OP_BOOL } type;
97 /* "V" prefix discarded for special characters relative to SSH specs */
98 { "INTR", 1, TTY_OP_CHAR },
99 { "QUIT", 2, TTY_OP_CHAR },
100 { "ERASE", 3, TTY_OP_CHAR },
101 { "KILL", 4, TTY_OP_CHAR },
102 { "EOF", 5, TTY_OP_CHAR },
103 { "EOL", 6, TTY_OP_CHAR },
104 { "EOL2", 7, TTY_OP_CHAR },
105 { "START", 8, TTY_OP_CHAR },
106 { "STOP", 9, TTY_OP_CHAR },
107 { "SUSP", 10, TTY_OP_CHAR },
108 { "DSUSP", 11, TTY_OP_CHAR },
109 { "REPRINT", 12, TTY_OP_CHAR },
110 { "WERASE", 13, TTY_OP_CHAR },
111 { "LNEXT", 14, TTY_OP_CHAR },
112 { "FLUSH", 15, TTY_OP_CHAR },
113 { "SWTCH", 16, TTY_OP_CHAR },
114 { "STATUS", 17, TTY_OP_CHAR },
115 { "DISCARD", 18, TTY_OP_CHAR },
116 { "IGNPAR", 30, TTY_OP_BOOL },
117 { "PARMRK", 31, TTY_OP_BOOL },
118 { "INPCK", 32, TTY_OP_BOOL },
119 { "ISTRIP", 33, TTY_OP_BOOL },
120 { "INLCR", 34, TTY_OP_BOOL },
121 { "IGNCR", 35, TTY_OP_BOOL },
122 { "ICRNL", 36, TTY_OP_BOOL },
123 { "IUCLC", 37, TTY_OP_BOOL },
124 { "IXON", 38, TTY_OP_BOOL },
125 { "IXANY", 39, TTY_OP_BOOL },
126 { "IXOFF", 40, TTY_OP_BOOL },
127 { "IMAXBEL", 41, TTY_OP_BOOL },
128 { "ISIG", 50, TTY_OP_BOOL },
129 { "ICANON", 51, TTY_OP_BOOL },
130 { "XCASE", 52, TTY_OP_BOOL },
131 { "ECHO", 53, TTY_OP_BOOL },
132 { "ECHOE", 54, TTY_OP_BOOL },
133 { "ECHOK", 55, TTY_OP_BOOL },
134 { "ECHONL", 56, TTY_OP_BOOL },
135 { "NOFLSH", 57, TTY_OP_BOOL },
136 { "TOSTOP", 58, TTY_OP_BOOL },
137 { "IEXTEN", 59, TTY_OP_BOOL },
138 { "ECHOCTL", 60, TTY_OP_BOOL },
139 { "ECHOKE", 61, TTY_OP_BOOL },
140 { "PENDIN", 62, TTY_OP_BOOL }, /* XXX is this a real mode? */
141 { "OPOST", 70, TTY_OP_BOOL },
142 { "OLCUC", 71, TTY_OP_BOOL },
143 { "ONLCR", 72, TTY_OP_BOOL },
144 { "OCRNL", 73, TTY_OP_BOOL },
145 { "ONOCR", 74, TTY_OP_BOOL },
146 { "ONLRET", 75, TTY_OP_BOOL },
147 { "CS7", 90, TTY_OP_BOOL },
148 { "CS8", 91, TTY_OP_BOOL },
149 { "PARENB", 92, TTY_OP_BOOL },
150 { "PARODD", 93, TTY_OP_BOOL }
153 /* Miscellaneous other tty-related constants. */
154 #define SSH_TTY_OP_END 0
155 /* The opcodes for ISPEED/OSPEED differ between SSH-1 and SSH-2. */
156 #define SSH1_TTY_OP_ISPEED 192
157 #define SSH1_TTY_OP_OSPEED 193
158 #define SSH2_TTY_OP_ISPEED 128
159 #define SSH2_TTY_OP_OSPEED 129
161 /* Helper functions for parsing tty-related config. */
162 static unsigned int ssh_tty_parse_specchar(char *s)
167 ret = ctrlparse(s, &next);
168 if (!next) ret = s[0];
170 ret = 255; /* special value meaning "don't set" */
174 static unsigned int ssh_tty_parse_boolean(char *s)
176 if (stricmp(s, "yes") == 0 ||
177 stricmp(s, "on") == 0 ||
178 stricmp(s, "true") == 0 ||
179 stricmp(s, "+") == 0)
181 else if (stricmp(s, "no") == 0 ||
182 stricmp(s, "off") == 0 ||
183 stricmp(s, "false") == 0 ||
184 stricmp(s, "-") == 0)
185 return 0; /* false */
187 return (atoi(s) != 0);
190 #define translate(x) if (type == x) return #x
191 #define translatek(x,ctx) if (type == x && (pkt_kctx == ctx)) return #x
192 #define translatea(x,ctx) if (type == x && (pkt_actx == ctx)) return #x
193 static const char *ssh1_pkt_type(int type)
195 translate(SSH1_MSG_DISCONNECT);
196 translate(SSH1_SMSG_PUBLIC_KEY);
197 translate(SSH1_CMSG_SESSION_KEY);
198 translate(SSH1_CMSG_USER);
199 translate(SSH1_CMSG_AUTH_RSA);
200 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
201 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
202 translate(SSH1_CMSG_AUTH_PASSWORD);
203 translate(SSH1_CMSG_REQUEST_PTY);
204 translate(SSH1_CMSG_WINDOW_SIZE);
205 translate(SSH1_CMSG_EXEC_SHELL);
206 translate(SSH1_CMSG_EXEC_CMD);
207 translate(SSH1_SMSG_SUCCESS);
208 translate(SSH1_SMSG_FAILURE);
209 translate(SSH1_CMSG_STDIN_DATA);
210 translate(SSH1_SMSG_STDOUT_DATA);
211 translate(SSH1_SMSG_STDERR_DATA);
212 translate(SSH1_CMSG_EOF);
213 translate(SSH1_SMSG_EXIT_STATUS);
214 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
215 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
216 translate(SSH1_MSG_CHANNEL_DATA);
217 translate(SSH1_MSG_CHANNEL_CLOSE);
218 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
219 translate(SSH1_SMSG_X11_OPEN);
220 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
221 translate(SSH1_MSG_PORT_OPEN);
222 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
223 translate(SSH1_SMSG_AGENT_OPEN);
224 translate(SSH1_MSG_IGNORE);
225 translate(SSH1_CMSG_EXIT_CONFIRMATION);
226 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
227 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
228 translate(SSH1_MSG_DEBUG);
229 translate(SSH1_CMSG_REQUEST_COMPRESSION);
230 translate(SSH1_CMSG_AUTH_TIS);
231 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
232 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
233 translate(SSH1_CMSG_AUTH_CCARD);
234 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
235 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
238 static const char *ssh2_pkt_type(Pkt_KCtx pkt_kctx, Pkt_ACtx pkt_actx,
241 translatea(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE,SSH2_PKTCTX_GSSAPI);
242 translatea(SSH2_MSG_USERAUTH_GSSAPI_TOKEN,SSH2_PKTCTX_GSSAPI);
243 translatea(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE,SSH2_PKTCTX_GSSAPI);
244 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERROR,SSH2_PKTCTX_GSSAPI);
245 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK,SSH2_PKTCTX_GSSAPI);
246 translatea(SSH2_MSG_USERAUTH_GSSAPI_MIC, SSH2_PKTCTX_GSSAPI);
247 translate(SSH2_MSG_DISCONNECT);
248 translate(SSH2_MSG_IGNORE);
249 translate(SSH2_MSG_UNIMPLEMENTED);
250 translate(SSH2_MSG_DEBUG);
251 translate(SSH2_MSG_SERVICE_REQUEST);
252 translate(SSH2_MSG_SERVICE_ACCEPT);
253 translate(SSH2_MSG_KEXINIT);
254 translate(SSH2_MSG_NEWKEYS);
255 translatek(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP);
256 translatek(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP);
257 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD, SSH2_PKTCTX_DHGEX);
258 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
259 translatek(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
260 translatek(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
261 translatek(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
262 translatek(SSH2_MSG_KEXRSA_PUBKEY, SSH2_PKTCTX_RSAKEX);
263 translatek(SSH2_MSG_KEXRSA_SECRET, SSH2_PKTCTX_RSAKEX);
264 translatek(SSH2_MSG_KEXRSA_DONE, SSH2_PKTCTX_RSAKEX);
265 translatek(SSH2_MSG_KEX_ECDH_INIT, SSH2_PKTCTX_ECDHKEX);
266 translatek(SSH2_MSG_KEX_ECDH_REPLY, SSH2_PKTCTX_ECDHKEX);
267 translate(SSH2_MSG_USERAUTH_REQUEST);
268 translate(SSH2_MSG_USERAUTH_FAILURE);
269 translate(SSH2_MSG_USERAUTH_SUCCESS);
270 translate(SSH2_MSG_USERAUTH_BANNER);
271 translatea(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
272 translatea(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
273 translatea(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
274 translatea(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
275 translate(SSH2_MSG_GLOBAL_REQUEST);
276 translate(SSH2_MSG_REQUEST_SUCCESS);
277 translate(SSH2_MSG_REQUEST_FAILURE);
278 translate(SSH2_MSG_CHANNEL_OPEN);
279 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
280 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
281 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
282 translate(SSH2_MSG_CHANNEL_DATA);
283 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
284 translate(SSH2_MSG_CHANNEL_EOF);
285 translate(SSH2_MSG_CHANNEL_CLOSE);
286 translate(SSH2_MSG_CHANNEL_REQUEST);
287 translate(SSH2_MSG_CHANNEL_SUCCESS);
288 translate(SSH2_MSG_CHANNEL_FAILURE);
294 /* Enumeration values for fields in SSH-1 packets */
296 PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
300 * Coroutine mechanics for the sillier bits of the code. If these
301 * macros look impenetrable to you, you might find it helpful to
304 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
306 * which explains the theory behind these macros.
308 * In particular, if you are getting `case expression not constant'
309 * errors when building with MS Visual Studio, this is because MS's
310 * Edit and Continue debugging feature causes their compiler to
311 * violate ANSI C. To disable Edit and Continue debugging:
313 * - right-click ssh.c in the FileView
315 * - select the C/C++ tab and the General category
316 * - under `Debug info:', select anything _other_ than `Program
317 * Database for Edit and Continue'.
319 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
320 #define crBeginState crBegin(s->crLine)
321 #define crStateP(t, v) \
323 if (!(v)) { s = (v) = snew(struct t); s->crLine = 0; } \
325 #define crState(t) crStateP(t, ssh->t)
326 #define crFinish(z) } *crLine = 0; return (z); }
327 #define crFinishV } *crLine = 0; return; }
328 #define crFinishFree(z) } sfree(s); return (z); }
329 #define crFinishFreeV } sfree(s); return; }
330 #define crReturn(z) \
332 *crLine =__LINE__; return (z); case __LINE__:;\
336 *crLine=__LINE__; return; case __LINE__:;\
338 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
339 #define crStopV do{ *crLine = 0; return; }while(0)
340 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
341 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
345 static struct Packet *ssh1_pkt_init(int pkt_type);
346 static struct Packet *ssh2_pkt_init(int pkt_type);
347 static void ssh_pkt_ensure(struct Packet *, int length);
348 static void ssh_pkt_adddata(struct Packet *, const void *data, int len);
349 static void ssh_pkt_addbyte(struct Packet *, unsigned char value);
350 static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
351 static void ssh_pkt_adduint32(struct Packet *, unsigned long value);
352 static void ssh_pkt_addstring_start(struct Packet *);
353 static void ssh_pkt_addstring_str(struct Packet *, const char *data);
354 static void ssh_pkt_addstring_data(struct Packet *, const char *data, int len);
355 static void ssh_pkt_addstring(struct Packet *, const char *data);
356 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
357 static void ssh1_pkt_addmp(struct Packet *, Bignum b);
358 static void ssh2_pkt_addmp(struct Packet *, Bignum b);
359 static int ssh2_pkt_construct(Ssh, struct Packet *);
360 static void ssh2_pkt_send(Ssh, struct Packet *);
361 static void ssh2_pkt_send_noqueue(Ssh, struct Packet *);
362 static int do_ssh1_login(Ssh ssh, const unsigned char *in, int inlen,
363 struct Packet *pktin);
364 static void do_ssh2_authconn(Ssh ssh, const unsigned char *in, int inlen,
365 struct Packet *pktin);
366 static void ssh2_channel_check_close(struct ssh_channel *c);
367 static void ssh_channel_destroy(struct ssh_channel *c);
368 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin);
371 * Buffer management constants. There are several of these for
372 * various different purposes:
374 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
375 * on a local data stream before we throttle the whole SSH
376 * connection (in SSH-1 only). Throttling the whole connection is
377 * pretty drastic so we set this high in the hope it won't
380 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
381 * on the SSH connection itself before we defensively throttle
382 * _all_ local data streams. This is pretty drastic too (though
383 * thankfully unlikely in SSH-2 since the window mechanism should
384 * ensure that the server never has any need to throttle its end
385 * of the connection), so we set this high as well.
387 * - OUR_V2_WINSIZE is the maximum window size we present on SSH-2
390 * - OUR_V2_BIGWIN is the window size we advertise for the only
391 * channel in a simple connection. It must be <= INT_MAX.
393 * - OUR_V2_MAXPKT is the official "maximum packet size" we send
394 * to the remote side. This actually has nothing to do with the
395 * size of the _packet_, but is instead a limit on the amount
396 * of data we're willing to receive in a single SSH2 channel
399 * - OUR_V2_PACKETLIMIT is actually the maximum size of SSH
400 * _packet_ we're prepared to cope with. It must be a multiple
401 * of the cipher block size, and must be at least 35000.
404 #define SSH1_BUFFER_LIMIT 32768
405 #define SSH_MAX_BACKLOG 32768
406 #define OUR_V2_WINSIZE 16384
407 #define OUR_V2_BIGWIN 0x7fffffff
408 #define OUR_V2_MAXPKT 0x4000UL
409 #define OUR_V2_PACKETLIMIT 0x9000UL
411 struct ssh_signkey_with_user_pref_id {
412 const struct ssh_signkey *alg;
415 const static struct ssh_signkey_with_user_pref_id hostkey_algs[] = {
416 { &ssh_ecdsa_ed25519, HK_ED25519 },
417 { &ssh_ecdsa_nistp256, HK_ECDSA },
418 { &ssh_ecdsa_nistp384, HK_ECDSA },
419 { &ssh_ecdsa_nistp521, HK_ECDSA },
420 { &ssh_dss, HK_DSA },
421 { &ssh_rsa, HK_RSA },
424 const static struct ssh_mac *const macs[] = {
425 &ssh_hmac_sha256, &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
427 const static struct ssh_mac *const buggymacs[] = {
428 &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
431 static void *ssh_comp_none_init(void)
435 static void ssh_comp_none_cleanup(void *handle)
438 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
439 unsigned char **outblock, int *outlen)
443 static int ssh_comp_none_disable(void *handle)
447 const static struct ssh_compress ssh_comp_none = {
449 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
450 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
451 ssh_comp_none_disable, NULL
453 extern const struct ssh_compress ssh_zlib;
454 const static struct ssh_compress *const compressions[] = {
455 &ssh_zlib, &ssh_comp_none
458 enum { /* channel types */
463 CHAN_SOCKDATA_DORMANT, /* one the remote hasn't confirmed */
465 * CHAN_SHARING indicates a channel which is tracked here on
466 * behalf of a connection-sharing downstream. We do almost nothing
467 * with these channels ourselves: all messages relating to them
468 * get thrown straight to sshshare.c and passed on almost
469 * unmodified to downstream.
473 * CHAN_ZOMBIE is used to indicate a channel for which we've
474 * already destroyed the local data source: for instance, if a
475 * forwarded port experiences a socket error on the local side, we
476 * immediately destroy its local socket and turn the SSH channel
482 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
483 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
484 typedef void (*cchandler_fn_t)(struct ssh_channel *, struct Packet *, void *);
487 * Each channel has a queue of outstanding CHANNEL_REQUESTS and their
490 struct outstanding_channel_request {
491 cchandler_fn_t handler;
493 struct outstanding_channel_request *next;
497 * 2-3-4 tree storing channels.
500 Ssh ssh; /* pointer back to main context */
501 unsigned remoteid, localid;
503 /* True if we opened this channel but server hasn't confirmed. */
506 * In SSH-1, this value contains four bits:
508 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
509 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
510 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
511 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
513 * A channel is completely finished with when all four bits are set.
515 * In SSH-2, the four bits mean:
517 * 1 We have sent SSH2_MSG_CHANNEL_EOF.
518 * 2 We have sent SSH2_MSG_CHANNEL_CLOSE.
519 * 4 We have received SSH2_MSG_CHANNEL_EOF.
520 * 8 We have received SSH2_MSG_CHANNEL_CLOSE.
522 * A channel is completely finished with when we have both sent
523 * and received CLOSE.
525 * The symbolic constants below use the SSH-2 terminology, which
526 * is a bit confusing in SSH-1, but we have to use _something_.
528 #define CLOSES_SENT_EOF 1
529 #define CLOSES_SENT_CLOSE 2
530 #define CLOSES_RCVD_EOF 4
531 #define CLOSES_RCVD_CLOSE 8
535 * This flag indicates that an EOF is pending on the outgoing side
536 * of the channel: that is, wherever we're getting the data for
537 * this channel has sent us some data followed by EOF. We can't
538 * actually send the EOF until we've finished sending the data, so
539 * we set this flag instead to remind us to do so once our buffer
545 * True if this channel is causing the underlying connection to be
550 struct ssh2_data_channel {
552 unsigned remwindow, remmaxpkt;
553 /* locwindow is signed so we can cope with excess data. */
554 int locwindow, locmaxwin;
556 * remlocwin is the amount of local window that we think
557 * the remote end had available to it after it sent the
558 * last data packet or window adjust ack.
562 * These store the list of channel requests that haven't
565 struct outstanding_channel_request *chanreq_head, *chanreq_tail;
566 enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
570 struct ssh_agent_channel {
571 unsigned char *message;
572 unsigned char msglen[4];
573 unsigned lensofar, totallen;
574 int outstanding_requests;
576 struct ssh_x11_channel {
577 struct X11Connection *xconn;
580 struct ssh_pfd_channel {
581 struct PortForwarding *pf;
583 struct ssh_sharing_channel {
590 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
591 * use this structure in different ways, reflecting SSH-2's
592 * altogether saner approach to port forwarding.
594 * In SSH-1, you arrange a remote forwarding by sending the server
595 * the remote port number, and the local destination host:port.
596 * When a connection comes in, the server sends you back that
597 * host:port pair, and you connect to it. This is a ready-made
598 * security hole if you're not on the ball: a malicious server
599 * could send you back _any_ host:port pair, so if you trustingly
600 * connect to the address it gives you then you've just opened the
601 * entire inside of your corporate network just by connecting
602 * through it to a dodgy SSH server. Hence, we must store a list of
603 * host:port pairs we _are_ trying to forward to, and reject a
604 * connection request from the server if it's not in the list.
606 * In SSH-2, each side of the connection minds its own business and
607 * doesn't send unnecessary information to the other. You arrange a
608 * remote forwarding by sending the server just the remote port
609 * number. When a connection comes in, the server tells you which
610 * of its ports was connected to; and _you_ have to remember what
611 * local host:port pair went with that port number.
613 * Hence, in SSH-1 this structure is indexed by destination
614 * host:port pair, whereas in SSH-2 it is indexed by source port.
616 struct ssh_portfwd; /* forward declaration */
618 struct ssh_rportfwd {
619 unsigned sport, dport;
623 struct ssh_portfwd *pfrec;
626 static void free_rportfwd(struct ssh_rportfwd *pf)
629 sfree(pf->sportdesc);
637 * Separately to the rportfwd tree (which is for looking up port
638 * open requests from the server), a tree of _these_ structures is
639 * used to keep track of all the currently open port forwardings,
640 * so that we can reconfigure in mid-session if the user requests
644 enum { DESTROY, KEEP, CREATE } status;
646 unsigned sport, dport;
649 struct ssh_rportfwd *remote;
651 struct PortListener *local;
653 #define free_portfwd(pf) ( \
654 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
655 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
658 long length; /* length of packet: see below */
659 long forcepad; /* SSH-2: force padding to at least this length */
660 int type; /* only used for incoming packets */
661 unsigned long sequence; /* SSH-2 incoming sequence number */
662 unsigned char *data; /* allocated storage */
663 unsigned char *body; /* offset of payload within `data' */
664 long savedpos; /* dual-purpose saved packet position: see below */
665 long maxlen; /* amount of storage allocated for `data' */
666 long encrypted_len; /* for SSH-2 total-size counting */
669 * A note on the 'length' and 'savedpos' fields above.
671 * Incoming packets are set up so that pkt->length is measured
672 * relative to pkt->body, which itself points to a few bytes after
673 * pkt->data (skipping some uninteresting header fields including
674 * the packet type code). The ssh_pkt_get* functions all expect
675 * this setup, and they also use pkt->savedpos to indicate how far
676 * through the packet being decoded they've got - and that, too,
677 * is an offset from pkt->body rather than pkt->data.
679 * During construction of an outgoing packet, however, pkt->length
680 * is measured relative to the base pointer pkt->data, and
681 * pkt->body is not really used for anything until the packet is
682 * ready for sending. In this mode, pkt->savedpos is reused as a
683 * temporary variable by the addstring functions, which write out
684 * a string length field and then keep going back and updating it
685 * as more data is appended to the subsequent string data field;
686 * pkt->savedpos stores the offset (again relative to pkt->data)
687 * of the start of the string data field.
690 /* Extra metadata used in SSH packet logging mode, allowing us to
691 * log in the packet header line that the packet came from a
692 * connection-sharing downstream and what if anything unusual was
693 * done to it. The additional_log_text field is expected to be a
694 * static string - it will not be freed. */
695 unsigned downstream_id;
696 const char *additional_log_text;
699 static void ssh1_protocol(Ssh ssh, const void *vin, int inlen,
700 struct Packet *pktin);
701 static void ssh2_protocol(Ssh ssh, const void *vin, int inlen,
702 struct Packet *pktin);
703 static void ssh2_bare_connection_protocol(Ssh ssh, const void *vin, int inlen,
704 struct Packet *pktin);
705 static void ssh1_protocol_setup(Ssh ssh);
706 static void ssh2_protocol_setup(Ssh ssh);
707 static void ssh2_bare_connection_protocol_setup(Ssh ssh);
708 static void ssh_size(void *handle, int width, int height);
709 static void ssh_special(void *handle, Telnet_Special);
710 static int ssh2_try_send(struct ssh_channel *c);
711 static void ssh2_add_channel_data(struct ssh_channel *c,
712 const char *buf, int len);
713 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
714 static void ssh2_set_window(struct ssh_channel *c, int newwin);
715 static int ssh_sendbuffer(void *handle);
716 static int ssh_do_close(Ssh ssh, int notify_exit);
717 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
718 static int ssh2_pkt_getbool(struct Packet *pkt);
719 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
720 static void ssh2_timer(void *ctx, unsigned long now);
721 static void do_ssh2_transport(Ssh ssh, const void *vin, int inlen,
722 struct Packet *pktin);
723 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin);
725 struct rdpkt1_state_tag {
726 long len, pad, biglen, to_read;
727 unsigned long realcrc, gotcrc;
731 struct Packet *pktin;
734 struct rdpkt2_state_tag {
735 long len, pad, payload, packetlen, maclen;
738 unsigned long incoming_sequence;
739 struct Packet *pktin;
742 struct rdpkt2_bare_state_tag {
746 unsigned long incoming_sequence;
747 struct Packet *pktin;
750 struct queued_handler;
751 struct queued_handler {
753 chandler_fn_t handler;
755 struct queued_handler *next;
759 const struct plug_function_table *fn;
760 /* the above field _must_ be first in the structure */
770 unsigned char session_key[32];
772 int v1_remote_protoflags;
773 int v1_local_protoflags;
774 int agentfwd_enabled;
777 const struct ssh_cipher *cipher;
780 const struct ssh2_cipher *cscipher, *sccipher;
781 void *cs_cipher_ctx, *sc_cipher_ctx;
782 const struct ssh_mac *csmac, *scmac;
783 int csmac_etm, scmac_etm;
784 void *cs_mac_ctx, *sc_mac_ctx;
785 const struct ssh_compress *cscomp, *sccomp;
786 void *cs_comp_ctx, *sc_comp_ctx;
787 const struct ssh_kex *kex;
788 const struct ssh_signkey *hostkey;
789 char *hostkey_str; /* string representation, for easy checking in rekeys */
790 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
791 int v2_session_id_len;
795 int attempting_connshare;
801 int echoing, editing;
806 int ospeed, ispeed; /* temporaries */
807 int term_width, term_height;
809 tree234 *channels; /* indexed by local id */
810 struct ssh_channel *mainchan; /* primary session channel */
811 int ncmode; /* is primary channel direct-tcpip? */
816 tree234 *rportfwds, *portfwds;
820 SSH_STATE_BEFORE_SIZE,
826 int size_needed, eof_needed;
827 int sent_console_eof;
828 int got_pty; /* affects EOF behaviour on main channel */
830 struct Packet **queue;
831 int queuelen, queuesize;
833 unsigned char *deferred_send_data;
834 int deferred_len, deferred_size;
837 * Gross hack: pscp will try to start SFTP but fall back to
838 * scp1 if that fails. This variable is the means by which
839 * scp.c can reach into the SSH code and find out which one it
844 bufchain banner; /* accumulates banners during do_ssh2_authconn */
849 struct X11Display *x11disp;
850 struct X11FakeAuth *x11auth;
851 tree234 *x11authtree;
854 int conn_throttle_count;
857 int v1_stdout_throttling;
858 unsigned long v2_outgoing_sequence;
860 int ssh1_rdpkt_crstate;
861 int ssh2_rdpkt_crstate;
862 int ssh2_bare_rdpkt_crstate;
863 int ssh_gotdata_crstate;
864 int do_ssh1_connection_crstate;
866 void *do_ssh_init_state;
867 void *do_ssh1_login_state;
868 void *do_ssh2_transport_state;
869 void *do_ssh2_authconn_state;
870 void *do_ssh_connection_init_state;
872 struct rdpkt1_state_tag rdpkt1_state;
873 struct rdpkt2_state_tag rdpkt2_state;
874 struct rdpkt2_bare_state_tag rdpkt2_bare_state;
876 /* SSH-1 and SSH-2 use this for different things, but both use it */
877 int protocol_initial_phase_done;
879 void (*protocol) (Ssh ssh, const void *vin, int inlen,
881 struct Packet *(*s_rdpkt) (Ssh ssh, const unsigned char **data,
883 int (*do_ssh_init)(Ssh ssh, unsigned char c);
886 * We maintain our own copy of a Conf structure here. That way,
887 * when we're passed a new one for reconfiguration, we can check
888 * the differences and potentially reconfigure port forwardings
889 * etc in mid-session.
894 * Values cached out of conf so as to avoid the tree234 lookup
895 * cost every time they're used.
900 * Dynamically allocated username string created during SSH
901 * login. Stored in here rather than in the coroutine state so
902 * that it'll be reliably freed if we shut down the SSH session
903 * at some unexpected moment.
908 * Used to transfer data back from async callbacks.
910 void *agent_response;
911 int agent_response_len;
915 * The SSH connection can be set as `frozen', meaning we are
916 * not currently accepting incoming data from the network. This
917 * is slightly more serious than setting the _socket_ as
918 * frozen, because we may already have had data passed to us
919 * from the network which we need to delay processing until
920 * after the freeze is lifted, so we also need a bufchain to
924 bufchain queued_incoming_data;
927 * Dispatch table for packet types that we may have to deal
930 handler_fn_t packet_dispatch[256];
933 * Queues of one-off handler functions for success/failure
934 * indications from a request.
936 struct queued_handler *qhead, *qtail;
937 handler_fn_t q_saved_handler1, q_saved_handler2;
940 * This module deals with sending keepalives.
945 * Track incoming and outgoing data sizes and time, for
948 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
949 unsigned long max_data_size;
951 unsigned long next_rekey, last_rekey;
952 const char *deferred_rekey_reason;
955 * Fully qualified host name, which we need if doing GSSAPI.
961 * GSSAPI libraries for this session.
963 struct ssh_gss_liblist *gsslibs;
967 * The last list returned from get_specials.
969 struct telnet_special *specials;
972 * List of host key algorithms for which we _don't_ have a stored
973 * host key. These are indices into the main hostkey_algs[] array
975 int uncert_hostkeys[lenof(hostkey_algs)];
976 int n_uncert_hostkeys;
979 * Flag indicating that the current rekey is intended to finish
980 * with a newly cross-certified host key.
982 int cross_certifying;
985 #define logevent(s) logevent(ssh->frontend, s)
987 /* logevent, only printf-formatted. */
988 static void logeventf(Ssh ssh, const char *fmt, ...)
994 buf = dupvprintf(fmt, ap);
1000 static void bomb_out(Ssh ssh, char *text)
1002 ssh_do_close(ssh, FALSE);
1004 connection_fatal(ssh->frontend, "%s", text);
1008 #define bombout(msg) bomb_out(ssh, dupprintf msg)
1010 /* Helper function for common bits of parsing ttymodes. */
1011 static void parse_ttymodes(Ssh ssh,
1012 void (*do_mode)(void *data, char *mode, char *val),
1017 for (val = conf_get_str_strs(ssh->conf, CONF_ttymodes, NULL, &key);
1019 val = conf_get_str_strs(ssh->conf, CONF_ttymodes, key, &key)) {
1021 * val[0] is either 'V', indicating that an explicit value
1022 * follows it, or 'A' indicating that we should pass the
1023 * value through from the local environment via get_ttymode.
1025 if (val[0] == 'A') {
1026 val = get_ttymode(ssh->frontend, key);
1028 do_mode(data, key, val);
1032 do_mode(data, key, val + 1); /* skip the 'V' */
1036 static int ssh_channelcmp(void *av, void *bv)
1038 struct ssh_channel *a = (struct ssh_channel *) av;
1039 struct ssh_channel *b = (struct ssh_channel *) bv;
1040 if (a->localid < b->localid)
1042 if (a->localid > b->localid)
1046 static int ssh_channelfind(void *av, void *bv)
1048 unsigned *a = (unsigned *) av;
1049 struct ssh_channel *b = (struct ssh_channel *) bv;
1050 if (*a < b->localid)
1052 if (*a > b->localid)
1057 static int ssh_rportcmp_ssh1(void *av, void *bv)
1059 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1060 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1062 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
1063 return i < 0 ? -1 : +1;
1064 if (a->dport > b->dport)
1066 if (a->dport < b->dport)
1071 static int ssh_rportcmp_ssh2(void *av, void *bv)
1073 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1074 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1076 if ( (i = strcmp(a->shost, b->shost)) != 0)
1077 return i < 0 ? -1 : +1;
1078 if (a->sport > b->sport)
1080 if (a->sport < b->sport)
1086 * Special form of strcmp which can cope with NULL inputs. NULL is
1087 * defined to sort before even the empty string.
1089 static int nullstrcmp(const char *a, const char *b)
1091 if (a == NULL && b == NULL)
1097 return strcmp(a, b);
1100 static int ssh_portcmp(void *av, void *bv)
1102 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1103 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1105 if (a->type > b->type)
1107 if (a->type < b->type)
1109 if (a->addressfamily > b->addressfamily)
1111 if (a->addressfamily < b->addressfamily)
1113 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1114 return i < 0 ? -1 : +1;
1115 if (a->sport > b->sport)
1117 if (a->sport < b->sport)
1119 if (a->type != 'D') {
1120 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1121 return i < 0 ? -1 : +1;
1122 if (a->dport > b->dport)
1124 if (a->dport < b->dport)
1130 static int alloc_channel_id(Ssh ssh)
1132 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1133 unsigned low, high, mid;
1135 struct ssh_channel *c;
1138 * First-fit allocation of channel numbers: always pick the
1139 * lowest unused one. To do this, binary-search using the
1140 * counted B-tree to find the largest channel ID which is in a
1141 * contiguous sequence from the beginning. (Precisely
1142 * everything in that sequence must have ID equal to its tree
1143 * index plus CHANNEL_NUMBER_OFFSET.)
1145 tsize = count234(ssh->channels);
1149 while (high - low > 1) {
1150 mid = (high + low) / 2;
1151 c = index234(ssh->channels, mid);
1152 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1153 low = mid; /* this one is fine */
1155 high = mid; /* this one is past it */
1158 * Now low points to either -1, or the tree index of the
1159 * largest ID in the initial sequence.
1162 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1163 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1165 return low + 1 + CHANNEL_NUMBER_OFFSET;
1168 static void c_write_stderr(int trusted, const char *buf, int len)
1171 for (i = 0; i < len; i++)
1172 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1173 fputc(buf[i], stderr);
1176 static void c_write(Ssh ssh, const char *buf, int len)
1178 if (flags & FLAG_STDERR)
1179 c_write_stderr(1, buf, len);
1181 from_backend(ssh->frontend, 1, buf, len);
1184 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1186 if (flags & FLAG_STDERR)
1187 c_write_stderr(0, buf, len);
1189 from_backend_untrusted(ssh->frontend, buf, len);
1192 static void c_write_str(Ssh ssh, const char *buf)
1194 c_write(ssh, buf, strlen(buf));
1197 static void ssh_free_packet(struct Packet *pkt)
1202 static struct Packet *ssh_new_packet(void)
1204 struct Packet *pkt = snew(struct Packet);
1206 pkt->body = pkt->data = NULL;
1212 static void ssh1_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1215 struct logblank_t blanks[4];
1221 if (ssh->logomitdata &&
1222 (pkt->type == SSH1_SMSG_STDOUT_DATA ||
1223 pkt->type == SSH1_SMSG_STDERR_DATA ||
1224 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1225 /* "Session data" packets - omit the data string. */
1226 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1227 ssh_pkt_getuint32(pkt); /* skip channel id */
1228 blanks[nblanks].offset = pkt->savedpos + 4;
1229 blanks[nblanks].type = PKTLOG_OMIT;
1230 ssh_pkt_getstring(pkt, &str, &slen);
1232 blanks[nblanks].len = slen;
1236 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1237 ssh1_pkt_type(pkt->type),
1238 pkt->body, pkt->length, nblanks, blanks, NULL,
1242 static void ssh1_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1245 struct logblank_t blanks[4];
1250 * For outgoing packets, pkt->length represents the length of the
1251 * whole packet starting at pkt->data (including some header), and
1252 * pkt->body refers to the point within that where the log-worthy
1253 * payload begins. However, incoming packets expect pkt->length to
1254 * represent only the payload length (that is, it's measured from
1255 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1256 * packet to conform to the incoming-packet semantics, so that we
1257 * can analyse it with the ssh_pkt_get functions.
1259 pkt->length -= (pkt->body - pkt->data);
1262 if (ssh->logomitdata &&
1263 (pkt->type == SSH1_CMSG_STDIN_DATA ||
1264 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1265 /* "Session data" packets - omit the data string. */
1266 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1267 ssh_pkt_getuint32(pkt); /* skip channel id */
1268 blanks[nblanks].offset = pkt->savedpos + 4;
1269 blanks[nblanks].type = PKTLOG_OMIT;
1270 ssh_pkt_getstring(pkt, &str, &slen);
1272 blanks[nblanks].len = slen;
1277 if ((pkt->type == SSH1_CMSG_AUTH_PASSWORD ||
1278 pkt->type == SSH1_CMSG_AUTH_TIS_RESPONSE ||
1279 pkt->type == SSH1_CMSG_AUTH_CCARD_RESPONSE) &&
1280 conf_get_int(ssh->conf, CONF_logomitpass)) {
1281 /* If this is a password or similar packet, blank the password(s). */
1282 blanks[nblanks].offset = 0;
1283 blanks[nblanks].len = pkt->length;
1284 blanks[nblanks].type = PKTLOG_BLANK;
1286 } else if (pkt->type == SSH1_CMSG_X11_REQUEST_FORWARDING &&
1287 conf_get_int(ssh->conf, CONF_logomitpass)) {
1289 * If this is an X forwarding request packet, blank the fake
1292 * Note that while we blank the X authentication data here, we
1293 * don't take any special action to blank the start of an X11
1294 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1295 * an X connection without having session blanking enabled is
1296 * likely to leak your cookie into the log.
1299 ssh_pkt_getstring(pkt, &str, &slen);
1300 blanks[nblanks].offset = pkt->savedpos;
1301 blanks[nblanks].type = PKTLOG_BLANK;
1302 ssh_pkt_getstring(pkt, &str, &slen);
1304 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1309 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1310 ssh1_pkt_type(pkt->data[12]),
1311 pkt->body, pkt->length,
1312 nblanks, blanks, NULL, 0, NULL);
1315 * Undo the above adjustment of pkt->length, to put the packet
1316 * back in the state we found it.
1318 pkt->length += (pkt->body - pkt->data);
1322 * Collect incoming data in the incoming packet buffer.
1323 * Decipher and verify the packet when it is completely read.
1324 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1325 * Update the *data and *datalen variables.
1326 * Return a Packet structure when a packet is completed.
1328 static struct Packet *ssh1_rdpkt(Ssh ssh, const unsigned char **data,
1331 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1333 crBegin(ssh->ssh1_rdpkt_crstate);
1335 st->pktin = ssh_new_packet();
1337 st->pktin->type = 0;
1338 st->pktin->length = 0;
1340 for (st->i = st->len = 0; st->i < 4; st->i++) {
1341 while ((*datalen) == 0)
1343 st->len = (st->len << 8) + **data;
1344 (*data)++, (*datalen)--;
1347 st->pad = 8 - (st->len % 8);
1348 st->biglen = st->len + st->pad;
1349 st->pktin->length = st->len - 5;
1351 if (st->biglen < 0) {
1352 bombout(("Extremely large packet length from server suggests"
1353 " data stream corruption"));
1354 ssh_free_packet(st->pktin);
1358 st->pktin->maxlen = st->biglen;
1359 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1361 st->to_read = st->biglen;
1362 st->p = st->pktin->data;
1363 while (st->to_read > 0) {
1364 st->chunk = st->to_read;
1365 while ((*datalen) == 0)
1367 if (st->chunk > (*datalen))
1368 st->chunk = (*datalen);
1369 memcpy(st->p, *data, st->chunk);
1371 *datalen -= st->chunk;
1373 st->to_read -= st->chunk;
1376 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1377 st->biglen, NULL)) {
1378 bombout(("Network attack (CRC compensation) detected!"));
1379 ssh_free_packet(st->pktin);
1384 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1386 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1387 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1388 if (st->gotcrc != st->realcrc) {
1389 bombout(("Incorrect CRC received on packet"));
1390 ssh_free_packet(st->pktin);
1394 st->pktin->body = st->pktin->data + st->pad + 1;
1396 if (ssh->v1_compressing) {
1397 unsigned char *decompblk;
1399 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1400 st->pktin->body - 1, st->pktin->length + 1,
1401 &decompblk, &decomplen)) {
1402 bombout(("Zlib decompression encountered invalid data"));
1403 ssh_free_packet(st->pktin);
1407 if (st->pktin->maxlen < st->pad + decomplen) {
1408 st->pktin->maxlen = st->pad + decomplen;
1409 st->pktin->data = sresize(st->pktin->data,
1410 st->pktin->maxlen + APIEXTRA,
1412 st->pktin->body = st->pktin->data + st->pad + 1;
1415 memcpy(st->pktin->body - 1, decompblk, decomplen);
1417 st->pktin->length = decomplen - 1;
1420 st->pktin->type = st->pktin->body[-1];
1423 * Now pktin->body and pktin->length identify the semantic content
1424 * of the packet, excluding the initial type byte.
1428 ssh1_log_incoming_packet(ssh, st->pktin);
1430 st->pktin->savedpos = 0;
1432 crFinish(st->pktin);
1435 static void ssh2_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1438 struct logblank_t blanks[4];
1444 if (ssh->logomitdata &&
1445 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1446 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1447 /* "Session data" packets - omit the data string. */
1448 ssh_pkt_getuint32(pkt); /* skip channel id */
1449 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1450 ssh_pkt_getuint32(pkt); /* skip extended data type */
1451 blanks[nblanks].offset = pkt->savedpos + 4;
1452 blanks[nblanks].type = PKTLOG_OMIT;
1453 ssh_pkt_getstring(pkt, &str, &slen);
1455 blanks[nblanks].len = slen;
1460 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1461 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->type),
1462 pkt->body, pkt->length, nblanks, blanks, &pkt->sequence,
1466 static void ssh2_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1469 struct logblank_t blanks[4];
1474 * For outgoing packets, pkt->length represents the length of the
1475 * whole packet starting at pkt->data (including some header), and
1476 * pkt->body refers to the point within that where the log-worthy
1477 * payload begins. However, incoming packets expect pkt->length to
1478 * represent only the payload length (that is, it's measured from
1479 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1480 * packet to conform to the incoming-packet semantics, so that we
1481 * can analyse it with the ssh_pkt_get functions.
1483 pkt->length -= (pkt->body - pkt->data);
1486 if (ssh->logomitdata &&
1487 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1488 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1489 /* "Session data" packets - omit the data string. */
1490 ssh_pkt_getuint32(pkt); /* skip channel id */
1491 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1492 ssh_pkt_getuint32(pkt); /* skip extended data type */
1493 blanks[nblanks].offset = pkt->savedpos + 4;
1494 blanks[nblanks].type = PKTLOG_OMIT;
1495 ssh_pkt_getstring(pkt, &str, &slen);
1497 blanks[nblanks].len = slen;
1502 if (pkt->type == SSH2_MSG_USERAUTH_REQUEST &&
1503 conf_get_int(ssh->conf, CONF_logomitpass)) {
1504 /* If this is a password packet, blank the password(s). */
1506 ssh_pkt_getstring(pkt, &str, &slen);
1507 ssh_pkt_getstring(pkt, &str, &slen);
1508 ssh_pkt_getstring(pkt, &str, &slen);
1509 if (slen == 8 && !memcmp(str, "password", 8)) {
1510 ssh2_pkt_getbool(pkt);
1511 /* Blank the password field. */
1512 blanks[nblanks].offset = pkt->savedpos;
1513 blanks[nblanks].type = PKTLOG_BLANK;
1514 ssh_pkt_getstring(pkt, &str, &slen);
1516 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1518 /* If there's another password field beyond it (change of
1519 * password), blank that too. */
1520 ssh_pkt_getstring(pkt, &str, &slen);
1522 blanks[nblanks-1].len =
1523 pkt->savedpos - blanks[nblanks].offset;
1526 } else if (ssh->pkt_actx == SSH2_PKTCTX_KBDINTER &&
1527 pkt->type == SSH2_MSG_USERAUTH_INFO_RESPONSE &&
1528 conf_get_int(ssh->conf, CONF_logomitpass)) {
1529 /* If this is a keyboard-interactive response packet, blank
1532 ssh_pkt_getuint32(pkt);
1533 blanks[nblanks].offset = pkt->savedpos;
1534 blanks[nblanks].type = PKTLOG_BLANK;
1536 ssh_pkt_getstring(pkt, &str, &slen);
1540 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1542 } else if (pkt->type == SSH2_MSG_CHANNEL_REQUEST &&
1543 conf_get_int(ssh->conf, CONF_logomitpass)) {
1545 * If this is an X forwarding request packet, blank the fake
1548 * Note that while we blank the X authentication data here, we
1549 * don't take any special action to blank the start of an X11
1550 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1551 * an X connection without having session blanking enabled is
1552 * likely to leak your cookie into the log.
1555 ssh_pkt_getuint32(pkt);
1556 ssh_pkt_getstring(pkt, &str, &slen);
1557 if (slen == 7 && !memcmp(str, "x11-req", 0)) {
1558 ssh2_pkt_getbool(pkt);
1559 ssh2_pkt_getbool(pkt);
1560 ssh_pkt_getstring(pkt, &str, &slen);
1561 blanks[nblanks].offset = pkt->savedpos;
1562 blanks[nblanks].type = PKTLOG_BLANK;
1563 ssh_pkt_getstring(pkt, &str, &slen);
1565 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1571 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1572 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1573 pkt->body, pkt->length, nblanks, blanks,
1574 &ssh->v2_outgoing_sequence,
1575 pkt->downstream_id, pkt->additional_log_text);
1578 * Undo the above adjustment of pkt->length, to put the packet
1579 * back in the state we found it.
1581 pkt->length += (pkt->body - pkt->data);
1584 static struct Packet *ssh2_rdpkt(Ssh ssh, const unsigned char **data,
1587 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1589 crBegin(ssh->ssh2_rdpkt_crstate);
1591 st->pktin = ssh_new_packet();
1593 st->pktin->type = 0;
1594 st->pktin->length = 0;
1596 st->cipherblk = ssh->sccipher->blksize;
1599 if (st->cipherblk < 8)
1601 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1603 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1604 ssh->scmac && !ssh->scmac_etm) {
1606 * When dealing with a CBC-mode cipher, we want to avoid the
1607 * possibility of an attacker's tweaking the ciphertext stream
1608 * so as to cause us to feed the same block to the block
1609 * cipher more than once and thus leak information
1610 * (VU#958563). The way we do this is not to take any
1611 * decisions on the basis of anything we've decrypted until
1612 * we've verified it with a MAC. That includes the packet
1613 * length, so we just read data and check the MAC repeatedly,
1614 * and when the MAC passes, see if the length we've got is
1617 * This defence is unnecessary in OpenSSH ETM mode, because
1618 * the whole point of ETM mode is that the attacker can't
1619 * tweak the ciphertext stream at all without the MAC
1620 * detecting it before we decrypt anything.
1623 /* May as well allocate the whole lot now. */
1624 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1627 /* Read an amount corresponding to the MAC. */
1628 for (st->i = 0; st->i < st->maclen; st->i++) {
1629 while ((*datalen) == 0)
1631 st->pktin->data[st->i] = *(*data)++;
1637 unsigned char seq[4];
1638 ssh->scmac->start(ssh->sc_mac_ctx);
1639 PUT_32BIT(seq, st->incoming_sequence);
1640 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1643 for (;;) { /* Once around this loop per cipher block. */
1644 /* Read another cipher-block's worth, and tack it onto the end. */
1645 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1646 while ((*datalen) == 0)
1648 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1651 /* Decrypt one more block (a little further back in the stream). */
1652 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1653 st->pktin->data + st->packetlen,
1655 /* Feed that block to the MAC. */
1656 ssh->scmac->bytes(ssh->sc_mac_ctx,
1657 st->pktin->data + st->packetlen, st->cipherblk);
1658 st->packetlen += st->cipherblk;
1659 /* See if that gives us a valid packet. */
1660 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1661 st->pktin->data + st->packetlen) &&
1662 ((st->len = toint(GET_32BIT(st->pktin->data))) ==
1665 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1666 bombout(("No valid incoming packet found"));
1667 ssh_free_packet(st->pktin);
1671 st->pktin->maxlen = st->packetlen + st->maclen;
1672 st->pktin->data = sresize(st->pktin->data,
1673 st->pktin->maxlen + APIEXTRA,
1675 } else if (ssh->scmac && ssh->scmac_etm) {
1676 st->pktin->data = snewn(4 + APIEXTRA, unsigned char);
1679 * OpenSSH encrypt-then-MAC mode: the packet length is
1680 * unencrypted, unless the cipher supports length encryption.
1682 for (st->i = st->len = 0; st->i < 4; st->i++) {
1683 while ((*datalen) == 0)
1685 st->pktin->data[st->i] = *(*data)++;
1688 /* Cipher supports length decryption, so do it */
1689 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_SEPARATE_LENGTH)) {
1690 /* Keep the packet the same though, so the MAC passes */
1691 unsigned char len[4];
1692 memcpy(len, st->pktin->data, 4);
1693 ssh->sccipher->decrypt_length(ssh->sc_cipher_ctx, len, 4, st->incoming_sequence);
1694 st->len = toint(GET_32BIT(len));
1696 st->len = toint(GET_32BIT(st->pktin->data));
1700 * _Completely_ silly lengths should be stomped on before they
1701 * do us any more damage.
1703 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1704 st->len % st->cipherblk != 0) {
1705 bombout(("Incoming packet length field was garbled"));
1706 ssh_free_packet(st->pktin);
1711 * So now we can work out the total packet length.
1713 st->packetlen = st->len + 4;
1716 * Allocate memory for the rest of the packet.
1718 st->pktin->maxlen = st->packetlen + st->maclen;
1719 st->pktin->data = sresize(st->pktin->data,
1720 st->pktin->maxlen + APIEXTRA,
1724 * Read the remainder of the packet.
1726 for (st->i = 4; st->i < st->packetlen + st->maclen; st->i++) {
1727 while ((*datalen) == 0)
1729 st->pktin->data[st->i] = *(*data)++;
1737 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1738 st->len + 4, st->incoming_sequence)) {
1739 bombout(("Incorrect MAC received on packet"));
1740 ssh_free_packet(st->pktin);
1744 /* Decrypt everything between the length field and the MAC. */
1746 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1747 st->pktin->data + 4,
1750 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1753 * Acquire and decrypt the first block of the packet. This will
1754 * contain the length and padding details.
1756 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1757 while ((*datalen) == 0)
1759 st->pktin->data[st->i] = *(*data)++;
1764 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1765 st->pktin->data, st->cipherblk);
1768 * Now get the length figure.
1770 st->len = toint(GET_32BIT(st->pktin->data));
1773 * _Completely_ silly lengths should be stomped on before they
1774 * do us any more damage.
1776 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1777 (st->len + 4) % st->cipherblk != 0) {
1778 bombout(("Incoming packet was garbled on decryption"));
1779 ssh_free_packet(st->pktin);
1784 * So now we can work out the total packet length.
1786 st->packetlen = st->len + 4;
1789 * Allocate memory for the rest of the packet.
1791 st->pktin->maxlen = st->packetlen + st->maclen;
1792 st->pktin->data = sresize(st->pktin->data,
1793 st->pktin->maxlen + APIEXTRA,
1797 * Read and decrypt the remainder of the packet.
1799 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1801 while ((*datalen) == 0)
1803 st->pktin->data[st->i] = *(*data)++;
1806 /* Decrypt everything _except_ the MAC. */
1808 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1809 st->pktin->data + st->cipherblk,
1810 st->packetlen - st->cipherblk);
1816 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1817 st->len + 4, st->incoming_sequence)) {
1818 bombout(("Incorrect MAC received on packet"));
1819 ssh_free_packet(st->pktin);
1823 /* Get and sanity-check the amount of random padding. */
1824 st->pad = st->pktin->data[4];
1825 if (st->pad < 4 || st->len - st->pad < 1) {
1826 bombout(("Invalid padding length on received packet"));
1827 ssh_free_packet(st->pktin);
1831 * This enables us to deduce the payload length.
1833 st->payload = st->len - st->pad - 1;
1835 st->pktin->length = st->payload + 5;
1836 st->pktin->encrypted_len = st->packetlen;
1838 st->pktin->sequence = st->incoming_sequence++;
1840 st->pktin->length = st->packetlen - st->pad;
1841 assert(st->pktin->length >= 0);
1844 * Decompress packet payload.
1847 unsigned char *newpayload;
1850 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1851 st->pktin->data + 5, st->pktin->length - 5,
1852 &newpayload, &newlen)) {
1853 if (st->pktin->maxlen < newlen + 5) {
1854 st->pktin->maxlen = newlen + 5;
1855 st->pktin->data = sresize(st->pktin->data,
1856 st->pktin->maxlen + APIEXTRA,
1859 st->pktin->length = 5 + newlen;
1860 memcpy(st->pktin->data + 5, newpayload, newlen);
1866 * RFC 4253 doesn't explicitly say that completely empty packets
1867 * with no type byte are forbidden, so treat them as deserving
1868 * an SSH_MSG_UNIMPLEMENTED.
1870 if (st->pktin->length <= 5) { /* == 5 we hope, but robustness */
1871 ssh2_msg_something_unimplemented(ssh, st->pktin);
1875 * pktin->body and pktin->length should identify the semantic
1876 * content of the packet, excluding the initial type byte.
1878 st->pktin->type = st->pktin->data[5];
1879 st->pktin->body = st->pktin->data + 6;
1880 st->pktin->length -= 6;
1881 assert(st->pktin->length >= 0); /* one last double-check */
1884 ssh2_log_incoming_packet(ssh, st->pktin);
1886 st->pktin->savedpos = 0;
1888 crFinish(st->pktin);
1891 static struct Packet *ssh2_bare_connection_rdpkt(Ssh ssh,
1892 const unsigned char **data,
1895 struct rdpkt2_bare_state_tag *st = &ssh->rdpkt2_bare_state;
1897 crBegin(ssh->ssh2_bare_rdpkt_crstate);
1900 * Read the packet length field.
1902 for (st->i = 0; st->i < 4; st->i++) {
1903 while ((*datalen) == 0)
1905 st->length[st->i] = *(*data)++;
1909 st->packetlen = toint(GET_32BIT_MSB_FIRST(st->length));
1910 if (st->packetlen <= 0 || st->packetlen >= OUR_V2_PACKETLIMIT) {
1911 bombout(("Invalid packet length received"));
1915 st->pktin = ssh_new_packet();
1916 st->pktin->data = snewn(st->packetlen, unsigned char);
1918 st->pktin->encrypted_len = st->packetlen;
1920 st->pktin->sequence = st->incoming_sequence++;
1923 * Read the remainder of the packet.
1925 for (st->i = 0; st->i < st->packetlen; st->i++) {
1926 while ((*datalen) == 0)
1928 st->pktin->data[st->i] = *(*data)++;
1933 * pktin->body and pktin->length should identify the semantic
1934 * content of the packet, excluding the initial type byte.
1936 st->pktin->type = st->pktin->data[0];
1937 st->pktin->body = st->pktin->data + 1;
1938 st->pktin->length = st->packetlen - 1;
1941 * Log incoming packet, possibly omitting sensitive fields.
1944 ssh2_log_incoming_packet(ssh, st->pktin);
1946 st->pktin->savedpos = 0;
1948 crFinish(st->pktin);
1951 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1953 int pad, biglen, i, pktoffs;
1957 * XXX various versions of SC (including 8.8.4) screw up the
1958 * register allocation in this function and use the same register
1959 * (D6) for len and as a temporary, with predictable results. The
1960 * following sledgehammer prevents this.
1967 ssh1_log_outgoing_packet(ssh, pkt);
1969 if (ssh->v1_compressing) {
1970 unsigned char *compblk;
1972 zlib_compress_block(ssh->cs_comp_ctx,
1973 pkt->data + 12, pkt->length - 12,
1974 &compblk, &complen);
1975 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1976 memcpy(pkt->data + 12, compblk, complen);
1978 pkt->length = complen + 12;
1981 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1983 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1984 pad = 8 - (len % 8);
1986 biglen = len + pad; /* len(padding+type+data+CRC) */
1988 for (i = pktoffs; i < 4+8; i++)
1989 pkt->data[i] = random_byte();
1990 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
1991 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
1992 PUT_32BIT(pkt->data + pktoffs, len);
1995 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
1996 pkt->data + pktoffs + 4, biglen);
1998 if (offset_p) *offset_p = pktoffs;
1999 return biglen + 4; /* len(length+padding+type+data+CRC) */
2002 static int s_write(Ssh ssh, void *data, int len)
2005 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
2006 0, NULL, NULL, 0, NULL);
2009 return sk_write(ssh->s, (char *)data, len);
2012 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
2014 int len, backlog, offset;
2015 len = s_wrpkt_prepare(ssh, pkt, &offset);
2016 backlog = s_write(ssh, pkt->data + offset, len);
2017 if (backlog > SSH_MAX_BACKLOG)
2018 ssh_throttle_all(ssh, 1, backlog);
2019 ssh_free_packet(pkt);
2022 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
2025 len = s_wrpkt_prepare(ssh, pkt, &offset);
2026 if (ssh->deferred_len + len > ssh->deferred_size) {
2027 ssh->deferred_size = ssh->deferred_len + len + 128;
2028 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2032 memcpy(ssh->deferred_send_data + ssh->deferred_len,
2033 pkt->data + offset, len);
2034 ssh->deferred_len += len;
2035 ssh_free_packet(pkt);
2039 * Construct a SSH-1 packet with the specified contents.
2040 * (This all-at-once interface used to be the only one, but now SSH-1
2041 * packets can also be constructed incrementally.)
2043 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
2049 pkt = ssh1_pkt_init(pkttype);
2051 while ((argtype = va_arg(ap, int)) != PKT_END) {
2052 unsigned char *argp, argchar;
2054 unsigned long argint;
2057 /* Actual fields in the packet */
2059 argint = va_arg(ap, int);
2060 ssh_pkt_adduint32(pkt, argint);
2063 argchar = (unsigned char) va_arg(ap, int);
2064 ssh_pkt_addbyte(pkt, argchar);
2067 argp = va_arg(ap, unsigned char *);
2068 arglen = va_arg(ap, int);
2069 ssh_pkt_adddata(pkt, argp, arglen);
2072 sargp = va_arg(ap, char *);
2073 ssh_pkt_addstring(pkt, sargp);
2076 bn = va_arg(ap, Bignum);
2077 ssh1_pkt_addmp(pkt, bn);
2085 static void send_packet(Ssh ssh, int pkttype, ...)
2089 va_start(ap, pkttype);
2090 pkt = construct_packet(ssh, pkttype, ap);
2095 static void defer_packet(Ssh ssh, int pkttype, ...)
2099 va_start(ap, pkttype);
2100 pkt = construct_packet(ssh, pkttype, ap);
2102 s_wrpkt_defer(ssh, pkt);
2105 static int ssh_versioncmp(const char *a, const char *b)
2108 unsigned long av, bv;
2110 av = strtoul(a, &ae, 10);
2111 bv = strtoul(b, &be, 10);
2113 return (av < bv ? -1 : +1);
2118 av = strtoul(ae, &ae, 10);
2119 bv = strtoul(be, &be, 10);
2121 return (av < bv ? -1 : +1);
2126 * Utility routines for putting an SSH-protocol `string' and
2127 * `uint32' into a hash state.
2129 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
2131 unsigned char lenblk[4];
2132 PUT_32BIT(lenblk, len);
2133 h->bytes(s, lenblk, 4);
2134 h->bytes(s, str, len);
2137 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
2139 unsigned char intblk[4];
2140 PUT_32BIT(intblk, i);
2141 h->bytes(s, intblk, 4);
2145 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
2147 static void ssh_pkt_ensure(struct Packet *pkt, int length)
2149 if (pkt->maxlen < length) {
2150 unsigned char *body = pkt->body;
2151 int offset = body ? body - pkt->data : 0;
2152 pkt->maxlen = length + 256;
2153 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
2154 if (body) pkt->body = pkt->data + offset;
2157 static void ssh_pkt_adddata(struct Packet *pkt, const void *data, int len)
2160 ssh_pkt_ensure(pkt, pkt->length);
2161 memcpy(pkt->data + pkt->length - len, data, len);
2163 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
2165 ssh_pkt_adddata(pkt, &byte, 1);
2167 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
2169 ssh_pkt_adddata(pkt, &value, 1);
2171 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
2174 PUT_32BIT(x, value);
2175 ssh_pkt_adddata(pkt, x, 4);
2177 static void ssh_pkt_addstring_start(struct Packet *pkt)
2179 ssh_pkt_adduint32(pkt, 0);
2180 pkt->savedpos = pkt->length;
2182 static void ssh_pkt_addstring_data(struct Packet *pkt, const char *data,
2185 ssh_pkt_adddata(pkt, data, len);
2186 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
2188 static void ssh_pkt_addstring_str(struct Packet *pkt, const char *data)
2190 ssh_pkt_addstring_data(pkt, data, strlen(data));
2192 static void ssh_pkt_addstring(struct Packet *pkt, const char *data)
2194 ssh_pkt_addstring_start(pkt);
2195 ssh_pkt_addstring_str(pkt, data);
2197 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
2199 int len = ssh1_bignum_length(b);
2200 unsigned char *data = snewn(len, unsigned char);
2201 (void) ssh1_write_bignum(data, b);
2202 ssh_pkt_adddata(pkt, data, len);
2205 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
2208 int i, n = (bignum_bitcount(b) + 7) / 8;
2209 p = snewn(n + 1, unsigned char);
2211 for (i = 1; i <= n; i++)
2212 p[i] = bignum_byte(b, n - i);
2214 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
2216 memmove(p, p + i, n + 1 - i);
2220 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
2224 p = ssh2_mpint_fmt(b, &len);
2225 ssh_pkt_addstring_start(pkt);
2226 ssh_pkt_addstring_data(pkt, (char *)p, len);
2230 static struct Packet *ssh1_pkt_init(int pkt_type)
2232 struct Packet *pkt = ssh_new_packet();
2233 pkt->length = 4 + 8; /* space for length + max padding */
2234 ssh_pkt_addbyte(pkt, pkt_type);
2235 pkt->body = pkt->data + pkt->length;
2236 pkt->type = pkt_type;
2237 pkt->downstream_id = 0;
2238 pkt->additional_log_text = NULL;
2242 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
2243 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
2244 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
2245 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
2246 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
2247 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
2248 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
2249 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
2250 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
2252 static struct Packet *ssh2_pkt_init(int pkt_type)
2254 struct Packet *pkt = ssh_new_packet();
2255 pkt->length = 5; /* space for packet length + padding length */
2257 pkt->type = pkt_type;
2258 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
2259 pkt->body = pkt->data + pkt->length; /* after packet type */
2260 pkt->downstream_id = 0;
2261 pkt->additional_log_text = NULL;
2266 * Construct an SSH-2 final-form packet: compress it, encrypt it,
2267 * put the MAC on it. Final packet, ready to be sent, is stored in
2268 * pkt->data. Total length is returned.
2270 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
2272 int cipherblk, maclen, padding, unencrypted_prefix, i;
2275 ssh2_log_outgoing_packet(ssh, pkt);
2277 if (ssh->bare_connection) {
2279 * Trivial packet construction for the bare connection
2282 PUT_32BIT(pkt->data + 1, pkt->length - 5);
2283 pkt->body = pkt->data + 1;
2284 ssh->v2_outgoing_sequence++; /* only for diagnostics, really */
2285 return pkt->length - 1;
2289 * Compress packet payload.
2292 unsigned char *newpayload;
2295 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
2297 &newpayload, &newlen)) {
2299 ssh2_pkt_adddata(pkt, newpayload, newlen);
2305 * Add padding. At least four bytes, and must also bring total
2306 * length (minus MAC) up to a multiple of the block size.
2307 * If pkt->forcepad is set, make sure the packet is at least that size
2310 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
2311 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
2313 unencrypted_prefix = (ssh->csmac && ssh->csmac_etm) ? 4 : 0;
2314 if (pkt->length + padding < pkt->forcepad)
2315 padding = pkt->forcepad - pkt->length;
2317 (cipherblk - (pkt->length - unencrypted_prefix + padding) % cipherblk)
2319 assert(padding <= 255);
2320 maclen = ssh->csmac ? ssh->csmac->len : 0;
2321 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
2322 pkt->data[4] = padding;
2323 for (i = 0; i < padding; i++)
2324 pkt->data[pkt->length + i] = random_byte();
2325 PUT_32BIT(pkt->data, pkt->length + padding - 4);
2327 /* Encrypt length if the scheme requires it */
2328 if (ssh->cscipher && (ssh->cscipher->flags & SSH_CIPHER_SEPARATE_LENGTH)) {
2329 ssh->cscipher->encrypt_length(ssh->cs_cipher_ctx, pkt->data, 4,
2330 ssh->v2_outgoing_sequence);
2333 if (ssh->csmac && ssh->csmac_etm) {
2335 * OpenSSH-defined encrypt-then-MAC protocol.
2338 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2339 pkt->data + 4, pkt->length + padding - 4);
2340 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2341 pkt->length + padding,
2342 ssh->v2_outgoing_sequence);
2345 * SSH-2 standard protocol.
2348 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2349 pkt->length + padding,
2350 ssh->v2_outgoing_sequence);
2352 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2353 pkt->data, pkt->length + padding);
2356 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
2357 pkt->encrypted_len = pkt->length + padding;
2359 /* Ready-to-send packet starts at pkt->data. We return length. */
2360 pkt->body = pkt->data;
2361 return pkt->length + padding + maclen;
2365 * Routines called from the main SSH code to send packets. There
2366 * are quite a few of these, because we have two separate
2367 * mechanisms for delaying the sending of packets:
2369 * - In order to send an IGNORE message and a password message in
2370 * a single fixed-length blob, we require the ability to
2371 * concatenate the encrypted forms of those two packets _into_ a
2372 * single blob and then pass it to our <network.h> transport
2373 * layer in one go. Hence, there's a deferment mechanism which
2374 * works after packet encryption.
2376 * - In order to avoid sending any connection-layer messages
2377 * during repeat key exchange, we have to queue up any such
2378 * outgoing messages _before_ they are encrypted (and in
2379 * particular before they're allocated sequence numbers), and
2380 * then send them once we've finished.
2382 * I call these mechanisms `defer' and `queue' respectively, so as
2383 * to distinguish them reasonably easily.
2385 * The functions send_noqueue() and defer_noqueue() free the packet
2386 * structure they are passed. Every outgoing packet goes through
2387 * precisely one of these functions in its life; packets passed to
2388 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
2389 * these or get queued, and then when the queue is later emptied
2390 * the packets are all passed to defer_noqueue().
2392 * When using a CBC-mode cipher, it's necessary to ensure that an
2393 * attacker can't provide data to be encrypted using an IV that they
2394 * know. We ensure this by prefixing each packet that might contain
2395 * user data with an SSH_MSG_IGNORE. This is done using the deferral
2396 * mechanism, so in this case send_noqueue() ends up redirecting to
2397 * defer_noqueue(). If you don't like this inefficiency, don't use
2401 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
2402 static void ssh_pkt_defersend(Ssh);
2405 * Send an SSH-2 packet immediately, without queuing or deferring.
2407 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
2411 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
2412 /* We need to send two packets, so use the deferral mechanism. */
2413 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2414 ssh_pkt_defersend(ssh);
2417 len = ssh2_pkt_construct(ssh, pkt);
2418 backlog = s_write(ssh, pkt->body, len);
2419 if (backlog > SSH_MAX_BACKLOG)
2420 ssh_throttle_all(ssh, 1, backlog);
2422 ssh->outgoing_data_size += pkt->encrypted_len;
2423 if (!ssh->kex_in_progress &&
2424 !ssh->bare_connection &&
2425 ssh->max_data_size != 0 &&
2426 ssh->outgoing_data_size > ssh->max_data_size)
2427 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2429 ssh_free_packet(pkt);
2433 * Defer an SSH-2 packet.
2435 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2438 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2439 ssh->deferred_len == 0 && !noignore &&
2440 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2442 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2443 * get encrypted with a known IV.
2445 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2446 ssh2_pkt_addstring_start(ipkt);
2447 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2449 len = ssh2_pkt_construct(ssh, pkt);
2450 if (ssh->deferred_len + len > ssh->deferred_size) {
2451 ssh->deferred_size = ssh->deferred_len + len + 128;
2452 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2456 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->body, len);
2457 ssh->deferred_len += len;
2458 ssh->deferred_data_size += pkt->encrypted_len;
2459 ssh_free_packet(pkt);
2463 * Queue an SSH-2 packet.
2465 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2467 assert(ssh->queueing);
2469 if (ssh->queuelen >= ssh->queuesize) {
2470 ssh->queuesize = ssh->queuelen + 32;
2471 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2474 ssh->queue[ssh->queuelen++] = pkt;
2478 * Either queue or send a packet, depending on whether queueing is
2481 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2484 ssh2_pkt_queue(ssh, pkt);
2486 ssh2_pkt_send_noqueue(ssh, pkt);
2490 * Either queue or defer a packet, depending on whether queueing is
2493 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2496 ssh2_pkt_queue(ssh, pkt);
2498 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2502 * Send the whole deferred data block constructed by
2503 * ssh2_pkt_defer() or SSH-1's defer_packet().
2505 * The expected use of the defer mechanism is that you call
2506 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2507 * not currently queueing, this simply sets up deferred_send_data
2508 * and then sends it. If we _are_ currently queueing, the calls to
2509 * ssh2_pkt_defer() put the deferred packets on to the queue
2510 * instead, and therefore ssh_pkt_defersend() has no deferred data
2511 * to send. Hence, there's no need to make it conditional on
2514 static void ssh_pkt_defersend(Ssh ssh)
2517 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2518 ssh->deferred_len = ssh->deferred_size = 0;
2519 sfree(ssh->deferred_send_data);
2520 ssh->deferred_send_data = NULL;
2521 if (backlog > SSH_MAX_BACKLOG)
2522 ssh_throttle_all(ssh, 1, backlog);
2524 ssh->outgoing_data_size += ssh->deferred_data_size;
2525 if (!ssh->kex_in_progress &&
2526 !ssh->bare_connection &&
2527 ssh->max_data_size != 0 &&
2528 ssh->outgoing_data_size > ssh->max_data_size)
2529 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2530 ssh->deferred_data_size = 0;
2534 * Send a packet whose length needs to be disguised (typically
2535 * passwords or keyboard-interactive responses).
2537 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2543 * The simplest way to do this is to adjust the
2544 * variable-length padding field in the outgoing packet.
2546 * Currently compiled out, because some Cisco SSH servers
2547 * don't like excessively padded packets (bah, why's it
2550 pkt->forcepad = padsize;
2551 ssh2_pkt_send(ssh, pkt);
2556 * If we can't do that, however, an alternative approach is
2557 * to use the pkt_defer mechanism to bundle the packet
2558 * tightly together with an SSH_MSG_IGNORE such that their
2559 * combined length is a constant. So first we construct the
2560 * final form of this packet and defer its sending.
2562 ssh2_pkt_defer(ssh, pkt);
2565 * Now construct an SSH_MSG_IGNORE which includes a string
2566 * that's an exact multiple of the cipher block size. (If
2567 * the cipher is NULL so that the block size is
2568 * unavailable, we don't do this trick at all, because we
2569 * gain nothing by it.)
2571 if (ssh->cscipher &&
2572 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2575 stringlen = (256 - ssh->deferred_len);
2576 stringlen += ssh->cscipher->blksize - 1;
2577 stringlen -= (stringlen % ssh->cscipher->blksize);
2580 * Temporarily disable actual compression, so we
2581 * can guarantee to get this string exactly the
2582 * length we want it. The compression-disabling
2583 * routine should return an integer indicating how
2584 * many bytes we should adjust our string length
2588 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2590 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2591 ssh2_pkt_addstring_start(pkt);
2592 for (i = 0; i < stringlen; i++) {
2593 char c = (char) random_byte();
2594 ssh2_pkt_addstring_data(pkt, &c, 1);
2596 ssh2_pkt_defer(ssh, pkt);
2598 ssh_pkt_defersend(ssh);
2603 * Send all queued SSH-2 packets. We send them by means of
2604 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2605 * packets that needed to be lumped together.
2607 static void ssh2_pkt_queuesend(Ssh ssh)
2611 assert(!ssh->queueing);
2613 for (i = 0; i < ssh->queuelen; i++)
2614 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2617 ssh_pkt_defersend(ssh);
2621 void bndebug(char *string, Bignum b)
2625 p = ssh2_mpint_fmt(b, &len);
2626 debug(("%s", string));
2627 for (i = 0; i < len; i++)
2628 debug((" %02x", p[i]));
2634 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2638 p = ssh2_mpint_fmt(b, &len);
2639 hash_string(h, s, p, len);
2644 * Packet decode functions for both SSH-1 and SSH-2.
2646 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2648 unsigned long value;
2649 if (pkt->length - pkt->savedpos < 4)
2650 return 0; /* arrgh, no way to decline (FIXME?) */
2651 value = GET_32BIT(pkt->body + pkt->savedpos);
2655 static int ssh2_pkt_getbool(struct Packet *pkt)
2657 unsigned long value;
2658 if (pkt->length - pkt->savedpos < 1)
2659 return 0; /* arrgh, no way to decline (FIXME?) */
2660 value = pkt->body[pkt->savedpos] != 0;
2664 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2669 if (pkt->length - pkt->savedpos < 4)
2671 len = toint(GET_32BIT(pkt->body + pkt->savedpos));
2676 if (pkt->length - pkt->savedpos < *length)
2678 *p = (char *)(pkt->body + pkt->savedpos);
2679 pkt->savedpos += *length;
2681 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2683 if (pkt->length - pkt->savedpos < length)
2685 pkt->savedpos += length;
2686 return pkt->body + (pkt->savedpos - length);
2688 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2689 const unsigned char **keystr)
2693 j = makekey(pkt->body + pkt->savedpos,
2694 pkt->length - pkt->savedpos,
2701 assert(pkt->savedpos < pkt->length);
2705 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2710 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2711 pkt->length - pkt->savedpos, &b);
2719 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2725 ssh_pkt_getstring(pkt, &p, &length);
2730 b = bignum_from_bytes((unsigned char *)p, length);
2735 * Helper function to add an SSH-2 signature blob to a packet.
2736 * Expects to be shown the public key blob as well as the signature
2737 * blob. Normally works just like ssh2_pkt_addstring, but will
2738 * fiddle with the signature packet if necessary for
2739 * BUG_SSH2_RSA_PADDING.
2741 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2742 void *pkblob_v, int pkblob_len,
2743 void *sigblob_v, int sigblob_len)
2745 unsigned char *pkblob = (unsigned char *)pkblob_v;
2746 unsigned char *sigblob = (unsigned char *)sigblob_v;
2748 /* dmemdump(pkblob, pkblob_len); */
2749 /* dmemdump(sigblob, sigblob_len); */
2752 * See if this is in fact an ssh-rsa signature and a buggy
2753 * server; otherwise we can just do this the easy way.
2755 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) && pkblob_len > 4+7+4 &&
2756 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2757 int pos, len, siglen;
2760 * Find the byte length of the modulus.
2763 pos = 4+7; /* skip over "ssh-rsa" */
2764 len = toint(GET_32BIT(pkblob+pos)); /* get length of exponent */
2765 if (len < 0 || len > pkblob_len - pos - 4)
2767 pos += 4 + len; /* skip over exponent */
2768 if (pkblob_len - pos < 4)
2770 len = toint(GET_32BIT(pkblob+pos)); /* find length of modulus */
2771 if (len < 0 || len > pkblob_len - pos - 4)
2773 pos += 4; /* find modulus itself */
2774 while (len > 0 && pkblob[pos] == 0)
2776 /* debug(("modulus length is %d\n", len)); */
2779 * Now find the signature integer.
2781 pos = 4+7; /* skip over "ssh-rsa" */
2782 if (sigblob_len < pos+4)
2784 siglen = toint(GET_32BIT(sigblob+pos));
2785 if (siglen != sigblob_len - pos - 4)
2787 /* debug(("signature length is %d\n", siglen)); */
2789 if (len != siglen) {
2790 unsigned char newlen[4];
2791 ssh2_pkt_addstring_start(pkt);
2792 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2793 /* dmemdump(sigblob, pos); */
2794 pos += 4; /* point to start of actual sig */
2795 PUT_32BIT(newlen, len);
2796 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2797 /* dmemdump(newlen, 4); */
2799 while (len-- > siglen) {
2800 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2801 /* dmemdump(newlen, 1); */
2803 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2804 /* dmemdump(sigblob+pos, siglen); */
2808 /* Otherwise fall through and do it the easy way. We also come
2809 * here as a fallback if we discover above that the key blob
2810 * is misformatted in some way. */
2814 ssh2_pkt_addstring_start(pkt);
2815 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2819 * Examine the remote side's version string and compare it against
2820 * a list of known buggy implementations.
2822 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2824 char *imp; /* pointer to implementation part */
2826 imp += strcspn(imp, "-");
2828 imp += strcspn(imp, "-");
2831 ssh->remote_bugs = 0;
2834 * General notes on server version strings:
2835 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2836 * here -- in particular, we've heard of one that's perfectly happy
2837 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2838 * so we can't distinguish them.
2840 if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
2841 (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
2842 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2843 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2844 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2845 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2847 * These versions don't support SSH1_MSG_IGNORE, so we have
2848 * to use a different defence against password length
2851 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2852 logevent("We believe remote version has SSH-1 ignore bug");
2855 if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
2856 (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
2857 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2859 * These versions need a plain password sent; they can't
2860 * handle having a null and a random length of data after
2863 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2864 logevent("We believe remote version needs a plain SSH-1 password");
2867 if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
2868 (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
2869 (!strcmp(imp, "Cisco-1.25")))) {
2871 * These versions apparently have no clue whatever about
2872 * RSA authentication and will panic and die if they see
2873 * an AUTH_RSA message.
2875 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2876 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2879 if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
2880 (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
2881 !wc_match("* VShell", imp) &&
2882 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2883 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2884 wc_match("2.1 *", imp)))) {
2886 * These versions have the HMAC bug.
2888 ssh->remote_bugs |= BUG_SSH2_HMAC;
2889 logevent("We believe remote version has SSH-2 HMAC bug");
2892 if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
2893 (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
2894 !wc_match("* VShell", imp) &&
2895 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2897 * These versions have the key-derivation bug (failing to
2898 * include the literal shared secret in the hashes that
2899 * generate the keys).
2901 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2902 logevent("We believe remote version has SSH-2 key-derivation bug");
2905 if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
2906 (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
2907 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2908 wc_match("OpenSSH_3.[0-2]*", imp) ||
2909 wc_match("mod_sftp/0.[0-8]*", imp) ||
2910 wc_match("mod_sftp/0.9.[0-8]", imp)))) {
2912 * These versions have the SSH-2 RSA padding bug.
2914 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2915 logevent("We believe remote version has SSH-2 RSA padding bug");
2918 if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
2919 (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
2920 wc_match("OpenSSH_2.[0-2]*", imp))) {
2922 * These versions have the SSH-2 session-ID bug in
2923 * public-key authentication.
2925 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2926 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2929 if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
2930 (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
2931 (wc_match("DigiSSH_2.0", imp) ||
2932 wc_match("OpenSSH_2.[0-4]*", imp) ||
2933 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2934 wc_match("Sun_SSH_1.0", imp) ||
2935 wc_match("Sun_SSH_1.0.1", imp) ||
2936 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2937 wc_match("WeOnlyDo-*", imp)))) {
2939 * These versions have the SSH-2 rekey bug.
2941 ssh->remote_bugs |= BUG_SSH2_REKEY;
2942 logevent("We believe remote version has SSH-2 rekey bug");
2945 if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
2946 (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
2947 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2948 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2950 * This version ignores our makpkt and needs to be throttled.
2952 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2953 logevent("We believe remote version ignores SSH-2 maximum packet size");
2956 if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
2958 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2959 * none detected automatically.
2961 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2962 logevent("We believe remote version has SSH-2 ignore bug");
2965 if (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == FORCE_ON ||
2966 (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == AUTO &&
2967 (wc_match("OpenSSH_2.[235]*", imp)))) {
2969 * These versions only support the original (pre-RFC4419)
2970 * SSH-2 GEX request, and disconnect with a protocol error if
2971 * we use the newer version.
2973 ssh->remote_bugs |= BUG_SSH2_OLDGEX;
2974 logevent("We believe remote version has outdated SSH-2 GEX");
2977 if (conf_get_int(ssh->conf, CONF_sshbug_winadj) == FORCE_ON) {
2979 * Servers that don't support our winadj request for one
2980 * reason or another. Currently, none detected automatically.
2982 ssh->remote_bugs |= BUG_CHOKES_ON_WINADJ;
2983 logevent("We believe remote version has winadj bug");
2986 if (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == FORCE_ON ||
2987 (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == AUTO &&
2988 (wc_match("OpenSSH_[2-5].*", imp) ||
2989 wc_match("OpenSSH_6.[0-6]*", imp) ||
2990 wc_match("dropbear_0.[2-4][0-9]*", imp) ||
2991 wc_match("dropbear_0.5[01]*", imp)))) {
2993 * These versions have the SSH-2 channel request bug.
2994 * OpenSSH 6.7 and above do not:
2995 * https://bugzilla.mindrot.org/show_bug.cgi?id=1818
2996 * dropbear_0.52 and above do not:
2997 * https://secure.ucc.asn.au/hg/dropbear/rev/cd02449b709c
2999 ssh->remote_bugs |= BUG_SENDS_LATE_REQUEST_REPLY;
3000 logevent("We believe remote version has SSH-2 channel request bug");
3005 * The `software version' part of an SSH version string is required
3006 * to contain no spaces or minus signs.
3008 static void ssh_fix_verstring(char *str)
3010 /* Eat "<protoversion>-". */
3011 while (*str && *str != '-') str++;
3012 assert(*str == '-'); str++;
3014 /* Convert minus signs and spaces in the remaining string into
3017 if (*str == '-' || *str == ' ')
3024 * Send an appropriate SSH version string.
3026 static void ssh_send_verstring(Ssh ssh, const char *protoname, char *svers)
3030 if (ssh->version == 2) {
3032 * Construct a v2 version string.
3034 verstring = dupprintf("%s2.0-%s\015\012", protoname, sshver);
3037 * Construct a v1 version string.
3039 assert(!strcmp(protoname, "SSH-")); /* no v1 bare connection protocol */
3040 verstring = dupprintf("SSH-%s-%s\012",
3041 (ssh_versioncmp(svers, "1.5") <= 0 ?
3046 ssh_fix_verstring(verstring + strlen(protoname));
3048 /* FUZZING make PuTTY insecure, so make live use difficult. */
3052 if (ssh->version == 2) {
3055 * Record our version string.
3057 len = strcspn(verstring, "\015\012");
3058 ssh->v_c = snewn(len + 1, char);
3059 memcpy(ssh->v_c, verstring, len);
3063 logeventf(ssh, "We claim version: %.*s",
3064 strcspn(verstring, "\015\012"), verstring);
3065 s_write(ssh, verstring, strlen(verstring));
3069 static int do_ssh_init(Ssh ssh, unsigned char c)
3071 static const char protoname[] = "SSH-";
3073 struct do_ssh_init_state {
3082 crState(do_ssh_init_state);
3086 /* Search for a line beginning with the protocol name prefix in
3089 for (s->i = 0; protoname[s->i]; s->i++) {
3090 if ((char)c != protoname[s->i]) goto no;
3100 ssh->session_started = TRUE;
3102 s->vstrsize = sizeof(protoname) + 16;
3103 s->vstring = snewn(s->vstrsize, char);
3104 strcpy(s->vstring, protoname);
3105 s->vslen = strlen(protoname);
3108 if (s->vslen >= s->vstrsize - 1) {
3110 s->vstring = sresize(s->vstring, s->vstrsize, char);
3112 s->vstring[s->vslen++] = c;
3115 s->version[s->i] = '\0';
3117 } else if (s->i < sizeof(s->version) - 1)
3118 s->version[s->i++] = c;
3119 } else if (c == '\012')
3121 crReturn(1); /* get another char */
3124 ssh->agentfwd_enabled = FALSE;
3125 ssh->rdpkt2_state.incoming_sequence = 0;
3127 s->vstring[s->vslen] = 0;
3128 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3129 logeventf(ssh, "Server version: %s", s->vstring);
3130 ssh_detect_bugs(ssh, s->vstring);
3133 * Decide which SSH protocol version to support.
3136 /* Anything strictly below "2.0" means protocol 1 is supported. */
3137 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
3138 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
3139 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
3141 if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
3143 bombout(("SSH protocol version 1 required by our configuration "
3144 "but not provided by server"));
3147 } else if (conf_get_int(ssh->conf, CONF_sshprot) == 3) {
3149 bombout(("SSH protocol version 2 required by our configuration "
3150 "but server only provides (old, insecure) SSH-1"));
3154 /* No longer support values 1 or 2 for CONF_sshprot */
3155 assert(!"Unexpected value for CONF_sshprot");
3158 if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
3163 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
3165 /* Send the version string, if we haven't already */
3166 if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
3167 ssh_send_verstring(ssh, protoname, s->version);
3169 if (ssh->version == 2) {
3172 * Record their version string.
3174 len = strcspn(s->vstring, "\015\012");
3175 ssh->v_s = snewn(len + 1, char);
3176 memcpy(ssh->v_s, s->vstring, len);
3180 * Initialise SSH-2 protocol.
3182 ssh->protocol = ssh2_protocol;
3183 ssh2_protocol_setup(ssh);
3184 ssh->s_rdpkt = ssh2_rdpkt;
3187 * Initialise SSH-1 protocol.
3189 ssh->protocol = ssh1_protocol;
3190 ssh1_protocol_setup(ssh);
3191 ssh->s_rdpkt = ssh1_rdpkt;
3193 if (ssh->version == 2)
3194 do_ssh2_transport(ssh, NULL, -1, NULL);
3196 update_specials_menu(ssh->frontend);
3197 ssh->state = SSH_STATE_BEFORE_SIZE;
3198 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3205 static int do_ssh_connection_init(Ssh ssh, unsigned char c)
3208 * Ordinary SSH begins with the banner "SSH-x.y-...". This is just
3209 * the ssh-connection part, extracted and given a trivial binary
3210 * packet protocol, so we replace 'SSH-' at the start with a new
3211 * name. In proper SSH style (though of course this part of the
3212 * proper SSH protocol _isn't_ subject to this kind of
3213 * DNS-domain-based extension), we define the new name in our
3216 static const char protoname[] =
3217 "SSHCONNECTION@putty.projects.tartarus.org-";
3219 struct do_ssh_connection_init_state {
3227 crState(do_ssh_connection_init_state);
3231 /* Search for a line beginning with the protocol name prefix in
3234 for (s->i = 0; protoname[s->i]; s->i++) {
3235 if ((char)c != protoname[s->i]) goto no;
3245 s->vstrsize = sizeof(protoname) + 16;
3246 s->vstring = snewn(s->vstrsize, char);
3247 strcpy(s->vstring, protoname);
3248 s->vslen = strlen(protoname);
3251 if (s->vslen >= s->vstrsize - 1) {
3253 s->vstring = sresize(s->vstring, s->vstrsize, char);
3255 s->vstring[s->vslen++] = c;
3258 s->version[s->i] = '\0';
3260 } else if (s->i < sizeof(s->version) - 1)
3261 s->version[s->i++] = c;
3262 } else if (c == '\012')
3264 crReturn(1); /* get another char */
3267 ssh->agentfwd_enabled = FALSE;
3268 ssh->rdpkt2_bare_state.incoming_sequence = 0;
3270 s->vstring[s->vslen] = 0;
3271 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3272 logeventf(ssh, "Server version: %s", s->vstring);
3273 ssh_detect_bugs(ssh, s->vstring);
3276 * Decide which SSH protocol version to support. This is easy in
3277 * bare ssh-connection mode: only 2.0 is legal.
3279 if (ssh_versioncmp(s->version, "2.0") < 0) {
3280 bombout(("Server announces compatibility with SSH-1 in bare ssh-connection protocol"));
3283 if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
3284 bombout(("Bare ssh-connection protocol cannot be run in SSH-1-only mode"));
3290 logeventf(ssh, "Using bare ssh-connection protocol");
3292 /* Send the version string, if we haven't already */
3293 ssh_send_verstring(ssh, protoname, s->version);
3296 * Initialise bare connection protocol.
3298 ssh->protocol = ssh2_bare_connection_protocol;
3299 ssh2_bare_connection_protocol_setup(ssh);
3300 ssh->s_rdpkt = ssh2_bare_connection_rdpkt;
3302 update_specials_menu(ssh->frontend);
3303 ssh->state = SSH_STATE_BEFORE_SIZE;
3304 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3307 * Get authconn (really just conn) under way.
3309 do_ssh2_authconn(ssh, NULL, 0, NULL);
3316 static void ssh_process_incoming_data(Ssh ssh,
3317 const unsigned char **data, int *datalen)
3319 struct Packet *pktin;
3321 pktin = ssh->s_rdpkt(ssh, data, datalen);
3323 ssh->protocol(ssh, NULL, 0, pktin);
3324 ssh_free_packet(pktin);
3328 static void ssh_queue_incoming_data(Ssh ssh,
3329 const unsigned char **data, int *datalen)
3331 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
3336 static void ssh_process_queued_incoming_data(Ssh ssh)
3339 const unsigned char *data;
3342 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
3343 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
3347 while (!ssh->frozen && len > 0)
3348 ssh_process_incoming_data(ssh, &data, &len);
3351 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
3355 static void ssh_set_frozen(Ssh ssh, int frozen)
3358 sk_set_frozen(ssh->s, frozen);
3359 ssh->frozen = frozen;
3362 static void ssh_gotdata(Ssh ssh, const unsigned char *data, int datalen)
3364 /* Log raw data, if we're in that mode. */
3366 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
3367 0, NULL, NULL, 0, NULL);
3369 crBegin(ssh->ssh_gotdata_crstate);
3372 * To begin with, feed the characters one by one to the
3373 * protocol initialisation / selection function do_ssh_init().
3374 * When that returns 0, we're done with the initial greeting
3375 * exchange and can move on to packet discipline.
3378 int ret; /* need not be kept across crReturn */
3380 crReturnV; /* more data please */
3381 ret = ssh->do_ssh_init(ssh, *data);
3389 * We emerge from that loop when the initial negotiation is
3390 * over and we have selected an s_rdpkt function. Now pass
3391 * everything to s_rdpkt, and then pass the resulting packets
3392 * to the proper protocol handler.
3396 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
3398 ssh_queue_incoming_data(ssh, &data, &datalen);
3399 /* This uses up all data and cannot cause anything interesting
3400 * to happen; indeed, for anything to happen at all, we must
3401 * return, so break out. */
3403 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
3404 /* This uses up some or all data, and may freeze the
3406 ssh_process_queued_incoming_data(ssh);
3408 /* This uses up some or all data, and may freeze the
3410 ssh_process_incoming_data(ssh, &data, &datalen);
3412 /* FIXME this is probably EBW. */
3413 if (ssh->state == SSH_STATE_CLOSED)
3416 /* We're out of data. Go and get some more. */
3422 static int ssh_do_close(Ssh ssh, int notify_exit)
3425 struct ssh_channel *c;
3427 ssh->state = SSH_STATE_CLOSED;
3428 expire_timer_context(ssh);
3433 notify_remote_exit(ssh->frontend);
3438 * Now we must shut down any port- and X-forwarded channels going
3439 * through this connection.
3441 if (ssh->channels) {
3442 while (NULL != (c = index234(ssh->channels, 0))) {
3445 x11_close(c->u.x11.xconn);
3448 case CHAN_SOCKDATA_DORMANT:
3449 pfd_close(c->u.pfd.pf);
3452 del234(ssh->channels, c); /* moving next one to index 0 */
3453 if (ssh->version == 2)
3454 bufchain_clear(&c->v.v2.outbuffer);
3459 * Go through port-forwardings, and close any associated
3460 * listening sockets.
3462 if (ssh->portfwds) {
3463 struct ssh_portfwd *pf;
3464 while (NULL != (pf = index234(ssh->portfwds, 0))) {
3465 /* Dispose of any listening socket. */
3467 pfl_terminate(pf->local);
3468 del234(ssh->portfwds, pf); /* moving next one to index 0 */
3471 freetree234(ssh->portfwds);
3472 ssh->portfwds = NULL;
3476 * Also stop attempting to connection-share.
3478 if (ssh->connshare) {
3479 sharestate_free(ssh->connshare);
3480 ssh->connshare = NULL;
3486 static void ssh_socket_log(Plug plug, int type, SockAddr addr, int port,
3487 const char *error_msg, int error_code)
3489 Ssh ssh = (Ssh) plug;
3492 * While we're attempting connection sharing, don't loudly log
3493 * everything that happens. Real TCP connections need to be logged
3494 * when we _start_ trying to connect, because it might be ages
3495 * before they respond if something goes wrong; but connection
3496 * sharing is local and quick to respond, and it's sufficient to
3497 * simply wait and see whether it worked afterwards.
3500 if (!ssh->attempting_connshare)
3501 backend_socket_log(ssh->frontend, type, addr, port,
3502 error_msg, error_code, ssh->conf,
3503 ssh->session_started);
3506 void ssh_connshare_log(Ssh ssh, int event, const char *logtext,
3507 const char *ds_err, const char *us_err)
3509 if (event == SHARE_NONE) {
3510 /* In this case, 'logtext' is an error message indicating a
3511 * reason why connection sharing couldn't be set up _at all_.
3512 * Failing that, ds_err and us_err indicate why we couldn't be
3513 * a downstream and an upstream respectively. */
3515 logeventf(ssh, "Could not set up connection sharing: %s", logtext);
3518 logeventf(ssh, "Could not set up connection sharing"
3519 " as downstream: %s", ds_err);
3521 logeventf(ssh, "Could not set up connection sharing"
3522 " as upstream: %s", us_err);
3524 } else if (event == SHARE_DOWNSTREAM) {
3525 /* In this case, 'logtext' is a local endpoint address */
3526 logeventf(ssh, "Using existing shared connection at %s", logtext);
3527 /* Also we should mention this in the console window to avoid
3528 * confusing users as to why this window doesn't behave the
3530 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
3531 c_write_str(ssh,"Reusing a shared connection to this server.\r\n");
3533 } else if (event == SHARE_UPSTREAM) {
3534 /* In this case, 'logtext' is a local endpoint address too */
3535 logeventf(ssh, "Sharing this connection at %s", logtext);
3539 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
3542 Ssh ssh = (Ssh) plug;
3543 int need_notify = ssh_do_close(ssh, FALSE);
3546 if (!ssh->close_expected)
3547 error_msg = "Server unexpectedly closed network connection";
3549 error_msg = "Server closed network connection";
3552 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
3556 notify_remote_exit(ssh->frontend);
3559 logevent(error_msg);
3560 if (!ssh->close_expected || !ssh->clean_exit)
3561 connection_fatal(ssh->frontend, "%s", error_msg);
3565 static int ssh_receive(Plug plug, int urgent, char *data, int len)
3567 Ssh ssh = (Ssh) plug;
3568 ssh_gotdata(ssh, (unsigned char *)data, len);
3569 if (ssh->state == SSH_STATE_CLOSED) {
3570 ssh_do_close(ssh, TRUE);
3576 static void ssh_sent(Plug plug, int bufsize)
3578 Ssh ssh = (Ssh) plug;
3580 * If the send backlog on the SSH socket itself clears, we
3581 * should unthrottle the whole world if it was throttled.
3583 if (bufsize < SSH_MAX_BACKLOG)
3584 ssh_throttle_all(ssh, 0, bufsize);
3587 static void ssh_hostport_setup(const char *host, int port, Conf *conf,
3588 char **savedhost, int *savedport,
3591 char *loghost = conf_get_str(conf, CONF_loghost);
3593 *loghost_ret = loghost;
3599 tmphost = dupstr(loghost);
3600 *savedport = 22; /* default ssh port */
3603 * A colon suffix on the hostname string also lets us affect
3604 * savedport. (Unless there are multiple colons, in which case
3605 * we assume this is an unbracketed IPv6 literal.)
3607 colon = host_strrchr(tmphost, ':');
3608 if (colon && colon == host_strchr(tmphost, ':')) {
3611 *savedport = atoi(colon);
3614 *savedhost = host_strduptrim(tmphost);
3617 *savedhost = host_strduptrim(host);
3619 port = 22; /* default ssh port */
3624 static int ssh_test_for_upstream(const char *host, int port, Conf *conf)
3630 random_ref(); /* platform may need this to determine share socket name */
3631 ssh_hostport_setup(host, port, conf, &savedhost, &savedport, NULL);
3632 ret = ssh_share_test_for_upstream(savedhost, savedport, conf);
3640 * Connect to specified host and port.
3641 * Returns an error message, or NULL on success.
3642 * Also places the canonical host name into `realhost'. It must be
3643 * freed by the caller.
3645 static const char *connect_to_host(Ssh ssh, const char *host, int port,
3646 char **realhost, int nodelay, int keepalive)
3648 static const struct plug_function_table fn_table = {
3659 int addressfamily, sshprot;
3661 ssh_hostport_setup(host, port, ssh->conf,
3662 &ssh->savedhost, &ssh->savedport, &loghost);
3664 ssh->fn = &fn_table; /* make 'ssh' usable as a Plug */
3667 * Try connection-sharing, in case that means we don't open a
3668 * socket after all. ssh_connection_sharing_init will connect to a
3669 * previously established upstream if it can, and failing that,
3670 * establish a listening socket for _us_ to be the upstream. In
3671 * the latter case it will return NULL just as if it had done
3672 * nothing, because here we only need to care if we're a
3673 * downstream and need to do our connection setup differently.
3675 ssh->connshare = NULL;
3676 ssh->attempting_connshare = TRUE; /* affects socket logging behaviour */
3677 ssh->s = ssh_connection_sharing_init(ssh->savedhost, ssh->savedport,
3678 ssh->conf, ssh, &ssh->connshare);
3679 ssh->attempting_connshare = FALSE;
3680 if (ssh->s != NULL) {
3682 * We are a downstream.
3684 ssh->bare_connection = TRUE;
3685 ssh->do_ssh_init = do_ssh_connection_init;
3686 ssh->fullhostname = NULL;
3687 *realhost = dupstr(host); /* best we can do */
3690 * We're not a downstream, so open a normal socket.
3692 ssh->do_ssh_init = do_ssh_init;
3697 addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
3698 addr = name_lookup(host, port, realhost, ssh->conf, addressfamily,
3699 ssh->frontend, "SSH connection");
3700 if ((err = sk_addr_error(addr)) != NULL) {
3704 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
3706 ssh->s = new_connection(addr, *realhost, port,
3707 0, 1, nodelay, keepalive,
3708 (Plug) ssh, ssh->conf);
3709 if ((err = sk_socket_error(ssh->s)) != NULL) {
3711 notify_remote_exit(ssh->frontend);
3717 * The SSH version number is always fixed (since we no longer support
3718 * fallback between versions), so set it now, and if it's SSH-2,
3719 * send the version string now too.
3721 sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3722 assert(sshprot == 0 || sshprot == 3);
3726 if (sshprot == 3 && !ssh->bare_connection) {
3729 ssh_send_verstring(ssh, "SSH-", NULL);
3733 * loghost, if configured, overrides realhost.
3737 *realhost = dupstr(loghost);
3744 * Throttle or unthrottle the SSH connection.
3746 static void ssh_throttle_conn(Ssh ssh, int adjust)
3748 int old_count = ssh->conn_throttle_count;
3749 ssh->conn_throttle_count += adjust;
3750 assert(ssh->conn_throttle_count >= 0);
3751 if (ssh->conn_throttle_count && !old_count) {
3752 ssh_set_frozen(ssh, 1);
3753 } else if (!ssh->conn_throttle_count && old_count) {
3754 ssh_set_frozen(ssh, 0);
3759 * Throttle or unthrottle _all_ local data streams (for when sends
3760 * on the SSH connection itself back up).
3762 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3765 struct ssh_channel *c;
3767 if (enable == ssh->throttled_all)
3769 ssh->throttled_all = enable;
3770 ssh->overall_bufsize = bufsize;
3773 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3775 case CHAN_MAINSESSION:
3777 * This is treated separately, outside the switch.
3781 x11_override_throttle(c->u.x11.xconn, enable);
3784 /* Agent channels require no buffer management. */
3787 pfd_override_throttle(c->u.pfd.pf, enable);
3793 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3795 Ssh ssh = (Ssh) sshv;
3797 ssh->agent_response = reply;
3798 ssh->agent_response_len = replylen;
3800 if (ssh->version == 1)
3801 do_ssh1_login(ssh, NULL, -1, NULL);
3803 do_ssh2_authconn(ssh, NULL, -1, NULL);
3806 static void ssh_dialog_callback(void *sshv, int ret)
3808 Ssh ssh = (Ssh) sshv;
3810 ssh->user_response = ret;
3812 if (ssh->version == 1)
3813 do_ssh1_login(ssh, NULL, -1, NULL);
3815 do_ssh2_transport(ssh, NULL, -1, NULL);
3818 * This may have unfrozen the SSH connection, so do a
3821 ssh_process_queued_incoming_data(ssh);
3824 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3826 struct ssh_channel *c = (struct ssh_channel *)cv;
3828 const void *sentreply = reply;
3830 c->u.a.outstanding_requests--;
3832 /* Fake SSH_AGENT_FAILURE. */
3833 sentreply = "\0\0\0\1\5";
3836 if (ssh->version == 2) {
3837 ssh2_add_channel_data(c, sentreply, replylen);
3840 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3841 PKT_INT, c->remoteid,
3843 PKT_DATA, sentreply, replylen,
3849 * If we've already seen an incoming EOF but haven't sent an
3850 * outgoing one, this may be the moment to send it.
3852 if (c->u.a.outstanding_requests == 0 && (c->closes & CLOSES_RCVD_EOF))
3853 sshfwd_write_eof(c);
3857 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3858 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3859 * => log `wire_reason'.
3861 static void ssh_disconnect(Ssh ssh, const char *client_reason,
3862 const char *wire_reason,
3863 int code, int clean_exit)
3867 client_reason = wire_reason;
3869 error = dupprintf("Disconnected: %s", client_reason);
3871 error = dupstr("Disconnected");
3873 if (ssh->version == 1) {
3874 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3876 } else if (ssh->version == 2) {
3877 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3878 ssh2_pkt_adduint32(pktout, code);
3879 ssh2_pkt_addstring(pktout, wire_reason);
3880 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3881 ssh2_pkt_send_noqueue(ssh, pktout);
3884 ssh->close_expected = TRUE;
3885 ssh->clean_exit = clean_exit;
3886 ssh_closing((Plug)ssh, error, 0, 0);
3890 int verify_ssh_manual_host_key(Ssh ssh, const char *fingerprint,
3891 const struct ssh_signkey *ssh2keytype,
3894 if (!conf_get_str_nthstrkey(ssh->conf, CONF_ssh_manual_hostkeys, 0)) {
3895 return -1; /* no manual keys configured */
3900 * The fingerprint string we've been given will have things
3901 * like 'ssh-rsa 2048' at the front of it. Strip those off and
3902 * narrow down to just the colon-separated hex block at the
3903 * end of the string.
3905 const char *p = strrchr(fingerprint, ' ');
3906 fingerprint = p ? p+1 : fingerprint;
3907 /* Quick sanity checks, including making sure it's in lowercase */
3908 assert(strlen(fingerprint) == 16*3 - 1);
3909 assert(fingerprint[2] == ':');
3910 assert(fingerprint[strspn(fingerprint, "0123456789abcdef:")] == 0);
3912 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3914 return 1; /* success */
3919 * Construct the base64-encoded public key blob and see if
3922 unsigned char *binblob;
3924 int binlen, atoms, i;
3925 binblob = ssh2keytype->public_blob(ssh2keydata, &binlen);
3926 atoms = (binlen + 2) / 3;
3927 base64blob = snewn(atoms * 4 + 1, char);
3928 for (i = 0; i < atoms; i++)
3929 base64_encode_atom(binblob + 3*i, binlen - 3*i, base64blob + 4*i);
3930 base64blob[atoms * 4] = '\0';
3932 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3935 return 1; /* success */
3944 * Handle the key exchange and user authentication phases.
3946 static int do_ssh1_login(Ssh ssh, const unsigned char *in, int inlen,
3947 struct Packet *pktin)
3950 unsigned char cookie[8], *ptr;
3951 struct MD5Context md5c;
3952 struct do_ssh1_login_state {
3955 unsigned char *rsabuf;
3956 const unsigned char *keystr1, *keystr2;
3957 unsigned long supported_ciphers_mask, supported_auths_mask;
3958 int tried_publickey, tried_agent;
3959 int tis_auth_refused, ccard_auth_refused;
3960 unsigned char session_id[16];
3962 void *publickey_blob;
3963 int publickey_bloblen;
3964 char *publickey_comment;
3965 int privatekey_available, privatekey_encrypted;
3966 prompts_t *cur_prompt;
3969 unsigned char request[5], *response, *p;
3979 struct RSAKey servkey, hostkey;
3981 crState(do_ssh1_login_state);
3988 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3989 bombout(("Public key packet not received"));
3993 logevent("Received public keys");
3995 ptr = ssh_pkt_getdata(pktin, 8);
3997 bombout(("SSH-1 public key packet stopped before random cookie"));
4000 memcpy(cookie, ptr, 8);
4002 if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
4003 !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) {
4004 bombout(("Failed to read SSH-1 public keys from public key packet"));
4009 * Log the host key fingerprint.
4013 logevent("Host key fingerprint is:");
4014 strcpy(logmsg, " ");
4015 s->hostkey.comment = NULL;
4016 rsa_fingerprint(logmsg + strlen(logmsg),
4017 sizeof(logmsg) - strlen(logmsg), &s->hostkey);
4021 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
4022 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
4023 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
4024 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
4025 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
4027 ssh->v1_local_protoflags =
4028 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
4029 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
4032 MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
4033 MD5Update(&md5c, s->keystr1, s->servkey.bytes);
4034 MD5Update(&md5c, cookie, 8);
4035 MD5Final(s->session_id, &md5c);
4037 for (i = 0; i < 32; i++)
4038 ssh->session_key[i] = random_byte();
4041 * Verify that the `bits' and `bytes' parameters match.
4043 if (s->hostkey.bits > s->hostkey.bytes * 8 ||
4044 s->servkey.bits > s->servkey.bytes * 8) {
4045 bombout(("SSH-1 public keys were badly formatted"));
4049 s->len = (s->hostkey.bytes > s->servkey.bytes ?
4050 s->hostkey.bytes : s->servkey.bytes);
4052 s->rsabuf = snewn(s->len, unsigned char);
4055 * Verify the host key.
4059 * First format the key into a string.
4061 int len = rsastr_len(&s->hostkey);
4062 char fingerprint[100];
4063 char *keystr = snewn(len, char);
4064 rsastr_fmt(keystr, &s->hostkey);
4065 rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
4067 /* First check against manually configured host keys. */
4068 s->dlgret = verify_ssh_manual_host_key(ssh, fingerprint, NULL, NULL);
4069 if (s->dlgret == 0) { /* did not match */
4070 bombout(("Host key did not appear in manually configured list"));
4073 } else if (s->dlgret < 0) { /* none configured; use standard handling */
4074 ssh_set_frozen(ssh, 1);
4075 s->dlgret = verify_ssh_host_key(ssh->frontend,
4076 ssh->savedhost, ssh->savedport,
4077 "rsa", keystr, fingerprint,
4078 ssh_dialog_callback, ssh);
4083 if (s->dlgret < 0) {
4087 bombout(("Unexpected data from server while waiting"
4088 " for user host key response"));
4091 } while (pktin || inlen > 0);
4092 s->dlgret = ssh->user_response;
4094 ssh_set_frozen(ssh, 0);
4096 if (s->dlgret == 0) {
4097 ssh_disconnect(ssh, "User aborted at host key verification",
4106 for (i = 0; i < 32; i++) {
4107 s->rsabuf[i] = ssh->session_key[i];
4109 s->rsabuf[i] ^= s->session_id[i];
4112 if (s->hostkey.bytes > s->servkey.bytes) {
4113 ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
4115 ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
4117 ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
4119 ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
4122 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
4126 logevent("Encrypted session key");
4129 int cipher_chosen = 0, warn = 0;
4130 const char *cipher_string = NULL;
4132 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
4133 int next_cipher = conf_get_int_int(ssh->conf,
4134 CONF_ssh_cipherlist, i);
4135 if (next_cipher == CIPHER_WARN) {
4136 /* If/when we choose a cipher, warn about it */
4138 } else if (next_cipher == CIPHER_AES) {
4139 /* XXX Probably don't need to mention this. */
4140 logevent("AES not supported in SSH-1, skipping");
4142 switch (next_cipher) {
4143 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
4144 cipher_string = "3DES"; break;
4145 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
4146 cipher_string = "Blowfish"; break;
4147 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
4148 cipher_string = "single-DES"; break;
4150 if (s->supported_ciphers_mask & (1 << s->cipher_type))
4154 if (!cipher_chosen) {
4155 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
4156 bombout(("Server violates SSH-1 protocol by not "
4157 "supporting 3DES encryption"));
4159 /* shouldn't happen */
4160 bombout(("No supported ciphers found"));
4164 /* Warn about chosen cipher if necessary. */
4166 ssh_set_frozen(ssh, 1);
4167 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
4168 ssh_dialog_callback, ssh);
4169 if (s->dlgret < 0) {
4173 bombout(("Unexpected data from server while waiting"
4174 " for user response"));
4177 } while (pktin || inlen > 0);
4178 s->dlgret = ssh->user_response;
4180 ssh_set_frozen(ssh, 0);
4181 if (s->dlgret == 0) {
4182 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
4189 switch (s->cipher_type) {
4190 case SSH_CIPHER_3DES:
4191 logevent("Using 3DES encryption");
4193 case SSH_CIPHER_DES:
4194 logevent("Using single-DES encryption");
4196 case SSH_CIPHER_BLOWFISH:
4197 logevent("Using Blowfish encryption");
4201 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
4202 PKT_CHAR, s->cipher_type,
4203 PKT_DATA, cookie, 8,
4204 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
4205 PKT_DATA, s->rsabuf, s->len,
4206 PKT_INT, ssh->v1_local_protoflags, PKT_END);
4208 logevent("Trying to enable encryption...");
4212 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
4213 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
4215 ssh->v1_cipher_ctx = ssh->cipher->make_context();
4216 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
4217 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
4219 ssh->crcda_ctx = crcda_make_context();
4220 logevent("Installing CRC compensation attack detector");
4222 if (s->servkey.modulus) {
4223 sfree(s->servkey.modulus);
4224 s->servkey.modulus = NULL;
4226 if (s->servkey.exponent) {
4227 sfree(s->servkey.exponent);
4228 s->servkey.exponent = NULL;
4230 if (s->hostkey.modulus) {
4231 sfree(s->hostkey.modulus);
4232 s->hostkey.modulus = NULL;
4234 if (s->hostkey.exponent) {
4235 sfree(s->hostkey.exponent);
4236 s->hostkey.exponent = NULL;
4240 if (pktin->type != SSH1_SMSG_SUCCESS) {
4241 bombout(("Encryption not successfully enabled"));
4245 logevent("Successfully started encryption");
4247 fflush(stdout); /* FIXME eh? */
4249 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
4250 int ret; /* need not be kept over crReturn */
4251 s->cur_prompt = new_prompts(ssh->frontend);
4252 s->cur_prompt->to_server = TRUE;
4253 s->cur_prompt->name = dupstr("SSH login name");
4254 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
4255 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4258 crWaitUntil(!pktin);
4259 ret = get_userpass_input(s->cur_prompt, in, inlen);
4264 * Failed to get a username. Terminate.
4266 free_prompts(s->cur_prompt);
4267 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
4270 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
4271 free_prompts(s->cur_prompt);
4274 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
4276 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
4278 if (flags & FLAG_INTERACTIVE &&
4279 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
4280 c_write_str(ssh, userlog);
4281 c_write_str(ssh, "\r\n");
4289 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
4290 /* We must not attempt PK auth. Pretend we've already tried it. */
4291 s->tried_publickey = s->tried_agent = 1;
4293 s->tried_publickey = s->tried_agent = 0;
4295 s->tis_auth_refused = s->ccard_auth_refused = 0;
4297 * Load the public half of any configured keyfile for later use.
4299 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4300 if (!filename_is_null(s->keyfile)) {
4302 logeventf(ssh, "Reading key file \"%.150s\"",
4303 filename_to_str(s->keyfile));
4304 keytype = key_type(s->keyfile);
4305 if (keytype == SSH_KEYTYPE_SSH1 ||
4306 keytype == SSH_KEYTYPE_SSH1_PUBLIC) {
4308 if (rsakey_pubblob(s->keyfile,
4309 &s->publickey_blob, &s->publickey_bloblen,
4310 &s->publickey_comment, &error)) {
4311 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH1);
4312 if (!s->privatekey_available)
4313 logeventf(ssh, "Key file contains public key only");
4314 s->privatekey_encrypted = rsakey_encrypted(s->keyfile,
4318 logeventf(ssh, "Unable to load key (%s)", error);
4319 msgbuf = dupprintf("Unable to load key file "
4320 "\"%.150s\" (%s)\r\n",
4321 filename_to_str(s->keyfile),
4323 c_write_str(ssh, msgbuf);
4325 s->publickey_blob = NULL;
4329 logeventf(ssh, "Unable to use this key file (%s)",
4330 key_type_to_str(keytype));
4331 msgbuf = dupprintf("Unable to use key file \"%.150s\""
4333 filename_to_str(s->keyfile),
4334 key_type_to_str(keytype));
4335 c_write_str(ssh, msgbuf);
4337 s->publickey_blob = NULL;
4340 s->publickey_blob = NULL;
4342 while (pktin->type == SSH1_SMSG_FAILURE) {
4343 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
4345 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
4347 * Attempt RSA authentication using Pageant.
4353 logevent("Pageant is running. Requesting keys.");
4355 /* Request the keys held by the agent. */
4356 PUT_32BIT(s->request, 1);
4357 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
4358 if (!agent_query(s->request, 5, &r, &s->responselen,
4359 ssh_agent_callback, ssh)) {
4363 bombout(("Unexpected data from server while waiting"
4364 " for agent response"));
4367 } while (pktin || inlen > 0);
4368 r = ssh->agent_response;
4369 s->responselen = ssh->agent_response_len;
4371 s->response = (unsigned char *) r;
4372 if (s->response && s->responselen >= 5 &&
4373 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
4374 s->p = s->response + 5;
4375 s->nkeys = toint(GET_32BIT(s->p));
4377 logeventf(ssh, "Pageant reported negative key count %d",
4382 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
4383 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
4384 unsigned char *pkblob = s->p;
4388 do { /* do while (0) to make breaking easy */
4389 n = ssh1_read_bignum
4390 (s->p, toint(s->responselen-(s->p-s->response)),
4395 n = ssh1_read_bignum
4396 (s->p, toint(s->responselen-(s->p-s->response)),
4401 if (s->responselen - (s->p-s->response) < 4)
4403 s->commentlen = toint(GET_32BIT(s->p));
4405 if (s->commentlen < 0 ||
4406 toint(s->responselen - (s->p-s->response)) <
4409 s->commentp = (char *)s->p;
4410 s->p += s->commentlen;
4414 logevent("Pageant key list packet was truncated");
4418 if (s->publickey_blob) {
4419 if (!memcmp(pkblob, s->publickey_blob,
4420 s->publickey_bloblen)) {
4421 logeventf(ssh, "Pageant key #%d matches "
4422 "configured key file", s->keyi);
4423 s->tried_publickey = 1;
4425 /* Skip non-configured key */
4428 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
4429 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4430 PKT_BIGNUM, s->key.modulus, PKT_END);
4432 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4433 logevent("Key refused");
4436 logevent("Received RSA challenge");
4437 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4438 bombout(("Server's RSA challenge was badly formatted"));
4443 char *agentreq, *q, *ret;
4446 len = 1 + 4; /* message type, bit count */
4447 len += ssh1_bignum_length(s->key.exponent);
4448 len += ssh1_bignum_length(s->key.modulus);
4449 len += ssh1_bignum_length(s->challenge);
4450 len += 16; /* session id */
4451 len += 4; /* response format */
4452 agentreq = snewn(4 + len, char);
4453 PUT_32BIT(agentreq, len);
4455 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
4456 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
4458 q += ssh1_write_bignum(q, s->key.exponent);
4459 q += ssh1_write_bignum(q, s->key.modulus);
4460 q += ssh1_write_bignum(q, s->challenge);
4461 memcpy(q, s->session_id, 16);
4463 PUT_32BIT(q, 1); /* response format */
4464 if (!agent_query(agentreq, len + 4, &vret, &retlen,
4465 ssh_agent_callback, ssh)) {
4470 bombout(("Unexpected data from server"
4471 " while waiting for agent"
4475 } while (pktin || inlen > 0);
4476 vret = ssh->agent_response;
4477 retlen = ssh->agent_response_len;
4482 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
4483 logevent("Sending Pageant's response");
4484 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4485 PKT_DATA, ret + 5, 16,
4489 if (pktin->type == SSH1_SMSG_SUCCESS) {
4491 ("Pageant's response accepted");
4492 if (flags & FLAG_VERBOSE) {
4493 c_write_str(ssh, "Authenticated using"
4495 c_write(ssh, s->commentp,
4497 c_write_str(ssh, "\" from agent\r\n");
4502 ("Pageant's response not accepted");
4505 ("Pageant failed to answer challenge");
4509 logevent("No reply received from Pageant");
4512 freebn(s->key.exponent);
4513 freebn(s->key.modulus);
4514 freebn(s->challenge);
4519 if (s->publickey_blob && !s->tried_publickey)
4520 logevent("Configured key file not in Pageant");
4522 logevent("Failed to get reply from Pageant");
4527 if (s->publickey_blob && s->privatekey_available &&
4528 !s->tried_publickey) {
4530 * Try public key authentication with the specified
4533 int got_passphrase; /* need not be kept over crReturn */
4534 if (flags & FLAG_VERBOSE)
4535 c_write_str(ssh, "Trying public key authentication.\r\n");
4536 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4537 logeventf(ssh, "Trying public key \"%s\"",
4538 filename_to_str(s->keyfile));
4539 s->tried_publickey = 1;
4540 got_passphrase = FALSE;
4541 while (!got_passphrase) {
4543 * Get a passphrase, if necessary.
4545 char *passphrase = NULL; /* only written after crReturn */
4547 if (!s->privatekey_encrypted) {
4548 if (flags & FLAG_VERBOSE)
4549 c_write_str(ssh, "No passphrase required.\r\n");
4552 int ret; /* need not be kept over crReturn */
4553 s->cur_prompt = new_prompts(ssh->frontend);
4554 s->cur_prompt->to_server = FALSE;
4555 s->cur_prompt->name = dupstr("SSH key passphrase");
4556 add_prompt(s->cur_prompt,
4557 dupprintf("Passphrase for key \"%.100s\": ",
4558 s->publickey_comment), FALSE);
4559 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4562 crWaitUntil(!pktin);
4563 ret = get_userpass_input(s->cur_prompt, in, inlen);
4567 /* Failed to get a passphrase. Terminate. */
4568 free_prompts(s->cur_prompt);
4569 ssh_disconnect(ssh, NULL, "Unable to authenticate",
4573 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
4574 free_prompts(s->cur_prompt);
4577 * Try decrypting key with passphrase.
4579 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4580 ret = loadrsakey(s->keyfile, &s->key, passphrase,
4583 smemclr(passphrase, strlen(passphrase));
4587 /* Correct passphrase. */
4588 got_passphrase = TRUE;
4589 } else if (ret == 0) {
4590 c_write_str(ssh, "Couldn't load private key from ");
4591 c_write_str(ssh, filename_to_str(s->keyfile));
4592 c_write_str(ssh, " (");
4593 c_write_str(ssh, error);
4594 c_write_str(ssh, ").\r\n");
4595 got_passphrase = FALSE;
4596 break; /* go and try something else */
4597 } else if (ret == -1) {
4598 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
4599 got_passphrase = FALSE;
4602 assert(0 && "unexpected return from loadrsakey()");
4603 got_passphrase = FALSE; /* placate optimisers */
4607 if (got_passphrase) {
4610 * Send a public key attempt.
4612 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4613 PKT_BIGNUM, s->key.modulus, PKT_END);
4616 if (pktin->type == SSH1_SMSG_FAILURE) {
4617 c_write_str(ssh, "Server refused our public key.\r\n");
4618 continue; /* go and try something else */
4620 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4621 bombout(("Bizarre response to offer of public key"));
4627 unsigned char buffer[32];
4628 Bignum challenge, response;
4630 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4631 bombout(("Server's RSA challenge was badly formatted"));
4634 response = rsadecrypt(challenge, &s->key);
4635 freebn(s->key.private_exponent);/* burn the evidence */
4637 for (i = 0; i < 32; i++) {
4638 buffer[i] = bignum_byte(response, 31 - i);
4642 MD5Update(&md5c, buffer, 32);
4643 MD5Update(&md5c, s->session_id, 16);
4644 MD5Final(buffer, &md5c);
4646 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4647 PKT_DATA, buffer, 16, PKT_END);
4654 if (pktin->type == SSH1_SMSG_FAILURE) {
4655 if (flags & FLAG_VERBOSE)
4656 c_write_str(ssh, "Failed to authenticate with"
4657 " our public key.\r\n");
4658 continue; /* go and try something else */
4659 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4660 bombout(("Bizarre response to RSA authentication response"));
4664 break; /* we're through! */
4670 * Otherwise, try various forms of password-like authentication.
4672 s->cur_prompt = new_prompts(ssh->frontend);
4674 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4675 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
4676 !s->tis_auth_refused) {
4677 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
4678 logevent("Requested TIS authentication");
4679 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
4681 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
4682 logevent("TIS authentication declined");
4683 if (flags & FLAG_INTERACTIVE)
4684 c_write_str(ssh, "TIS authentication refused.\r\n");
4685 s->tis_auth_refused = 1;
4690 char *instr_suf, *prompt;
4692 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4694 bombout(("TIS challenge packet was badly formed"));
4697 logevent("Received TIS challenge");
4698 s->cur_prompt->to_server = TRUE;
4699 s->cur_prompt->name = dupstr("SSH TIS authentication");
4700 /* Prompt heuristic comes from OpenSSH */
4701 if (memchr(challenge, '\n', challengelen)) {
4702 instr_suf = dupstr("");
4703 prompt = dupprintf("%.*s", challengelen, challenge);
4705 instr_suf = dupprintf("%.*s", challengelen, challenge);
4706 prompt = dupstr("Response: ");
4708 s->cur_prompt->instruction =
4709 dupprintf("Using TIS authentication.%s%s",
4710 (*instr_suf) ? "\n" : "",
4712 s->cur_prompt->instr_reqd = TRUE;
4713 add_prompt(s->cur_prompt, prompt, FALSE);
4717 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4718 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
4719 !s->ccard_auth_refused) {
4720 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
4721 logevent("Requested CryptoCard authentication");
4722 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
4724 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
4725 logevent("CryptoCard authentication declined");
4726 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
4727 s->ccard_auth_refused = 1;
4732 char *instr_suf, *prompt;
4734 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4736 bombout(("CryptoCard challenge packet was badly formed"));
4739 logevent("Received CryptoCard challenge");
4740 s->cur_prompt->to_server = TRUE;
4741 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4742 s->cur_prompt->name_reqd = FALSE;
4743 /* Prompt heuristic comes from OpenSSH */
4744 if (memchr(challenge, '\n', challengelen)) {
4745 instr_suf = dupstr("");
4746 prompt = dupprintf("%.*s", challengelen, challenge);
4748 instr_suf = dupprintf("%.*s", challengelen, challenge);
4749 prompt = dupstr("Response: ");
4751 s->cur_prompt->instruction =
4752 dupprintf("Using CryptoCard authentication.%s%s",
4753 (*instr_suf) ? "\n" : "",
4755 s->cur_prompt->instr_reqd = TRUE;
4756 add_prompt(s->cur_prompt, prompt, FALSE);
4760 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4761 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4762 bombout(("No supported authentication methods available"));
4765 s->cur_prompt->to_server = TRUE;
4766 s->cur_prompt->name = dupstr("SSH password");
4767 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4768 ssh->username, ssh->savedhost),
4773 * Show password prompt, having first obtained it via a TIS
4774 * or CryptoCard exchange if we're doing TIS or CryptoCard
4778 int ret; /* need not be kept over crReturn */
4779 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4782 crWaitUntil(!pktin);
4783 ret = get_userpass_input(s->cur_prompt, in, inlen);
4788 * Failed to get a password (for example
4789 * because one was supplied on the command line
4790 * which has already failed to work). Terminate.
4792 free_prompts(s->cur_prompt);
4793 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4798 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4800 * Defence against traffic analysis: we send a
4801 * whole bunch of packets containing strings of
4802 * different lengths. One of these strings is the
4803 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4804 * The others are all random data in
4805 * SSH1_MSG_IGNORE packets. This way a passive
4806 * listener can't tell which is the password, and
4807 * hence can't deduce the password length.
4809 * Anybody with a password length greater than 16
4810 * bytes is going to have enough entropy in their
4811 * password that a listener won't find it _that_
4812 * much help to know how long it is. So what we'll
4815 * - if password length < 16, we send 15 packets
4816 * containing string lengths 1 through 15
4818 * - otherwise, we let N be the nearest multiple
4819 * of 8 below the password length, and send 8
4820 * packets containing string lengths N through
4821 * N+7. This won't obscure the order of
4822 * magnitude of the password length, but it will
4823 * introduce a bit of extra uncertainty.
4825 * A few servers can't deal with SSH1_MSG_IGNORE, at
4826 * least in this context. For these servers, we need
4827 * an alternative defence. We make use of the fact
4828 * that the password is interpreted as a C string:
4829 * so we can append a NUL, then some random data.
4831 * A few servers can deal with neither SSH1_MSG_IGNORE
4832 * here _nor_ a padded password string.
4833 * For these servers we are left with no defences
4834 * against password length sniffing.
4836 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4837 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4839 * The server can deal with SSH1_MSG_IGNORE, so
4840 * we can use the primary defence.
4842 int bottom, top, pwlen, i;
4845 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4847 bottom = 0; /* zero length passwords are OK! :-) */
4850 bottom = pwlen & ~7;
4854 assert(pwlen >= bottom && pwlen <= top);
4856 randomstr = snewn(top + 1, char);
4858 for (i = bottom; i <= top; i++) {
4860 defer_packet(ssh, s->pwpkt_type,
4861 PKT_STR,s->cur_prompt->prompts[0]->result,
4864 for (j = 0; j < i; j++) {
4866 randomstr[j] = random_byte();
4867 } while (randomstr[j] == '\0');
4869 randomstr[i] = '\0';
4870 defer_packet(ssh, SSH1_MSG_IGNORE,
4871 PKT_STR, randomstr, PKT_END);
4874 logevent("Sending password with camouflage packets");
4875 ssh_pkt_defersend(ssh);
4878 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4880 * The server can't deal with SSH1_MSG_IGNORE
4881 * but can deal with padded passwords, so we
4882 * can use the secondary defence.
4888 len = strlen(s->cur_prompt->prompts[0]->result);
4889 if (len < sizeof(string)) {
4891 strcpy(string, s->cur_prompt->prompts[0]->result);
4892 len++; /* cover the zero byte */
4893 while (len < sizeof(string)) {
4894 string[len++] = (char) random_byte();
4897 ss = s->cur_prompt->prompts[0]->result;
4899 logevent("Sending length-padded password");
4900 send_packet(ssh, s->pwpkt_type,
4901 PKT_INT, len, PKT_DATA, ss, len,
4905 * The server is believed unable to cope with
4906 * any of our password camouflage methods.
4909 len = strlen(s->cur_prompt->prompts[0]->result);
4910 logevent("Sending unpadded password");
4911 send_packet(ssh, s->pwpkt_type,
4913 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4917 send_packet(ssh, s->pwpkt_type,
4918 PKT_STR, s->cur_prompt->prompts[0]->result,
4921 logevent("Sent password");
4922 free_prompts(s->cur_prompt);
4924 if (pktin->type == SSH1_SMSG_FAILURE) {
4925 if (flags & FLAG_VERBOSE)
4926 c_write_str(ssh, "Access denied\r\n");
4927 logevent("Authentication refused");
4928 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4929 bombout(("Strange packet received, type %d", pktin->type));
4935 if (s->publickey_blob) {
4936 sfree(s->publickey_blob);
4937 sfree(s->publickey_comment);
4940 logevent("Authentication successful");
4945 static void ssh_channel_try_eof(struct ssh_channel *c)
4948 assert(c->pending_eof); /* precondition for calling us */
4950 return; /* can't close: not even opened yet */
4951 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4952 return; /* can't send EOF: pending outgoing data */
4954 c->pending_eof = FALSE; /* we're about to send it */
4955 if (ssh->version == 1) {
4956 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4958 c->closes |= CLOSES_SENT_EOF;
4960 struct Packet *pktout;
4961 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4962 ssh2_pkt_adduint32(pktout, c->remoteid);
4963 ssh2_pkt_send(ssh, pktout);
4964 c->closes |= CLOSES_SENT_EOF;
4965 ssh2_channel_check_close(c);
4969 Conf *sshfwd_get_conf(struct ssh_channel *c)
4975 void sshfwd_write_eof(struct ssh_channel *c)
4979 if (ssh->state == SSH_STATE_CLOSED)
4982 if (c->closes & CLOSES_SENT_EOF)
4985 c->pending_eof = TRUE;
4986 ssh_channel_try_eof(c);
4989 void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
4993 if (ssh->state == SSH_STATE_CLOSED)
4998 x11_close(c->u.x11.xconn);
4999 logeventf(ssh, "Forwarded X11 connection terminated due to local "
5003 case CHAN_SOCKDATA_DORMANT:
5004 pfd_close(c->u.pfd.pf);
5005 logeventf(ssh, "Forwarded port closed due to local error: %s", err);
5008 c->type = CHAN_ZOMBIE;
5009 c->pending_eof = FALSE; /* this will confuse a zombie channel */
5011 ssh2_channel_check_close(c);
5014 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
5018 if (ssh->state == SSH_STATE_CLOSED)
5021 if (ssh->version == 1) {
5022 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
5023 PKT_INT, c->remoteid,
5024 PKT_INT, len, PKT_DATA, buf, len,
5027 * In SSH-1 we can return 0 here - implying that forwarded
5028 * connections are never individually throttled - because
5029 * the only circumstance that can cause throttling will be
5030 * the whole SSH connection backing up, in which case
5031 * _everything_ will be throttled as a whole.
5035 ssh2_add_channel_data(c, buf, len);
5036 return ssh2_try_send(c);
5040 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
5045 if (ssh->state == SSH_STATE_CLOSED)
5048 if (ssh->version == 1) {
5049 buflimit = SSH1_BUFFER_LIMIT;
5051 buflimit = c->v.v2.locmaxwin;
5052 ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
5054 if (c->throttling_conn && bufsize <= buflimit) {
5055 c->throttling_conn = 0;
5056 ssh_throttle_conn(ssh, -1);
5060 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
5062 struct queued_handler *qh = ssh->qhead;
5066 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
5069 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
5070 ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
5073 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
5074 ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
5078 ssh->qhead = qh->next;
5080 if (ssh->qhead->msg1 > 0) {
5081 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5082 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
5084 if (ssh->qhead->msg2 > 0) {
5085 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5086 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
5089 ssh->qhead = ssh->qtail = NULL;
5092 qh->handler(ssh, pktin, qh->ctx);
5097 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
5098 chandler_fn_t handler, void *ctx)
5100 struct queued_handler *qh;
5102 qh = snew(struct queued_handler);
5105 qh->handler = handler;
5109 if (ssh->qtail == NULL) {
5113 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5114 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
5117 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5118 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
5121 ssh->qtail->next = qh;
5126 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
5128 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
5130 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
5131 SSH2_MSG_REQUEST_SUCCESS)) {
5132 logeventf(ssh, "Remote port forwarding from %s enabled",
5135 logeventf(ssh, "Remote port forwarding from %s refused",
5138 rpf = del234(ssh->rportfwds, pf);
5140 pf->pfrec->remote = NULL;
5145 int ssh_alloc_sharing_rportfwd(Ssh ssh, const char *shost, int sport,
5148 struct ssh_rportfwd *pf = snew(struct ssh_rportfwd);
5151 pf->share_ctx = share_ctx;
5152 pf->shost = dupstr(shost);
5154 pf->sportdesc = NULL;
5155 if (!ssh->rportfwds) {
5156 assert(ssh->version == 2);
5157 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5159 if (add234(ssh->rportfwds, pf) != pf) {
5167 static void ssh_sharing_global_request_response(Ssh ssh, struct Packet *pktin,
5170 share_got_pkt_from_server(ctx, pktin->type,
5171 pktin->body, pktin->length);
5174 void ssh_sharing_queue_global_request(Ssh ssh, void *share_ctx)
5176 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE,
5177 ssh_sharing_global_request_response, share_ctx);
5180 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
5182 struct ssh_portfwd *epf;
5186 if (!ssh->portfwds) {
5187 ssh->portfwds = newtree234(ssh_portcmp);
5190 * Go through the existing port forwardings and tag them
5191 * with status==DESTROY. Any that we want to keep will be
5192 * re-enabled (status==KEEP) as we go through the
5193 * configuration and find out which bits are the same as
5196 struct ssh_portfwd *epf;
5198 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5199 epf->status = DESTROY;
5202 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
5204 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
5205 char *kp, *kp2, *vp, *vp2;
5206 char address_family, type;
5207 int sport,dport,sserv,dserv;
5208 char *sports, *dports, *saddr, *host;
5212 address_family = 'A';
5214 if (*kp == 'A' || *kp == '4' || *kp == '6')
5215 address_family = *kp++;
5216 if (*kp == 'L' || *kp == 'R')
5219 if ((kp2 = host_strchr(kp, ':')) != NULL) {
5221 * There's a colon in the middle of the source port
5222 * string, which means that the part before it is
5223 * actually a source address.
5225 char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp);
5226 saddr = host_strduptrim(saddr_tmp);
5233 sport = atoi(sports);
5237 sport = net_service_lookup(sports);
5239 logeventf(ssh, "Service lookup failed for source"
5240 " port \"%s\"", sports);
5244 if (type == 'L' && !strcmp(val, "D")) {
5245 /* dynamic forwarding */
5252 /* ordinary forwarding */
5254 vp2 = vp + host_strcspn(vp, ":");
5255 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
5259 dport = atoi(dports);
5263 dport = net_service_lookup(dports);
5265 logeventf(ssh, "Service lookup failed for destination"
5266 " port \"%s\"", dports);
5271 if (sport && dport) {
5272 /* Set up a description of the source port. */
5273 struct ssh_portfwd *pfrec, *epfrec;
5275 pfrec = snew(struct ssh_portfwd);
5277 pfrec->saddr = saddr;
5278 pfrec->sserv = sserv ? dupstr(sports) : NULL;
5279 pfrec->sport = sport;
5280 pfrec->daddr = host;
5281 pfrec->dserv = dserv ? dupstr(dports) : NULL;
5282 pfrec->dport = dport;
5283 pfrec->local = NULL;
5284 pfrec->remote = NULL;
5285 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
5286 address_family == '6' ? ADDRTYPE_IPV6 :
5289 epfrec = add234(ssh->portfwds, pfrec);
5290 if (epfrec != pfrec) {
5291 if (epfrec->status == DESTROY) {
5293 * We already have a port forwarding up and running
5294 * with precisely these parameters. Hence, no need
5295 * to do anything; simply re-tag the existing one
5298 epfrec->status = KEEP;
5301 * Anything else indicates that there was a duplicate
5302 * in our input, which we'll silently ignore.
5304 free_portfwd(pfrec);
5306 pfrec->status = CREATE;
5315 * Now go through and destroy any port forwardings which were
5318 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5319 if (epf->status == DESTROY) {
5322 message = dupprintf("%s port forwarding from %s%s%d",
5323 epf->type == 'L' ? "local" :
5324 epf->type == 'R' ? "remote" : "dynamic",
5325 epf->saddr ? epf->saddr : "",
5326 epf->saddr ? ":" : "",
5329 if (epf->type != 'D') {
5330 char *msg2 = dupprintf("%s to %s:%d", message,
5331 epf->daddr, epf->dport);
5336 logeventf(ssh, "Cancelling %s", message);
5339 /* epf->remote or epf->local may be NULL if setting up a
5340 * forwarding failed. */
5342 struct ssh_rportfwd *rpf = epf->remote;
5343 struct Packet *pktout;
5346 * Cancel the port forwarding at the server
5349 if (ssh->version == 1) {
5351 * We cannot cancel listening ports on the
5352 * server side in SSH-1! There's no message
5353 * to support it. Instead, we simply remove
5354 * the rportfwd record from the local end
5355 * so that any connections the server tries
5356 * to make on it are rejected.
5359 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5360 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
5361 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
5363 ssh2_pkt_addstring(pktout, epf->saddr);
5364 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5365 /* XXX: rport_acceptall may not represent
5366 * what was used to open the original connection,
5367 * since it's reconfigurable. */
5368 ssh2_pkt_addstring(pktout, "");
5370 ssh2_pkt_addstring(pktout, "localhost");
5372 ssh2_pkt_adduint32(pktout, epf->sport);
5373 ssh2_pkt_send(ssh, pktout);
5376 del234(ssh->rportfwds, rpf);
5378 } else if (epf->local) {
5379 pfl_terminate(epf->local);
5382 delpos234(ssh->portfwds, i);
5384 i--; /* so we don't skip one in the list */
5388 * And finally, set up any new port forwardings (status==CREATE).
5390 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5391 if (epf->status == CREATE) {
5392 char *sportdesc, *dportdesc;
5393 sportdesc = dupprintf("%s%s%s%s%d%s",
5394 epf->saddr ? epf->saddr : "",
5395 epf->saddr ? ":" : "",
5396 epf->sserv ? epf->sserv : "",
5397 epf->sserv ? "(" : "",
5399 epf->sserv ? ")" : "");
5400 if (epf->type == 'D') {
5403 dportdesc = dupprintf("%s:%s%s%d%s",
5405 epf->dserv ? epf->dserv : "",
5406 epf->dserv ? "(" : "",
5408 epf->dserv ? ")" : "");
5411 if (epf->type == 'L') {
5412 char *err = pfl_listen(epf->daddr, epf->dport,
5413 epf->saddr, epf->sport,
5414 ssh, conf, &epf->local,
5415 epf->addressfamily);
5417 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
5418 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5419 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5420 sportdesc, dportdesc,
5421 err ? " failed: " : "", err ? err : "");
5424 } else if (epf->type == 'D') {
5425 char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport,
5426 ssh, conf, &epf->local,
5427 epf->addressfamily);
5429 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
5430 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5431 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5433 err ? " failed: " : "", err ? err : "");
5438 struct ssh_rportfwd *pf;
5441 * Ensure the remote port forwardings tree exists.
5443 if (!ssh->rportfwds) {
5444 if (ssh->version == 1)
5445 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
5447 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5450 pf = snew(struct ssh_rportfwd);
5451 pf->share_ctx = NULL;
5452 pf->dhost = dupstr(epf->daddr);
5453 pf->dport = epf->dport;
5455 pf->shost = dupstr(epf->saddr);
5456 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5457 pf->shost = dupstr("");
5459 pf->shost = dupstr("localhost");
5461 pf->sport = epf->sport;
5462 if (add234(ssh->rportfwds, pf) != pf) {
5463 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
5464 epf->daddr, epf->dport);
5467 logeventf(ssh, "Requesting remote port %s"
5468 " forward to %s", sportdesc, dportdesc);
5470 pf->sportdesc = sportdesc;
5475 if (ssh->version == 1) {
5476 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
5477 PKT_INT, epf->sport,
5478 PKT_STR, epf->daddr,
5479 PKT_INT, epf->dport,
5481 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
5483 ssh_rportfwd_succfail, pf);
5485 struct Packet *pktout;
5486 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5487 ssh2_pkt_addstring(pktout, "tcpip-forward");
5488 ssh2_pkt_addbool(pktout, 1);/* want reply */
5489 ssh2_pkt_addstring(pktout, pf->shost);
5490 ssh2_pkt_adduint32(pktout, pf->sport);
5491 ssh2_pkt_send(ssh, pktout);
5493 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
5494 SSH2_MSG_REQUEST_FAILURE,
5495 ssh_rportfwd_succfail, pf);
5504 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
5507 int stringlen, bufsize;
5509 ssh_pkt_getstring(pktin, &string, &stringlen);
5510 if (string == NULL) {
5511 bombout(("Incoming terminal data packet was badly formed"));
5515 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
5517 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
5518 ssh->v1_stdout_throttling = 1;
5519 ssh_throttle_conn(ssh, +1);
5523 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
5525 /* Remote side is trying to open a channel to talk to our
5526 * X-Server. Give them back a local channel number. */
5527 struct ssh_channel *c;
5528 int remoteid = ssh_pkt_getuint32(pktin);
5530 logevent("Received X11 connect request");
5531 /* Refuse if X11 forwarding is disabled. */
5532 if (!ssh->X11_fwd_enabled) {
5533 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5534 PKT_INT, remoteid, PKT_END);
5535 logevent("Rejected X11 connect request");
5537 c = snew(struct ssh_channel);
5540 c->u.x11.xconn = x11_init(ssh->x11authtree, c, NULL, -1);
5541 c->remoteid = remoteid;
5542 c->halfopen = FALSE;
5543 c->localid = alloc_channel_id(ssh);
5545 c->pending_eof = FALSE;
5546 c->throttling_conn = 0;
5547 c->type = CHAN_X11; /* identify channel type */
5548 add234(ssh->channels, c);
5549 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5550 PKT_INT, c->remoteid, PKT_INT,
5551 c->localid, PKT_END);
5552 logevent("Opened X11 forward channel");
5556 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
5558 /* Remote side is trying to open a channel to talk to our
5559 * agent. Give them back a local channel number. */
5560 struct ssh_channel *c;
5561 int remoteid = ssh_pkt_getuint32(pktin);
5563 /* Refuse if agent forwarding is disabled. */
5564 if (!ssh->agentfwd_enabled) {
5565 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5566 PKT_INT, remoteid, PKT_END);
5568 c = snew(struct ssh_channel);
5570 c->remoteid = remoteid;
5571 c->halfopen = FALSE;
5572 c->localid = alloc_channel_id(ssh);
5574 c->pending_eof = FALSE;
5575 c->throttling_conn = 0;
5576 c->type = CHAN_AGENT; /* identify channel type */
5577 c->u.a.lensofar = 0;
5578 c->u.a.message = NULL;
5579 c->u.a.outstanding_requests = 0;
5580 add234(ssh->channels, c);
5581 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5582 PKT_INT, c->remoteid, PKT_INT, c->localid,
5587 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
5589 /* Remote side is trying to open a channel to talk to a
5590 * forwarded port. Give them back a local channel number. */
5591 struct ssh_rportfwd pf, *pfp;
5597 remoteid = ssh_pkt_getuint32(pktin);
5598 ssh_pkt_getstring(pktin, &host, &hostsize);
5599 port = ssh_pkt_getuint32(pktin);
5601 pf.dhost = dupprintf("%.*s", hostsize, NULLTOEMPTY(host));
5603 pfp = find234(ssh->rportfwds, &pf, NULL);
5606 logeventf(ssh, "Rejected remote port open request for %s:%d",
5608 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5609 PKT_INT, remoteid, PKT_END);
5611 struct ssh_channel *c = snew(struct ssh_channel);
5614 logeventf(ssh, "Received remote port open request for %s:%d",
5616 err = pfd_connect(&c->u.pfd.pf, pf.dhost, port,
5617 c, ssh->conf, pfp->pfrec->addressfamily);
5619 logeventf(ssh, "Port open failed: %s", err);
5622 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5623 PKT_INT, remoteid, PKT_END);
5625 c->remoteid = remoteid;
5626 c->halfopen = FALSE;
5627 c->localid = alloc_channel_id(ssh);
5629 c->pending_eof = FALSE;
5630 c->throttling_conn = 0;
5631 c->type = CHAN_SOCKDATA; /* identify channel type */
5632 add234(ssh->channels, c);
5633 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5634 PKT_INT, c->remoteid, PKT_INT,
5635 c->localid, PKT_END);
5636 logevent("Forwarded port opened successfully");
5643 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
5645 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5646 unsigned int localid = ssh_pkt_getuint32(pktin);
5647 struct ssh_channel *c;
5649 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5650 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5651 c->remoteid = localid;
5652 c->halfopen = FALSE;
5653 c->type = CHAN_SOCKDATA;
5654 c->throttling_conn = 0;
5655 pfd_confirm(c->u.pfd.pf);
5658 if (c && c->pending_eof) {
5660 * We have a pending close on this channel,
5661 * which we decided on before the server acked
5662 * the channel open. So now we know the
5663 * remoteid, we can close it again.
5665 ssh_channel_try_eof(c);
5669 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
5671 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5672 struct ssh_channel *c;
5674 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5675 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5676 logevent("Forwarded connection refused by server");
5677 pfd_close(c->u.pfd.pf);
5678 del234(ssh->channels, c);
5683 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
5685 /* Remote side closes a channel. */
5686 unsigned i = ssh_pkt_getuint32(pktin);
5687 struct ssh_channel *c;
5688 c = find234(ssh->channels, &i, ssh_channelfind);
5689 if (c && !c->halfopen) {
5691 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
5692 !(c->closes & CLOSES_RCVD_EOF)) {
5694 * Received CHANNEL_CLOSE, which we translate into
5697 int send_close = FALSE;
5699 c->closes |= CLOSES_RCVD_EOF;
5704 x11_send_eof(c->u.x11.xconn);
5710 pfd_send_eof(c->u.pfd.pf);
5719 if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
5720 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
5722 c->closes |= CLOSES_SENT_EOF;
5726 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
5727 !(c->closes & CLOSES_RCVD_CLOSE)) {
5729 if (!(c->closes & CLOSES_SENT_EOF)) {
5730 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %d"
5731 " for which we never sent CHANNEL_CLOSE\n", i));
5734 c->closes |= CLOSES_RCVD_CLOSE;
5737 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
5738 !(c->closes & CLOSES_SENT_CLOSE)) {
5739 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
5740 PKT_INT, c->remoteid, PKT_END);
5741 c->closes |= CLOSES_SENT_CLOSE;
5744 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
5745 ssh_channel_destroy(c);
5747 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
5748 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
5749 "_CONFIRMATION", c ? "half-open" : "nonexistent",
5754 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
5756 /* Data sent down one of our channels. */
5757 int i = ssh_pkt_getuint32(pktin);
5760 struct ssh_channel *c;
5762 ssh_pkt_getstring(pktin, &p, &len);
5764 c = find234(ssh->channels, &i, ssh_channelfind);
5769 bufsize = x11_send(c->u.x11.xconn, p, len);
5772 bufsize = pfd_send(c->u.pfd.pf, p, len);
5775 /* Data for an agent message. Buffer it. */
5777 if (c->u.a.lensofar < 4) {
5778 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)len);
5779 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
5783 c->u.a.lensofar += l;
5785 if (c->u.a.lensofar == 4) {
5787 4 + GET_32BIT(c->u.a.msglen);
5788 c->u.a.message = snewn(c->u.a.totallen,
5790 memcpy(c->u.a.message, c->u.a.msglen, 4);
5792 if (c->u.a.lensofar >= 4 && len > 0) {
5794 min(c->u.a.totallen - c->u.a.lensofar,
5796 memcpy(c->u.a.message + c->u.a.lensofar, p,
5800 c->u.a.lensofar += l;
5802 if (c->u.a.lensofar == c->u.a.totallen) {
5805 c->u.a.outstanding_requests++;
5806 if (agent_query(c->u.a.message,
5809 ssh_agentf_callback, c))
5810 ssh_agentf_callback(c, reply, replylen);
5811 sfree(c->u.a.message);
5812 c->u.a.lensofar = 0;
5815 bufsize = 0; /* agent channels never back up */
5818 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5819 c->throttling_conn = 1;
5820 ssh_throttle_conn(ssh, +1);
5825 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5827 ssh->exitcode = ssh_pkt_getuint32(pktin);
5828 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5829 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5831 * In case `helpful' firewalls or proxies tack
5832 * extra human-readable text on the end of the
5833 * session which we might mistake for another
5834 * encrypted packet, we close the session once
5835 * we've sent EXIT_CONFIRMATION.
5837 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5840 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5841 static void ssh1_send_ttymode(void *data, char *mode, char *val)
5843 struct Packet *pktout = (struct Packet *)data;
5845 unsigned int arg = 0;
5846 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
5847 if (i == lenof(ssh_ttymodes)) return;
5848 switch (ssh_ttymodes[i].type) {
5850 arg = ssh_tty_parse_specchar(val);
5853 arg = ssh_tty_parse_boolean(val);
5856 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
5857 ssh2_pkt_addbyte(pktout, arg);
5860 int ssh_agent_forwarding_permitted(Ssh ssh)
5862 return conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists();
5865 static void do_ssh1_connection(Ssh ssh, const unsigned char *in, int inlen,
5866 struct Packet *pktin)
5868 crBegin(ssh->do_ssh1_connection_crstate);
5870 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5871 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5872 ssh1_smsg_stdout_stderr_data;
5874 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5875 ssh1_msg_channel_open_confirmation;
5876 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5877 ssh1_msg_channel_open_failure;
5878 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5879 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5880 ssh1_msg_channel_close;
5881 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5882 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5884 if (ssh_agent_forwarding_permitted(ssh)) {
5885 logevent("Requesting agent forwarding");
5886 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5890 if (pktin->type != SSH1_SMSG_SUCCESS
5891 && pktin->type != SSH1_SMSG_FAILURE) {
5892 bombout(("Protocol confusion"));
5894 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5895 logevent("Agent forwarding refused");
5897 logevent("Agent forwarding enabled");
5898 ssh->agentfwd_enabled = TRUE;
5899 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5903 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
5905 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5907 if (!ssh->x11disp) {
5908 /* FIXME: return an error message from x11_setup_display */
5909 logevent("X11 forwarding not enabled: unable to"
5910 " initialise X display");
5912 ssh->x11auth = x11_invent_fake_auth
5913 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
5914 ssh->x11auth->disp = ssh->x11disp;
5916 logevent("Requesting X11 forwarding");
5917 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5918 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5919 PKT_STR, ssh->x11auth->protoname,
5920 PKT_STR, ssh->x11auth->datastring,
5921 PKT_INT, ssh->x11disp->screennum,
5924 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5925 PKT_STR, ssh->x11auth->protoname,
5926 PKT_STR, ssh->x11auth->datastring,
5932 if (pktin->type != SSH1_SMSG_SUCCESS
5933 && pktin->type != SSH1_SMSG_FAILURE) {
5934 bombout(("Protocol confusion"));
5936 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5937 logevent("X11 forwarding refused");
5939 logevent("X11 forwarding enabled");
5940 ssh->X11_fwd_enabled = TRUE;
5941 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5946 ssh_setup_portfwd(ssh, ssh->conf);
5947 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5949 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5951 /* Unpick the terminal-speed string. */
5952 /* XXX perhaps we should allow no speeds to be sent. */
5953 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5954 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5955 /* Send the pty request. */
5956 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5957 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5958 ssh_pkt_adduint32(pkt, ssh->term_height);
5959 ssh_pkt_adduint32(pkt, ssh->term_width);
5960 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5961 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5962 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5963 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5964 ssh_pkt_adduint32(pkt, ssh->ispeed);
5965 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5966 ssh_pkt_adduint32(pkt, ssh->ospeed);
5967 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5969 ssh->state = SSH_STATE_INTERMED;
5973 if (pktin->type != SSH1_SMSG_SUCCESS
5974 && pktin->type != SSH1_SMSG_FAILURE) {
5975 bombout(("Protocol confusion"));
5977 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5978 c_write_str(ssh, "Server refused to allocate pty\r\n");
5979 ssh->editing = ssh->echoing = 1;
5981 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5982 ssh->ospeed, ssh->ispeed);
5983 ssh->got_pty = TRUE;
5986 ssh->editing = ssh->echoing = 1;
5989 if (conf_get_int(ssh->conf, CONF_compression)) {
5990 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5994 if (pktin->type != SSH1_SMSG_SUCCESS
5995 && pktin->type != SSH1_SMSG_FAILURE) {
5996 bombout(("Protocol confusion"));
5998 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5999 c_write_str(ssh, "Server refused to compress\r\n");
6001 logevent("Started compression");
6002 ssh->v1_compressing = TRUE;
6003 ssh->cs_comp_ctx = zlib_compress_init();
6004 logevent("Initialised zlib (RFC1950) compression");
6005 ssh->sc_comp_ctx = zlib_decompress_init();
6006 logevent("Initialised zlib (RFC1950) decompression");
6010 * Start the shell or command.
6012 * Special case: if the first-choice command is an SSH-2
6013 * subsystem (hence not usable here) and the second choice
6014 * exists, we fall straight back to that.
6017 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
6019 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
6020 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
6021 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
6022 ssh->fallback_cmd = TRUE;
6025 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
6027 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
6028 logevent("Started session");
6031 ssh->state = SSH_STATE_SESSION;
6032 if (ssh->size_needed)
6033 ssh_size(ssh, ssh->term_width, ssh->term_height);
6034 if (ssh->eof_needed)
6035 ssh_special(ssh, TS_EOF);
6038 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
6040 ssh->channels = newtree234(ssh_channelcmp);
6044 * By this point, most incoming packets are already being
6045 * handled by the dispatch table, and we need only pay
6046 * attention to the unusual ones.
6051 if (pktin->type == SSH1_SMSG_SUCCESS) {
6052 /* may be from EXEC_SHELL on some servers */
6053 } else if (pktin->type == SSH1_SMSG_FAILURE) {
6054 /* may be from EXEC_SHELL on some servers
6055 * if no pty is available or in other odd cases. Ignore */
6057 bombout(("Strange packet received: type %d", pktin->type));
6062 int len = min(inlen, 512);
6063 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
6064 PKT_INT, len, PKT_DATA, in, len,
6076 * Handle the top-level SSH-2 protocol.
6078 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
6083 ssh_pkt_getstring(pktin, &msg, &msglen);
6084 logeventf(ssh, "Remote debug message: %.*s", msglen, NULLTOEMPTY(msg));
6087 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
6089 /* log reason code in disconnect message */
6093 ssh_pkt_getstring(pktin, &msg, &msglen);
6094 bombout(("Server sent disconnect message:\n\"%.*s\"",
6095 msglen, NULLTOEMPTY(msg)));
6098 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
6100 /* Do nothing, because we're ignoring it! Duhh. */
6103 static void ssh1_protocol_setup(Ssh ssh)
6108 * Most messages are handled by the coroutines.
6110 for (i = 0; i < 256; i++)
6111 ssh->packet_dispatch[i] = NULL;
6114 * These special message types we install handlers for.
6116 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
6117 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
6118 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
6121 static void ssh1_protocol(Ssh ssh, const void *vin, int inlen,
6122 struct Packet *pktin)
6124 const unsigned char *in = (const unsigned char *)vin;
6125 if (ssh->state == SSH_STATE_CLOSED)
6128 if (pktin && ssh->packet_dispatch[pktin->type]) {
6129 ssh->packet_dispatch[pktin->type](ssh, pktin);
6133 if (!ssh->protocol_initial_phase_done) {
6134 if (do_ssh1_login(ssh, in, inlen, pktin))
6135 ssh->protocol_initial_phase_done = TRUE;
6140 do_ssh1_connection(ssh, in, inlen, pktin);
6144 * Utility routines for decoding comma-separated strings in KEXINIT.
6146 static int first_in_commasep_string(char const *needle, char const *haystack,
6150 if (!needle || !haystack) /* protect against null pointers */
6152 needlen = strlen(needle);
6154 if (haylen >= needlen && /* haystack is long enough */
6155 !memcmp(needle, haystack, needlen) && /* initial match */
6156 (haylen == needlen || haystack[needlen] == ',')
6157 /* either , or EOS follows */
6163 static int in_commasep_string(char const *needle, char const *haystack,
6168 if (!needle || !haystack) /* protect against null pointers */
6171 * Is it at the start of the string?
6173 if (first_in_commasep_string(needle, haystack, haylen))
6176 * If not, search for the next comma and resume after that.
6177 * If no comma found, terminate.
6179 p = memchr(haystack, ',', haylen);
6181 /* + 1 to skip over comma */
6182 return in_commasep_string(needle, p + 1, haylen - (p + 1 - haystack));
6186 * Add a value to the comma-separated string at the end of the packet.
6188 static void ssh2_pkt_addstring_commasep(struct Packet *pkt, const char *data)
6190 if (pkt->length - pkt->savedpos > 0)
6191 ssh_pkt_addstring_str(pkt, ",");
6192 ssh_pkt_addstring_str(pkt, data);
6197 * SSH-2 key derivation (RFC 4253 section 7.2).
6199 static unsigned char *ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H,
6200 char chr, int keylen)
6202 const struct ssh_hash *h = ssh->kex->hash;
6210 /* Round up to the next multiple of hash length. */
6211 keylen_padded = ((keylen + h->hlen - 1) / h->hlen) * h->hlen;
6213 key = snewn(keylen_padded, unsigned char);
6215 /* First hlen bytes. */
6217 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6218 hash_mpint(h, s, K);
6219 h->bytes(s, H, h->hlen);
6220 h->bytes(s, &chr, 1);
6221 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
6224 /* Subsequent blocks of hlen bytes. */
6225 if (keylen_padded > h->hlen) {
6229 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6230 hash_mpint(h, s, K);
6231 h->bytes(s, H, h->hlen);
6233 for (offset = h->hlen; offset < keylen_padded; offset += h->hlen) {
6234 h->bytes(s, key + offset - h->hlen, h->hlen);
6236 h->final(s2, key + offset);
6242 /* Now clear any extra bytes of key material beyond the length
6243 * we're officially returning, because the caller won't know to
6245 if (keylen_padded > keylen)
6246 smemclr(key + keylen, keylen_padded - keylen);
6252 * Structure for constructing KEXINIT algorithm lists.
6254 #define MAXKEXLIST 16
6255 struct kexinit_algorithm {
6259 const struct ssh_kex *kex;
6263 const struct ssh_signkey *hostkey;
6267 const struct ssh2_cipher *cipher;
6271 const struct ssh_mac *mac;
6274 const struct ssh_compress *comp;
6279 * Find a slot in a KEXINIT algorithm list to use for a new algorithm.
6280 * If the algorithm is already in the list, return a pointer to its
6281 * entry, otherwise return an entry from the end of the list.
6282 * This assumes that every time a particular name is passed in, it
6283 * comes from the same string constant. If this isn't true, this
6284 * function may need to be rewritten to use strcmp() instead.
6286 static struct kexinit_algorithm *ssh2_kexinit_addalg(struct kexinit_algorithm
6287 *list, const char *name)
6291 for (i = 0; i < MAXKEXLIST; i++)
6292 if (list[i].name == NULL || list[i].name == name) {
6293 list[i].name = name;
6296 assert(!"No space in KEXINIT list");
6301 * Handle the SSH-2 transport layer.
6303 static void do_ssh2_transport(Ssh ssh, const void *vin, int inlen,
6304 struct Packet *pktin)
6306 const unsigned char *in = (const unsigned char *)vin;
6308 KEXLIST_KEX, KEXLIST_HOSTKEY, KEXLIST_CSCIPHER, KEXLIST_SCCIPHER,
6309 KEXLIST_CSMAC, KEXLIST_SCMAC, KEXLIST_CSCOMP, KEXLIST_SCCOMP,
6312 const char * kexlist_descr[NKEXLIST] = {
6313 "key exchange algorithm", "host key algorithm",
6314 "client-to-server cipher", "server-to-client cipher",
6315 "client-to-server MAC", "server-to-client MAC",
6316 "client-to-server compression method",
6317 "server-to-client compression method" };
6318 struct do_ssh2_transport_state {
6320 int nbits, pbits, warn_kex, warn_hk, warn_cscipher, warn_sccipher;
6321 Bignum p, g, e, f, K;
6324 int kex_init_value, kex_reply_value;
6325 const struct ssh_mac *const *maclist;
6327 const struct ssh2_cipher *cscipher_tobe;
6328 const struct ssh2_cipher *sccipher_tobe;
6329 const struct ssh_mac *csmac_tobe;
6330 const struct ssh_mac *scmac_tobe;
6331 int csmac_etm_tobe, scmac_etm_tobe;
6332 const struct ssh_compress *cscomp_tobe;
6333 const struct ssh_compress *sccomp_tobe;
6334 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
6335 int hostkeylen, siglen, rsakeylen;
6336 void *hkey; /* actual host key */
6337 void *rsakey; /* for RSA kex */
6338 void *eckey; /* for ECDH kex */
6339 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
6340 int n_preferred_kex;
6341 const struct ssh_kexes *preferred_kex[KEX_MAX];
6343 int preferred_hk[HK_MAX];
6344 int n_preferred_ciphers;
6345 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
6346 const struct ssh_compress *preferred_comp;
6347 int userauth_succeeded; /* for delayed compression */
6348 int pending_compression;
6349 int got_session_id, activated_authconn;
6350 struct Packet *pktout;
6354 struct kexinit_algorithm kexlists[NKEXLIST][MAXKEXLIST];
6356 crState(do_ssh2_transport_state);
6358 assert(!ssh->bare_connection);
6362 s->cscipher_tobe = s->sccipher_tobe = NULL;
6363 s->csmac_tobe = s->scmac_tobe = NULL;
6364 s->cscomp_tobe = s->sccomp_tobe = NULL;
6366 s->got_session_id = s->activated_authconn = FALSE;
6367 s->userauth_succeeded = FALSE;
6368 s->pending_compression = FALSE;
6371 * Be prepared to work around the buggy MAC problem.
6373 if (ssh->remote_bugs & BUG_SSH2_HMAC)
6374 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
6376 s->maclist = macs, s->nmacs = lenof(macs);
6379 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
6382 struct kexinit_algorithm *alg;
6385 * Set up the preferred key exchange. (NULL => warn below here)
6387 s->n_preferred_kex = 0;
6388 for (i = 0; i < KEX_MAX; i++) {
6389 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
6391 s->preferred_kex[s->n_preferred_kex++] =
6392 &ssh_diffiehellman_gex;
6395 s->preferred_kex[s->n_preferred_kex++] =
6396 &ssh_diffiehellman_group14;
6399 s->preferred_kex[s->n_preferred_kex++] =
6400 &ssh_diffiehellman_group1;
6403 s->preferred_kex[s->n_preferred_kex++] =
6407 s->preferred_kex[s->n_preferred_kex++] =
6411 /* Flag for later. Don't bother if it's the last in
6413 if (i < KEX_MAX - 1) {
6414 s->preferred_kex[s->n_preferred_kex++] = NULL;
6421 * Set up the preferred host key types. These are just the ids
6422 * in the enum in putty.h, so 'warn below here' is indicated
6425 s->n_preferred_hk = 0;
6426 for (i = 0; i < HK_MAX; i++) {
6427 int id = conf_get_int_int(ssh->conf, CONF_ssh_hklist, i);
6428 /* As above, don't bother with HK_WARN if it's last in the
6430 if (id != HK_WARN || i < HK_MAX - 1)
6431 s->preferred_hk[s->n_preferred_hk++] = id;
6435 * Set up the preferred ciphers. (NULL => warn below here)
6437 s->n_preferred_ciphers = 0;
6438 for (i = 0; i < CIPHER_MAX; i++) {
6439 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
6440 case CIPHER_BLOWFISH:
6441 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
6444 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
6445 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
6449 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
6452 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
6454 case CIPHER_ARCFOUR:
6455 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
6457 case CIPHER_CHACHA20:
6458 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_ccp;
6461 /* Flag for later. Don't bother if it's the last in
6463 if (i < CIPHER_MAX - 1) {
6464 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
6471 * Set up preferred compression.
6473 if (conf_get_int(ssh->conf, CONF_compression))
6474 s->preferred_comp = &ssh_zlib;
6476 s->preferred_comp = &ssh_comp_none;
6479 * Enable queueing of outgoing auth- or connection-layer
6480 * packets while we are in the middle of a key exchange.
6482 ssh->queueing = TRUE;
6485 * Flag that KEX is in progress.
6487 ssh->kex_in_progress = TRUE;
6489 for (i = 0; i < NKEXLIST; i++)
6490 for (j = 0; j < MAXKEXLIST; j++)
6491 s->kexlists[i][j].name = NULL;
6492 /* List key exchange algorithms. */
6494 for (i = 0; i < s->n_preferred_kex; i++) {
6495 const struct ssh_kexes *k = s->preferred_kex[i];
6496 if (!k) warn = TRUE;
6497 else for (j = 0; j < k->nkexes; j++) {
6498 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_KEX],
6500 alg->u.kex.kex = k->list[j];
6501 alg->u.kex.warn = warn;
6504 /* List server host key algorithms. */
6505 if (!s->got_session_id) {
6507 * In the first key exchange, we list all the algorithms
6508 * we're prepared to cope with, but prefer those algorithms
6509 * for which we have a host key for this host.
6511 * If the host key algorithm is below the warning
6512 * threshold, we warn even if we did already have a key
6513 * for it, on the basis that if the user has just
6514 * reconfigured that host key type to be warned about,
6515 * they surely _do_ want to be alerted that a server
6516 * they're actually connecting to is using it.
6519 for (i = 0; i < s->n_preferred_hk; i++) {
6520 if (s->preferred_hk[i] == HK_WARN)
6522 for (j = 0; j < lenof(hostkey_algs); j++) {
6523 if (hostkey_algs[j].id != s->preferred_hk[i])
6525 if (have_ssh_host_key(ssh->savedhost, ssh->savedport,
6526 hostkey_algs[j].alg->keytype)) {
6527 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6528 hostkey_algs[j].alg->name);
6529 alg->u.hk.hostkey = hostkey_algs[j].alg;
6530 alg->u.hk.warn = warn;
6535 for (i = 0; i < s->n_preferred_hk; i++) {
6536 if (s->preferred_hk[i] == HK_WARN)
6538 for (j = 0; j < lenof(hostkey_algs); j++) {
6539 if (hostkey_algs[j].id != s->preferred_hk[i])
6541 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6542 hostkey_algs[j].alg->name);
6543 alg->u.hk.hostkey = hostkey_algs[j].alg;
6544 alg->u.hk.warn = warn;
6549 * In subsequent key exchanges, we list only the kex
6550 * algorithm that was selected in the first key exchange,
6551 * so that we keep getting the same host key and hence
6552 * don't have to interrupt the user's session to ask for
6556 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6557 ssh->hostkey->name);
6558 alg->u.hk.hostkey = ssh->hostkey;
6559 alg->u.hk.warn = FALSE;
6561 /* List encryption algorithms (client->server then server->client). */
6562 for (k = KEXLIST_CSCIPHER; k <= KEXLIST_SCCIPHER; k++) {
6565 alg = ssh2_kexinit_addalg(s->kexlists[k], "none");
6566 alg->u.cipher.cipher = NULL;
6567 alg->u.cipher.warn = warn;
6568 #endif /* FUZZING */
6569 for (i = 0; i < s->n_preferred_ciphers; i++) {
6570 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6571 if (!c) warn = TRUE;
6572 else for (j = 0; j < c->nciphers; j++) {
6573 alg = ssh2_kexinit_addalg(s->kexlists[k],
6575 alg->u.cipher.cipher = c->list[j];
6576 alg->u.cipher.warn = warn;
6580 /* List MAC algorithms (client->server then server->client). */
6581 for (j = KEXLIST_CSMAC; j <= KEXLIST_SCMAC; j++) {
6583 alg = ssh2_kexinit_addalg(s->kexlists[j], "none");
6584 alg->u.mac.mac = NULL;
6585 alg->u.mac.etm = FALSE;
6586 #endif /* FUZZING */
6587 for (i = 0; i < s->nmacs; i++) {
6588 alg = ssh2_kexinit_addalg(s->kexlists[j], s->maclist[i]->name);
6589 alg->u.mac.mac = s->maclist[i];
6590 alg->u.mac.etm = FALSE;
6592 for (i = 0; i < s->nmacs; i++)
6593 /* For each MAC, there may also be an ETM version,
6594 * which we list second. */
6595 if (s->maclist[i]->etm_name) {
6596 alg = ssh2_kexinit_addalg(s->kexlists[j],
6597 s->maclist[i]->etm_name);
6598 alg->u.mac.mac = s->maclist[i];
6599 alg->u.mac.etm = TRUE;
6602 /* List client->server compression algorithms,
6603 * then server->client compression algorithms. (We use the
6604 * same set twice.) */
6605 for (j = KEXLIST_CSCOMP; j <= KEXLIST_SCCOMP; j++) {
6606 assert(lenof(compressions) > 1);
6607 /* Prefer non-delayed versions */
6608 alg = ssh2_kexinit_addalg(s->kexlists[j], s->preferred_comp->name);
6609 alg->u.comp = s->preferred_comp;
6610 /* We don't even list delayed versions of algorithms until
6611 * they're allowed to be used, to avoid a race. See the end of
6613 if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
6614 alg = ssh2_kexinit_addalg(s->kexlists[j],
6615 s->preferred_comp->delayed_name);
6616 alg->u.comp = s->preferred_comp;
6618 for (i = 0; i < lenof(compressions); i++) {
6619 const struct ssh_compress *c = compressions[i];
6620 alg = ssh2_kexinit_addalg(s->kexlists[j], c->name);
6622 if (s->userauth_succeeded && c->delayed_name) {
6623 alg = ssh2_kexinit_addalg(s->kexlists[j], c->delayed_name);
6629 * Construct and send our key exchange packet.
6631 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
6632 for (i = 0; i < 16; i++)
6633 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
6634 for (i = 0; i < NKEXLIST; i++) {
6635 ssh2_pkt_addstring_start(s->pktout);
6636 for (j = 0; j < MAXKEXLIST; j++) {
6637 if (s->kexlists[i][j].name == NULL) break;
6638 ssh2_pkt_addstring_commasep(s->pktout, s->kexlists[i][j].name);
6641 /* List client->server languages. Empty list. */
6642 ssh2_pkt_addstring_start(s->pktout);
6643 /* List server->client languages. Empty list. */
6644 ssh2_pkt_addstring_start(s->pktout);
6645 /* First KEX packet does _not_ follow, because we're not that brave. */
6646 ssh2_pkt_addbool(s->pktout, FALSE);
6648 ssh2_pkt_adduint32(s->pktout, 0);
6651 s->our_kexinitlen = s->pktout->length - 5;
6652 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
6653 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
6655 ssh2_pkt_send_noqueue(ssh, s->pktout);
6658 crWaitUntilV(pktin);
6661 * Now examine the other side's KEXINIT to see what we're up
6668 if (pktin->type != SSH2_MSG_KEXINIT) {
6669 bombout(("expected key exchange packet from server"));
6673 ssh->hostkey = NULL;
6674 s->cscipher_tobe = NULL;
6675 s->sccipher_tobe = NULL;
6676 s->csmac_tobe = NULL;
6677 s->scmac_tobe = NULL;
6678 s->cscomp_tobe = NULL;
6679 s->sccomp_tobe = NULL;
6680 s->warn_kex = s->warn_hk = FALSE;
6681 s->warn_cscipher = s->warn_sccipher = FALSE;
6683 pktin->savedpos += 16; /* skip garbage cookie */
6686 for (i = 0; i < NKEXLIST; i++) {
6687 ssh_pkt_getstring(pktin, &str, &len);
6689 bombout(("KEXINIT packet was incomplete"));
6693 /* If we've already selected a cipher which requires a
6694 * particular MAC, then just select that, and don't even
6695 * bother looking through the server's KEXINIT string for
6697 if (i == KEXLIST_CSMAC && s->cscipher_tobe &&
6698 s->cscipher_tobe->required_mac) {
6699 s->csmac_tobe = s->cscipher_tobe->required_mac;
6700 s->csmac_etm_tobe = !!(s->csmac_tobe->etm_name);
6703 if (i == KEXLIST_SCMAC && s->sccipher_tobe &&
6704 s->sccipher_tobe->required_mac) {
6705 s->scmac_tobe = s->sccipher_tobe->required_mac;
6706 s->scmac_etm_tobe = !!(s->scmac_tobe->etm_name);
6710 for (j = 0; j < MAXKEXLIST; j++) {
6711 struct kexinit_algorithm *alg = &s->kexlists[i][j];
6712 if (alg->name == NULL) break;
6713 if (in_commasep_string(alg->name, str, len)) {
6714 /* We've found a matching algorithm. */
6715 if (i == KEXLIST_KEX || i == KEXLIST_HOSTKEY) {
6716 /* Check if we might need to ignore first kex pkt */
6718 !first_in_commasep_string(alg->name, str, len))
6721 if (i == KEXLIST_KEX) {
6722 ssh->kex = alg->u.kex.kex;
6723 s->warn_kex = alg->u.kex.warn;
6724 } else if (i == KEXLIST_HOSTKEY) {
6725 ssh->hostkey = alg->u.hk.hostkey;
6726 s->warn_hk = alg->u.hk.warn;
6727 } else if (i == KEXLIST_CSCIPHER) {
6728 s->cscipher_tobe = alg->u.cipher.cipher;
6729 s->warn_cscipher = alg->u.cipher.warn;
6730 } else if (i == KEXLIST_SCCIPHER) {
6731 s->sccipher_tobe = alg->u.cipher.cipher;
6732 s->warn_sccipher = alg->u.cipher.warn;
6733 } else if (i == KEXLIST_CSMAC) {
6734 s->csmac_tobe = alg->u.mac.mac;
6735 s->csmac_etm_tobe = alg->u.mac.etm;
6736 } else if (i == KEXLIST_SCMAC) {
6737 s->scmac_tobe = alg->u.mac.mac;
6738 s->scmac_etm_tobe = alg->u.mac.etm;
6739 } else if (i == KEXLIST_CSCOMP) {
6740 s->cscomp_tobe = alg->u.comp;
6741 } else if (i == KEXLIST_SCCOMP) {
6742 s->sccomp_tobe = alg->u.comp;
6746 if ((i == KEXLIST_CSCOMP || i == KEXLIST_SCCOMP) &&
6747 in_commasep_string(alg->u.comp->delayed_name, str, len))
6748 s->pending_compression = TRUE; /* try this later */
6750 bombout(("Couldn't agree a %s (available: %.*s)",
6751 kexlist_descr[i], len, str));
6755 if (i == KEXLIST_HOSTKEY) {
6759 * In addition to deciding which host key we're
6760 * actually going to use, we should make a list of the
6761 * host keys offered by the server which we _don't_
6762 * have cached. These will be offered as cross-
6763 * certification options by ssh_get_specials.
6765 * We also count the key we're currently using for KEX
6766 * as one we've already got, because by the time this
6767 * menu becomes visible, it will be.
6769 ssh->n_uncert_hostkeys = 0;
6771 for (j = 0; j < lenof(hostkey_algs); j++) {
6772 if (hostkey_algs[j].alg != ssh->hostkey &&
6773 in_commasep_string(hostkey_algs[j].alg->name,
6775 !have_ssh_host_key(ssh->savedhost, ssh->savedport,
6776 hostkey_algs[j].alg->keytype)) {
6777 ssh->uncert_hostkeys[ssh->n_uncert_hostkeys++] = j;
6783 if (s->pending_compression) {
6784 logevent("Server supports delayed compression; "
6785 "will try this later");
6787 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
6788 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
6789 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
6791 ssh->exhash = ssh->kex->hash->init();
6792 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
6793 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
6794 hash_string(ssh->kex->hash, ssh->exhash,
6795 s->our_kexinit, s->our_kexinitlen);
6796 sfree(s->our_kexinit);
6797 /* Include the type byte in the hash of server's KEXINIT */
6798 hash_string(ssh->kex->hash, ssh->exhash,
6799 pktin->body - 1, pktin->length + 1);
6802 ssh_set_frozen(ssh, 1);
6803 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
6805 ssh_dialog_callback, ssh);
6806 if (s->dlgret < 0) {
6810 bombout(("Unexpected data from server while"
6811 " waiting for user response"));
6814 } while (pktin || inlen > 0);
6815 s->dlgret = ssh->user_response;
6817 ssh_set_frozen(ssh, 0);
6818 if (s->dlgret == 0) {
6819 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
6829 ssh_set_frozen(ssh, 1);
6832 * Change warning box wording depending on why we chose a
6833 * warning-level host key algorithm. If it's because
6834 * that's all we have *cached*, use the askhk mechanism,
6835 * and list the host keys we could usefully cross-certify.
6836 * Otherwise, use askalg for the standard wording.
6839 for (j = 0; j < ssh->n_uncert_hostkeys; j++) {
6840 const struct ssh_signkey_with_user_pref_id *hktype =
6841 &hostkey_algs[ssh->uncert_hostkeys[j]];
6843 for (k = 0; k < HK_MAX; k++) {
6844 int id = conf_get_int_int(ssh->conf, CONF_ssh_hklist, k);
6845 if (id == HK_WARN) {
6847 } else if (id == hktype->id) {
6854 char *old_ba = betteralgs;
6855 betteralgs = dupcat(betteralgs, ",",
6857 (const char *)NULL);
6860 betteralgs = dupstr(hktype->alg->name);
6865 s->dlgret = askhk(ssh->frontend, ssh->hostkey->name,
6866 betteralgs, ssh_dialog_callback, ssh);
6869 s->dlgret = askalg(ssh->frontend, "host key type",
6871 ssh_dialog_callback, ssh);
6873 if (s->dlgret < 0) {
6877 bombout(("Unexpected data from server while"
6878 " waiting for user response"));
6881 } while (pktin || inlen > 0);
6882 s->dlgret = ssh->user_response;
6884 ssh_set_frozen(ssh, 0);
6885 if (s->dlgret == 0) {
6886 ssh_disconnect(ssh, "User aborted at host key warning", NULL,
6892 if (s->warn_cscipher) {
6893 ssh_set_frozen(ssh, 1);
6894 s->dlgret = askalg(ssh->frontend,
6895 "client-to-server cipher",
6896 s->cscipher_tobe->name,
6897 ssh_dialog_callback, ssh);
6898 if (s->dlgret < 0) {
6902 bombout(("Unexpected data from server while"
6903 " waiting for user response"));
6906 } while (pktin || inlen > 0);
6907 s->dlgret = ssh->user_response;
6909 ssh_set_frozen(ssh, 0);
6910 if (s->dlgret == 0) {
6911 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6917 if (s->warn_sccipher) {
6918 ssh_set_frozen(ssh, 1);
6919 s->dlgret = askalg(ssh->frontend,
6920 "server-to-client cipher",
6921 s->sccipher_tobe->name,
6922 ssh_dialog_callback, ssh);
6923 if (s->dlgret < 0) {
6927 bombout(("Unexpected data from server while"
6928 " waiting for user response"));
6931 } while (pktin || inlen > 0);
6932 s->dlgret = ssh->user_response;
6934 ssh_set_frozen(ssh, 0);
6935 if (s->dlgret == 0) {
6936 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6942 if (s->ignorepkt) /* first_kex_packet_follows */
6943 crWaitUntilV(pktin); /* Ignore packet */
6946 if (ssh->kex->main_type == KEXTYPE_DH) {
6948 * Work out the number of bits of key we will need from the
6949 * key exchange. We start with the maximum key length of
6955 csbits = s->cscipher_tobe ? s->cscipher_tobe->real_keybits : 0;
6956 scbits = s->sccipher_tobe ? s->sccipher_tobe->real_keybits : 0;
6957 s->nbits = (csbits > scbits ? csbits : scbits);
6959 /* The keys only have hlen-bit entropy, since they're based on
6960 * a hash. So cap the key size at hlen bits. */
6961 if (s->nbits > ssh->kex->hash->hlen * 8)
6962 s->nbits = ssh->kex->hash->hlen * 8;
6965 * If we're doing Diffie-Hellman group exchange, start by
6966 * requesting a group.
6968 if (dh_is_gex(ssh->kex)) {
6969 logevent("Doing Diffie-Hellman group exchange");
6970 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
6972 * Work out how big a DH group we will need to allow that
6975 s->pbits = 512 << ((s->nbits - 1) / 64);
6976 if (s->pbits < DH_MIN_SIZE)
6977 s->pbits = DH_MIN_SIZE;
6978 if (s->pbits > DH_MAX_SIZE)
6979 s->pbits = DH_MAX_SIZE;
6980 if ((ssh->remote_bugs & BUG_SSH2_OLDGEX)) {
6981 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD);
6982 ssh2_pkt_adduint32(s->pktout, s->pbits);
6984 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
6985 ssh2_pkt_adduint32(s->pktout, DH_MIN_SIZE);
6986 ssh2_pkt_adduint32(s->pktout, s->pbits);
6987 ssh2_pkt_adduint32(s->pktout, DH_MAX_SIZE);
6989 ssh2_pkt_send_noqueue(ssh, s->pktout);
6991 crWaitUntilV(pktin);
6992 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
6993 bombout(("expected key exchange group packet from server"));
6996 s->p = ssh2_pkt_getmp(pktin);
6997 s->g = ssh2_pkt_getmp(pktin);
6998 if (!s->p || !s->g) {
6999 bombout(("unable to read mp-ints from incoming group packet"));
7002 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
7003 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
7004 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
7006 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
7007 ssh->kex_ctx = dh_setup_group(ssh->kex);
7008 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
7009 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
7010 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
7011 ssh->kex->groupname);
7014 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
7015 ssh->kex->hash->text_name);
7017 * Now generate and send e for Diffie-Hellman.
7019 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
7020 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
7021 s->pktout = ssh2_pkt_init(s->kex_init_value);
7022 ssh2_pkt_addmp(s->pktout, s->e);
7023 ssh2_pkt_send_noqueue(ssh, s->pktout);
7025 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
7026 crWaitUntilV(pktin);
7027 if (pktin->type != s->kex_reply_value) {
7028 bombout(("expected key exchange reply packet from server"));
7031 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
7032 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7033 if (!s->hostkeydata) {
7034 bombout(("unable to parse key exchange reply packet"));
7037 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7038 s->hostkeydata, s->hostkeylen);
7039 s->f = ssh2_pkt_getmp(pktin);
7041 bombout(("unable to parse key exchange reply packet"));
7044 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7046 bombout(("unable to parse key exchange reply packet"));
7051 const char *err = dh_validate_f(ssh->kex_ctx, s->f);
7053 bombout(("key exchange reply failed validation: %s", err));
7057 s->K = dh_find_K(ssh->kex_ctx, s->f);
7059 /* We assume everything from now on will be quick, and it might
7060 * involve user interaction. */
7061 set_busy_status(ssh->frontend, BUSY_NOT);
7063 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
7064 if (dh_is_gex(ssh->kex)) {
7065 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
7066 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MIN_SIZE);
7067 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
7068 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
7069 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MAX_SIZE);
7070 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
7071 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
7073 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
7074 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
7076 dh_cleanup(ssh->kex_ctx);
7078 if (dh_is_gex(ssh->kex)) {
7082 } else if (ssh->kex->main_type == KEXTYPE_ECDH) {
7084 logeventf(ssh, "Doing ECDH key exchange with curve %s and hash %s",
7085 ssh_ecdhkex_curve_textname(ssh->kex),
7086 ssh->kex->hash->text_name);
7087 ssh->pkt_kctx = SSH2_PKTCTX_ECDHKEX;
7089 s->eckey = ssh_ecdhkex_newkey(ssh->kex);
7091 bombout(("Unable to generate key for ECDH"));
7097 int publicPointLength;
7098 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
7100 ssh_ecdhkex_freekey(s->eckey);
7101 bombout(("Unable to encode public key for ECDH"));
7104 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_ECDH_INIT);
7105 ssh2_pkt_addstring_start(s->pktout);
7106 ssh2_pkt_addstring_data(s->pktout, publicPoint, publicPointLength);
7110 ssh2_pkt_send_noqueue(ssh, s->pktout);
7112 crWaitUntilV(pktin);
7113 if (pktin->type != SSH2_MSG_KEX_ECDH_REPLY) {
7114 ssh_ecdhkex_freekey(s->eckey);
7115 bombout(("expected ECDH reply packet from server"));
7119 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7120 if (!s->hostkeydata) {
7121 bombout(("unable to parse ECDH reply packet"));
7124 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
7125 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7126 s->hostkeydata, s->hostkeylen);
7130 int publicPointLength;
7131 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
7133 ssh_ecdhkex_freekey(s->eckey);
7134 bombout(("Unable to encode public key for ECDH hash"));
7137 hash_string(ssh->kex->hash, ssh->exhash,
7138 publicPoint, publicPointLength);
7145 ssh_pkt_getstring(pktin, &keydata, &keylen);
7147 bombout(("unable to parse ECDH reply packet"));
7150 hash_string(ssh->kex->hash, ssh->exhash, keydata, keylen);
7151 s->K = ssh_ecdhkex_getkey(s->eckey, keydata, keylen);
7153 ssh_ecdhkex_freekey(s->eckey);
7154 bombout(("point received in ECDH was not valid"));
7159 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7161 bombout(("unable to parse key exchange reply packet"));
7165 ssh_ecdhkex_freekey(s->eckey);
7167 logeventf(ssh, "Doing RSA key exchange with hash %s",
7168 ssh->kex->hash->text_name);
7169 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
7171 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
7174 crWaitUntilV(pktin);
7175 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
7176 bombout(("expected RSA public key packet from server"));
7180 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7181 if (!s->hostkeydata) {
7182 bombout(("unable to parse RSA public key packet"));
7185 hash_string(ssh->kex->hash, ssh->exhash,
7186 s->hostkeydata, s->hostkeylen);
7187 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7188 s->hostkeydata, s->hostkeylen);
7192 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
7194 bombout(("unable to parse RSA public key packet"));
7197 s->rsakeydata = snewn(s->rsakeylen, char);
7198 memcpy(s->rsakeydata, keydata, s->rsakeylen);
7201 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
7203 sfree(s->rsakeydata);
7204 bombout(("unable to parse RSA public key from server"));
7208 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
7211 * Next, set up a shared secret K, of precisely KLEN -
7212 * 2*HLEN - 49 bits, where KLEN is the bit length of the
7213 * RSA key modulus and HLEN is the bit length of the hash
7217 int klen = ssh_rsakex_klen(s->rsakey);
7218 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
7220 unsigned char *kstr1, *kstr2, *outstr;
7221 int kstr1len, kstr2len, outstrlen;
7223 s->K = bn_power_2(nbits - 1);
7225 for (i = 0; i < nbits; i++) {
7227 byte = random_byte();
7229 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
7233 * Encode this as an mpint.
7235 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
7236 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
7237 PUT_32BIT(kstr2, kstr1len);
7238 memcpy(kstr2 + 4, kstr1, kstr1len);
7241 * Encrypt it with the given RSA key.
7243 outstrlen = (klen + 7) / 8;
7244 outstr = snewn(outstrlen, unsigned char);
7245 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
7246 outstr, outstrlen, s->rsakey);
7249 * And send it off in a return packet.
7251 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
7252 ssh2_pkt_addstring_start(s->pktout);
7253 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
7254 ssh2_pkt_send_noqueue(ssh, s->pktout);
7256 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
7263 ssh_rsakex_freekey(s->rsakey);
7265 crWaitUntilV(pktin);
7266 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
7267 sfree(s->rsakeydata);
7268 bombout(("expected signature packet from server"));
7272 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7274 bombout(("unable to parse signature packet"));
7278 sfree(s->rsakeydata);
7281 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
7282 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
7283 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
7285 ssh->kex_ctx = NULL;
7288 debug(("Exchange hash is:\n"));
7289 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
7293 bombout(("Server's host key is invalid"));
7297 if (!ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
7298 (char *)s->exchange_hash,
7299 ssh->kex->hash->hlen)) {
7301 bombout(("Server's host key did not match the signature supplied"));
7306 s->keystr = ssh->hostkey->fmtkey(s->hkey);
7307 if (!s->got_session_id) {
7309 * Make a note of any other host key formats that are available.
7314 for (i = 0; i < lenof(hostkey_algs); i++) {
7315 if (hostkey_algs[i].alg == ssh->hostkey)
7318 for (j = 0; j < ssh->n_uncert_hostkeys; j++)
7319 if (ssh->uncert_hostkeys[j] == i)
7322 if (j < ssh->n_uncert_hostkeys) {
7325 newlist = dupprintf("%s/%s", list,
7326 hostkey_algs[i].alg->name);
7328 newlist = dupprintf("%s", hostkey_algs[i].alg->name);
7335 "Server also has %s host key%s, but we "
7336 "don't know %s", list,
7337 j > 1 ? "s" : "", j > 1 ? "any of them" : "it");
7343 * Authenticate remote host: verify host key. (We've already
7344 * checked the signature of the exchange hash.)
7346 s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
7347 logevent("Host key fingerprint is:");
7348 logevent(s->fingerprint);
7349 /* First check against manually configured host keys. */
7350 s->dlgret = verify_ssh_manual_host_key(ssh, s->fingerprint,
7351 ssh->hostkey, s->hkey);
7352 if (s->dlgret == 0) { /* did not match */
7353 bombout(("Host key did not appear in manually configured list"));
7355 } else if (s->dlgret < 0) { /* none configured; use standard handling */
7356 ssh_set_frozen(ssh, 1);
7357 s->dlgret = verify_ssh_host_key(ssh->frontend,
7358 ssh->savedhost, ssh->savedport,
7359 ssh->hostkey->keytype, s->keystr,
7361 ssh_dialog_callback, ssh);
7365 if (s->dlgret < 0) {
7369 bombout(("Unexpected data from server while waiting"
7370 " for user host key response"));
7373 } while (pktin || inlen > 0);
7374 s->dlgret = ssh->user_response;
7376 ssh_set_frozen(ssh, 0);
7377 if (s->dlgret == 0) {
7378 ssh_disconnect(ssh, "Aborted at host key verification", NULL,
7383 sfree(s->fingerprint);
7385 * Save this host key, to check against the one presented in
7386 * subsequent rekeys.
7388 ssh->hostkey_str = s->keystr;
7389 } else if (ssh->cross_certifying) {
7390 s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
7391 logevent("Storing additional host key for this host:");
7392 logevent(s->fingerprint);
7393 store_host_key(ssh->savedhost, ssh->savedport,
7394 ssh->hostkey->keytype, s->keystr);
7395 ssh->cross_certifying = FALSE;
7397 * Don't forget to store the new key as the one we'll be
7398 * re-checking in future normal rekeys.
7400 ssh->hostkey_str = s->keystr;
7403 * In a rekey, we never present an interactive host key
7404 * verification request to the user. Instead, we simply
7405 * enforce that the key we're seeing this time is identical to
7406 * the one we saw before.
7408 if (strcmp(ssh->hostkey_str, s->keystr)) {
7410 bombout(("Host key was different in repeat key exchange"));
7416 ssh->hostkey->freekey(s->hkey);
7419 * The exchange hash from the very first key exchange is also
7420 * the session id, used in session key construction and
7423 if (!s->got_session_id) {
7424 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
7425 memcpy(ssh->v2_session_id, s->exchange_hash,
7426 sizeof(s->exchange_hash));
7427 ssh->v2_session_id_len = ssh->kex->hash->hlen;
7428 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
7429 s->got_session_id = TRUE;
7433 * Send SSH2_MSG_NEWKEYS.
7435 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
7436 ssh2_pkt_send_noqueue(ssh, s->pktout);
7437 ssh->outgoing_data_size = 0; /* start counting from here */
7440 * We've sent client NEWKEYS, so create and initialise
7441 * client-to-server session keys.
7443 if (ssh->cs_cipher_ctx)
7444 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
7445 ssh->cscipher = s->cscipher_tobe;
7446 if (ssh->cscipher) ssh->cs_cipher_ctx = ssh->cscipher->make_context();
7448 if (ssh->cs_mac_ctx)
7449 ssh->csmac->free_context(ssh->cs_mac_ctx);
7450 ssh->csmac = s->csmac_tobe;
7451 ssh->csmac_etm = s->csmac_etm_tobe;
7453 ssh->cs_mac_ctx = ssh->csmac->make_context(ssh->cs_cipher_ctx);
7455 if (ssh->cs_comp_ctx)
7456 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
7457 ssh->cscomp = s->cscomp_tobe;
7458 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
7461 * Set IVs on client-to-server keys. Here we use the exchange
7462 * hash from the _first_ key exchange.
7464 if (ssh->cscipher) {
7467 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'C',
7468 ssh->cscipher->padded_keybytes);
7469 ssh->cscipher->setkey(ssh->cs_cipher_ctx, key);
7470 smemclr(key, ssh->cscipher->padded_keybytes);
7473 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'A',
7474 ssh->cscipher->blksize);
7475 ssh->cscipher->setiv(ssh->cs_cipher_ctx, key);
7476 smemclr(key, ssh->cscipher->blksize);
7482 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'E',
7483 ssh->csmac->keylen);
7484 ssh->csmac->setkey(ssh->cs_mac_ctx, key);
7485 smemclr(key, ssh->csmac->keylen);
7490 logeventf(ssh, "Initialised %.200s client->server encryption",
7491 ssh->cscipher->text_name);
7493 logeventf(ssh, "Initialised %.200s client->server MAC algorithm%s%s",
7494 ssh->csmac->text_name,
7495 ssh->csmac_etm ? " (in ETM mode)" : "",
7496 ssh->cscipher->required_mac ? " (required by cipher)" : "");
7497 if (ssh->cscomp->text_name)
7498 logeventf(ssh, "Initialised %s compression",
7499 ssh->cscomp->text_name);
7502 * Now our end of the key exchange is complete, we can send all
7503 * our queued higher-layer packets.
7505 ssh->queueing = FALSE;
7506 ssh2_pkt_queuesend(ssh);
7509 * Expect SSH2_MSG_NEWKEYS from server.
7511 crWaitUntilV(pktin);
7512 if (pktin->type != SSH2_MSG_NEWKEYS) {
7513 bombout(("expected new-keys packet from server"));
7516 ssh->incoming_data_size = 0; /* start counting from here */
7519 * We've seen server NEWKEYS, so create and initialise
7520 * server-to-client session keys.
7522 if (ssh->sc_cipher_ctx)
7523 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
7524 if (s->sccipher_tobe) {
7525 ssh->sccipher = s->sccipher_tobe;
7526 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
7529 if (ssh->sc_mac_ctx)
7530 ssh->scmac->free_context(ssh->sc_mac_ctx);
7531 if (s->scmac_tobe) {
7532 ssh->scmac = s->scmac_tobe;
7533 ssh->scmac_etm = s->scmac_etm_tobe;
7534 ssh->sc_mac_ctx = ssh->scmac->make_context(ssh->sc_cipher_ctx);
7537 if (ssh->sc_comp_ctx)
7538 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
7539 ssh->sccomp = s->sccomp_tobe;
7540 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
7543 * Set IVs on server-to-client keys. Here we use the exchange
7544 * hash from the _first_ key exchange.
7546 if (ssh->sccipher) {
7549 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'D',
7550 ssh->sccipher->padded_keybytes);
7551 ssh->sccipher->setkey(ssh->sc_cipher_ctx, key);
7552 smemclr(key, ssh->sccipher->padded_keybytes);
7555 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'B',
7556 ssh->sccipher->blksize);
7557 ssh->sccipher->setiv(ssh->sc_cipher_ctx, key);
7558 smemclr(key, ssh->sccipher->blksize);
7564 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'F',
7565 ssh->scmac->keylen);
7566 ssh->scmac->setkey(ssh->sc_mac_ctx, key);
7567 smemclr(key, ssh->scmac->keylen);
7571 logeventf(ssh, "Initialised %.200s server->client encryption",
7572 ssh->sccipher->text_name);
7574 logeventf(ssh, "Initialised %.200s server->client MAC algorithm%s%s",
7575 ssh->scmac->text_name,
7576 ssh->scmac_etm ? " (in ETM mode)" : "",
7577 ssh->sccipher->required_mac ? " (required by cipher)" : "");
7578 if (ssh->sccomp->text_name)
7579 logeventf(ssh, "Initialised %s decompression",
7580 ssh->sccomp->text_name);
7583 * Free shared secret.
7588 * Update the specials menu to list the remaining uncertified host
7591 update_specials_menu(ssh->frontend);
7594 * Key exchange is over. Loop straight back round if we have a
7595 * deferred rekey reason.
7597 if (ssh->deferred_rekey_reason) {
7598 logevent(ssh->deferred_rekey_reason);
7600 ssh->deferred_rekey_reason = NULL;
7601 goto begin_key_exchange;
7605 * Otherwise, schedule a timer for our next rekey.
7607 ssh->kex_in_progress = FALSE;
7608 ssh->last_rekey = GETTICKCOUNT();
7609 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
7610 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7614 * Now we're encrypting. Begin returning 1 to the protocol main
7615 * function so that other things can run on top of the
7616 * transport. If we ever see a KEXINIT, we must go back to the
7619 * We _also_ go back to the start if we see pktin==NULL and
7620 * inlen negative, because this is a special signal meaning
7621 * `initiate client-driven rekey', and `in' contains a message
7622 * giving the reason for the rekey.
7624 * inlen==-1 means always initiate a rekey;
7625 * inlen==-2 means that userauth has completed successfully and
7626 * we should consider rekeying (for delayed compression).
7628 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
7629 (!pktin && inlen < 0))) {
7631 if (!ssh->protocol_initial_phase_done) {
7632 ssh->protocol_initial_phase_done = TRUE;
7634 * Allow authconn to initialise itself.
7636 do_ssh2_authconn(ssh, NULL, 0, NULL);
7641 logevent("Server initiated key re-exchange");
7645 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
7646 * delayed compression, if it's available.
7648 * draft-miller-secsh-compression-delayed-00 says that you
7649 * negotiate delayed compression in the first key exchange, and
7650 * both sides start compressing when the server has sent
7651 * USERAUTH_SUCCESS. This has a race condition -- the server
7652 * can't know when the client has seen it, and thus which incoming
7653 * packets it should treat as compressed.
7655 * Instead, we do the initial key exchange without offering the
7656 * delayed methods, but note if the server offers them; when we
7657 * get here, if a delayed method was available that was higher
7658 * on our list than what we got, we initiate a rekey in which we
7659 * _do_ list the delayed methods (and hopefully get it as a
7660 * result). Subsequent rekeys will do the same.
7662 assert(!s->userauth_succeeded); /* should only happen once */
7663 s->userauth_succeeded = TRUE;
7664 if (!s->pending_compression)
7665 /* Can't see any point rekeying. */
7666 goto wait_for_rekey; /* this is utterly horrid */
7667 /* else fall through to rekey... */
7668 s->pending_compression = FALSE;
7671 * Now we've decided to rekey.
7673 * Special case: if the server bug is set that doesn't
7674 * allow rekeying, we give a different log message and
7675 * continue waiting. (If such a server _initiates_ a rekey,
7676 * we process it anyway!)
7678 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
7679 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
7681 /* Reset the counters, so that at least this message doesn't
7682 * hit the event log _too_ often. */
7683 ssh->outgoing_data_size = 0;
7684 ssh->incoming_data_size = 0;
7685 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
7687 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7690 goto wait_for_rekey; /* this is still utterly horrid */
7692 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
7695 goto begin_key_exchange;
7701 * Add data to an SSH-2 channel output buffer.
7703 static void ssh2_add_channel_data(struct ssh_channel *c, const char *buf,
7706 bufchain_add(&c->v.v2.outbuffer, buf, len);
7710 * Attempt to send data on an SSH-2 channel.
7712 static int ssh2_try_send(struct ssh_channel *c)
7715 struct Packet *pktout;
7718 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
7721 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
7722 if ((unsigned)len > c->v.v2.remwindow)
7723 len = c->v.v2.remwindow;
7724 if ((unsigned)len > c->v.v2.remmaxpkt)
7725 len = c->v.v2.remmaxpkt;
7726 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
7727 ssh2_pkt_adduint32(pktout, c->remoteid);
7728 ssh2_pkt_addstring_start(pktout);
7729 ssh2_pkt_addstring_data(pktout, data, len);
7730 ssh2_pkt_send(ssh, pktout);
7731 bufchain_consume(&c->v.v2.outbuffer, len);
7732 c->v.v2.remwindow -= len;
7736 * After having sent as much data as we can, return the amount
7739 ret = bufchain_size(&c->v.v2.outbuffer);
7742 * And if there's no data pending but we need to send an EOF, send
7745 if (!ret && c->pending_eof)
7746 ssh_channel_try_eof(c);
7751 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
7754 if (c->closes & CLOSES_SENT_EOF)
7755 return; /* don't send on channels we've EOFed */
7756 bufsize = ssh2_try_send(c);
7759 case CHAN_MAINSESSION:
7760 /* stdin need not receive an unthrottle
7761 * notification since it will be polled */
7764 x11_unthrottle(c->u.x11.xconn);
7767 /* agent sockets are request/response and need no
7768 * buffer management */
7771 pfd_unthrottle(c->u.pfd.pf);
7777 static int ssh_is_simple(Ssh ssh)
7780 * We use the 'simple' variant of the SSH protocol if we're asked
7781 * to, except not if we're also doing connection-sharing (either
7782 * tunnelling our packets over an upstream or expecting to be
7783 * tunnelled over ourselves), since then the assumption that we
7784 * have only one channel to worry about is not true after all.
7786 return (conf_get_int(ssh->conf, CONF_ssh_simple) &&
7787 !ssh->bare_connection && !ssh->connshare);
7791 * Set up most of a new ssh_channel for SSH-2.
7793 static void ssh2_channel_init(struct ssh_channel *c)
7796 c->localid = alloc_channel_id(ssh);
7798 c->pending_eof = FALSE;
7799 c->throttling_conn = FALSE;
7800 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
7801 ssh_is_simple(ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
7802 c->v.v2.chanreq_head = NULL;
7803 c->v.v2.throttle_state = UNTHROTTLED;
7804 bufchain_init(&c->v.v2.outbuffer);
7808 * Construct the common parts of a CHANNEL_OPEN.
7810 static struct Packet *ssh2_chanopen_init(struct ssh_channel *c,
7813 struct Packet *pktout;
7815 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7816 ssh2_pkt_addstring(pktout, type);
7817 ssh2_pkt_adduint32(pktout, c->localid);
7818 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
7819 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7824 * CHANNEL_FAILURE doesn't come with any indication of what message
7825 * caused it, so we have to keep track of the outstanding
7826 * CHANNEL_REQUESTs ourselves.
7828 static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
7829 cchandler_fn_t handler, void *ctx)
7831 struct outstanding_channel_request *ocr =
7832 snew(struct outstanding_channel_request);
7834 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7835 ocr->handler = handler;
7838 if (!c->v.v2.chanreq_head)
7839 c->v.v2.chanreq_head = ocr;
7841 c->v.v2.chanreq_tail->next = ocr;
7842 c->v.v2.chanreq_tail = ocr;
7846 * Construct the common parts of a CHANNEL_REQUEST. If handler is not
7847 * NULL then a reply will be requested and the handler will be called
7848 * when it arrives. The returned packet is ready to have any
7849 * request-specific data added and be sent. Note that if a handler is
7850 * provided, it's essential that the request actually be sent.
7852 * The handler will usually be passed the response packet in pktin. If
7853 * pktin is NULL, this means that no reply will ever be forthcoming
7854 * (e.g. because the entire connection is being destroyed, or because
7855 * the server initiated channel closure before we saw the response)
7856 * and the handler should free any storage it's holding.
7858 static struct Packet *ssh2_chanreq_init(struct ssh_channel *c,
7860 cchandler_fn_t handler, void *ctx)
7862 struct Packet *pktout;
7864 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7865 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7866 ssh2_pkt_adduint32(pktout, c->remoteid);
7867 ssh2_pkt_addstring(pktout, type);
7868 ssh2_pkt_addbool(pktout, handler != NULL);
7869 if (handler != NULL)
7870 ssh2_queue_chanreq_handler(c, handler, ctx);
7875 * Potentially enlarge the window on an SSH-2 channel.
7877 static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
7879 static void ssh2_set_window(struct ssh_channel *c, int newwin)
7884 * Never send WINDOW_ADJUST for a channel that the remote side has
7885 * already sent EOF on; there's no point, since it won't be
7886 * sending any more data anyway. Ditto if _we've_ already sent
7889 if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
7893 * Also, never widen the window for an X11 channel when we're
7894 * still waiting to see its initial auth and may yet hand it off
7897 if (c->type == CHAN_X11 && c->u.x11.initial)
7901 * If the remote end has a habit of ignoring maxpkt, limit the
7902 * window so that it has no choice (assuming it doesn't ignore the
7905 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
7906 newwin = OUR_V2_MAXPKT;
7909 * Only send a WINDOW_ADJUST if there's significantly more window
7910 * available than the other end thinks there is. This saves us
7911 * sending a WINDOW_ADJUST for every character in a shell session.
7913 * "Significant" is arbitrarily defined as half the window size.
7915 if (newwin / 2 >= c->v.v2.locwindow) {
7916 struct Packet *pktout;
7920 * In order to keep track of how much window the client
7921 * actually has available, we'd like it to acknowledge each
7922 * WINDOW_ADJUST. We can't do that directly, so we accompany
7923 * it with a CHANNEL_REQUEST that has to be acknowledged.
7925 * This is only necessary if we're opening the window wide.
7926 * If we're not, then throughput is being constrained by
7927 * something other than the maximum window size anyway.
7929 if (newwin == c->v.v2.locmaxwin &&
7930 !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
7931 up = snew(unsigned);
7932 *up = newwin - c->v.v2.locwindow;
7933 pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org",
7934 ssh2_handle_winadj_response, up);
7935 ssh2_pkt_send(ssh, pktout);
7937 if (c->v.v2.throttle_state != UNTHROTTLED)
7938 c->v.v2.throttle_state = UNTHROTTLING;
7940 /* Pretend the WINDOW_ADJUST was acked immediately. */
7941 c->v.v2.remlocwin = newwin;
7942 c->v.v2.throttle_state = THROTTLED;
7944 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
7945 ssh2_pkt_adduint32(pktout, c->remoteid);
7946 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
7947 ssh2_pkt_send(ssh, pktout);
7948 c->v.v2.locwindow = newwin;
7953 * Find the channel associated with a message. If there's no channel,
7954 * or it's not properly open, make a noise about it and return NULL.
7956 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
7958 unsigned localid = ssh_pkt_getuint32(pktin);
7959 struct ssh_channel *c;
7961 c = find234(ssh->channels, &localid, ssh_channelfind);
7963 (c->type != CHAN_SHARING && c->halfopen &&
7964 pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
7965 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
7966 char *buf = dupprintf("Received %s for %s channel %u",
7967 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
7969 c ? "half-open" : "nonexistent", localid);
7970 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
7977 static void ssh2_handle_winadj_response(struct ssh_channel *c,
7978 struct Packet *pktin, void *ctx)
7980 unsigned *sizep = ctx;
7983 * Winadj responses should always be failures. However, at least
7984 * one server ("boks_sshd") is known to return SUCCESS for channel
7985 * requests it's never heard of, such as "winadj@putty". Raised
7986 * with foxt.com as bug 090916-090424, but for the sake of a quiet
7987 * life, we don't worry about what kind of response we got.
7990 c->v.v2.remlocwin += *sizep;
7993 * winadj messages are only sent when the window is fully open, so
7994 * if we get an ack of one, we know any pending unthrottle is
7997 if (c->v.v2.throttle_state == UNTHROTTLING)
7998 c->v.v2.throttle_state = UNTHROTTLED;
8001 static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
8003 struct ssh_channel *c = ssh2_channel_msg(ssh, pktin);
8004 struct outstanding_channel_request *ocr;
8007 if (c->type == CHAN_SHARING) {
8008 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8009 pktin->body, pktin->length);
8012 ocr = c->v.v2.chanreq_head;
8014 ssh2_msg_unexpected(ssh, pktin);
8017 ocr->handler(c, pktin, ocr->ctx);
8018 c->v.v2.chanreq_head = ocr->next;
8021 * We may now initiate channel-closing procedures, if that
8022 * CHANNEL_REQUEST was the last thing outstanding before we send
8025 ssh2_channel_check_close(c);
8028 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
8030 struct ssh_channel *c;
8031 c = ssh2_channel_msg(ssh, pktin);
8034 if (c->type == CHAN_SHARING) {
8035 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8036 pktin->body, pktin->length);
8039 if (!(c->closes & CLOSES_SENT_EOF)) {
8040 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
8041 ssh2_try_send_and_unthrottle(ssh, c);
8045 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
8049 struct ssh_channel *c;
8050 c = ssh2_channel_msg(ssh, pktin);
8053 if (c->type == CHAN_SHARING) {
8054 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8055 pktin->body, pktin->length);
8058 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
8059 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
8060 return; /* extended but not stderr */
8061 ssh_pkt_getstring(pktin, &data, &length);
8064 c->v.v2.locwindow -= length;
8065 c->v.v2.remlocwin -= length;
8067 case CHAN_MAINSESSION:
8069 from_backend(ssh->frontend, pktin->type ==
8070 SSH2_MSG_CHANNEL_EXTENDED_DATA,
8074 bufsize = x11_send(c->u.x11.xconn, data, length);
8077 bufsize = pfd_send(c->u.pfd.pf, data, length);
8080 while (length > 0) {
8081 if (c->u.a.lensofar < 4) {
8082 unsigned int l = min(4 - c->u.a.lensofar,
8084 memcpy(c->u.a.msglen + c->u.a.lensofar,
8088 c->u.a.lensofar += l;
8090 if (c->u.a.lensofar == 4) {
8092 4 + GET_32BIT(c->u.a.msglen);
8093 c->u.a.message = snewn(c->u.a.totallen,
8095 memcpy(c->u.a.message, c->u.a.msglen, 4);
8097 if (c->u.a.lensofar >= 4 && length > 0) {
8099 min(c->u.a.totallen - c->u.a.lensofar,
8101 memcpy(c->u.a.message + c->u.a.lensofar,
8105 c->u.a.lensofar += l;
8107 if (c->u.a.lensofar == c->u.a.totallen) {
8110 c->u.a.outstanding_requests++;
8111 if (agent_query(c->u.a.message,
8114 ssh_agentf_callback, c))
8115 ssh_agentf_callback(c, reply, replylen);
8116 sfree(c->u.a.message);
8117 c->u.a.message = NULL;
8118 c->u.a.lensofar = 0;
8125 * If it looks like the remote end hit the end of its window,
8126 * and we didn't want it to do that, think about using a
8129 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
8130 c->v.v2.locmaxwin < 0x40000000)
8131 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
8133 * If we are not buffering too much data,
8134 * enlarge the window again at the remote side.
8135 * If we are buffering too much, we may still
8136 * need to adjust the window if the server's
8139 ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
8140 c->v.v2.locmaxwin - bufsize : 0);
8142 * If we're either buffering way too much data, or if we're
8143 * buffering anything at all and we're in "simple" mode,
8144 * throttle the whole channel.
8146 if ((bufsize > c->v.v2.locmaxwin || (ssh_is_simple(ssh) && bufsize>0))
8147 && !c->throttling_conn) {
8148 c->throttling_conn = 1;
8149 ssh_throttle_conn(ssh, +1);
8154 static void ssh_check_termination(Ssh ssh)
8156 if (ssh->version == 2 &&
8157 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
8158 (ssh->channels && count234(ssh->channels) == 0) &&
8159 !(ssh->connshare && share_ndownstreams(ssh->connshare) > 0)) {
8161 * We used to send SSH_MSG_DISCONNECT here, because I'd
8162 * believed that _every_ conforming SSH-2 connection had to
8163 * end with a disconnect being sent by at least one side;
8164 * apparently I was wrong and it's perfectly OK to
8165 * unceremoniously slam the connection shut when you're done,
8166 * and indeed OpenSSH feels this is more polite than sending a
8167 * DISCONNECT. So now we don't.
8169 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
8173 void ssh_sharing_downstream_connected(Ssh ssh, unsigned id,
8174 const char *peerinfo)
8177 logeventf(ssh, "Connection sharing downstream #%u connected from %s",
8180 logeventf(ssh, "Connection sharing downstream #%u connected", id);
8183 void ssh_sharing_downstream_disconnected(Ssh ssh, unsigned id)
8185 logeventf(ssh, "Connection sharing downstream #%u disconnected", id);
8186 ssh_check_termination(ssh);
8189 void ssh_sharing_logf(Ssh ssh, unsigned id, const char *logfmt, ...)
8194 va_start(ap, logfmt);
8195 buf = dupvprintf(logfmt, ap);
8198 logeventf(ssh, "Connection sharing downstream #%u: %s", id, buf);
8200 logeventf(ssh, "Connection sharing: %s", buf);
8204 static void ssh_channel_destroy(struct ssh_channel *c)
8209 case CHAN_MAINSESSION:
8210 ssh->mainchan = NULL;
8211 update_specials_menu(ssh->frontend);
8214 if (c->u.x11.xconn != NULL)
8215 x11_close(c->u.x11.xconn);
8216 logevent("Forwarded X11 connection terminated");
8219 sfree(c->u.a.message);
8222 if (c->u.pfd.pf != NULL)
8223 pfd_close(c->u.pfd.pf);
8224 logevent("Forwarded port closed");
8228 del234(ssh->channels, c);
8229 if (ssh->version == 2) {
8230 bufchain_clear(&c->v.v2.outbuffer);
8231 assert(c->v.v2.chanreq_head == NULL);
8236 * If that was the last channel left open, we might need to
8239 ssh_check_termination(ssh);
8242 static void ssh2_channel_check_close(struct ssh_channel *c)
8245 struct Packet *pktout;
8249 * If we've sent out our own CHANNEL_OPEN but not yet seen
8250 * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
8251 * it's too early to be sending close messages of any kind.
8256 if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
8257 c->type == CHAN_ZOMBIE) &&
8258 !c->v.v2.chanreq_head &&
8259 !(c->closes & CLOSES_SENT_CLOSE)) {
8261 * We have both sent and received EOF (or the channel is a
8262 * zombie), and we have no outstanding channel requests, which
8263 * means the channel is in final wind-up. But we haven't sent
8264 * CLOSE, so let's do so now.
8266 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
8267 ssh2_pkt_adduint32(pktout, c->remoteid);
8268 ssh2_pkt_send(ssh, pktout);
8269 c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
8272 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
8273 assert(c->v.v2.chanreq_head == NULL);
8275 * We have both sent and received CLOSE, which means we're
8276 * completely done with the channel.
8278 ssh_channel_destroy(c);
8282 static void ssh2_channel_got_eof(struct ssh_channel *c)
8284 if (c->closes & CLOSES_RCVD_EOF)
8285 return; /* already seen EOF */
8286 c->closes |= CLOSES_RCVD_EOF;
8288 if (c->type == CHAN_X11) {
8289 x11_send_eof(c->u.x11.xconn);
8290 } else if (c->type == CHAN_AGENT) {
8291 if (c->u.a.outstanding_requests == 0) {
8292 /* Manufacture an outgoing EOF in response to the incoming one. */
8293 sshfwd_write_eof(c);
8295 } else if (c->type == CHAN_SOCKDATA) {
8296 pfd_send_eof(c->u.pfd.pf);
8297 } else if (c->type == CHAN_MAINSESSION) {
8300 if (!ssh->sent_console_eof &&
8301 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
8303 * Either from_backend_eof told us that the front end
8304 * wants us to close the outgoing side of the connection
8305 * as soon as we see EOF from the far end, or else we've
8306 * unilaterally decided to do that because we've allocated
8307 * a remote pty and hence EOF isn't a particularly
8308 * meaningful concept.
8310 sshfwd_write_eof(c);
8312 ssh->sent_console_eof = TRUE;
8315 ssh2_channel_check_close(c);
8318 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
8320 struct ssh_channel *c;
8322 c = ssh2_channel_msg(ssh, pktin);
8325 if (c->type == CHAN_SHARING) {
8326 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8327 pktin->body, pktin->length);
8330 ssh2_channel_got_eof(c);
8333 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
8335 struct ssh_channel *c;
8337 c = ssh2_channel_msg(ssh, pktin);
8340 if (c->type == CHAN_SHARING) {
8341 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8342 pktin->body, pktin->length);
8347 * When we receive CLOSE on a channel, we assume it comes with an
8348 * implied EOF if we haven't seen EOF yet.
8350 ssh2_channel_got_eof(c);
8352 if (!(ssh->remote_bugs & BUG_SENDS_LATE_REQUEST_REPLY)) {
8354 * It also means we stop expecting to see replies to any
8355 * outstanding channel requests, so clean those up too.
8356 * (ssh_chanreq_init will enforce by assertion that we don't
8357 * subsequently put anything back on this list.)
8359 while (c->v.v2.chanreq_head) {
8360 struct outstanding_channel_request *ocr = c->v.v2.chanreq_head;
8361 ocr->handler(c, NULL, ocr->ctx);
8362 c->v.v2.chanreq_head = ocr->next;
8368 * And we also send an outgoing EOF, if we haven't already, on the
8369 * assumption that CLOSE is a pretty forceful announcement that
8370 * the remote side is doing away with the entire channel. (If it
8371 * had wanted to send us EOF and continue receiving data from us,
8372 * it would have just sent CHANNEL_EOF.)
8374 if (!(c->closes & CLOSES_SENT_EOF)) {
8376 * Make sure we don't read any more from whatever our local
8377 * data source is for this channel.
8380 case CHAN_MAINSESSION:
8381 ssh->send_ok = 0; /* stop trying to read from stdin */
8384 x11_override_throttle(c->u.x11.xconn, 1);
8387 pfd_override_throttle(c->u.pfd.pf, 1);
8392 * Abandon any buffered data we still wanted to send to this
8393 * channel. Receiving a CHANNEL_CLOSE is an indication that
8394 * the server really wants to get on and _destroy_ this
8395 * channel, and it isn't going to send us any further
8396 * WINDOW_ADJUSTs to permit us to send pending stuff.
8398 bufchain_clear(&c->v.v2.outbuffer);
8401 * Send outgoing EOF.
8403 sshfwd_write_eof(c);
8407 * Now process the actual close.
8409 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
8410 c->closes |= CLOSES_RCVD_CLOSE;
8411 ssh2_channel_check_close(c);
8415 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
8417 struct ssh_channel *c;
8419 c = ssh2_channel_msg(ssh, pktin);
8422 if (c->type == CHAN_SHARING) {
8423 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8424 pktin->body, pktin->length);
8427 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
8428 c->remoteid = ssh_pkt_getuint32(pktin);
8429 c->halfopen = FALSE;
8430 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8431 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8433 if (c->type == CHAN_SOCKDATA_DORMANT) {
8434 c->type = CHAN_SOCKDATA;
8436 pfd_confirm(c->u.pfd.pf);
8437 } else if (c->type == CHAN_ZOMBIE) {
8439 * This case can occur if a local socket error occurred
8440 * between us sending out CHANNEL_OPEN and receiving
8441 * OPEN_CONFIRMATION. In this case, all we can do is
8442 * immediately initiate close proceedings now that we know the
8443 * server's id to put in the close message.
8445 ssh2_channel_check_close(c);
8448 * We never expect to receive OPEN_CONFIRMATION for any
8449 * *other* channel type (since only local-to-remote port
8450 * forwardings cause us to send CHANNEL_OPEN after the main
8451 * channel is live - all other auxiliary channel types are
8452 * initiated from the server end). It's safe to enforce this
8453 * by assertion rather than by ssh_disconnect, because the
8454 * real point is that we never constructed a half-open channel
8455 * structure in the first place with any type other than the
8458 assert(!"Funny channel type in ssh2_msg_channel_open_confirmation");
8462 ssh_channel_try_eof(c); /* in case we had a pending EOF */
8465 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
8467 static const char *const reasons[] = {
8468 "<unknown reason code>",
8469 "Administratively prohibited",
8471 "Unknown channel type",
8472 "Resource shortage",
8474 unsigned reason_code;
8475 char *reason_string;
8477 struct ssh_channel *c;
8479 c = ssh2_channel_msg(ssh, pktin);
8482 if (c->type == CHAN_SHARING) {
8483 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8484 pktin->body, pktin->length);
8487 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
8489 if (c->type == CHAN_SOCKDATA_DORMANT) {
8490 reason_code = ssh_pkt_getuint32(pktin);
8491 if (reason_code >= lenof(reasons))
8492 reason_code = 0; /* ensure reasons[reason_code] in range */
8493 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
8494 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
8495 reasons[reason_code], reason_length,
8496 NULLTOEMPTY(reason_string));
8498 pfd_close(c->u.pfd.pf);
8499 } else if (c->type == CHAN_ZOMBIE) {
8501 * This case can occur if a local socket error occurred
8502 * between us sending out CHANNEL_OPEN and receiving
8503 * OPEN_FAILURE. In this case, we need do nothing except allow
8504 * the code below to throw the half-open channel away.
8508 * We never expect to receive OPEN_FAILURE for any *other*
8509 * channel type (since only local-to-remote port forwardings
8510 * cause us to send CHANNEL_OPEN after the main channel is
8511 * live - all other auxiliary channel types are initiated from
8512 * the server end). It's safe to enforce this by assertion
8513 * rather than by ssh_disconnect, because the real point is
8514 * that we never constructed a half-open channel structure in
8515 * the first place with any type other than the above.
8517 assert(!"Funny channel type in ssh2_msg_channel_open_failure");
8520 del234(ssh->channels, c);
8524 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
8527 int typelen, want_reply;
8528 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
8529 struct ssh_channel *c;
8530 struct Packet *pktout;
8532 c = ssh2_channel_msg(ssh, pktin);
8535 if (c->type == CHAN_SHARING) {
8536 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8537 pktin->body, pktin->length);
8540 ssh_pkt_getstring(pktin, &type, &typelen);
8541 want_reply = ssh2_pkt_getbool(pktin);
8543 if (c->closes & CLOSES_SENT_CLOSE) {
8545 * We don't reply to channel requests after we've sent
8546 * CHANNEL_CLOSE for the channel, because our reply might
8547 * cross in the network with the other side's CHANNEL_CLOSE
8548 * and arrive after they have wound the channel up completely.
8554 * Having got the channel number, we now look at
8555 * the request type string to see if it's something
8558 if (c == ssh->mainchan) {
8560 * We recognise "exit-status" and "exit-signal" on
8561 * the primary channel.
8563 if (typelen == 11 &&
8564 !memcmp(type, "exit-status", 11)) {
8566 ssh->exitcode = ssh_pkt_getuint32(pktin);
8567 logeventf(ssh, "Server sent command exit status %d",
8569 reply = SSH2_MSG_CHANNEL_SUCCESS;
8571 } else if (typelen == 11 &&
8572 !memcmp(type, "exit-signal", 11)) {
8574 int is_plausible = TRUE, is_int = FALSE;
8575 char *fmt_sig = NULL, *fmt_msg = NULL;
8577 int msglen = 0, core = FALSE;
8578 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
8579 * provide an `int' for the signal, despite its
8580 * having been a `string' in the drafts of RFC 4254 since at
8581 * least 2001. (Fixed in session.c 1.147.) Try to
8582 * infer which we can safely parse it as. */
8584 unsigned char *p = pktin->body +
8586 long len = pktin->length - pktin->savedpos;
8587 unsigned long num = GET_32BIT(p); /* what is it? */
8588 /* If it's 0, it hardly matters; assume string */
8592 int maybe_int = FALSE, maybe_str = FALSE;
8593 #define CHECK_HYPOTHESIS(offset, result) \
8596 int q = toint(offset); \
8597 if (q >= 0 && q+4 <= len) { \
8598 q = toint(q + 4 + GET_32BIT(p+q)); \
8599 if (q >= 0 && q+4 <= len && \
8600 ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
8605 CHECK_HYPOTHESIS(4+1, maybe_int);
8606 CHECK_HYPOTHESIS(4+num+1, maybe_str);
8607 #undef CHECK_HYPOTHESIS
8608 if (maybe_int && !maybe_str)
8610 else if (!maybe_int && maybe_str)
8613 /* Crikey. Either or neither. Panic. */
8614 is_plausible = FALSE;
8617 ssh->exitcode = 128; /* means `unknown signal' */
8620 /* Old non-standard OpenSSH. */
8621 int signum = ssh_pkt_getuint32(pktin);
8622 fmt_sig = dupprintf(" %d", signum);
8623 ssh->exitcode = 128 + signum;
8625 /* As per RFC 4254. */
8628 ssh_pkt_getstring(pktin, &sig, &siglen);
8629 /* Signal name isn't supposed to be blank, but
8630 * let's cope gracefully if it is. */
8632 fmt_sig = dupprintf(" \"%.*s\"",
8637 * Really hideous method of translating the
8638 * signal description back into a locally
8639 * meaningful number.
8644 #define TRANSLATE_SIGNAL(s) \
8645 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
8646 ssh->exitcode = 128 + SIG ## s
8648 TRANSLATE_SIGNAL(ABRT);
8651 TRANSLATE_SIGNAL(ALRM);
8654 TRANSLATE_SIGNAL(FPE);
8657 TRANSLATE_SIGNAL(HUP);
8660 TRANSLATE_SIGNAL(ILL);
8663 TRANSLATE_SIGNAL(INT);
8666 TRANSLATE_SIGNAL(KILL);
8669 TRANSLATE_SIGNAL(PIPE);
8672 TRANSLATE_SIGNAL(QUIT);
8675 TRANSLATE_SIGNAL(SEGV);
8678 TRANSLATE_SIGNAL(TERM);
8681 TRANSLATE_SIGNAL(USR1);
8684 TRANSLATE_SIGNAL(USR2);
8686 #undef TRANSLATE_SIGNAL
8688 ssh->exitcode = 128;
8690 core = ssh2_pkt_getbool(pktin);
8691 ssh_pkt_getstring(pktin, &msg, &msglen);
8693 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
8695 /* ignore lang tag */
8696 } /* else don't attempt to parse */
8697 logeventf(ssh, "Server exited on signal%s%s%s",
8698 fmt_sig ? fmt_sig : "",
8699 core ? " (core dumped)" : "",
8700 fmt_msg ? fmt_msg : "");
8703 reply = SSH2_MSG_CHANNEL_SUCCESS;
8708 * This is a channel request we don't know
8709 * about, so we now either ignore the request
8710 * or respond with CHANNEL_FAILURE, depending
8713 reply = SSH2_MSG_CHANNEL_FAILURE;
8716 pktout = ssh2_pkt_init(reply);
8717 ssh2_pkt_adduint32(pktout, c->remoteid);
8718 ssh2_pkt_send(ssh, pktout);
8722 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
8725 int typelen, want_reply;
8726 struct Packet *pktout;
8728 ssh_pkt_getstring(pktin, &type, &typelen);
8729 want_reply = ssh2_pkt_getbool(pktin);
8732 * We currently don't support any global requests
8733 * at all, so we either ignore the request or
8734 * respond with REQUEST_FAILURE, depending on
8738 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
8739 ssh2_pkt_send(ssh, pktout);
8743 struct X11FakeAuth *ssh_sharing_add_x11_display(Ssh ssh, int authtype,
8747 struct X11FakeAuth *auth;
8750 * Make up a new set of fake X11 auth data, and add it to the tree
8751 * of currently valid ones with an indication of the sharing
8752 * context that it's relevant to.
8754 auth = x11_invent_fake_auth(ssh->x11authtree, authtype);
8755 auth->share_cs = share_cs;
8756 auth->share_chan = share_chan;
8761 void ssh_sharing_remove_x11_display(Ssh ssh, struct X11FakeAuth *auth)
8763 del234(ssh->x11authtree, auth);
8764 x11_free_fake_auth(auth);
8767 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
8774 const char *error = NULL;
8775 struct ssh_channel *c;
8776 unsigned remid, winsize, pktsize;
8777 unsigned our_winsize_override = 0;
8778 struct Packet *pktout;
8780 ssh_pkt_getstring(pktin, &type, &typelen);
8781 c = snew(struct ssh_channel);
8784 remid = ssh_pkt_getuint32(pktin);
8785 winsize = ssh_pkt_getuint32(pktin);
8786 pktsize = ssh_pkt_getuint32(pktin);
8788 if (typelen == 3 && !memcmp(type, "x11", 3)) {
8791 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8792 addrstr = dupprintf("%.*s", peeraddrlen, NULLTOEMPTY(peeraddr));
8793 peerport = ssh_pkt_getuint32(pktin);
8795 logeventf(ssh, "Received X11 connect request from %s:%d",
8798 if (!ssh->X11_fwd_enabled && !ssh->connshare)
8799 error = "X11 forwarding is not enabled";
8801 c->u.x11.xconn = x11_init(ssh->x11authtree, c,
8804 c->u.x11.initial = TRUE;
8807 * If we are a connection-sharing upstream, then we should
8808 * initially present a very small window, adequate to take
8809 * the X11 initial authorisation packet but not much more.
8810 * Downstream will then present us a larger window (by
8811 * fiat of the connection-sharing protocol) and we can
8812 * guarantee to send a positive-valued WINDOW_ADJUST.
8815 our_winsize_override = 128;
8817 logevent("Opened X11 forward channel");
8821 } else if (typelen == 15 &&
8822 !memcmp(type, "forwarded-tcpip", 15)) {
8823 struct ssh_rportfwd pf, *realpf;
8826 ssh_pkt_getstring(pktin, &shost, &shostlen);/* skip address */
8827 pf.shost = dupprintf("%.*s", shostlen, NULLTOEMPTY(shost));
8828 pf.sport = ssh_pkt_getuint32(pktin);
8829 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8830 peerport = ssh_pkt_getuint32(pktin);
8831 realpf = find234(ssh->rportfwds, &pf, NULL);
8832 logeventf(ssh, "Received remote port %s:%d open request "
8833 "from %.*s:%d", pf.shost, pf.sport,
8834 peeraddrlen, NULLTOEMPTY(peeraddr), peerport);
8837 if (realpf == NULL) {
8838 error = "Remote port is not recognised";
8842 if (realpf->share_ctx) {
8844 * This port forwarding is on behalf of a
8845 * connection-sharing downstream, so abandon our own
8846 * channel-open procedure and just pass the message on
8849 share_got_pkt_from_server(realpf->share_ctx, pktin->type,
8850 pktin->body, pktin->length);
8855 err = pfd_connect(&c->u.pfd.pf, realpf->dhost, realpf->dport,
8856 c, ssh->conf, realpf->pfrec->addressfamily);
8857 logeventf(ssh, "Attempting to forward remote port to "
8858 "%s:%d", realpf->dhost, realpf->dport);
8860 logeventf(ssh, "Port open failed: %s", err);
8862 error = "Port open failed";
8864 logevent("Forwarded port opened successfully");
8865 c->type = CHAN_SOCKDATA;
8868 } else if (typelen == 22 &&
8869 !memcmp(type, "auth-agent@openssh.com", 22)) {
8870 if (!ssh->agentfwd_enabled)
8871 error = "Agent forwarding is not enabled";
8873 c->type = CHAN_AGENT; /* identify channel type */
8874 c->u.a.lensofar = 0;
8875 c->u.a.message = NULL;
8876 c->u.a.outstanding_requests = 0;
8879 error = "Unsupported channel type requested";
8882 c->remoteid = remid;
8883 c->halfopen = FALSE;
8885 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
8886 ssh2_pkt_adduint32(pktout, c->remoteid);
8887 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
8888 ssh2_pkt_addstring(pktout, error);
8889 ssh2_pkt_addstring(pktout, "en"); /* language tag */
8890 ssh2_pkt_send(ssh, pktout);
8891 logeventf(ssh, "Rejected channel open: %s", error);
8894 ssh2_channel_init(c);
8895 c->v.v2.remwindow = winsize;
8896 c->v.v2.remmaxpkt = pktsize;
8897 if (our_winsize_override) {
8898 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
8899 our_winsize_override;
8901 add234(ssh->channels, c);
8902 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
8903 ssh2_pkt_adduint32(pktout, c->remoteid);
8904 ssh2_pkt_adduint32(pktout, c->localid);
8905 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
8906 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
8907 ssh2_pkt_send(ssh, pktout);
8911 void sshfwd_x11_sharing_handover(struct ssh_channel *c,
8912 void *share_cs, void *share_chan,
8913 const char *peer_addr, int peer_port,
8914 int endian, int protomajor, int protominor,
8915 const void *initial_data, int initial_len)
8918 * This function is called when we've just discovered that an X
8919 * forwarding channel on which we'd been handling the initial auth
8920 * ourselves turns out to be destined for a connection-sharing
8921 * downstream. So we turn the channel into a CHAN_SHARING, meaning
8922 * that we completely stop tracking windows and buffering data and
8923 * just pass more or less unmodified SSH messages back and forth.
8925 c->type = CHAN_SHARING;
8926 c->u.sharing.ctx = share_cs;
8927 share_setup_x11_channel(share_cs, share_chan,
8928 c->localid, c->remoteid, c->v.v2.remwindow,
8929 c->v.v2.remmaxpkt, c->v.v2.locwindow,
8930 peer_addr, peer_port, endian,
8931 protomajor, protominor,
8932 initial_data, initial_len);
8935 void sshfwd_x11_is_local(struct ssh_channel *c)
8938 * This function is called when we've just discovered that an X
8939 * forwarding channel is _not_ destined for a connection-sharing
8940 * downstream but we're going to handle it ourselves. We stop
8941 * presenting a cautiously small window and go into ordinary data
8944 c->u.x11.initial = FALSE;
8945 ssh2_set_window(c, ssh_is_simple(c->ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE);
8949 * Buffer banner messages for later display at some convenient point,
8950 * if we're going to display them.
8952 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
8954 /* Arbitrary limit to prevent unbounded inflation of buffer */
8955 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
8956 bufchain_size(&ssh->banner) <= 131072) {
8957 char *banner = NULL;
8959 ssh_pkt_getstring(pktin, &banner, &size);
8961 bufchain_add(&ssh->banner, banner, size);
8965 /* Helper function to deal with sending tty modes for "pty-req" */
8966 static void ssh2_send_ttymode(void *data, char *mode, char *val)
8968 struct Packet *pktout = (struct Packet *)data;
8970 unsigned int arg = 0;
8971 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
8972 if (i == lenof(ssh_ttymodes)) return;
8973 switch (ssh_ttymodes[i].type) {
8975 arg = ssh_tty_parse_specchar(val);
8978 arg = ssh_tty_parse_boolean(val);
8981 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
8982 ssh2_pkt_adduint32(pktout, arg);
8985 static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
8988 struct ssh2_setup_x11_state {
8992 struct Packet *pktout;
8993 crStateP(ssh2_setup_x11_state, ctx);
8997 logevent("Requesting X11 forwarding");
8998 pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
9000 ssh2_pkt_addbool(pktout, 0); /* many connections */
9001 ssh2_pkt_addstring(pktout, ssh->x11auth->protoname);
9002 ssh2_pkt_addstring(pktout, ssh->x11auth->datastring);
9003 ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
9004 ssh2_pkt_send(ssh, pktout);
9006 /* Wait to be called back with either a response packet, or NULL
9007 * meaning clean up and free our data */
9011 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
9012 logevent("X11 forwarding enabled");
9013 ssh->X11_fwd_enabled = TRUE;
9015 logevent("X11 forwarding refused");
9021 static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
9024 struct ssh2_setup_agent_state {
9028 struct Packet *pktout;
9029 crStateP(ssh2_setup_agent_state, ctx);
9033 logevent("Requesting OpenSSH-style agent forwarding");
9034 pktout = ssh2_chanreq_init(ssh->mainchan, "auth-agent-req@openssh.com",
9035 ssh2_setup_agent, s);
9036 ssh2_pkt_send(ssh, pktout);
9038 /* Wait to be called back with either a response packet, or NULL
9039 * meaning clean up and free our data */
9043 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
9044 logevent("Agent forwarding enabled");
9045 ssh->agentfwd_enabled = TRUE;
9047 logevent("Agent forwarding refused");
9053 static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
9056 struct ssh2_setup_pty_state {
9060 struct Packet *pktout;
9061 crStateP(ssh2_setup_pty_state, ctx);
9065 /* Unpick the terminal-speed string. */
9066 /* XXX perhaps we should allow no speeds to be sent. */
9067 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
9068 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
9069 /* Build the pty request. */
9070 pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
9072 ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
9073 ssh2_pkt_adduint32(pktout, ssh->term_width);
9074 ssh2_pkt_adduint32(pktout, ssh->term_height);
9075 ssh2_pkt_adduint32(pktout, 0); /* pixel width */
9076 ssh2_pkt_adduint32(pktout, 0); /* pixel height */
9077 ssh2_pkt_addstring_start(pktout);
9078 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
9079 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
9080 ssh2_pkt_adduint32(pktout, ssh->ispeed);
9081 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
9082 ssh2_pkt_adduint32(pktout, ssh->ospeed);
9083 ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
9084 ssh2_pkt_send(ssh, pktout);
9085 ssh->state = SSH_STATE_INTERMED;
9087 /* Wait to be called back with either a response packet, or NULL
9088 * meaning clean up and free our data */
9092 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
9093 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
9094 ssh->ospeed, ssh->ispeed);
9095 ssh->got_pty = TRUE;
9097 c_write_str(ssh, "Server refused to allocate pty\r\n");
9098 ssh->editing = ssh->echoing = 1;
9105 static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
9108 struct ssh2_setup_env_state {
9110 int num_env, env_left, env_ok;
9113 struct Packet *pktout;
9114 crStateP(ssh2_setup_env_state, ctx);
9119 * Send environment variables.
9121 * Simplest thing here is to send all the requests at once, and
9122 * then wait for a whole bunch of successes or failures.
9128 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
9130 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
9131 pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
9132 ssh2_pkt_addstring(pktout, key);
9133 ssh2_pkt_addstring(pktout, val);
9134 ssh2_pkt_send(ssh, pktout);
9139 logeventf(ssh, "Sent %d environment variables", s->num_env);
9144 s->env_left = s->num_env;
9146 while (s->env_left > 0) {
9147 /* Wait to be called back with either a response packet,
9148 * or NULL meaning clean up and free our data */
9150 if (!pktin) goto out;
9151 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
9156 if (s->env_ok == s->num_env) {
9157 logevent("All environment variables successfully set");
9158 } else if (s->env_ok == 0) {
9159 logevent("All environment variables refused");
9160 c_write_str(ssh, "Server refused to set environment variables\r\n");
9162 logeventf(ssh, "%d environment variables refused",
9163 s->num_env - s->env_ok);
9164 c_write_str(ssh, "Server refused to set all environment variables\r\n");
9172 * Handle the SSH-2 userauth and connection layers.
9174 static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
9176 do_ssh2_authconn(ssh, NULL, 0, pktin);
9179 static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
9183 do_ssh2_authconn(c->ssh, NULL, 0, pktin);
9186 static void do_ssh2_authconn(Ssh ssh, const unsigned char *in, int inlen,
9187 struct Packet *pktin)
9189 struct do_ssh2_authconn_state {
9193 AUTH_TYPE_PUBLICKEY,
9194 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
9195 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
9197 AUTH_TYPE_GSSAPI, /* always QUIET */
9198 AUTH_TYPE_KEYBOARD_INTERACTIVE,
9199 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
9201 int done_service_req;
9202 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
9203 int tried_pubkey_config, done_agent;
9208 int kbd_inter_refused;
9209 int we_are_in, userauth_success;
9210 prompts_t *cur_prompt;
9215 void *publickey_blob;
9216 int publickey_bloblen;
9217 int privatekey_available, privatekey_encrypted;
9218 char *publickey_algorithm;
9219 char *publickey_comment;
9220 unsigned char agent_request[5], *agent_response, *agentp;
9221 int agent_responselen;
9222 unsigned char *pkblob_in_agent;
9224 char *pkblob, *alg, *commentp;
9225 int pklen, alglen, commentlen;
9226 int siglen, retlen, len;
9227 char *q, *agentreq, *ret;
9229 struct Packet *pktout;
9232 struct ssh_gss_library *gsslib;
9233 Ssh_gss_ctx gss_ctx;
9234 Ssh_gss_buf gss_buf;
9235 Ssh_gss_buf gss_rcvtok, gss_sndtok;
9236 Ssh_gss_name gss_srv_name;
9237 Ssh_gss_stat gss_stat;
9240 crState(do_ssh2_authconn_state);
9244 /* Register as a handler for all the messages this coroutine handles. */
9245 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
9246 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
9247 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
9248 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
9249 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
9250 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
9251 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
9252 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
9253 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
9254 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
9255 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
9256 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
9257 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
9258 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
9259 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
9260 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
9261 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
9262 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
9263 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
9264 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
9266 s->done_service_req = FALSE;
9267 s->we_are_in = s->userauth_success = FALSE;
9268 s->agent_response = NULL;
9270 s->tried_gssapi = FALSE;
9273 if (!ssh->bare_connection) {
9274 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
9276 * Request userauth protocol, and await a response to it.
9278 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
9279 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
9280 ssh2_pkt_send(ssh, s->pktout);
9281 crWaitUntilV(pktin);
9282 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
9283 s->done_service_req = TRUE;
9285 if (!s->done_service_req) {
9287 * Request connection protocol directly, without authentication.
9289 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
9290 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9291 ssh2_pkt_send(ssh, s->pktout);
9292 crWaitUntilV(pktin);
9293 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
9294 s->we_are_in = TRUE; /* no auth required */
9296 bombout(("Server refused service request"));
9301 s->we_are_in = TRUE;
9304 /* Arrange to be able to deal with any BANNERs that come in.
9305 * (We do this now as packets may come in during the next bit.) */
9306 bufchain_init(&ssh->banner);
9307 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
9308 ssh2_msg_userauth_banner;
9311 * Misc one-time setup for authentication.
9313 s->publickey_blob = NULL;
9314 if (!s->we_are_in) {
9317 * Load the public half of any configured public key file
9320 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9321 if (!filename_is_null(s->keyfile)) {
9323 logeventf(ssh, "Reading key file \"%.150s\"",
9324 filename_to_str(s->keyfile));
9325 keytype = key_type(s->keyfile);
9326 if (keytype == SSH_KEYTYPE_SSH2 ||
9327 keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 ||
9328 keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
9331 ssh2_userkey_loadpub(s->keyfile,
9332 &s->publickey_algorithm,
9333 &s->publickey_bloblen,
9334 &s->publickey_comment, &error);
9335 if (s->publickey_blob) {
9336 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH2);
9337 if (!s->privatekey_available)
9338 logeventf(ssh, "Key file contains public key only");
9339 s->privatekey_encrypted =
9340 ssh2_userkey_encrypted(s->keyfile, NULL);
9343 logeventf(ssh, "Unable to load key (%s)",
9345 msgbuf = dupprintf("Unable to load key file "
9346 "\"%.150s\" (%s)\r\n",
9347 filename_to_str(s->keyfile),
9349 c_write_str(ssh, msgbuf);
9354 logeventf(ssh, "Unable to use this key file (%s)",
9355 key_type_to_str(keytype));
9356 msgbuf = dupprintf("Unable to use key file \"%.150s\""
9358 filename_to_str(s->keyfile),
9359 key_type_to_str(keytype));
9360 c_write_str(ssh, msgbuf);
9362 s->publickey_blob = NULL;
9367 * Find out about any keys Pageant has (but if there's a
9368 * public key configured, filter out all others).
9371 s->agent_response = NULL;
9372 s->pkblob_in_agent = NULL;
9373 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
9377 logevent("Pageant is running. Requesting keys.");
9379 /* Request the keys held by the agent. */
9380 PUT_32BIT(s->agent_request, 1);
9381 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
9382 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
9383 ssh_agent_callback, ssh)) {
9387 bombout(("Unexpected data from server while"
9388 " waiting for agent response"));
9391 } while (pktin || inlen > 0);
9392 r = ssh->agent_response;
9393 s->agent_responselen = ssh->agent_response_len;
9395 s->agent_response = (unsigned char *) r;
9396 if (s->agent_response && s->agent_responselen >= 5 &&
9397 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
9400 p = s->agent_response + 5;
9401 s->nkeys = toint(GET_32BIT(p));
9404 * Vet the Pageant response to ensure that the key
9405 * count and blob lengths make sense.
9408 logeventf(ssh, "Pageant response contained a negative"
9409 " key count %d", s->nkeys);
9411 goto done_agent_query;
9413 unsigned char *q = p + 4;
9414 int lenleft = s->agent_responselen - 5 - 4;
9416 for (keyi = 0; keyi < s->nkeys; keyi++) {
9417 int bloblen, commentlen;
9419 logeventf(ssh, "Pageant response was truncated");
9421 goto done_agent_query;
9423 bloblen = toint(GET_32BIT(q));
9424 if (bloblen < 0 || bloblen > lenleft) {
9425 logeventf(ssh, "Pageant response was truncated");
9427 goto done_agent_query;
9429 lenleft -= 4 + bloblen;
9431 commentlen = toint(GET_32BIT(q));
9432 if (commentlen < 0 || commentlen > lenleft) {
9433 logeventf(ssh, "Pageant response was truncated");
9435 goto done_agent_query;
9437 lenleft -= 4 + commentlen;
9438 q += 4 + commentlen;
9443 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
9444 if (s->publickey_blob) {
9445 /* See if configured key is in agent. */
9446 for (keyi = 0; keyi < s->nkeys; keyi++) {
9447 s->pklen = toint(GET_32BIT(p));
9448 if (s->pklen == s->publickey_bloblen &&
9449 !memcmp(p+4, s->publickey_blob,
9450 s->publickey_bloblen)) {
9451 logeventf(ssh, "Pageant key #%d matches "
9452 "configured key file", keyi);
9454 s->pkblob_in_agent = p;
9458 p += toint(GET_32BIT(p)) + 4; /* comment */
9460 if (!s->pkblob_in_agent) {
9461 logevent("Configured key file not in Pageant");
9466 logevent("Failed to get reply from Pageant");
9474 * We repeat this whole loop, including the username prompt,
9475 * until we manage a successful authentication. If the user
9476 * types the wrong _password_, they can be sent back to the
9477 * beginning to try another username, if this is configured on.
9478 * (If they specify a username in the config, they are never
9479 * asked, even if they do give a wrong password.)
9481 * I think this best serves the needs of
9483 * - the people who have no configuration, no keys, and just
9484 * want to try repeated (username,password) pairs until they
9485 * type both correctly
9487 * - people who have keys and configuration but occasionally
9488 * need to fall back to passwords
9490 * - people with a key held in Pageant, who might not have
9491 * logged in to a particular machine before; so they want to
9492 * type a username, and then _either_ their key will be
9493 * accepted, _or_ they will type a password. If they mistype
9494 * the username they will want to be able to get back and
9497 s->got_username = FALSE;
9498 while (!s->we_are_in) {
9502 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
9504 * We got a username last time round this loop, and
9505 * with change_username turned off we don't try to get
9508 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
9509 int ret; /* need not be kept over crReturn */
9510 s->cur_prompt = new_prompts(ssh->frontend);
9511 s->cur_prompt->to_server = TRUE;
9512 s->cur_prompt->name = dupstr("SSH login name");
9513 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
9514 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9517 crWaitUntilV(!pktin);
9518 ret = get_userpass_input(s->cur_prompt, in, inlen);
9523 * get_userpass_input() failed to get a username.
9526 free_prompts(s->cur_prompt);
9527 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
9530 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
9531 free_prompts(s->cur_prompt);
9534 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
9535 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
9536 c_write_str(ssh, stuff);
9540 s->got_username = TRUE;
9543 * Send an authentication request using method "none": (a)
9544 * just in case it succeeds, and (b) so that we know what
9545 * authentication methods we can usefully try next.
9547 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9549 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9550 ssh2_pkt_addstring(s->pktout, ssh->username);
9551 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
9552 ssh2_pkt_addstring(s->pktout, "none"); /* method */
9553 ssh2_pkt_send(ssh, s->pktout);
9554 s->type = AUTH_TYPE_NONE;
9556 s->we_are_in = FALSE;
9558 s->tried_pubkey_config = FALSE;
9559 s->kbd_inter_refused = FALSE;
9561 /* Reset agent request state. */
9562 s->done_agent = FALSE;
9563 if (s->agent_response) {
9564 if (s->pkblob_in_agent) {
9565 s->agentp = s->pkblob_in_agent;
9567 s->agentp = s->agent_response + 5 + 4;
9573 char *methods = NULL;
9577 * Wait for the result of the last authentication request.
9580 crWaitUntilV(pktin);
9582 * Now is a convenient point to spew any banner material
9583 * that we've accumulated. (This should ensure that when
9584 * we exit the auth loop, we haven't any left to deal
9588 int size = bufchain_size(&ssh->banner);
9590 * Don't show the banner if we're operating in
9591 * non-verbose non-interactive mode. (It's probably
9592 * a script, which means nobody will read the
9593 * banner _anyway_, and moreover the printing of
9594 * the banner will screw up processing on the
9595 * output of (say) plink.)
9597 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
9598 char *banner = snewn(size, char);
9599 bufchain_fetch(&ssh->banner, banner, size);
9600 c_write_untrusted(ssh, banner, size);
9603 bufchain_clear(&ssh->banner);
9605 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
9606 logevent("Access granted");
9607 s->we_are_in = s->userauth_success = TRUE;
9611 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
9612 bombout(("Strange packet received during authentication: "
9613 "type %d", pktin->type));
9620 * OK, we're now sitting on a USERAUTH_FAILURE message, so
9621 * we can look at the string in it and know what we can
9622 * helpfully try next.
9624 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
9625 ssh_pkt_getstring(pktin, &methods, &methlen);
9626 if (!ssh2_pkt_getbool(pktin)) {
9628 * We have received an unequivocal Access
9629 * Denied. This can translate to a variety of
9630 * messages, or no message at all.
9632 * For forms of authentication which are attempted
9633 * implicitly, by which I mean without printing
9634 * anything in the window indicating that we're
9635 * trying them, we should never print 'Access
9638 * If we do print a message saying that we're
9639 * attempting some kind of authentication, it's OK
9640 * to print a followup message saying it failed -
9641 * but the message may sometimes be more specific
9642 * than simply 'Access denied'.
9644 * Additionally, if we'd just tried password
9645 * authentication, we should break out of this
9646 * whole loop so as to go back to the username
9647 * prompt (iff we're configured to allow
9648 * username change attempts).
9650 if (s->type == AUTH_TYPE_NONE) {
9652 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
9653 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
9654 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
9655 c_write_str(ssh, "Server refused our key\r\n");
9656 logevent("Server refused our key");
9657 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
9658 /* This _shouldn't_ happen except by a
9659 * protocol bug causing client and server to
9660 * disagree on what is a correct signature. */
9661 c_write_str(ssh, "Server refused public-key signature"
9662 " despite accepting key!\r\n");
9663 logevent("Server refused public-key signature"
9664 " despite accepting key!");
9665 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
9666 /* quiet, so no c_write */
9667 logevent("Server refused keyboard-interactive authentication");
9668 } else if (s->type==AUTH_TYPE_GSSAPI) {
9669 /* always quiet, so no c_write */
9670 /* also, the code down in the GSSAPI block has
9671 * already logged this in the Event Log */
9672 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
9673 logevent("Keyboard-interactive authentication failed");
9674 c_write_str(ssh, "Access denied\r\n");
9676 assert(s->type == AUTH_TYPE_PASSWORD);
9677 logevent("Password authentication failed");
9678 c_write_str(ssh, "Access denied\r\n");
9680 if (conf_get_int(ssh->conf, CONF_change_username)) {
9681 /* XXX perhaps we should allow
9682 * keyboard-interactive to do this too? */
9683 s->we_are_in = FALSE;
9688 c_write_str(ssh, "Further authentication required\r\n");
9689 logevent("Further authentication required");
9693 in_commasep_string("publickey", methods, methlen);
9695 in_commasep_string("password", methods, methlen);
9696 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
9697 in_commasep_string("keyboard-interactive", methods, methlen);
9699 if (conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
9700 in_commasep_string("gssapi-with-mic", methods, methlen)) {
9701 /* Try loading the GSS libraries and see if we
9704 ssh->gsslibs = ssh_gss_setup(ssh->conf);
9705 s->can_gssapi = (ssh->gsslibs->nlibraries > 0);
9707 /* No point in even bothering to try to load the
9708 * GSS libraries, if the user configuration and
9709 * server aren't both prepared to attempt GSSAPI
9710 * auth in the first place. */
9711 s->can_gssapi = FALSE;
9716 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9718 if (s->can_pubkey && !s->done_agent && s->nkeys) {
9721 * Attempt public-key authentication using a key from Pageant.
9724 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9726 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
9728 /* Unpack key from agent response */
9729 s->pklen = toint(GET_32BIT(s->agentp));
9731 s->pkblob = (char *)s->agentp;
9732 s->agentp += s->pklen;
9733 s->alglen = toint(GET_32BIT(s->pkblob));
9734 s->alg = s->pkblob + 4;
9735 s->commentlen = toint(GET_32BIT(s->agentp));
9737 s->commentp = (char *)s->agentp;
9738 s->agentp += s->commentlen;
9739 /* s->agentp now points at next key, if any */
9741 /* See if server will accept it */
9742 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9743 ssh2_pkt_addstring(s->pktout, ssh->username);
9744 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9745 /* service requested */
9746 ssh2_pkt_addstring(s->pktout, "publickey");
9748 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
9749 ssh2_pkt_addstring_start(s->pktout);
9750 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9751 ssh2_pkt_addstring_start(s->pktout);
9752 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9753 ssh2_pkt_send(ssh, s->pktout);
9754 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
9756 crWaitUntilV(pktin);
9757 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9759 /* Offer of key refused. */
9766 if (flags & FLAG_VERBOSE) {
9767 c_write_str(ssh, "Authenticating with "
9769 c_write(ssh, s->commentp, s->commentlen);
9770 c_write_str(ssh, "\" from agent\r\n");
9774 * Server is willing to accept the key.
9775 * Construct a SIGN_REQUEST.
9777 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9778 ssh2_pkt_addstring(s->pktout, ssh->username);
9779 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9780 /* service requested */
9781 ssh2_pkt_addstring(s->pktout, "publickey");
9783 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
9784 ssh2_pkt_addstring_start(s->pktout);
9785 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9786 ssh2_pkt_addstring_start(s->pktout);
9787 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9789 /* Ask agent for signature. */
9790 s->siglen = s->pktout->length - 5 + 4 +
9791 ssh->v2_session_id_len;
9792 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9794 s->len = 1; /* message type */
9795 s->len += 4 + s->pklen; /* key blob */
9796 s->len += 4 + s->siglen; /* data to sign */
9797 s->len += 4; /* flags */
9798 s->agentreq = snewn(4 + s->len, char);
9799 PUT_32BIT(s->agentreq, s->len);
9800 s->q = s->agentreq + 4;
9801 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
9802 PUT_32BIT(s->q, s->pklen);
9804 memcpy(s->q, s->pkblob, s->pklen);
9806 PUT_32BIT(s->q, s->siglen);
9808 /* Now the data to be signed... */
9809 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9810 PUT_32BIT(s->q, ssh->v2_session_id_len);
9813 memcpy(s->q, ssh->v2_session_id,
9814 ssh->v2_session_id_len);
9815 s->q += ssh->v2_session_id_len;
9816 memcpy(s->q, s->pktout->data + 5,
9817 s->pktout->length - 5);
9818 s->q += s->pktout->length - 5;
9819 /* And finally the (zero) flags word. */
9821 if (!agent_query(s->agentreq, s->len + 4,
9823 ssh_agent_callback, ssh)) {
9827 bombout(("Unexpected data from server"
9828 " while waiting for agent"
9832 } while (pktin || inlen > 0);
9833 vret = ssh->agent_response;
9834 s->retlen = ssh->agent_response_len;
9839 if (s->retlen >= 9 &&
9840 s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
9841 GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
9842 logevent("Sending Pageant's response");
9843 ssh2_add_sigblob(ssh, s->pktout,
9844 s->pkblob, s->pklen,
9846 GET_32BIT(s->ret + 5));
9847 ssh2_pkt_send(ssh, s->pktout);
9848 s->type = AUTH_TYPE_PUBLICKEY;
9850 /* FIXME: less drastic response */
9851 bombout(("Pageant failed to answer challenge"));
9857 /* Do we have any keys left to try? */
9858 if (s->pkblob_in_agent) {
9859 s->done_agent = TRUE;
9860 s->tried_pubkey_config = TRUE;
9863 if (s->keyi >= s->nkeys)
9864 s->done_agent = TRUE;
9867 } else if (s->can_pubkey && s->publickey_blob &&
9868 s->privatekey_available && !s->tried_pubkey_config) {
9870 struct ssh2_userkey *key; /* not live over crReturn */
9871 char *passphrase; /* not live over crReturn */
9873 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9875 s->tried_pubkey_config = TRUE;
9878 * Try the public key supplied in the configuration.
9880 * First, offer the public blob to see if the server is
9881 * willing to accept it.
9883 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9884 ssh2_pkt_addstring(s->pktout, ssh->username);
9885 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9886 /* service requested */
9887 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
9888 ssh2_pkt_addbool(s->pktout, FALSE);
9889 /* no signature included */
9890 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
9891 ssh2_pkt_addstring_start(s->pktout);
9892 ssh2_pkt_addstring_data(s->pktout,
9893 (char *)s->publickey_blob,
9894 s->publickey_bloblen);
9895 ssh2_pkt_send(ssh, s->pktout);
9896 logevent("Offered public key");
9898 crWaitUntilV(pktin);
9899 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9900 /* Key refused. Give up. */
9901 s->gotit = TRUE; /* reconsider message next loop */
9902 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
9903 continue; /* process this new message */
9905 logevent("Offer of public key accepted");
9908 * Actually attempt a serious authentication using
9911 if (flags & FLAG_VERBOSE) {
9912 c_write_str(ssh, "Authenticating with public key \"");
9913 c_write_str(ssh, s->publickey_comment);
9914 c_write_str(ssh, "\"\r\n");
9918 const char *error; /* not live over crReturn */
9919 if (s->privatekey_encrypted) {
9921 * Get a passphrase from the user.
9923 int ret; /* need not be kept over crReturn */
9924 s->cur_prompt = new_prompts(ssh->frontend);
9925 s->cur_prompt->to_server = FALSE;
9926 s->cur_prompt->name = dupstr("SSH key passphrase");
9927 add_prompt(s->cur_prompt,
9928 dupprintf("Passphrase for key \"%.100s\": ",
9929 s->publickey_comment),
9931 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9934 crWaitUntilV(!pktin);
9935 ret = get_userpass_input(s->cur_prompt,
9940 /* Failed to get a passphrase. Terminate. */
9941 free_prompts(s->cur_prompt);
9942 ssh_disconnect(ssh, NULL,
9943 "Unable to authenticate",
9944 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9949 dupstr(s->cur_prompt->prompts[0]->result);
9950 free_prompts(s->cur_prompt);
9952 passphrase = NULL; /* no passphrase needed */
9956 * Try decrypting the key.
9958 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9959 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
9961 /* burn the evidence */
9962 smemclr(passphrase, strlen(passphrase));
9965 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
9967 (key == SSH2_WRONG_PASSPHRASE)) {
9968 c_write_str(ssh, "Wrong passphrase\r\n");
9970 /* and loop again */
9972 c_write_str(ssh, "Unable to load private key (");
9973 c_write_str(ssh, error);
9974 c_write_str(ssh, ")\r\n");
9976 break; /* try something else */
9982 unsigned char *pkblob, *sigblob, *sigdata;
9983 int pkblob_len, sigblob_len, sigdata_len;
9987 * We have loaded the private key and the server
9988 * has announced that it's willing to accept it.
9989 * Hallelujah. Generate a signature and send it.
9991 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9992 ssh2_pkt_addstring(s->pktout, ssh->username);
9993 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9994 /* service requested */
9995 ssh2_pkt_addstring(s->pktout, "publickey");
9997 ssh2_pkt_addbool(s->pktout, TRUE);
9998 /* signature follows */
9999 ssh2_pkt_addstring(s->pktout, key->alg->name);
10000 pkblob = key->alg->public_blob(key->data,
10002 ssh2_pkt_addstring_start(s->pktout);
10003 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
10007 * The data to be signed is:
10009 * string session-id
10011 * followed by everything so far placed in the
10014 sigdata_len = s->pktout->length - 5 + 4 +
10015 ssh->v2_session_id_len;
10016 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
10018 sigdata = snewn(sigdata_len, unsigned char);
10020 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
10021 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
10024 memcpy(sigdata+p, ssh->v2_session_id,
10025 ssh->v2_session_id_len);
10026 p += ssh->v2_session_id_len;
10027 memcpy(sigdata+p, s->pktout->data + 5,
10028 s->pktout->length - 5);
10029 p += s->pktout->length - 5;
10030 assert(p == sigdata_len);
10031 sigblob = key->alg->sign(key->data, (char *)sigdata,
10032 sigdata_len, &sigblob_len);
10033 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
10034 sigblob, sigblob_len);
10039 ssh2_pkt_send(ssh, s->pktout);
10040 logevent("Sent public key signature");
10041 s->type = AUTH_TYPE_PUBLICKEY;
10042 key->alg->freekey(key->data);
10043 sfree(key->comment);
10048 } else if (s->can_gssapi && !s->tried_gssapi) {
10050 /* GSSAPI Authentication */
10052 int micoffset, len;
10055 s->type = AUTH_TYPE_GSSAPI;
10056 s->tried_gssapi = TRUE;
10058 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
10061 * Pick the highest GSS library on the preference
10067 for (i = 0; i < ngsslibs; i++) {
10068 int want_id = conf_get_int_int(ssh->conf,
10069 CONF_ssh_gsslist, i);
10070 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
10071 if (ssh->gsslibs->libraries[j].id == want_id) {
10072 s->gsslib = &ssh->gsslibs->libraries[j];
10073 goto got_gsslib; /* double break */
10078 * We always expect to have found something in
10079 * the above loop: we only came here if there
10080 * was at least one viable GSS library, and the
10081 * preference list should always mention
10082 * everything and only change the order.
10087 if (s->gsslib->gsslogmsg)
10088 logevent(s->gsslib->gsslogmsg);
10090 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
10091 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10092 ssh2_pkt_addstring(s->pktout, ssh->username);
10093 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10094 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
10095 logevent("Attempting GSSAPI authentication");
10097 /* add mechanism info */
10098 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
10100 /* number of GSSAPI mechanisms */
10101 ssh2_pkt_adduint32(s->pktout,1);
10103 /* length of OID + 2 */
10104 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
10105 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
10107 /* length of OID */
10108 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
10110 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
10111 s->gss_buf.length);
10112 ssh2_pkt_send(ssh, s->pktout);
10113 crWaitUntilV(pktin);
10114 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
10115 logevent("GSSAPI authentication request refused");
10119 /* check returned packet ... */
10121 ssh_pkt_getstring(pktin, &data, &len);
10122 s->gss_rcvtok.value = data;
10123 s->gss_rcvtok.length = len;
10124 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
10125 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
10126 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
10127 memcmp((char *)s->gss_rcvtok.value + 2,
10128 s->gss_buf.value,s->gss_buf.length) ) {
10129 logevent("GSSAPI authentication - wrong response from server");
10133 /* now start running */
10134 s->gss_stat = s->gsslib->import_name(s->gsslib,
10137 if (s->gss_stat != SSH_GSS_OK) {
10138 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
10139 logevent("GSSAPI import name failed - Bad service name");
10141 logevent("GSSAPI import name failed");
10145 /* fetch TGT into GSS engine */
10146 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
10148 if (s->gss_stat != SSH_GSS_OK) {
10149 logevent("GSSAPI authentication failed to get credentials");
10150 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10154 /* initial tokens are empty */
10155 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
10156 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
10158 /* now enter the loop */
10160 s->gss_stat = s->gsslib->init_sec_context
10164 conf_get_int(ssh->conf, CONF_gssapifwd),
10168 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
10169 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
10170 logevent("GSSAPI authentication initialisation failed");
10172 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
10173 &s->gss_buf) == SSH_GSS_OK) {
10174 logevent(s->gss_buf.value);
10175 sfree(s->gss_buf.value);
10180 logevent("GSSAPI authentication initialised");
10182 /* Client and server now exchange tokens until GSSAPI
10183 * no longer says CONTINUE_NEEDED */
10185 if (s->gss_sndtok.length != 0) {
10186 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
10187 ssh_pkt_addstring_start(s->pktout);
10188 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
10189 ssh2_pkt_send(ssh, s->pktout);
10190 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
10193 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
10194 crWaitUntilV(pktin);
10195 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
10196 logevent("GSSAPI authentication - bad server response");
10197 s->gss_stat = SSH_GSS_FAILURE;
10200 ssh_pkt_getstring(pktin, &data, &len);
10201 s->gss_rcvtok.value = data;
10202 s->gss_rcvtok.length = len;
10204 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
10206 if (s->gss_stat != SSH_GSS_OK) {
10207 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10208 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
10211 logevent("GSSAPI authentication loop finished OK");
10213 /* Now send the MIC */
10215 s->pktout = ssh2_pkt_init(0);
10216 micoffset = s->pktout->length;
10217 ssh_pkt_addstring_start(s->pktout);
10218 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
10219 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
10220 ssh_pkt_addstring(s->pktout, ssh->username);
10221 ssh_pkt_addstring(s->pktout, "ssh-connection");
10222 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
10224 s->gss_buf.value = (char *)s->pktout->data + micoffset;
10225 s->gss_buf.length = s->pktout->length - micoffset;
10227 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
10228 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
10229 ssh_pkt_addstring_start(s->pktout);
10230 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
10231 ssh2_pkt_send(ssh, s->pktout);
10232 s->gsslib->free_mic(s->gsslib, &mic);
10236 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10237 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
10240 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
10243 * Keyboard-interactive authentication.
10246 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
10248 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
10250 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10251 ssh2_pkt_addstring(s->pktout, ssh->username);
10252 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10253 /* service requested */
10254 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
10256 ssh2_pkt_addstring(s->pktout, ""); /* lang */
10257 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
10258 ssh2_pkt_send(ssh, s->pktout);
10260 logevent("Attempting keyboard-interactive authentication");
10262 crWaitUntilV(pktin);
10263 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
10264 /* Server is not willing to do keyboard-interactive
10265 * at all (or, bizarrely but legally, accepts the
10266 * user without actually issuing any prompts).
10267 * Give up on it entirely. */
10269 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
10270 s->kbd_inter_refused = TRUE; /* don't try it again */
10275 * Loop while the server continues to send INFO_REQUESTs.
10277 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
10279 char *name, *inst, *lang;
10280 int name_len, inst_len, lang_len;
10284 * We've got a fresh USERAUTH_INFO_REQUEST.
10285 * Get the preamble and start building a prompt.
10287 ssh_pkt_getstring(pktin, &name, &name_len);
10288 ssh_pkt_getstring(pktin, &inst, &inst_len);
10289 ssh_pkt_getstring(pktin, &lang, &lang_len);
10290 s->cur_prompt = new_prompts(ssh->frontend);
10291 s->cur_prompt->to_server = TRUE;
10294 * Get any prompt(s) from the packet.
10296 s->num_prompts = ssh_pkt_getuint32(pktin);
10297 for (i = 0; i < s->num_prompts; i++) {
10301 static char noprompt[] =
10302 "<server failed to send prompt>: ";
10304 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10305 echo = ssh2_pkt_getbool(pktin);
10308 prompt_len = lenof(noprompt)-1;
10310 add_prompt(s->cur_prompt,
10311 dupprintf("%.*s", prompt_len, prompt),
10316 /* FIXME: better prefix to distinguish from
10317 * local prompts? */
10318 s->cur_prompt->name =
10319 dupprintf("SSH server: %.*s", name_len, name);
10320 s->cur_prompt->name_reqd = TRUE;
10322 s->cur_prompt->name =
10323 dupstr("SSH server authentication");
10324 s->cur_prompt->name_reqd = FALSE;
10326 /* We add a prefix to try to make it clear that a prompt
10327 * has come from the server.
10328 * FIXME: ugly to print "Using..." in prompt _every_
10329 * time round. Can this be done more subtly? */
10330 /* Special case: for reasons best known to themselves,
10331 * some servers send k-i requests with no prompts and
10332 * nothing to display. Keep quiet in this case. */
10333 if (s->num_prompts || name_len || inst_len) {
10334 s->cur_prompt->instruction =
10335 dupprintf("Using keyboard-interactive authentication.%s%.*s",
10336 inst_len ? "\n" : "", inst_len, inst);
10337 s->cur_prompt->instr_reqd = TRUE;
10339 s->cur_prompt->instr_reqd = FALSE;
10343 * Display any instructions, and get the user's
10347 int ret; /* not live over crReturn */
10348 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10351 crWaitUntilV(!pktin);
10352 ret = get_userpass_input(s->cur_prompt, in, inlen);
10357 * Failed to get responses. Terminate.
10359 free_prompts(s->cur_prompt);
10360 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10361 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10368 * Send the response(s) to the server.
10370 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
10371 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
10372 for (i=0; i < s->num_prompts; i++) {
10373 ssh2_pkt_addstring(s->pktout,
10374 s->cur_prompt->prompts[i]->result);
10376 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10379 * Free the prompts structure from this iteration.
10380 * If there's another, a new one will be allocated
10381 * when we return to the top of this while loop.
10383 free_prompts(s->cur_prompt);
10386 * Get the next packet in case it's another
10389 crWaitUntilV(pktin);
10394 * We should have SUCCESS or FAILURE now.
10398 } else if (s->can_passwd) {
10401 * Plain old password authentication.
10403 int ret; /* not live over crReturn */
10404 int changereq_first_time; /* not live over crReturn */
10406 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
10408 s->cur_prompt = new_prompts(ssh->frontend);
10409 s->cur_prompt->to_server = TRUE;
10410 s->cur_prompt->name = dupstr("SSH password");
10411 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
10416 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10419 crWaitUntilV(!pktin);
10420 ret = get_userpass_input(s->cur_prompt, in, inlen);
10425 * Failed to get responses. Terminate.
10427 free_prompts(s->cur_prompt);
10428 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10429 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10434 * Squirrel away the password. (We may need it later if
10435 * asked to change it.)
10437 s->password = dupstr(s->cur_prompt->prompts[0]->result);
10438 free_prompts(s->cur_prompt);
10441 * Send the password packet.
10443 * We pad out the password packet to 256 bytes to make
10444 * it harder for an attacker to find the length of the
10447 * Anyone using a password longer than 256 bytes
10448 * probably doesn't have much to worry about from
10449 * people who find out how long their password is!
10451 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10452 ssh2_pkt_addstring(s->pktout, ssh->username);
10453 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10454 /* service requested */
10455 ssh2_pkt_addstring(s->pktout, "password");
10456 ssh2_pkt_addbool(s->pktout, FALSE);
10457 ssh2_pkt_addstring(s->pktout, s->password);
10458 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10459 logevent("Sent password");
10460 s->type = AUTH_TYPE_PASSWORD;
10463 * Wait for next packet, in case it's a password change
10466 crWaitUntilV(pktin);
10467 changereq_first_time = TRUE;
10469 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
10472 * We're being asked for a new password
10473 * (perhaps not for the first time).
10474 * Loop until the server accepts it.
10477 int got_new = FALSE; /* not live over crReturn */
10478 char *prompt; /* not live over crReturn */
10479 int prompt_len; /* not live over crReturn */
10483 if (changereq_first_time)
10484 msg = "Server requested password change";
10486 msg = "Server rejected new password";
10488 c_write_str(ssh, msg);
10489 c_write_str(ssh, "\r\n");
10492 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10494 s->cur_prompt = new_prompts(ssh->frontend);
10495 s->cur_prompt->to_server = TRUE;
10496 s->cur_prompt->name = dupstr("New SSH password");
10497 s->cur_prompt->instruction =
10498 dupprintf("%.*s", prompt_len, NULLTOEMPTY(prompt));
10499 s->cur_prompt->instr_reqd = TRUE;
10501 * There's no explicit requirement in the protocol
10502 * for the "old" passwords in the original and
10503 * password-change messages to be the same, and
10504 * apparently some Cisco kit supports password change
10505 * by the user entering a blank password originally
10506 * and the real password subsequently, so,
10507 * reluctantly, we prompt for the old password again.
10509 * (On the other hand, some servers don't even bother
10510 * to check this field.)
10512 add_prompt(s->cur_prompt,
10513 dupstr("Current password (blank for previously entered password): "),
10515 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
10517 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
10521 * Loop until the user manages to enter the same
10526 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10529 crWaitUntilV(!pktin);
10530 ret = get_userpass_input(s->cur_prompt, in, inlen);
10535 * Failed to get responses. Terminate.
10537 /* burn the evidence */
10538 free_prompts(s->cur_prompt);
10539 smemclr(s->password, strlen(s->password));
10540 sfree(s->password);
10541 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10542 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10548 * If the user specified a new original password
10549 * (IYSWIM), overwrite any previously specified
10551 * (A side effect is that the user doesn't have to
10552 * re-enter it if they louse up the new password.)
10554 if (s->cur_prompt->prompts[0]->result[0]) {
10555 smemclr(s->password, strlen(s->password));
10556 /* burn the evidence */
10557 sfree(s->password);
10559 dupstr(s->cur_prompt->prompts[0]->result);
10563 * Check the two new passwords match.
10565 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
10566 s->cur_prompt->prompts[2]->result)
10569 /* They don't. Silly user. */
10570 c_write_str(ssh, "Passwords do not match\r\n");
10575 * Send the new password (along with the old one).
10576 * (see above for padding rationale)
10578 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10579 ssh2_pkt_addstring(s->pktout, ssh->username);
10580 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10581 /* service requested */
10582 ssh2_pkt_addstring(s->pktout, "password");
10583 ssh2_pkt_addbool(s->pktout, TRUE);
10584 ssh2_pkt_addstring(s->pktout, s->password);
10585 ssh2_pkt_addstring(s->pktout,
10586 s->cur_prompt->prompts[1]->result);
10587 free_prompts(s->cur_prompt);
10588 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10589 logevent("Sent new password");
10592 * Now see what the server has to say about it.
10593 * (If it's CHANGEREQ again, it's not happy with the
10596 crWaitUntilV(pktin);
10597 changereq_first_time = FALSE;
10602 * We need to reexamine the current pktin at the top
10603 * of the loop. Either:
10604 * - we weren't asked to change password at all, in
10605 * which case it's a SUCCESS or FAILURE with the
10607 * - we sent a new password, and the server was
10608 * either OK with it (SUCCESS or FAILURE w/partial
10609 * success) or unhappy with the _old_ password
10610 * (FAILURE w/o partial success)
10611 * In any of these cases, we go back to the top of
10612 * the loop and start again.
10617 * We don't need the old password any more, in any
10618 * case. Burn the evidence.
10620 smemclr(s->password, strlen(s->password));
10621 sfree(s->password);
10624 char *str = dupprintf("No supported authentication methods available"
10625 " (server sent: %.*s)",
10628 ssh_disconnect(ssh, str,
10629 "No supported authentication methods available",
10630 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
10640 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
10642 /* Clear up various bits and pieces from authentication. */
10643 if (s->publickey_blob) {
10644 sfree(s->publickey_algorithm);
10645 sfree(s->publickey_blob);
10646 sfree(s->publickey_comment);
10648 if (s->agent_response)
10649 sfree(s->agent_response);
10651 if (s->userauth_success && !ssh->bare_connection) {
10653 * We've just received USERAUTH_SUCCESS, and we haven't sent any
10654 * packets since. Signal the transport layer to consider enacting
10655 * delayed compression.
10657 * (Relying on we_are_in is not sufficient, as
10658 * draft-miller-secsh-compression-delayed is quite clear that it
10659 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
10660 * become set for other reasons.)
10662 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
10665 ssh->channels = newtree234(ssh_channelcmp);
10668 * Set up handlers for some connection protocol messages, so we
10669 * don't have to handle them repeatedly in this coroutine.
10671 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
10672 ssh2_msg_channel_window_adjust;
10673 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
10674 ssh2_msg_global_request;
10677 * Create the main session channel.
10679 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
10680 ssh->mainchan = NULL;
10682 ssh->mainchan = snew(struct ssh_channel);
10683 ssh->mainchan->ssh = ssh;
10684 ssh2_channel_init(ssh->mainchan);
10686 if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
10688 * Just start a direct-tcpip channel and use it as the main
10691 ssh_send_port_open(ssh->mainchan,
10692 conf_get_str(ssh->conf, CONF_ssh_nc_host),
10693 conf_get_int(ssh->conf, CONF_ssh_nc_port),
10695 ssh->ncmode = TRUE;
10697 s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
10698 logevent("Opening session as main channel");
10699 ssh2_pkt_send(ssh, s->pktout);
10700 ssh->ncmode = FALSE;
10702 crWaitUntilV(pktin);
10703 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
10704 bombout(("Server refused to open channel"));
10706 /* FIXME: error data comes back in FAILURE packet */
10708 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
10709 bombout(("Server's channel confirmation cited wrong channel"));
10712 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
10713 ssh->mainchan->halfopen = FALSE;
10714 ssh->mainchan->type = CHAN_MAINSESSION;
10715 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
10716 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
10717 add234(ssh->channels, ssh->mainchan);
10718 update_specials_menu(ssh->frontend);
10719 logevent("Opened main channel");
10723 * Now we have a channel, make dispatch table entries for
10724 * general channel-based messages.
10726 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
10727 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
10728 ssh2_msg_channel_data;
10729 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
10730 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
10731 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
10732 ssh2_msg_channel_open_confirmation;
10733 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
10734 ssh2_msg_channel_open_failure;
10735 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
10736 ssh2_msg_channel_request;
10737 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
10738 ssh2_msg_channel_open;
10739 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
10740 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
10743 * Now the connection protocol is properly up and running, with
10744 * all those dispatch table entries, so it's safe to let
10745 * downstreams start trying to open extra channels through us.
10747 if (ssh->connshare)
10748 share_activate(ssh->connshare, ssh->v_s);
10750 if (ssh->mainchan && ssh_is_simple(ssh)) {
10752 * This message indicates to the server that we promise
10753 * not to try to run any other channel in parallel with
10754 * this one, so it's safe for it to advertise a very large
10755 * window and leave the flow control to TCP.
10757 s->pktout = ssh2_chanreq_init(ssh->mainchan,
10758 "simple@putty.projects.tartarus.org",
10760 ssh2_pkt_send(ssh, s->pktout);
10764 * Enable port forwardings.
10766 ssh_setup_portfwd(ssh, ssh->conf);
10768 if (ssh->mainchan && !ssh->ncmode) {
10770 * Send the CHANNEL_REQUESTS for the main session channel.
10771 * Each one is handled by its own little asynchronous
10775 /* Potentially enable X11 forwarding. */
10776 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
10778 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
10780 if (!ssh->x11disp) {
10781 /* FIXME: return an error message from x11_setup_display */
10782 logevent("X11 forwarding not enabled: unable to"
10783 " initialise X display");
10785 ssh->x11auth = x11_invent_fake_auth
10786 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
10787 ssh->x11auth->disp = ssh->x11disp;
10789 ssh2_setup_x11(ssh->mainchan, NULL, NULL);
10793 /* Potentially enable agent forwarding. */
10794 if (ssh_agent_forwarding_permitted(ssh))
10795 ssh2_setup_agent(ssh->mainchan, NULL, NULL);
10797 /* Now allocate a pty for the session. */
10798 if (!conf_get_int(ssh->conf, CONF_nopty))
10799 ssh2_setup_pty(ssh->mainchan, NULL, NULL);
10801 /* Send environment variables. */
10802 ssh2_setup_env(ssh->mainchan, NULL, NULL);
10805 * Start a shell or a remote command. We may have to attempt
10806 * this twice if the config data has provided a second choice
10813 if (ssh->fallback_cmd) {
10814 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
10815 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
10817 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
10818 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
10822 s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
10823 ssh2_response_authconn, NULL);
10824 ssh2_pkt_addstring(s->pktout, cmd);
10826 s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
10827 ssh2_response_authconn, NULL);
10828 ssh2_pkt_addstring(s->pktout, cmd);
10830 s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
10831 ssh2_response_authconn, NULL);
10833 ssh2_pkt_send(ssh, s->pktout);
10835 crWaitUntilV(pktin);
10837 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
10838 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
10839 bombout(("Unexpected response to shell/command request:"
10840 " packet type %d", pktin->type));
10844 * We failed to start the command. If this is the
10845 * fallback command, we really are finished; if it's
10846 * not, and if the fallback command exists, try falling
10847 * back to it before complaining.
10849 if (!ssh->fallback_cmd &&
10850 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
10851 logevent("Primary command failed; attempting fallback");
10852 ssh->fallback_cmd = TRUE;
10855 bombout(("Server refused to start a shell/command"));
10858 logevent("Started a shell/command");
10863 ssh->editing = ssh->echoing = TRUE;
10866 ssh->state = SSH_STATE_SESSION;
10867 if (ssh->size_needed)
10868 ssh_size(ssh, ssh->term_width, ssh->term_height);
10869 if (ssh->eof_needed)
10870 ssh_special(ssh, TS_EOF);
10876 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
10881 s->try_send = FALSE;
10885 * _All_ the connection-layer packets we expect to
10886 * receive are now handled by the dispatch table.
10887 * Anything that reaches here must be bogus.
10890 bombout(("Strange packet received: type %d", pktin->type));
10892 } else if (ssh->mainchan) {
10894 * We have spare data. Add it to the channel buffer.
10896 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
10897 s->try_send = TRUE;
10901 struct ssh_channel *c;
10903 * Try to send data on all channels if we can.
10905 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
10906 if (c->type != CHAN_SHARING)
10907 ssh2_try_send_and_unthrottle(ssh, c);
10915 * Handlers for SSH-2 messages that might arrive at any moment.
10917 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
10919 /* log reason code in disconnect message */
10921 int reason, msglen;
10923 reason = ssh_pkt_getuint32(pktin);
10924 ssh_pkt_getstring(pktin, &msg, &msglen);
10926 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
10927 buf = dupprintf("Received disconnect message (%s)",
10928 ssh2_disconnect_reasons[reason]);
10930 buf = dupprintf("Received disconnect message (unknown"
10931 " type %d)", reason);
10935 buf = dupprintf("Disconnection message text: %.*s",
10936 msglen, NULLTOEMPTY(msg));
10938 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
10940 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
10941 ssh2_disconnect_reasons[reason] : "unknown",
10942 msglen, NULLTOEMPTY(msg)));
10946 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
10948 /* log the debug message */
10952 /* XXX maybe we should actually take notice of the return value */
10953 ssh2_pkt_getbool(pktin);
10954 ssh_pkt_getstring(pktin, &msg, &msglen);
10956 logeventf(ssh, "Remote debug message: %.*s", msglen, NULLTOEMPTY(msg));
10959 static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
10961 do_ssh2_transport(ssh, NULL, 0, pktin);
10965 * Called if we receive a packet that isn't allowed by the protocol.
10966 * This only applies to packets whose meaning PuTTY understands.
10967 * Entirely unknown packets are handled below.
10969 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
10971 char *buf = dupprintf("Server protocol violation: unexpected %s packet",
10972 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
10974 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
10978 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
10980 struct Packet *pktout;
10981 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
10982 ssh2_pkt_adduint32(pktout, pktin->sequence);
10984 * UNIMPLEMENTED messages MUST appear in the same order as the
10985 * messages they respond to. Hence, never queue them.
10987 ssh2_pkt_send_noqueue(ssh, pktout);
10991 * Handle the top-level SSH-2 protocol.
10993 static void ssh2_protocol_setup(Ssh ssh)
10998 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
11000 for (i = 0; i < 256; i++)
11001 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
11004 * Initially, we only accept transport messages (and a few generic
11005 * ones). do_ssh2_authconn will add more when it starts.
11006 * Messages that are understood but not currently acceptable go to
11007 * ssh2_msg_unexpected.
11009 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
11010 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
11011 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
11012 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
11013 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
11014 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
11015 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
11016 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
11017 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
11018 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
11019 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
11020 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
11021 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
11022 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
11023 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
11024 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
11025 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
11026 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
11027 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
11028 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
11029 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
11030 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
11031 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
11032 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
11033 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
11034 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
11035 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
11036 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
11037 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
11038 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
11039 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
11040 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
11041 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
11044 * These messages have a special handler from the start.
11046 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
11047 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
11048 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
11051 static void ssh2_bare_connection_protocol_setup(Ssh ssh)
11056 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
11058 for (i = 0; i < 256; i++)
11059 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
11062 * Initially, we set all ssh-connection messages to 'unexpected';
11063 * do_ssh2_authconn will fill things in properly. We also handle a
11064 * couple of messages from the transport protocol which aren't
11065 * related to key exchange (UNIMPLEMENTED, IGNORE, DEBUG,
11068 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
11069 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
11070 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
11071 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
11072 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
11073 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
11074 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
11075 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
11076 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
11077 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
11078 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
11079 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
11080 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
11081 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
11083 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
11086 * These messages have a special handler from the start.
11088 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
11089 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore;
11090 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
11093 static void ssh2_timer(void *ctx, unsigned long now)
11095 Ssh ssh = (Ssh)ctx;
11097 if (ssh->state == SSH_STATE_CLOSED)
11100 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11101 conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
11102 now == ssh->next_rekey) {
11103 do_ssh2_transport(ssh, "timeout", -1, NULL);
11107 static void ssh2_protocol(Ssh ssh, const void *vin, int inlen,
11108 struct Packet *pktin)
11110 const unsigned char *in = (const unsigned char *)vin;
11111 if (ssh->state == SSH_STATE_CLOSED)
11115 ssh->incoming_data_size += pktin->encrypted_len;
11116 if (!ssh->kex_in_progress &&
11117 ssh->max_data_size != 0 &&
11118 ssh->incoming_data_size > ssh->max_data_size)
11119 do_ssh2_transport(ssh, "too much data received", -1, NULL);
11123 ssh->packet_dispatch[pktin->type](ssh, pktin);
11124 else if (!ssh->protocol_initial_phase_done)
11125 do_ssh2_transport(ssh, in, inlen, pktin);
11127 do_ssh2_authconn(ssh, in, inlen, pktin);
11130 static void ssh2_bare_connection_protocol(Ssh ssh, const void *vin, int inlen,
11131 struct Packet *pktin)
11133 const unsigned char *in = (const unsigned char *)vin;
11134 if (ssh->state == SSH_STATE_CLOSED)
11138 ssh->packet_dispatch[pktin->type](ssh, pktin);
11140 do_ssh2_authconn(ssh, in, inlen, pktin);
11143 static void ssh_cache_conf_values(Ssh ssh)
11145 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
11149 * Called to set up the connection.
11151 * Returns an error message, or NULL on success.
11153 static const char *ssh_init(void *frontend_handle, void **backend_handle,
11155 const char *host, int port, char **realhost,
11156 int nodelay, int keepalive)
11161 ssh = snew(struct ssh_tag);
11162 ssh->conf = conf_copy(conf);
11163 ssh_cache_conf_values(ssh);
11164 ssh->version = 0; /* when not ready yet */
11166 ssh->cipher = NULL;
11167 ssh->v1_cipher_ctx = NULL;
11168 ssh->crcda_ctx = NULL;
11169 ssh->cscipher = NULL;
11170 ssh->cs_cipher_ctx = NULL;
11171 ssh->sccipher = NULL;
11172 ssh->sc_cipher_ctx = NULL;
11174 ssh->cs_mac_ctx = NULL;
11176 ssh->sc_mac_ctx = NULL;
11177 ssh->cscomp = NULL;
11178 ssh->cs_comp_ctx = NULL;
11179 ssh->sccomp = NULL;
11180 ssh->sc_comp_ctx = NULL;
11182 ssh->kex_ctx = NULL;
11183 ssh->hostkey = NULL;
11184 ssh->hostkey_str = NULL;
11185 ssh->exitcode = -1;
11186 ssh->close_expected = FALSE;
11187 ssh->clean_exit = FALSE;
11188 ssh->state = SSH_STATE_PREPACKET;
11189 ssh->size_needed = FALSE;
11190 ssh->eof_needed = FALSE;
11192 ssh->logctx = NULL;
11193 ssh->deferred_send_data = NULL;
11194 ssh->deferred_len = 0;
11195 ssh->deferred_size = 0;
11196 ssh->fallback_cmd = 0;
11197 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
11198 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
11199 ssh->x11disp = NULL;
11200 ssh->x11auth = NULL;
11201 ssh->x11authtree = newtree234(x11_authcmp);
11202 ssh->v1_compressing = FALSE;
11203 ssh->v2_outgoing_sequence = 0;
11204 ssh->ssh1_rdpkt_crstate = 0;
11205 ssh->ssh2_rdpkt_crstate = 0;
11206 ssh->ssh2_bare_rdpkt_crstate = 0;
11207 ssh->ssh_gotdata_crstate = 0;
11208 ssh->do_ssh1_connection_crstate = 0;
11209 ssh->do_ssh_init_state = NULL;
11210 ssh->do_ssh_connection_init_state = NULL;
11211 ssh->do_ssh1_login_state = NULL;
11212 ssh->do_ssh2_transport_state = NULL;
11213 ssh->do_ssh2_authconn_state = NULL;
11216 ssh->mainchan = NULL;
11217 ssh->throttled_all = 0;
11218 ssh->v1_stdout_throttling = 0;
11220 ssh->queuelen = ssh->queuesize = 0;
11221 ssh->queueing = FALSE;
11222 ssh->qhead = ssh->qtail = NULL;
11223 ssh->deferred_rekey_reason = NULL;
11224 bufchain_init(&ssh->queued_incoming_data);
11225 ssh->frozen = FALSE;
11226 ssh->username = NULL;
11227 ssh->sent_console_eof = FALSE;
11228 ssh->got_pty = FALSE;
11229 ssh->bare_connection = FALSE;
11230 ssh->X11_fwd_enabled = FALSE;
11231 ssh->connshare = NULL;
11232 ssh->attempting_connshare = FALSE;
11233 ssh->session_started = FALSE;
11234 ssh->specials = NULL;
11235 ssh->n_uncert_hostkeys = 0;
11236 ssh->cross_certifying = FALSE;
11238 *backend_handle = ssh;
11241 if (crypto_startup() == 0)
11242 return "Microsoft high encryption pack not installed!";
11245 ssh->frontend = frontend_handle;
11246 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
11247 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
11249 ssh->channels = NULL;
11250 ssh->rportfwds = NULL;
11251 ssh->portfwds = NULL;
11256 ssh->conn_throttle_count = 0;
11257 ssh->overall_bufsize = 0;
11258 ssh->fallback_cmd = 0;
11260 ssh->protocol = NULL;
11262 ssh->protocol_initial_phase_done = FALSE;
11264 ssh->pinger = NULL;
11266 ssh->incoming_data_size = ssh->outgoing_data_size =
11267 ssh->deferred_data_size = 0L;
11268 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11269 CONF_ssh_rekey_data));
11270 ssh->kex_in_progress = FALSE;
11273 ssh->gsslibs = NULL;
11276 random_ref(); /* do this now - may be needed by sharing setup code */
11278 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
11287 static void ssh_free(void *handle)
11289 Ssh ssh = (Ssh) handle;
11290 struct ssh_channel *c;
11291 struct ssh_rportfwd *pf;
11292 struct X11FakeAuth *auth;
11294 if (ssh->v1_cipher_ctx)
11295 ssh->cipher->free_context(ssh->v1_cipher_ctx);
11296 if (ssh->cs_cipher_ctx)
11297 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
11298 if (ssh->sc_cipher_ctx)
11299 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
11300 if (ssh->cs_mac_ctx)
11301 ssh->csmac->free_context(ssh->cs_mac_ctx);
11302 if (ssh->sc_mac_ctx)
11303 ssh->scmac->free_context(ssh->sc_mac_ctx);
11304 if (ssh->cs_comp_ctx) {
11306 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
11308 zlib_compress_cleanup(ssh->cs_comp_ctx);
11310 if (ssh->sc_comp_ctx) {
11312 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
11314 zlib_decompress_cleanup(ssh->sc_comp_ctx);
11317 dh_cleanup(ssh->kex_ctx);
11318 sfree(ssh->savedhost);
11320 while (ssh->queuelen-- > 0)
11321 ssh_free_packet(ssh->queue[ssh->queuelen]);
11324 while (ssh->qhead) {
11325 struct queued_handler *qh = ssh->qhead;
11326 ssh->qhead = qh->next;
11329 ssh->qhead = ssh->qtail = NULL;
11331 if (ssh->channels) {
11332 while ((c = delpos234(ssh->channels, 0)) != NULL) {
11335 if (c->u.x11.xconn != NULL)
11336 x11_close(c->u.x11.xconn);
11338 case CHAN_SOCKDATA:
11339 case CHAN_SOCKDATA_DORMANT:
11340 if (c->u.pfd.pf != NULL)
11341 pfd_close(c->u.pfd.pf);
11344 if (ssh->version == 2) {
11345 struct outstanding_channel_request *ocr, *nocr;
11346 ocr = c->v.v2.chanreq_head;
11348 ocr->handler(c, NULL, ocr->ctx);
11353 bufchain_clear(&c->v.v2.outbuffer);
11357 freetree234(ssh->channels);
11358 ssh->channels = NULL;
11361 if (ssh->connshare)
11362 sharestate_free(ssh->connshare);
11364 if (ssh->rportfwds) {
11365 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
11367 freetree234(ssh->rportfwds);
11368 ssh->rportfwds = NULL;
11370 sfree(ssh->deferred_send_data);
11372 x11_free_display(ssh->x11disp);
11373 while ((auth = delpos234(ssh->x11authtree, 0)) != NULL)
11374 x11_free_fake_auth(auth);
11375 freetree234(ssh->x11authtree);
11376 sfree(ssh->do_ssh_init_state);
11377 sfree(ssh->do_ssh1_login_state);
11378 sfree(ssh->do_ssh2_transport_state);
11379 sfree(ssh->do_ssh2_authconn_state);
11382 sfree(ssh->fullhostname);
11383 sfree(ssh->hostkey_str);
11384 sfree(ssh->specials);
11385 if (ssh->crcda_ctx) {
11386 crcda_free_context(ssh->crcda_ctx);
11387 ssh->crcda_ctx = NULL;
11390 ssh_do_close(ssh, TRUE);
11391 expire_timer_context(ssh);
11393 pinger_free(ssh->pinger);
11394 bufchain_clear(&ssh->queued_incoming_data);
11395 sfree(ssh->username);
11396 conf_free(ssh->conf);
11399 ssh_gss_cleanup(ssh->gsslibs);
11407 * Reconfigure the SSH backend.
11409 static void ssh_reconfig(void *handle, Conf *conf)
11411 Ssh ssh = (Ssh) handle;
11412 const char *rekeying = NULL;
11413 int rekey_mandatory = FALSE;
11414 unsigned long old_max_data_size;
11417 pinger_reconfig(ssh->pinger, ssh->conf, conf);
11419 ssh_setup_portfwd(ssh, conf);
11421 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
11422 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
11424 unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
11425 unsigned long now = GETTICKCOUNT();
11427 if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
11428 rekeying = "timeout shortened";
11430 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
11434 old_max_data_size = ssh->max_data_size;
11435 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11436 CONF_ssh_rekey_data));
11437 if (old_max_data_size != ssh->max_data_size &&
11438 ssh->max_data_size != 0) {
11439 if (ssh->outgoing_data_size > ssh->max_data_size ||
11440 ssh->incoming_data_size > ssh->max_data_size)
11441 rekeying = "data limit lowered";
11444 if (conf_get_int(ssh->conf, CONF_compression) !=
11445 conf_get_int(conf, CONF_compression)) {
11446 rekeying = "compression setting changed";
11447 rekey_mandatory = TRUE;
11450 for (i = 0; i < CIPHER_MAX; i++)
11451 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
11452 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
11453 rekeying = "cipher settings changed";
11454 rekey_mandatory = TRUE;
11456 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
11457 conf_get_int(conf, CONF_ssh2_des_cbc)) {
11458 rekeying = "cipher settings changed";
11459 rekey_mandatory = TRUE;
11462 conf_free(ssh->conf);
11463 ssh->conf = conf_copy(conf);
11464 ssh_cache_conf_values(ssh);
11466 if (!ssh->bare_connection && rekeying) {
11467 if (!ssh->kex_in_progress) {
11468 do_ssh2_transport(ssh, rekeying, -1, NULL);
11469 } else if (rekey_mandatory) {
11470 ssh->deferred_rekey_reason = rekeying;
11476 * Called to send data down the SSH connection.
11478 static int ssh_send(void *handle, const char *buf, int len)
11480 Ssh ssh = (Ssh) handle;
11482 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11485 ssh->protocol(ssh, (const unsigned char *)buf, len, 0);
11487 return ssh_sendbuffer(ssh);
11491 * Called to query the current amount of buffered stdin data.
11493 static int ssh_sendbuffer(void *handle)
11495 Ssh ssh = (Ssh) handle;
11496 int override_value;
11498 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11502 * If the SSH socket itself has backed up, add the total backup
11503 * size on that to any individual buffer on the stdin channel.
11505 override_value = 0;
11506 if (ssh->throttled_all)
11507 override_value = ssh->overall_bufsize;
11509 if (ssh->version == 1) {
11510 return override_value;
11511 } else if (ssh->version == 2) {
11512 if (!ssh->mainchan)
11513 return override_value;
11515 return (override_value +
11516 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
11523 * Called to set the size of the window from SSH's POV.
11525 static void ssh_size(void *handle, int width, int height)
11527 Ssh ssh = (Ssh) handle;
11528 struct Packet *pktout;
11530 ssh->term_width = width;
11531 ssh->term_height = height;
11533 switch (ssh->state) {
11534 case SSH_STATE_BEFORE_SIZE:
11535 case SSH_STATE_PREPACKET:
11536 case SSH_STATE_CLOSED:
11537 break; /* do nothing */
11538 case SSH_STATE_INTERMED:
11539 ssh->size_needed = TRUE; /* buffer for later */
11541 case SSH_STATE_SESSION:
11542 if (!conf_get_int(ssh->conf, CONF_nopty)) {
11543 if (ssh->version == 1) {
11544 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
11545 PKT_INT, ssh->term_height,
11546 PKT_INT, ssh->term_width,
11547 PKT_INT, 0, PKT_INT, 0, PKT_END);
11548 } else if (ssh->mainchan) {
11549 pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
11551 ssh2_pkt_adduint32(pktout, ssh->term_width);
11552 ssh2_pkt_adduint32(pktout, ssh->term_height);
11553 ssh2_pkt_adduint32(pktout, 0);
11554 ssh2_pkt_adduint32(pktout, 0);
11555 ssh2_pkt_send(ssh, pktout);
11563 * Return a list of the special codes that make sense in this
11566 static const struct telnet_special *ssh_get_specials(void *handle)
11568 static const struct telnet_special ssh1_ignore_special[] = {
11569 {"IGNORE message", TS_NOP}
11571 static const struct telnet_special ssh2_ignore_special[] = {
11572 {"IGNORE message", TS_NOP},
11574 static const struct telnet_special ssh2_rekey_special[] = {
11575 {"Repeat key exchange", TS_REKEY},
11577 static const struct telnet_special ssh2_session_specials[] = {
11580 /* These are the signal names defined by RFC 4254.
11581 * They include all the ISO C signals, but are a subset of the POSIX
11582 * required signals. */
11583 {"SIGINT (Interrupt)", TS_SIGINT},
11584 {"SIGTERM (Terminate)", TS_SIGTERM},
11585 {"SIGKILL (Kill)", TS_SIGKILL},
11586 {"SIGQUIT (Quit)", TS_SIGQUIT},
11587 {"SIGHUP (Hangup)", TS_SIGHUP},
11588 {"More signals", TS_SUBMENU},
11589 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
11590 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
11591 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
11592 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
11593 {NULL, TS_EXITMENU}
11595 static const struct telnet_special specials_end[] = {
11596 {NULL, TS_EXITMENU}
11599 struct telnet_special *specials = NULL;
11600 int nspecials = 0, specialsize = 0;
11602 Ssh ssh = (Ssh) handle;
11604 sfree(ssh->specials);
11606 #define ADD_SPECIALS(name) do \
11608 int len = lenof(name); \
11609 if (nspecials + len > specialsize) { \
11610 specialsize = (nspecials + len) * 5 / 4 + 32; \
11611 specials = sresize(specials, specialsize, struct telnet_special); \
11613 memcpy(specials+nspecials, name, len*sizeof(struct telnet_special)); \
11614 nspecials += len; \
11617 if (ssh->version == 1) {
11618 /* Don't bother offering IGNORE if we've decided the remote
11619 * won't cope with it, since we wouldn't bother sending it if
11621 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11622 ADD_SPECIALS(ssh1_ignore_special);
11623 } else if (ssh->version == 2) {
11624 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
11625 ADD_SPECIALS(ssh2_ignore_special);
11626 if (!(ssh->remote_bugs & BUG_SSH2_REKEY) && !ssh->bare_connection)
11627 ADD_SPECIALS(ssh2_rekey_special);
11629 ADD_SPECIALS(ssh2_session_specials);
11631 if (ssh->n_uncert_hostkeys) {
11632 static const struct telnet_special uncert_start[] = {
11634 {"Cache new host key type", TS_SUBMENU},
11636 static const struct telnet_special uncert_end[] = {
11637 {NULL, TS_EXITMENU},
11641 ADD_SPECIALS(uncert_start);
11642 for (i = 0; i < ssh->n_uncert_hostkeys; i++) {
11643 struct telnet_special uncert[1];
11644 const struct ssh_signkey *alg =
11645 hostkey_algs[ssh->uncert_hostkeys[i]].alg;
11646 uncert[0].name = alg->name;
11647 uncert[0].code = TS_LOCALSTART + ssh->uncert_hostkeys[i];
11648 ADD_SPECIALS(uncert);
11650 ADD_SPECIALS(uncert_end);
11652 } /* else we're not ready yet */
11655 ADD_SPECIALS(specials_end);
11657 ssh->specials = specials;
11664 #undef ADD_SPECIALS
11668 * Send special codes. TS_EOF is useful for `plink', so you
11669 * can send an EOF and collect resulting output (e.g. `plink
11672 static void ssh_special(void *handle, Telnet_Special code)
11674 Ssh ssh = (Ssh) handle;
11675 struct Packet *pktout;
11677 if (code == TS_EOF) {
11678 if (ssh->state != SSH_STATE_SESSION) {
11680 * Buffer the EOF in case we are pre-SESSION, so we can
11681 * send it as soon as we reach SESSION.
11683 if (code == TS_EOF)
11684 ssh->eof_needed = TRUE;
11687 if (ssh->version == 1) {
11688 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
11689 } else if (ssh->mainchan) {
11690 sshfwd_write_eof(ssh->mainchan);
11691 ssh->send_ok = 0; /* now stop trying to read from stdin */
11693 logevent("Sent EOF message");
11694 } else if (code == TS_PING || code == TS_NOP) {
11695 if (ssh->state == SSH_STATE_CLOSED
11696 || ssh->state == SSH_STATE_PREPACKET) return;
11697 if (ssh->version == 1) {
11698 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11699 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
11701 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
11702 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
11703 ssh2_pkt_addstring_start(pktout);
11704 ssh2_pkt_send_noqueue(ssh, pktout);
11707 } else if (code == TS_REKEY) {
11708 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11709 ssh->version == 2) {
11710 do_ssh2_transport(ssh, "at user request", -1, NULL);
11712 } else if (code >= TS_LOCALSTART) {
11713 ssh->hostkey = hostkey_algs[code - TS_LOCALSTART].alg;
11714 ssh->cross_certifying = TRUE;
11715 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11716 ssh->version == 2) {
11717 do_ssh2_transport(ssh, "cross-certifying new host key", -1, NULL);
11719 } else if (code == TS_BRK) {
11720 if (ssh->state == SSH_STATE_CLOSED
11721 || ssh->state == SSH_STATE_PREPACKET) return;
11722 if (ssh->version == 1) {
11723 logevent("Unable to send BREAK signal in SSH-1");
11724 } else if (ssh->mainchan) {
11725 pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
11726 ssh2_pkt_adduint32(pktout, 0); /* default break length */
11727 ssh2_pkt_send(ssh, pktout);
11730 /* Is is a POSIX signal? */
11731 const char *signame = NULL;
11732 if (code == TS_SIGABRT) signame = "ABRT";
11733 if (code == TS_SIGALRM) signame = "ALRM";
11734 if (code == TS_SIGFPE) signame = "FPE";
11735 if (code == TS_SIGHUP) signame = "HUP";
11736 if (code == TS_SIGILL) signame = "ILL";
11737 if (code == TS_SIGINT) signame = "INT";
11738 if (code == TS_SIGKILL) signame = "KILL";
11739 if (code == TS_SIGPIPE) signame = "PIPE";
11740 if (code == TS_SIGQUIT) signame = "QUIT";
11741 if (code == TS_SIGSEGV) signame = "SEGV";
11742 if (code == TS_SIGTERM) signame = "TERM";
11743 if (code == TS_SIGUSR1) signame = "USR1";
11744 if (code == TS_SIGUSR2) signame = "USR2";
11745 /* The SSH-2 protocol does in principle support arbitrary named
11746 * signals, including signame@domain, but we don't support those. */
11748 /* It's a signal. */
11749 if (ssh->version == 2 && ssh->mainchan) {
11750 pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
11751 ssh2_pkt_addstring(pktout, signame);
11752 ssh2_pkt_send(ssh, pktout);
11753 logeventf(ssh, "Sent signal SIG%s", signame);
11756 /* Never heard of it. Do nothing */
11761 void *new_sock_channel(void *handle, struct PortForwarding *pf)
11763 Ssh ssh = (Ssh) handle;
11764 struct ssh_channel *c;
11765 c = snew(struct ssh_channel);
11768 ssh2_channel_init(c);
11769 c->halfopen = TRUE;
11770 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
11772 add234(ssh->channels, c);
11776 unsigned ssh_alloc_sharing_channel(Ssh ssh, void *sharing_ctx)
11778 struct ssh_channel *c;
11779 c = snew(struct ssh_channel);
11782 ssh2_channel_init(c);
11783 c->type = CHAN_SHARING;
11784 c->u.sharing.ctx = sharing_ctx;
11785 add234(ssh->channels, c);
11789 void ssh_delete_sharing_channel(Ssh ssh, unsigned localid)
11791 struct ssh_channel *c;
11793 c = find234(ssh->channels, &localid, ssh_channelfind);
11795 ssh_channel_destroy(c);
11798 void ssh_send_packet_from_downstream(Ssh ssh, unsigned id, int type,
11799 const void *data, int datalen,
11800 const char *additional_log_text)
11802 struct Packet *pkt;
11804 pkt = ssh2_pkt_init(type);
11805 pkt->downstream_id = id;
11806 pkt->additional_log_text = additional_log_text;
11807 ssh2_pkt_adddata(pkt, data, datalen);
11808 ssh2_pkt_send(ssh, pkt);
11812 * This is called when stdout/stderr (the entity to which
11813 * from_backend sends data) manages to clear some backlog.
11815 static void ssh_unthrottle(void *handle, int bufsize)
11817 Ssh ssh = (Ssh) handle;
11820 if (ssh->version == 1) {
11821 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
11822 ssh->v1_stdout_throttling = 0;
11823 ssh_throttle_conn(ssh, -1);
11826 if (ssh->mainchan) {
11827 ssh2_set_window(ssh->mainchan,
11828 bufsize < ssh->mainchan->v.v2.locmaxwin ?
11829 ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
11830 if (ssh_is_simple(ssh))
11833 buflimit = ssh->mainchan->v.v2.locmaxwin;
11834 if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
11835 ssh->mainchan->throttling_conn = 0;
11836 ssh_throttle_conn(ssh, -1);
11842 * Now process any SSH connection data that was stashed in our
11843 * queue while we were frozen.
11845 ssh_process_queued_incoming_data(ssh);
11848 void ssh_send_port_open(void *channel, const char *hostname, int port,
11851 struct ssh_channel *c = (struct ssh_channel *)channel;
11853 struct Packet *pktout;
11855 logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
11857 if (ssh->version == 1) {
11858 send_packet(ssh, SSH1_MSG_PORT_OPEN,
11859 PKT_INT, c->localid,
11862 /* PKT_STR, <org:orgport>, */
11865 pktout = ssh2_chanopen_init(c, "direct-tcpip");
11867 char *trimmed_host = host_strduptrim(hostname);
11868 ssh2_pkt_addstring(pktout, trimmed_host);
11869 sfree(trimmed_host);
11871 ssh2_pkt_adduint32(pktout, port);
11873 * We make up values for the originator data; partly it's
11874 * too much hassle to keep track, and partly I'm not
11875 * convinced the server should be told details like that
11876 * about my local network configuration.
11877 * The "originator IP address" is syntactically a numeric
11878 * IP address, and some servers (e.g., Tectia) get upset
11879 * if it doesn't match this syntax.
11881 ssh2_pkt_addstring(pktout, "0.0.0.0");
11882 ssh2_pkt_adduint32(pktout, 0);
11883 ssh2_pkt_send(ssh, pktout);
11887 static int ssh_connected(void *handle)
11889 Ssh ssh = (Ssh) handle;
11890 return ssh->s != NULL;
11893 static int ssh_sendok(void *handle)
11895 Ssh ssh = (Ssh) handle;
11896 return ssh->send_ok;
11899 static int ssh_ldisc(void *handle, int option)
11901 Ssh ssh = (Ssh) handle;
11902 if (option == LD_ECHO)
11903 return ssh->echoing;
11904 if (option == LD_EDIT)
11905 return ssh->editing;
11909 static void ssh_provide_ldisc(void *handle, void *ldisc)
11911 Ssh ssh = (Ssh) handle;
11912 ssh->ldisc = ldisc;
11915 static void ssh_provide_logctx(void *handle, void *logctx)
11917 Ssh ssh = (Ssh) handle;
11918 ssh->logctx = logctx;
11921 static int ssh_return_exitcode(void *handle)
11923 Ssh ssh = (Ssh) handle;
11924 if (ssh->s != NULL)
11927 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
11931 * cfg_info for SSH is the protocol running in this session.
11932 * (1 or 2 for the full SSH-1 or SSH-2 protocol; -1 for the bare
11933 * SSH-2 connection protocol, i.e. a downstream; 0 for not-decided-yet.)
11935 static int ssh_cfg_info(void *handle)
11937 Ssh ssh = (Ssh) handle;
11938 if (ssh->version == 0)
11939 return 0; /* don't know yet */
11940 else if (ssh->bare_connection)
11943 return ssh->version;
11947 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
11948 * that fails. This variable is the means by which scp.c can reach
11949 * into the SSH code and find out which one it got.
11951 extern int ssh_fallback_cmd(void *handle)
11953 Ssh ssh = (Ssh) handle;
11954 return ssh->fallback_cmd;
11957 Backend ssh_backend = {
11967 ssh_return_exitcode,
11971 ssh_provide_logctx,
11974 ssh_test_for_upstream,