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
92 static const struct ssh_ttymode {
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 default 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 int ssh_send_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,
1013 const struct ssh_ttymode *mode,
1018 const struct ssh_ttymode *mode;
1020 char default_val[2];
1022 strcpy(default_val, "A");
1024 for (i = 0; i < lenof(ssh_ttymodes); i++) {
1025 mode = ssh_ttymodes + i;
1026 val = conf_get_str_str_opt(ssh->conf, CONF_ttymodes, mode->mode);
1031 * val[0] is either 'V', indicating that an explicit value
1032 * follows it, or 'A' indicating that we should pass the
1033 * value through from the local environment via get_ttymode.
1035 if (val[0] == 'A') {
1036 val = get_ttymode(ssh->frontend, mode->mode);
1038 do_mode(data, mode, val);
1042 do_mode(data, mode, val + 1); /* skip the 'V' */
1046 static int ssh_channelcmp(void *av, void *bv)
1048 struct ssh_channel *a = (struct ssh_channel *) av;
1049 struct ssh_channel *b = (struct ssh_channel *) bv;
1050 if (a->localid < b->localid)
1052 if (a->localid > b->localid)
1056 static int ssh_channelfind(void *av, void *bv)
1058 unsigned *a = (unsigned *) av;
1059 struct ssh_channel *b = (struct ssh_channel *) bv;
1060 if (*a < b->localid)
1062 if (*a > b->localid)
1067 static int ssh_rportcmp_ssh1(void *av, void *bv)
1069 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1070 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1072 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
1073 return i < 0 ? -1 : +1;
1074 if (a->dport > b->dport)
1076 if (a->dport < b->dport)
1081 static int ssh_rportcmp_ssh2(void *av, void *bv)
1083 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1084 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1086 if ( (i = strcmp(a->shost, b->shost)) != 0)
1087 return i < 0 ? -1 : +1;
1088 if (a->sport > b->sport)
1090 if (a->sport < b->sport)
1096 * Special form of strcmp which can cope with NULL inputs. NULL is
1097 * defined to sort before even the empty string.
1099 static int nullstrcmp(const char *a, const char *b)
1101 if (a == NULL && b == NULL)
1107 return strcmp(a, b);
1110 static int ssh_portcmp(void *av, void *bv)
1112 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1113 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1115 if (a->type > b->type)
1117 if (a->type < b->type)
1119 if (a->addressfamily > b->addressfamily)
1121 if (a->addressfamily < b->addressfamily)
1123 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1124 return i < 0 ? -1 : +1;
1125 if (a->sport > b->sport)
1127 if (a->sport < b->sport)
1129 if (a->type != 'D') {
1130 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1131 return i < 0 ? -1 : +1;
1132 if (a->dport > b->dport)
1134 if (a->dport < b->dport)
1140 static int alloc_channel_id(Ssh ssh)
1142 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1143 unsigned low, high, mid;
1145 struct ssh_channel *c;
1148 * First-fit allocation of channel numbers: always pick the
1149 * lowest unused one. To do this, binary-search using the
1150 * counted B-tree to find the largest channel ID which is in a
1151 * contiguous sequence from the beginning. (Precisely
1152 * everything in that sequence must have ID equal to its tree
1153 * index plus CHANNEL_NUMBER_OFFSET.)
1155 tsize = count234(ssh->channels);
1159 while (high - low > 1) {
1160 mid = (high + low) / 2;
1161 c = index234(ssh->channels, mid);
1162 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1163 low = mid; /* this one is fine */
1165 high = mid; /* this one is past it */
1168 * Now low points to either -1, or the tree index of the
1169 * largest ID in the initial sequence.
1172 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1173 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1175 return low + 1 + CHANNEL_NUMBER_OFFSET;
1178 static void c_write_stderr(int trusted, const char *buf, int len)
1181 for (i = 0; i < len; i++)
1182 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1183 fputc(buf[i], stderr);
1186 static void c_write(Ssh ssh, const char *buf, int len)
1188 if (flags & FLAG_STDERR)
1189 c_write_stderr(1, buf, len);
1191 from_backend(ssh->frontend, 1, buf, len);
1194 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1196 if (flags & FLAG_STDERR)
1197 c_write_stderr(0, buf, len);
1199 from_backend_untrusted(ssh->frontend, buf, len);
1202 static void c_write_str(Ssh ssh, const char *buf)
1204 c_write(ssh, buf, strlen(buf));
1207 static void ssh_free_packet(struct Packet *pkt)
1212 static struct Packet *ssh_new_packet(void)
1214 struct Packet *pkt = snew(struct Packet);
1216 pkt->body = pkt->data = NULL;
1222 static void ssh1_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1225 struct logblank_t blanks[4];
1231 if (ssh->logomitdata &&
1232 (pkt->type == SSH1_SMSG_STDOUT_DATA ||
1233 pkt->type == SSH1_SMSG_STDERR_DATA ||
1234 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1235 /* "Session data" packets - omit the data string. */
1236 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1237 ssh_pkt_getuint32(pkt); /* skip channel id */
1238 blanks[nblanks].offset = pkt->savedpos + 4;
1239 blanks[nblanks].type = PKTLOG_OMIT;
1240 ssh_pkt_getstring(pkt, &str, &slen);
1242 blanks[nblanks].len = slen;
1246 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1247 ssh1_pkt_type(pkt->type),
1248 pkt->body, pkt->length, nblanks, blanks, NULL,
1252 static void ssh1_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1255 struct logblank_t blanks[4];
1260 * For outgoing packets, pkt->length represents the length of the
1261 * whole packet starting at pkt->data (including some header), and
1262 * pkt->body refers to the point within that where the log-worthy
1263 * payload begins. However, incoming packets expect pkt->length to
1264 * represent only the payload length (that is, it's measured from
1265 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1266 * packet to conform to the incoming-packet semantics, so that we
1267 * can analyse it with the ssh_pkt_get functions.
1269 pkt->length -= (pkt->body - pkt->data);
1272 if (ssh->logomitdata &&
1273 (pkt->type == SSH1_CMSG_STDIN_DATA ||
1274 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1275 /* "Session data" packets - omit the data string. */
1276 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1277 ssh_pkt_getuint32(pkt); /* skip channel id */
1278 blanks[nblanks].offset = pkt->savedpos + 4;
1279 blanks[nblanks].type = PKTLOG_OMIT;
1280 ssh_pkt_getstring(pkt, &str, &slen);
1282 blanks[nblanks].len = slen;
1287 if ((pkt->type == SSH1_CMSG_AUTH_PASSWORD ||
1288 pkt->type == SSH1_CMSG_AUTH_TIS_RESPONSE ||
1289 pkt->type == SSH1_CMSG_AUTH_CCARD_RESPONSE) &&
1290 conf_get_int(ssh->conf, CONF_logomitpass)) {
1291 /* If this is a password or similar packet, blank the password(s). */
1292 blanks[nblanks].offset = 0;
1293 blanks[nblanks].len = pkt->length;
1294 blanks[nblanks].type = PKTLOG_BLANK;
1296 } else if (pkt->type == SSH1_CMSG_X11_REQUEST_FORWARDING &&
1297 conf_get_int(ssh->conf, CONF_logomitpass)) {
1299 * If this is an X forwarding request packet, blank the fake
1302 * Note that while we blank the X authentication data here, we
1303 * don't take any special action to blank the start of an X11
1304 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1305 * an X connection without having session blanking enabled is
1306 * likely to leak your cookie into the log.
1309 ssh_pkt_getstring(pkt, &str, &slen);
1310 blanks[nblanks].offset = pkt->savedpos;
1311 blanks[nblanks].type = PKTLOG_BLANK;
1312 ssh_pkt_getstring(pkt, &str, &slen);
1314 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1319 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1320 ssh1_pkt_type(pkt->data[12]),
1321 pkt->body, pkt->length,
1322 nblanks, blanks, NULL, 0, NULL);
1325 * Undo the above adjustment of pkt->length, to put the packet
1326 * back in the state we found it.
1328 pkt->length += (pkt->body - pkt->data);
1332 * Collect incoming data in the incoming packet buffer.
1333 * Decipher and verify the packet when it is completely read.
1334 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1335 * Update the *data and *datalen variables.
1336 * Return a Packet structure when a packet is completed.
1338 static struct Packet *ssh1_rdpkt(Ssh ssh, const unsigned char **data,
1341 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1343 crBegin(ssh->ssh1_rdpkt_crstate);
1345 st->pktin = ssh_new_packet();
1347 st->pktin->type = 0;
1348 st->pktin->length = 0;
1350 for (st->i = st->len = 0; st->i < 4; st->i++) {
1351 while ((*datalen) == 0)
1353 st->len = (st->len << 8) + **data;
1354 (*data)++, (*datalen)--;
1357 st->pad = 8 - (st->len % 8);
1358 st->biglen = st->len + st->pad;
1359 st->pktin->length = st->len - 5;
1361 if (st->biglen < 0) {
1362 bombout(("Extremely large packet length from server suggests"
1363 " data stream corruption"));
1364 ssh_free_packet(st->pktin);
1368 st->pktin->maxlen = st->biglen;
1369 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1371 st->to_read = st->biglen;
1372 st->p = st->pktin->data;
1373 while (st->to_read > 0) {
1374 st->chunk = st->to_read;
1375 while ((*datalen) == 0)
1377 if (st->chunk > (*datalen))
1378 st->chunk = (*datalen);
1379 memcpy(st->p, *data, st->chunk);
1381 *datalen -= st->chunk;
1383 st->to_read -= st->chunk;
1386 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1387 st->biglen, NULL)) {
1388 bombout(("Network attack (CRC compensation) detected!"));
1389 ssh_free_packet(st->pktin);
1394 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1396 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1397 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1398 if (st->gotcrc != st->realcrc) {
1399 bombout(("Incorrect CRC received on packet"));
1400 ssh_free_packet(st->pktin);
1404 st->pktin->body = st->pktin->data + st->pad + 1;
1406 if (ssh->v1_compressing) {
1407 unsigned char *decompblk;
1409 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1410 st->pktin->body - 1, st->pktin->length + 1,
1411 &decompblk, &decomplen)) {
1412 bombout(("Zlib decompression encountered invalid data"));
1413 ssh_free_packet(st->pktin);
1417 if (st->pktin->maxlen < st->pad + decomplen) {
1418 st->pktin->maxlen = st->pad + decomplen;
1419 st->pktin->data = sresize(st->pktin->data,
1420 st->pktin->maxlen + APIEXTRA,
1422 st->pktin->body = st->pktin->data + st->pad + 1;
1425 memcpy(st->pktin->body - 1, decompblk, decomplen);
1427 st->pktin->length = decomplen - 1;
1430 st->pktin->type = st->pktin->body[-1];
1433 * Now pktin->body and pktin->length identify the semantic content
1434 * of the packet, excluding the initial type byte.
1438 ssh1_log_incoming_packet(ssh, st->pktin);
1440 st->pktin->savedpos = 0;
1442 crFinish(st->pktin);
1445 static void ssh2_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1448 struct logblank_t blanks[4];
1454 if (ssh->logomitdata &&
1455 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1456 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1457 /* "Session data" packets - omit the data string. */
1458 ssh_pkt_getuint32(pkt); /* skip channel id */
1459 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1460 ssh_pkt_getuint32(pkt); /* skip extended data type */
1461 blanks[nblanks].offset = pkt->savedpos + 4;
1462 blanks[nblanks].type = PKTLOG_OMIT;
1463 ssh_pkt_getstring(pkt, &str, &slen);
1465 blanks[nblanks].len = slen;
1470 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1471 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->type),
1472 pkt->body, pkt->length, nblanks, blanks, &pkt->sequence,
1476 static void ssh2_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1479 struct logblank_t blanks[4];
1484 * For outgoing packets, pkt->length represents the length of the
1485 * whole packet starting at pkt->data (including some header), and
1486 * pkt->body refers to the point within that where the log-worthy
1487 * payload begins. However, incoming packets expect pkt->length to
1488 * represent only the payload length (that is, it's measured from
1489 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1490 * packet to conform to the incoming-packet semantics, so that we
1491 * can analyse it with the ssh_pkt_get functions.
1493 pkt->length -= (pkt->body - pkt->data);
1496 if (ssh->logomitdata &&
1497 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1498 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1499 /* "Session data" packets - omit the data string. */
1500 ssh_pkt_getuint32(pkt); /* skip channel id */
1501 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1502 ssh_pkt_getuint32(pkt); /* skip extended data type */
1503 blanks[nblanks].offset = pkt->savedpos + 4;
1504 blanks[nblanks].type = PKTLOG_OMIT;
1505 ssh_pkt_getstring(pkt, &str, &slen);
1507 blanks[nblanks].len = slen;
1512 if (pkt->type == SSH2_MSG_USERAUTH_REQUEST &&
1513 conf_get_int(ssh->conf, CONF_logomitpass)) {
1514 /* If this is a password packet, blank the password(s). */
1516 ssh_pkt_getstring(pkt, &str, &slen);
1517 ssh_pkt_getstring(pkt, &str, &slen);
1518 ssh_pkt_getstring(pkt, &str, &slen);
1519 if (slen == 8 && !memcmp(str, "password", 8)) {
1520 ssh2_pkt_getbool(pkt);
1521 /* Blank the password field. */
1522 blanks[nblanks].offset = pkt->savedpos;
1523 blanks[nblanks].type = PKTLOG_BLANK;
1524 ssh_pkt_getstring(pkt, &str, &slen);
1526 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1528 /* If there's another password field beyond it (change of
1529 * password), blank that too. */
1530 ssh_pkt_getstring(pkt, &str, &slen);
1532 blanks[nblanks-1].len =
1533 pkt->savedpos - blanks[nblanks].offset;
1536 } else if (ssh->pkt_actx == SSH2_PKTCTX_KBDINTER &&
1537 pkt->type == SSH2_MSG_USERAUTH_INFO_RESPONSE &&
1538 conf_get_int(ssh->conf, CONF_logomitpass)) {
1539 /* If this is a keyboard-interactive response packet, blank
1542 ssh_pkt_getuint32(pkt);
1543 blanks[nblanks].offset = pkt->savedpos;
1544 blanks[nblanks].type = PKTLOG_BLANK;
1546 ssh_pkt_getstring(pkt, &str, &slen);
1550 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1552 } else if (pkt->type == SSH2_MSG_CHANNEL_REQUEST &&
1553 conf_get_int(ssh->conf, CONF_logomitpass)) {
1555 * If this is an X forwarding request packet, blank the fake
1558 * Note that while we blank the X authentication data here, we
1559 * don't take any special action to blank the start of an X11
1560 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1561 * an X connection without having session blanking enabled is
1562 * likely to leak your cookie into the log.
1565 ssh_pkt_getuint32(pkt);
1566 ssh_pkt_getstring(pkt, &str, &slen);
1567 if (slen == 7 && !memcmp(str, "x11-req", 0)) {
1568 ssh2_pkt_getbool(pkt);
1569 ssh2_pkt_getbool(pkt);
1570 ssh_pkt_getstring(pkt, &str, &slen);
1571 blanks[nblanks].offset = pkt->savedpos;
1572 blanks[nblanks].type = PKTLOG_BLANK;
1573 ssh_pkt_getstring(pkt, &str, &slen);
1575 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1581 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1582 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1583 pkt->body, pkt->length, nblanks, blanks,
1584 &ssh->v2_outgoing_sequence,
1585 pkt->downstream_id, pkt->additional_log_text);
1588 * Undo the above adjustment of pkt->length, to put the packet
1589 * back in the state we found it.
1591 pkt->length += (pkt->body - pkt->data);
1594 static struct Packet *ssh2_rdpkt(Ssh ssh, const unsigned char **data,
1597 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1599 crBegin(ssh->ssh2_rdpkt_crstate);
1601 st->pktin = ssh_new_packet();
1603 st->pktin->type = 0;
1604 st->pktin->length = 0;
1606 st->cipherblk = ssh->sccipher->blksize;
1609 if (st->cipherblk < 8)
1611 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1613 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1614 ssh->scmac && !ssh->scmac_etm) {
1616 * When dealing with a CBC-mode cipher, we want to avoid the
1617 * possibility of an attacker's tweaking the ciphertext stream
1618 * so as to cause us to feed the same block to the block
1619 * cipher more than once and thus leak information
1620 * (VU#958563). The way we do this is not to take any
1621 * decisions on the basis of anything we've decrypted until
1622 * we've verified it with a MAC. That includes the packet
1623 * length, so we just read data and check the MAC repeatedly,
1624 * and when the MAC passes, see if the length we've got is
1627 * This defence is unnecessary in OpenSSH ETM mode, because
1628 * the whole point of ETM mode is that the attacker can't
1629 * tweak the ciphertext stream at all without the MAC
1630 * detecting it before we decrypt anything.
1633 /* May as well allocate the whole lot now. */
1634 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1637 /* Read an amount corresponding to the MAC. */
1638 for (st->i = 0; st->i < st->maclen; st->i++) {
1639 while ((*datalen) == 0)
1641 st->pktin->data[st->i] = *(*data)++;
1647 unsigned char seq[4];
1648 ssh->scmac->start(ssh->sc_mac_ctx);
1649 PUT_32BIT(seq, st->incoming_sequence);
1650 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1653 for (;;) { /* Once around this loop per cipher block. */
1654 /* Read another cipher-block's worth, and tack it onto the end. */
1655 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1656 while ((*datalen) == 0)
1658 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1661 /* Decrypt one more block (a little further back in the stream). */
1662 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1663 st->pktin->data + st->packetlen,
1665 /* Feed that block to the MAC. */
1666 ssh->scmac->bytes(ssh->sc_mac_ctx,
1667 st->pktin->data + st->packetlen, st->cipherblk);
1668 st->packetlen += st->cipherblk;
1669 /* See if that gives us a valid packet. */
1670 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1671 st->pktin->data + st->packetlen) &&
1672 ((st->len = toint(GET_32BIT(st->pktin->data))) ==
1675 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1676 bombout(("No valid incoming packet found"));
1677 ssh_free_packet(st->pktin);
1681 st->pktin->maxlen = st->packetlen + st->maclen;
1682 st->pktin->data = sresize(st->pktin->data,
1683 st->pktin->maxlen + APIEXTRA,
1685 } else if (ssh->scmac && ssh->scmac_etm) {
1686 st->pktin->data = snewn(4 + APIEXTRA, unsigned char);
1689 * OpenSSH encrypt-then-MAC mode: the packet length is
1690 * unencrypted, unless the cipher supports length encryption.
1692 for (st->i = st->len = 0; st->i < 4; st->i++) {
1693 while ((*datalen) == 0)
1695 st->pktin->data[st->i] = *(*data)++;
1698 /* Cipher supports length decryption, so do it */
1699 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_SEPARATE_LENGTH)) {
1700 /* Keep the packet the same though, so the MAC passes */
1701 unsigned char len[4];
1702 memcpy(len, st->pktin->data, 4);
1703 ssh->sccipher->decrypt_length(ssh->sc_cipher_ctx, len, 4, st->incoming_sequence);
1704 st->len = toint(GET_32BIT(len));
1706 st->len = toint(GET_32BIT(st->pktin->data));
1710 * _Completely_ silly lengths should be stomped on before they
1711 * do us any more damage.
1713 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1714 st->len % st->cipherblk != 0) {
1715 bombout(("Incoming packet length field was garbled"));
1716 ssh_free_packet(st->pktin);
1721 * So now we can work out the total packet length.
1723 st->packetlen = st->len + 4;
1726 * Allocate memory for the rest of the packet.
1728 st->pktin->maxlen = st->packetlen + st->maclen;
1729 st->pktin->data = sresize(st->pktin->data,
1730 st->pktin->maxlen + APIEXTRA,
1734 * Read the remainder of the packet.
1736 for (st->i = 4; st->i < st->packetlen + st->maclen; st->i++) {
1737 while ((*datalen) == 0)
1739 st->pktin->data[st->i] = *(*data)++;
1747 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1748 st->len + 4, st->incoming_sequence)) {
1749 bombout(("Incorrect MAC received on packet"));
1750 ssh_free_packet(st->pktin);
1754 /* Decrypt everything between the length field and the MAC. */
1756 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1757 st->pktin->data + 4,
1760 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1763 * Acquire and decrypt the first block of the packet. This will
1764 * contain the length and padding details.
1766 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1767 while ((*datalen) == 0)
1769 st->pktin->data[st->i] = *(*data)++;
1774 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1775 st->pktin->data, st->cipherblk);
1778 * Now get the length figure.
1780 st->len = toint(GET_32BIT(st->pktin->data));
1783 * _Completely_ silly lengths should be stomped on before they
1784 * do us any more damage.
1786 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1787 (st->len + 4) % st->cipherblk != 0) {
1788 bombout(("Incoming packet was garbled on decryption"));
1789 ssh_free_packet(st->pktin);
1794 * So now we can work out the total packet length.
1796 st->packetlen = st->len + 4;
1799 * Allocate memory for the rest of the packet.
1801 st->pktin->maxlen = st->packetlen + st->maclen;
1802 st->pktin->data = sresize(st->pktin->data,
1803 st->pktin->maxlen + APIEXTRA,
1807 * Read and decrypt the remainder of the packet.
1809 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1811 while ((*datalen) == 0)
1813 st->pktin->data[st->i] = *(*data)++;
1816 /* Decrypt everything _except_ the MAC. */
1818 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1819 st->pktin->data + st->cipherblk,
1820 st->packetlen - st->cipherblk);
1826 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1827 st->len + 4, st->incoming_sequence)) {
1828 bombout(("Incorrect MAC received on packet"));
1829 ssh_free_packet(st->pktin);
1833 /* Get and sanity-check the amount of random padding. */
1834 st->pad = st->pktin->data[4];
1835 if (st->pad < 4 || st->len - st->pad < 1) {
1836 bombout(("Invalid padding length on received packet"));
1837 ssh_free_packet(st->pktin);
1841 * This enables us to deduce the payload length.
1843 st->payload = st->len - st->pad - 1;
1845 st->pktin->length = st->payload + 5;
1846 st->pktin->encrypted_len = st->packetlen;
1848 st->pktin->sequence = st->incoming_sequence++;
1850 st->pktin->length = st->packetlen - st->pad;
1851 assert(st->pktin->length >= 0);
1854 * Decompress packet payload.
1857 unsigned char *newpayload;
1860 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1861 st->pktin->data + 5, st->pktin->length - 5,
1862 &newpayload, &newlen)) {
1863 if (st->pktin->maxlen < newlen + 5) {
1864 st->pktin->maxlen = newlen + 5;
1865 st->pktin->data = sresize(st->pktin->data,
1866 st->pktin->maxlen + APIEXTRA,
1869 st->pktin->length = 5 + newlen;
1870 memcpy(st->pktin->data + 5, newpayload, newlen);
1876 * RFC 4253 doesn't explicitly say that completely empty packets
1877 * with no type byte are forbidden, so treat them as deserving
1878 * an SSH_MSG_UNIMPLEMENTED.
1880 if (st->pktin->length <= 5) { /* == 5 we hope, but robustness */
1881 ssh2_msg_something_unimplemented(ssh, st->pktin);
1885 * pktin->body and pktin->length should identify the semantic
1886 * content of the packet, excluding the initial type byte.
1888 st->pktin->type = st->pktin->data[5];
1889 st->pktin->body = st->pktin->data + 6;
1890 st->pktin->length -= 6;
1891 assert(st->pktin->length >= 0); /* one last double-check */
1894 ssh2_log_incoming_packet(ssh, st->pktin);
1896 st->pktin->savedpos = 0;
1898 crFinish(st->pktin);
1901 static struct Packet *ssh2_bare_connection_rdpkt(Ssh ssh,
1902 const unsigned char **data,
1905 struct rdpkt2_bare_state_tag *st = &ssh->rdpkt2_bare_state;
1907 crBegin(ssh->ssh2_bare_rdpkt_crstate);
1910 * Read the packet length field.
1912 for (st->i = 0; st->i < 4; st->i++) {
1913 while ((*datalen) == 0)
1915 st->length[st->i] = *(*data)++;
1919 st->packetlen = toint(GET_32BIT_MSB_FIRST(st->length));
1920 if (st->packetlen <= 0 || st->packetlen >= OUR_V2_PACKETLIMIT) {
1921 bombout(("Invalid packet length received"));
1925 st->pktin = ssh_new_packet();
1926 st->pktin->data = snewn(st->packetlen, unsigned char);
1928 st->pktin->encrypted_len = st->packetlen;
1930 st->pktin->sequence = st->incoming_sequence++;
1933 * Read the remainder of the packet.
1935 for (st->i = 0; st->i < st->packetlen; st->i++) {
1936 while ((*datalen) == 0)
1938 st->pktin->data[st->i] = *(*data)++;
1943 * pktin->body and pktin->length should identify the semantic
1944 * content of the packet, excluding the initial type byte.
1946 st->pktin->type = st->pktin->data[0];
1947 st->pktin->body = st->pktin->data + 1;
1948 st->pktin->length = st->packetlen - 1;
1951 * Log incoming packet, possibly omitting sensitive fields.
1954 ssh2_log_incoming_packet(ssh, st->pktin);
1956 st->pktin->savedpos = 0;
1958 crFinish(st->pktin);
1961 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1963 int pad, biglen, i, pktoffs;
1967 * XXX various versions of SC (including 8.8.4) screw up the
1968 * register allocation in this function and use the same register
1969 * (D6) for len and as a temporary, with predictable results. The
1970 * following sledgehammer prevents this.
1977 ssh1_log_outgoing_packet(ssh, pkt);
1979 if (ssh->v1_compressing) {
1980 unsigned char *compblk;
1982 zlib_compress_block(ssh->cs_comp_ctx,
1983 pkt->data + 12, pkt->length - 12,
1984 &compblk, &complen);
1985 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1986 memcpy(pkt->data + 12, compblk, complen);
1988 pkt->length = complen + 12;
1991 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1993 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1994 pad = 8 - (len % 8);
1996 biglen = len + pad; /* len(padding+type+data+CRC) */
1998 for (i = pktoffs; i < 4+8; i++)
1999 pkt->data[i] = random_byte();
2000 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
2001 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
2002 PUT_32BIT(pkt->data + pktoffs, len);
2005 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
2006 pkt->data + pktoffs + 4, biglen);
2008 if (offset_p) *offset_p = pktoffs;
2009 return biglen + 4; /* len(length+padding+type+data+CRC) */
2012 static int s_write(Ssh ssh, void *data, int len)
2015 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
2016 0, NULL, NULL, 0, NULL);
2019 return sk_write(ssh->s, (char *)data, len);
2022 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
2024 int len, backlog, offset;
2025 len = s_wrpkt_prepare(ssh, pkt, &offset);
2026 backlog = s_write(ssh, pkt->data + offset, len);
2027 if (backlog > SSH_MAX_BACKLOG)
2028 ssh_throttle_all(ssh, 1, backlog);
2029 ssh_free_packet(pkt);
2032 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
2035 len = s_wrpkt_prepare(ssh, pkt, &offset);
2036 if (ssh->deferred_len + len > ssh->deferred_size) {
2037 ssh->deferred_size = ssh->deferred_len + len + 128;
2038 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2042 memcpy(ssh->deferred_send_data + ssh->deferred_len,
2043 pkt->data + offset, len);
2044 ssh->deferred_len += len;
2045 ssh_free_packet(pkt);
2049 * Construct a SSH-1 packet with the specified contents.
2050 * (This all-at-once interface used to be the only one, but now SSH-1
2051 * packets can also be constructed incrementally.)
2053 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
2059 pkt = ssh1_pkt_init(pkttype);
2061 while ((argtype = va_arg(ap, int)) != PKT_END) {
2062 unsigned char *argp, argchar;
2064 unsigned long argint;
2067 /* Actual fields in the packet */
2069 argint = va_arg(ap, int);
2070 ssh_pkt_adduint32(pkt, argint);
2073 argchar = (unsigned char) va_arg(ap, int);
2074 ssh_pkt_addbyte(pkt, argchar);
2077 argp = va_arg(ap, unsigned char *);
2078 arglen = va_arg(ap, int);
2079 ssh_pkt_adddata(pkt, argp, arglen);
2082 sargp = va_arg(ap, char *);
2083 ssh_pkt_addstring(pkt, sargp);
2086 bn = va_arg(ap, Bignum);
2087 ssh1_pkt_addmp(pkt, bn);
2095 static void send_packet(Ssh ssh, int pkttype, ...)
2099 va_start(ap, pkttype);
2100 pkt = construct_packet(ssh, pkttype, ap);
2105 static void defer_packet(Ssh ssh, int pkttype, ...)
2109 va_start(ap, pkttype);
2110 pkt = construct_packet(ssh, pkttype, ap);
2112 s_wrpkt_defer(ssh, pkt);
2115 static int ssh_versioncmp(const char *a, const char *b)
2118 unsigned long av, bv;
2120 av = strtoul(a, &ae, 10);
2121 bv = strtoul(b, &be, 10);
2123 return (av < bv ? -1 : +1);
2128 av = strtoul(ae, &ae, 10);
2129 bv = strtoul(be, &be, 10);
2131 return (av < bv ? -1 : +1);
2136 * Utility routines for putting an SSH-protocol `string' and
2137 * `uint32' into a hash state.
2139 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
2141 unsigned char lenblk[4];
2142 PUT_32BIT(lenblk, len);
2143 h->bytes(s, lenblk, 4);
2144 h->bytes(s, str, len);
2147 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
2149 unsigned char intblk[4];
2150 PUT_32BIT(intblk, i);
2151 h->bytes(s, intblk, 4);
2155 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
2157 static void ssh_pkt_ensure(struct Packet *pkt, int length)
2159 if (pkt->maxlen < length) {
2160 unsigned char *body = pkt->body;
2161 int offset = body ? body - pkt->data : 0;
2162 pkt->maxlen = length + 256;
2163 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
2164 if (body) pkt->body = pkt->data + offset;
2167 static void ssh_pkt_adddata(struct Packet *pkt, const void *data, int len)
2170 ssh_pkt_ensure(pkt, pkt->length);
2171 memcpy(pkt->data + pkt->length - len, data, len);
2173 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
2175 ssh_pkt_adddata(pkt, &byte, 1);
2177 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
2179 ssh_pkt_adddata(pkt, &value, 1);
2181 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
2184 PUT_32BIT(x, value);
2185 ssh_pkt_adddata(pkt, x, 4);
2187 static void ssh_pkt_addstring_start(struct Packet *pkt)
2189 ssh_pkt_adduint32(pkt, 0);
2190 pkt->savedpos = pkt->length;
2192 static void ssh_pkt_addstring_data(struct Packet *pkt, const char *data,
2195 ssh_pkt_adddata(pkt, data, len);
2196 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
2198 static void ssh_pkt_addstring_str(struct Packet *pkt, const char *data)
2200 ssh_pkt_addstring_data(pkt, data, strlen(data));
2202 static void ssh_pkt_addstring(struct Packet *pkt, const char *data)
2204 ssh_pkt_addstring_start(pkt);
2205 ssh_pkt_addstring_str(pkt, data);
2207 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
2209 int len = ssh1_bignum_length(b);
2210 unsigned char *data = snewn(len, unsigned char);
2211 (void) ssh1_write_bignum(data, b);
2212 ssh_pkt_adddata(pkt, data, len);
2215 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
2218 int i, n = (bignum_bitcount(b) + 7) / 8;
2219 p = snewn(n + 1, unsigned char);
2221 for (i = 1; i <= n; i++)
2222 p[i] = bignum_byte(b, n - i);
2224 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
2226 memmove(p, p + i, n + 1 - i);
2230 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
2234 p = ssh2_mpint_fmt(b, &len);
2235 ssh_pkt_addstring_start(pkt);
2236 ssh_pkt_addstring_data(pkt, (char *)p, len);
2240 static struct Packet *ssh1_pkt_init(int pkt_type)
2242 struct Packet *pkt = ssh_new_packet();
2243 pkt->length = 4 + 8; /* space for length + max padding */
2244 ssh_pkt_addbyte(pkt, pkt_type);
2245 pkt->body = pkt->data + pkt->length;
2246 pkt->type = pkt_type;
2247 pkt->downstream_id = 0;
2248 pkt->additional_log_text = NULL;
2252 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
2253 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
2254 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
2255 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
2256 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
2257 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
2258 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
2259 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
2260 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
2262 static struct Packet *ssh2_pkt_init(int pkt_type)
2264 struct Packet *pkt = ssh_new_packet();
2265 pkt->length = 5; /* space for packet length + padding length */
2267 pkt->type = pkt_type;
2268 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
2269 pkt->body = pkt->data + pkt->length; /* after packet type */
2270 pkt->downstream_id = 0;
2271 pkt->additional_log_text = NULL;
2276 * Construct an SSH-2 final-form packet: compress it, encrypt it,
2277 * put the MAC on it. Final packet, ready to be sent, is stored in
2278 * pkt->data. Total length is returned.
2280 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
2282 int cipherblk, maclen, padding, unencrypted_prefix, i;
2285 ssh2_log_outgoing_packet(ssh, pkt);
2287 if (ssh->bare_connection) {
2289 * Trivial packet construction for the bare connection
2292 PUT_32BIT(pkt->data + 1, pkt->length - 5);
2293 pkt->body = pkt->data + 1;
2294 ssh->v2_outgoing_sequence++; /* only for diagnostics, really */
2295 return pkt->length - 1;
2299 * Compress packet payload.
2302 unsigned char *newpayload;
2305 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
2307 &newpayload, &newlen)) {
2309 ssh2_pkt_adddata(pkt, newpayload, newlen);
2315 * Add padding. At least four bytes, and must also bring total
2316 * length (minus MAC) up to a multiple of the block size.
2317 * If pkt->forcepad is set, make sure the packet is at least that size
2320 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
2321 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
2323 unencrypted_prefix = (ssh->csmac && ssh->csmac_etm) ? 4 : 0;
2324 if (pkt->length + padding < pkt->forcepad)
2325 padding = pkt->forcepad - pkt->length;
2327 (cipherblk - (pkt->length - unencrypted_prefix + padding) % cipherblk)
2329 assert(padding <= 255);
2330 maclen = ssh->csmac ? ssh->csmac->len : 0;
2331 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
2332 pkt->data[4] = padding;
2333 for (i = 0; i < padding; i++)
2334 pkt->data[pkt->length + i] = random_byte();
2335 PUT_32BIT(pkt->data, pkt->length + padding - 4);
2337 /* Encrypt length if the scheme requires it */
2338 if (ssh->cscipher && (ssh->cscipher->flags & SSH_CIPHER_SEPARATE_LENGTH)) {
2339 ssh->cscipher->encrypt_length(ssh->cs_cipher_ctx, pkt->data, 4,
2340 ssh->v2_outgoing_sequence);
2343 if (ssh->csmac && ssh->csmac_etm) {
2345 * OpenSSH-defined encrypt-then-MAC protocol.
2348 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2349 pkt->data + 4, pkt->length + padding - 4);
2350 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2351 pkt->length + padding,
2352 ssh->v2_outgoing_sequence);
2355 * SSH-2 standard protocol.
2358 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2359 pkt->length + padding,
2360 ssh->v2_outgoing_sequence);
2362 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2363 pkt->data, pkt->length + padding);
2366 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
2367 pkt->encrypted_len = pkt->length + padding;
2369 /* Ready-to-send packet starts at pkt->data. We return length. */
2370 pkt->body = pkt->data;
2371 return pkt->length + padding + maclen;
2375 * Routines called from the main SSH code to send packets. There
2376 * are quite a few of these, because we have two separate
2377 * mechanisms for delaying the sending of packets:
2379 * - In order to send an IGNORE message and a password message in
2380 * a single fixed-length blob, we require the ability to
2381 * concatenate the encrypted forms of those two packets _into_ a
2382 * single blob and then pass it to our <network.h> transport
2383 * layer in one go. Hence, there's a deferment mechanism which
2384 * works after packet encryption.
2386 * - In order to avoid sending any connection-layer messages
2387 * during repeat key exchange, we have to queue up any such
2388 * outgoing messages _before_ they are encrypted (and in
2389 * particular before they're allocated sequence numbers), and
2390 * then send them once we've finished.
2392 * I call these mechanisms `defer' and `queue' respectively, so as
2393 * to distinguish them reasonably easily.
2395 * The functions send_noqueue() and defer_noqueue() free the packet
2396 * structure they are passed. Every outgoing packet goes through
2397 * precisely one of these functions in its life; packets passed to
2398 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
2399 * these or get queued, and then when the queue is later emptied
2400 * the packets are all passed to defer_noqueue().
2402 * When using a CBC-mode cipher, it's necessary to ensure that an
2403 * attacker can't provide data to be encrypted using an IV that they
2404 * know. We ensure this by prefixing each packet that might contain
2405 * user data with an SSH_MSG_IGNORE. This is done using the deferral
2406 * mechanism, so in this case send_noqueue() ends up redirecting to
2407 * defer_noqueue(). If you don't like this inefficiency, don't use
2411 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
2412 static void ssh_pkt_defersend(Ssh);
2415 * Send an SSH-2 packet immediately, without queuing or deferring.
2417 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
2421 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
2422 /* We need to send two packets, so use the deferral mechanism. */
2423 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2424 ssh_pkt_defersend(ssh);
2427 len = ssh2_pkt_construct(ssh, pkt);
2428 backlog = s_write(ssh, pkt->body, len);
2429 if (backlog > SSH_MAX_BACKLOG)
2430 ssh_throttle_all(ssh, 1, backlog);
2432 ssh->outgoing_data_size += pkt->encrypted_len;
2433 if (!ssh->kex_in_progress &&
2434 !ssh->bare_connection &&
2435 ssh->max_data_size != 0 &&
2436 ssh->outgoing_data_size > ssh->max_data_size)
2437 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2439 ssh_free_packet(pkt);
2443 * Defer an SSH-2 packet.
2445 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2448 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2449 ssh->deferred_len == 0 && !noignore &&
2450 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2452 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2453 * get encrypted with a known IV.
2455 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2456 ssh2_pkt_addstring_start(ipkt);
2457 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2459 len = ssh2_pkt_construct(ssh, pkt);
2460 if (ssh->deferred_len + len > ssh->deferred_size) {
2461 ssh->deferred_size = ssh->deferred_len + len + 128;
2462 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2466 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->body, len);
2467 ssh->deferred_len += len;
2468 ssh->deferred_data_size += pkt->encrypted_len;
2469 ssh_free_packet(pkt);
2473 * Queue an SSH-2 packet.
2475 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2477 assert(ssh->queueing);
2479 if (ssh->queuelen >= ssh->queuesize) {
2480 ssh->queuesize = ssh->queuelen + 32;
2481 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2484 ssh->queue[ssh->queuelen++] = pkt;
2488 * Either queue or send a packet, depending on whether queueing is
2491 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2494 ssh2_pkt_queue(ssh, pkt);
2496 ssh2_pkt_send_noqueue(ssh, pkt);
2500 * Either queue or defer a packet, depending on whether queueing is
2503 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2506 ssh2_pkt_queue(ssh, pkt);
2508 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2512 * Send the whole deferred data block constructed by
2513 * ssh2_pkt_defer() or SSH-1's defer_packet().
2515 * The expected use of the defer mechanism is that you call
2516 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2517 * not currently queueing, this simply sets up deferred_send_data
2518 * and then sends it. If we _are_ currently queueing, the calls to
2519 * ssh2_pkt_defer() put the deferred packets on to the queue
2520 * instead, and therefore ssh_pkt_defersend() has no deferred data
2521 * to send. Hence, there's no need to make it conditional on
2524 static void ssh_pkt_defersend(Ssh ssh)
2527 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2528 ssh->deferred_len = ssh->deferred_size = 0;
2529 sfree(ssh->deferred_send_data);
2530 ssh->deferred_send_data = NULL;
2531 if (backlog > SSH_MAX_BACKLOG)
2532 ssh_throttle_all(ssh, 1, backlog);
2534 if (ssh->version == 2) {
2535 ssh->outgoing_data_size += ssh->deferred_data_size;
2536 ssh->deferred_data_size = 0;
2537 if (!ssh->kex_in_progress &&
2538 !ssh->bare_connection &&
2539 ssh->max_data_size != 0 &&
2540 ssh->outgoing_data_size > ssh->max_data_size)
2541 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2546 * Send a packet whose length needs to be disguised (typically
2547 * passwords or keyboard-interactive responses).
2549 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2555 * The simplest way to do this is to adjust the
2556 * variable-length padding field in the outgoing packet.
2558 * Currently compiled out, because some Cisco SSH servers
2559 * don't like excessively padded packets (bah, why's it
2562 pkt->forcepad = padsize;
2563 ssh2_pkt_send(ssh, pkt);
2568 * If we can't do that, however, an alternative approach is
2569 * to use the pkt_defer mechanism to bundle the packet
2570 * tightly together with an SSH_MSG_IGNORE such that their
2571 * combined length is a constant. So first we construct the
2572 * final form of this packet and defer its sending.
2574 ssh2_pkt_defer(ssh, pkt);
2577 * Now construct an SSH_MSG_IGNORE which includes a string
2578 * that's an exact multiple of the cipher block size. (If
2579 * the cipher is NULL so that the block size is
2580 * unavailable, we don't do this trick at all, because we
2581 * gain nothing by it.)
2583 if (ssh->cscipher &&
2584 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2587 stringlen = (256 - ssh->deferred_len);
2588 stringlen += ssh->cscipher->blksize - 1;
2589 stringlen -= (stringlen % ssh->cscipher->blksize);
2592 * Temporarily disable actual compression, so we
2593 * can guarantee to get this string exactly the
2594 * length we want it. The compression-disabling
2595 * routine should return an integer indicating how
2596 * many bytes we should adjust our string length
2600 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2602 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2603 ssh2_pkt_addstring_start(pkt);
2604 for (i = 0; i < stringlen; i++) {
2605 char c = (char) random_byte();
2606 ssh2_pkt_addstring_data(pkt, &c, 1);
2608 ssh2_pkt_defer(ssh, pkt);
2610 ssh_pkt_defersend(ssh);
2615 * Send all queued SSH-2 packets. We send them by means of
2616 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2617 * packets that needed to be lumped together.
2619 static void ssh2_pkt_queuesend(Ssh ssh)
2623 assert(!ssh->queueing);
2625 for (i = 0; i < ssh->queuelen; i++)
2626 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2629 ssh_pkt_defersend(ssh);
2633 void bndebug(char *string, Bignum b)
2637 p = ssh2_mpint_fmt(b, &len);
2638 debug(("%s", string));
2639 for (i = 0; i < len; i++)
2640 debug((" %02x", p[i]));
2646 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2650 p = ssh2_mpint_fmt(b, &len);
2651 hash_string(h, s, p, len);
2656 * Packet decode functions for both SSH-1 and SSH-2.
2658 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2660 unsigned long value;
2661 if (pkt->length - pkt->savedpos < 4)
2662 return 0; /* arrgh, no way to decline (FIXME?) */
2663 value = GET_32BIT(pkt->body + pkt->savedpos);
2667 static int ssh2_pkt_getbool(struct Packet *pkt)
2669 unsigned long value;
2670 if (pkt->length - pkt->savedpos < 1)
2671 return 0; /* arrgh, no way to decline (FIXME?) */
2672 value = pkt->body[pkt->savedpos] != 0;
2676 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2681 if (pkt->length - pkt->savedpos < 4)
2683 len = toint(GET_32BIT(pkt->body + pkt->savedpos));
2688 if (pkt->length - pkt->savedpos < *length)
2690 *p = (char *)(pkt->body + pkt->savedpos);
2691 pkt->savedpos += *length;
2693 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2695 if (pkt->length - pkt->savedpos < length)
2697 pkt->savedpos += length;
2698 return pkt->body + (pkt->savedpos - length);
2700 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2701 const unsigned char **keystr)
2705 j = makekey(pkt->body + pkt->savedpos,
2706 pkt->length - pkt->savedpos,
2713 assert(pkt->savedpos < pkt->length);
2717 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2722 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2723 pkt->length - pkt->savedpos, &b);
2731 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2737 ssh_pkt_getstring(pkt, &p, &length);
2742 b = bignum_from_bytes((unsigned char *)p, length);
2747 * Helper function to add an SSH-2 signature blob to a packet.
2748 * Expects to be shown the public key blob as well as the signature
2749 * blob. Normally works just like ssh2_pkt_addstring, but will
2750 * fiddle with the signature packet if necessary for
2751 * BUG_SSH2_RSA_PADDING.
2753 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2754 void *pkblob_v, int pkblob_len,
2755 void *sigblob_v, int sigblob_len)
2757 unsigned char *pkblob = (unsigned char *)pkblob_v;
2758 unsigned char *sigblob = (unsigned char *)sigblob_v;
2760 /* dmemdump(pkblob, pkblob_len); */
2761 /* dmemdump(sigblob, sigblob_len); */
2764 * See if this is in fact an ssh-rsa signature and a buggy
2765 * server; otherwise we can just do this the easy way.
2767 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) && pkblob_len > 4+7+4 &&
2768 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2769 int pos, len, siglen;
2772 * Find the byte length of the modulus.
2775 pos = 4+7; /* skip over "ssh-rsa" */
2776 len = toint(GET_32BIT(pkblob+pos)); /* get length of exponent */
2777 if (len < 0 || len > pkblob_len - pos - 4)
2779 pos += 4 + len; /* skip over exponent */
2780 if (pkblob_len - pos < 4)
2782 len = toint(GET_32BIT(pkblob+pos)); /* find length of modulus */
2783 if (len < 0 || len > pkblob_len - pos - 4)
2785 pos += 4; /* find modulus itself */
2786 while (len > 0 && pkblob[pos] == 0)
2788 /* debug(("modulus length is %d\n", len)); */
2791 * Now find the signature integer.
2793 pos = 4+7; /* skip over "ssh-rsa" */
2794 if (sigblob_len < pos+4)
2796 siglen = toint(GET_32BIT(sigblob+pos));
2797 if (siglen != sigblob_len - pos - 4)
2799 /* debug(("signature length is %d\n", siglen)); */
2801 if (len != siglen) {
2802 unsigned char newlen[4];
2803 ssh2_pkt_addstring_start(pkt);
2804 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2805 /* dmemdump(sigblob, pos); */
2806 pos += 4; /* point to start of actual sig */
2807 PUT_32BIT(newlen, len);
2808 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2809 /* dmemdump(newlen, 4); */
2811 while (len-- > siglen) {
2812 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2813 /* dmemdump(newlen, 1); */
2815 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2816 /* dmemdump(sigblob+pos, siglen); */
2820 /* Otherwise fall through and do it the easy way. We also come
2821 * here as a fallback if we discover above that the key blob
2822 * is misformatted in some way. */
2826 ssh2_pkt_addstring_start(pkt);
2827 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2831 * Examine the remote side's version string and compare it against
2832 * a list of known buggy implementations.
2834 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2836 char *imp; /* pointer to implementation part */
2838 imp += strcspn(imp, "-");
2840 imp += strcspn(imp, "-");
2843 ssh->remote_bugs = 0;
2846 * General notes on server version strings:
2847 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2848 * here -- in particular, we've heard of one that's perfectly happy
2849 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2850 * so we can't distinguish them.
2852 if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
2853 (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
2854 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2855 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2856 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2857 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2859 * These versions don't support SSH1_MSG_IGNORE, so we have
2860 * to use a different defence against password length
2863 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2864 logevent("We believe remote version has SSH-1 ignore bug");
2867 if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
2868 (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
2869 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2871 * These versions need a plain password sent; they can't
2872 * handle having a null and a random length of data after
2875 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2876 logevent("We believe remote version needs a plain SSH-1 password");
2879 if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
2880 (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
2881 (!strcmp(imp, "Cisco-1.25")))) {
2883 * These versions apparently have no clue whatever about
2884 * RSA authentication and will panic and die if they see
2885 * an AUTH_RSA message.
2887 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2888 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2891 if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
2892 (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
2893 !wc_match("* VShell", imp) &&
2894 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2895 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2896 wc_match("2.1 *", imp)))) {
2898 * These versions have the HMAC bug.
2900 ssh->remote_bugs |= BUG_SSH2_HMAC;
2901 logevent("We believe remote version has SSH-2 HMAC bug");
2904 if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
2905 (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
2906 !wc_match("* VShell", imp) &&
2907 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2909 * These versions have the key-derivation bug (failing to
2910 * include the literal shared secret in the hashes that
2911 * generate the keys).
2913 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2914 logevent("We believe remote version has SSH-2 key-derivation bug");
2917 if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
2918 (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
2919 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2920 wc_match("OpenSSH_3.[0-2]*", imp) ||
2921 wc_match("mod_sftp/0.[0-8]*", imp) ||
2922 wc_match("mod_sftp/0.9.[0-8]", imp)))) {
2924 * These versions have the SSH-2 RSA padding bug.
2926 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2927 logevent("We believe remote version has SSH-2 RSA padding bug");
2930 if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
2931 (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
2932 wc_match("OpenSSH_2.[0-2]*", imp))) {
2934 * These versions have the SSH-2 session-ID bug in
2935 * public-key authentication.
2937 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2938 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2941 if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
2942 (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
2943 (wc_match("DigiSSH_2.0", imp) ||
2944 wc_match("OpenSSH_2.[0-4]*", imp) ||
2945 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2946 wc_match("Sun_SSH_1.0", imp) ||
2947 wc_match("Sun_SSH_1.0.1", imp) ||
2948 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2949 wc_match("WeOnlyDo-*", imp)))) {
2951 * These versions have the SSH-2 rekey bug.
2953 ssh->remote_bugs |= BUG_SSH2_REKEY;
2954 logevent("We believe remote version has SSH-2 rekey bug");
2957 if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
2958 (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
2959 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2960 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2962 * This version ignores our makpkt and needs to be throttled.
2964 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2965 logevent("We believe remote version ignores SSH-2 maximum packet size");
2968 if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
2970 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2971 * none detected automatically.
2973 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2974 logevent("We believe remote version has SSH-2 ignore bug");
2977 if (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == FORCE_ON ||
2978 (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == AUTO &&
2979 (wc_match("OpenSSH_2.[235]*", imp)))) {
2981 * These versions only support the original (pre-RFC4419)
2982 * SSH-2 GEX request, and disconnect with a protocol error if
2983 * we use the newer version.
2985 ssh->remote_bugs |= BUG_SSH2_OLDGEX;
2986 logevent("We believe remote version has outdated SSH-2 GEX");
2989 if (conf_get_int(ssh->conf, CONF_sshbug_winadj) == FORCE_ON) {
2991 * Servers that don't support our winadj request for one
2992 * reason or another. Currently, none detected automatically.
2994 ssh->remote_bugs |= BUG_CHOKES_ON_WINADJ;
2995 logevent("We believe remote version has winadj bug");
2998 if (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == FORCE_ON ||
2999 (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == AUTO &&
3000 (wc_match("OpenSSH_[2-5].*", imp) ||
3001 wc_match("OpenSSH_6.[0-6]*", imp) ||
3002 wc_match("dropbear_0.[2-4][0-9]*", imp) ||
3003 wc_match("dropbear_0.5[01]*", imp)))) {
3005 * These versions have the SSH-2 channel request bug.
3006 * OpenSSH 6.7 and above do not:
3007 * https://bugzilla.mindrot.org/show_bug.cgi?id=1818
3008 * dropbear_0.52 and above do not:
3009 * https://secure.ucc.asn.au/hg/dropbear/rev/cd02449b709c
3011 ssh->remote_bugs |= BUG_SENDS_LATE_REQUEST_REPLY;
3012 logevent("We believe remote version has SSH-2 channel request bug");
3017 * The `software version' part of an SSH version string is required
3018 * to contain no spaces or minus signs.
3020 static void ssh_fix_verstring(char *str)
3022 /* Eat "<protoversion>-". */
3023 while (*str && *str != '-') str++;
3024 assert(*str == '-'); str++;
3026 /* Convert minus signs and spaces in the remaining string into
3029 if (*str == '-' || *str == ' ')
3036 * Send an appropriate SSH version string.
3038 static void ssh_send_verstring(Ssh ssh, const char *protoname, char *svers)
3042 if (ssh->version == 2) {
3044 * Construct a v2 version string.
3046 verstring = dupprintf("%s2.0-%s\015\012", protoname, sshver);
3049 * Construct a v1 version string.
3051 assert(!strcmp(protoname, "SSH-")); /* no v1 bare connection protocol */
3052 verstring = dupprintf("SSH-%s-%s\012",
3053 (ssh_versioncmp(svers, "1.5") <= 0 ?
3058 ssh_fix_verstring(verstring + strlen(protoname));
3060 /* FUZZING make PuTTY insecure, so make live use difficult. */
3064 if (ssh->version == 2) {
3067 * Record our version string.
3069 len = strcspn(verstring, "\015\012");
3070 ssh->v_c = snewn(len + 1, char);
3071 memcpy(ssh->v_c, verstring, len);
3075 logeventf(ssh, "We claim version: %.*s",
3076 strcspn(verstring, "\015\012"), verstring);
3077 s_write(ssh, verstring, strlen(verstring));
3081 static int do_ssh_init(Ssh ssh, unsigned char c)
3083 static const char protoname[] = "SSH-";
3085 struct do_ssh_init_state {
3094 crState(do_ssh_init_state);
3098 /* Search for a line beginning with the protocol name prefix in
3101 for (s->i = 0; protoname[s->i]; s->i++) {
3102 if ((char)c != protoname[s->i]) goto no;
3112 ssh->session_started = TRUE;
3114 s->vstrsize = sizeof(protoname) + 16;
3115 s->vstring = snewn(s->vstrsize, char);
3116 strcpy(s->vstring, protoname);
3117 s->vslen = strlen(protoname);
3120 if (s->vslen >= s->vstrsize - 1) {
3122 s->vstring = sresize(s->vstring, s->vstrsize, char);
3124 s->vstring[s->vslen++] = c;
3127 s->version[s->i] = '\0';
3129 } else if (s->i < sizeof(s->version) - 1)
3130 s->version[s->i++] = c;
3131 } else if (c == '\012')
3133 crReturn(1); /* get another char */
3136 ssh->agentfwd_enabled = FALSE;
3137 ssh->rdpkt2_state.incoming_sequence = 0;
3139 s->vstring[s->vslen] = 0;
3140 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3141 logeventf(ssh, "Server version: %s", s->vstring);
3142 ssh_detect_bugs(ssh, s->vstring);
3145 * Decide which SSH protocol version to support.
3148 /* Anything strictly below "2.0" means protocol 1 is supported. */
3149 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
3150 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
3151 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
3153 if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
3155 bombout(("SSH protocol version 1 required by our configuration "
3156 "but not provided by server"));
3159 } else if (conf_get_int(ssh->conf, CONF_sshprot) == 3) {
3161 bombout(("SSH protocol version 2 required by our configuration "
3162 "but server only provides (old, insecure) SSH-1"));
3166 /* No longer support values 1 or 2 for CONF_sshprot */
3167 assert(!"Unexpected value for CONF_sshprot");
3170 if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
3175 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
3177 /* Send the version string, if we haven't already */
3178 if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
3179 ssh_send_verstring(ssh, protoname, s->version);
3181 if (ssh->version == 2) {
3184 * Record their version string.
3186 len = strcspn(s->vstring, "\015\012");
3187 ssh->v_s = snewn(len + 1, char);
3188 memcpy(ssh->v_s, s->vstring, len);
3192 * Initialise SSH-2 protocol.
3194 ssh->protocol = ssh2_protocol;
3195 ssh2_protocol_setup(ssh);
3196 ssh->s_rdpkt = ssh2_rdpkt;
3199 * Initialise SSH-1 protocol.
3201 ssh->protocol = ssh1_protocol;
3202 ssh1_protocol_setup(ssh);
3203 ssh->s_rdpkt = ssh1_rdpkt;
3205 if (ssh->version == 2)
3206 do_ssh2_transport(ssh, NULL, -1, NULL);
3208 update_specials_menu(ssh->frontend);
3209 ssh->state = SSH_STATE_BEFORE_SIZE;
3210 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3217 static int do_ssh_connection_init(Ssh ssh, unsigned char c)
3220 * Ordinary SSH begins with the banner "SSH-x.y-...". This is just
3221 * the ssh-connection part, extracted and given a trivial binary
3222 * packet protocol, so we replace 'SSH-' at the start with a new
3223 * name. In proper SSH style (though of course this part of the
3224 * proper SSH protocol _isn't_ subject to this kind of
3225 * DNS-domain-based extension), we define the new name in our
3228 static const char protoname[] =
3229 "SSHCONNECTION@putty.projects.tartarus.org-";
3231 struct do_ssh_connection_init_state {
3239 crState(do_ssh_connection_init_state);
3243 /* Search for a line beginning with the protocol name prefix in
3246 for (s->i = 0; protoname[s->i]; s->i++) {
3247 if ((char)c != protoname[s->i]) goto no;
3257 s->vstrsize = sizeof(protoname) + 16;
3258 s->vstring = snewn(s->vstrsize, char);
3259 strcpy(s->vstring, protoname);
3260 s->vslen = strlen(protoname);
3263 if (s->vslen >= s->vstrsize - 1) {
3265 s->vstring = sresize(s->vstring, s->vstrsize, char);
3267 s->vstring[s->vslen++] = c;
3270 s->version[s->i] = '\0';
3272 } else if (s->i < sizeof(s->version) - 1)
3273 s->version[s->i++] = c;
3274 } else if (c == '\012')
3276 crReturn(1); /* get another char */
3279 ssh->agentfwd_enabled = FALSE;
3280 ssh->rdpkt2_bare_state.incoming_sequence = 0;
3282 s->vstring[s->vslen] = 0;
3283 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3284 logeventf(ssh, "Server version: %s", s->vstring);
3285 ssh_detect_bugs(ssh, s->vstring);
3288 * Decide which SSH protocol version to support. This is easy in
3289 * bare ssh-connection mode: only 2.0 is legal.
3291 if (ssh_versioncmp(s->version, "2.0") < 0) {
3292 bombout(("Server announces compatibility with SSH-1 in bare ssh-connection protocol"));
3295 if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
3296 bombout(("Bare ssh-connection protocol cannot be run in SSH-1-only mode"));
3302 logeventf(ssh, "Using bare ssh-connection protocol");
3304 /* Send the version string, if we haven't already */
3305 ssh_send_verstring(ssh, protoname, s->version);
3308 * Initialise bare connection protocol.
3310 ssh->protocol = ssh2_bare_connection_protocol;
3311 ssh2_bare_connection_protocol_setup(ssh);
3312 ssh->s_rdpkt = ssh2_bare_connection_rdpkt;
3314 update_specials_menu(ssh->frontend);
3315 ssh->state = SSH_STATE_BEFORE_SIZE;
3316 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3319 * Get authconn (really just conn) under way.
3321 do_ssh2_authconn(ssh, NULL, 0, NULL);
3328 static void ssh_process_incoming_data(Ssh ssh,
3329 const unsigned char **data, int *datalen)
3331 struct Packet *pktin;
3333 pktin = ssh->s_rdpkt(ssh, data, datalen);
3335 ssh->protocol(ssh, NULL, 0, pktin);
3336 ssh_free_packet(pktin);
3340 static void ssh_queue_incoming_data(Ssh ssh,
3341 const unsigned char **data, int *datalen)
3343 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
3348 static void ssh_process_queued_incoming_data(Ssh ssh)
3351 const unsigned char *data;
3354 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
3355 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
3359 while (!ssh->frozen && len > 0)
3360 ssh_process_incoming_data(ssh, &data, &len);
3363 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
3367 static void ssh_set_frozen(Ssh ssh, int frozen)
3370 sk_set_frozen(ssh->s, frozen);
3371 ssh->frozen = frozen;
3374 static void ssh_gotdata(Ssh ssh, const unsigned char *data, int datalen)
3376 /* Log raw data, if we're in that mode. */
3378 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
3379 0, NULL, NULL, 0, NULL);
3381 crBegin(ssh->ssh_gotdata_crstate);
3384 * To begin with, feed the characters one by one to the
3385 * protocol initialisation / selection function do_ssh_init().
3386 * When that returns 0, we're done with the initial greeting
3387 * exchange and can move on to packet discipline.
3390 int ret; /* need not be kept across crReturn */
3392 crReturnV; /* more data please */
3393 ret = ssh->do_ssh_init(ssh, *data);
3401 * We emerge from that loop when the initial negotiation is
3402 * over and we have selected an s_rdpkt function. Now pass
3403 * everything to s_rdpkt, and then pass the resulting packets
3404 * to the proper protocol handler.
3408 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
3410 ssh_queue_incoming_data(ssh, &data, &datalen);
3411 /* This uses up all data and cannot cause anything interesting
3412 * to happen; indeed, for anything to happen at all, we must
3413 * return, so break out. */
3415 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
3416 /* This uses up some or all data, and may freeze the
3418 ssh_process_queued_incoming_data(ssh);
3420 /* This uses up some or all data, and may freeze the
3422 ssh_process_incoming_data(ssh, &data, &datalen);
3424 /* FIXME this is probably EBW. */
3425 if (ssh->state == SSH_STATE_CLOSED)
3428 /* We're out of data. Go and get some more. */
3434 static int ssh_do_close(Ssh ssh, int notify_exit)
3437 struct ssh_channel *c;
3439 ssh->state = SSH_STATE_CLOSED;
3440 expire_timer_context(ssh);
3445 notify_remote_exit(ssh->frontend);
3450 * Now we must shut down any port- and X-forwarded channels going
3451 * through this connection.
3453 if (ssh->channels) {
3454 while (NULL != (c = index234(ssh->channels, 0))) {
3457 x11_close(c->u.x11.xconn);
3460 case CHAN_SOCKDATA_DORMANT:
3461 pfd_close(c->u.pfd.pf);
3464 del234(ssh->channels, c); /* moving next one to index 0 */
3465 if (ssh->version == 2)
3466 bufchain_clear(&c->v.v2.outbuffer);
3471 * Go through port-forwardings, and close any associated
3472 * listening sockets.
3474 if (ssh->portfwds) {
3475 struct ssh_portfwd *pf;
3476 while (NULL != (pf = index234(ssh->portfwds, 0))) {
3477 /* Dispose of any listening socket. */
3479 pfl_terminate(pf->local);
3480 del234(ssh->portfwds, pf); /* moving next one to index 0 */
3483 freetree234(ssh->portfwds);
3484 ssh->portfwds = NULL;
3488 * Also stop attempting to connection-share.
3490 if (ssh->connshare) {
3491 sharestate_free(ssh->connshare);
3492 ssh->connshare = NULL;
3498 static void ssh_socket_log(Plug plug, int type, SockAddr addr, int port,
3499 const char *error_msg, int error_code)
3501 Ssh ssh = (Ssh) plug;
3504 * While we're attempting connection sharing, don't loudly log
3505 * everything that happens. Real TCP connections need to be logged
3506 * when we _start_ trying to connect, because it might be ages
3507 * before they respond if something goes wrong; but connection
3508 * sharing is local and quick to respond, and it's sufficient to
3509 * simply wait and see whether it worked afterwards.
3512 if (!ssh->attempting_connshare)
3513 backend_socket_log(ssh->frontend, type, addr, port,
3514 error_msg, error_code, ssh->conf,
3515 ssh->session_started);
3518 void ssh_connshare_log(Ssh ssh, int event, const char *logtext,
3519 const char *ds_err, const char *us_err)
3521 if (event == SHARE_NONE) {
3522 /* In this case, 'logtext' is an error message indicating a
3523 * reason why connection sharing couldn't be set up _at all_.
3524 * Failing that, ds_err and us_err indicate why we couldn't be
3525 * a downstream and an upstream respectively. */
3527 logeventf(ssh, "Could not set up connection sharing: %s", logtext);
3530 logeventf(ssh, "Could not set up connection sharing"
3531 " as downstream: %s", ds_err);
3533 logeventf(ssh, "Could not set up connection sharing"
3534 " as upstream: %s", us_err);
3536 } else if (event == SHARE_DOWNSTREAM) {
3537 /* In this case, 'logtext' is a local endpoint address */
3538 logeventf(ssh, "Using existing shared connection at %s", logtext);
3539 /* Also we should mention this in the console window to avoid
3540 * confusing users as to why this window doesn't behave the
3542 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
3543 c_write_str(ssh,"Reusing a shared connection to this server.\r\n");
3545 } else if (event == SHARE_UPSTREAM) {
3546 /* In this case, 'logtext' is a local endpoint address too */
3547 logeventf(ssh, "Sharing this connection at %s", logtext);
3551 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
3554 Ssh ssh = (Ssh) plug;
3555 int need_notify = ssh_do_close(ssh, FALSE);
3558 if (!ssh->close_expected)
3559 error_msg = "Server unexpectedly closed network connection";
3561 error_msg = "Server closed network connection";
3564 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
3568 notify_remote_exit(ssh->frontend);
3571 logevent(error_msg);
3572 if (!ssh->close_expected || !ssh->clean_exit)
3573 connection_fatal(ssh->frontend, "%s", error_msg);
3577 static int ssh_receive(Plug plug, int urgent, char *data, int len)
3579 Ssh ssh = (Ssh) plug;
3580 ssh_gotdata(ssh, (unsigned char *)data, len);
3581 if (ssh->state == SSH_STATE_CLOSED) {
3582 ssh_do_close(ssh, TRUE);
3588 static void ssh_sent(Plug plug, int bufsize)
3590 Ssh ssh = (Ssh) plug;
3592 * If the send backlog on the SSH socket itself clears, we
3593 * should unthrottle the whole world if it was throttled.
3595 if (bufsize < SSH_MAX_BACKLOG)
3596 ssh_throttle_all(ssh, 0, bufsize);
3599 static void ssh_hostport_setup(const char *host, int port, Conf *conf,
3600 char **savedhost, int *savedport,
3603 char *loghost = conf_get_str(conf, CONF_loghost);
3605 *loghost_ret = loghost;
3611 tmphost = dupstr(loghost);
3612 *savedport = 22; /* default ssh port */
3615 * A colon suffix on the hostname string also lets us affect
3616 * savedport. (Unless there are multiple colons, in which case
3617 * we assume this is an unbracketed IPv6 literal.)
3619 colon = host_strrchr(tmphost, ':');
3620 if (colon && colon == host_strchr(tmphost, ':')) {
3623 *savedport = atoi(colon);
3626 *savedhost = host_strduptrim(tmphost);
3629 *savedhost = host_strduptrim(host);
3631 port = 22; /* default ssh port */
3636 static int ssh_test_for_upstream(const char *host, int port, Conf *conf)
3642 random_ref(); /* platform may need this to determine share socket name */
3643 ssh_hostport_setup(host, port, conf, &savedhost, &savedport, NULL);
3644 ret = ssh_share_test_for_upstream(savedhost, savedport, conf);
3652 * Connect to specified host and port.
3653 * Returns an error message, or NULL on success.
3654 * Also places the canonical host name into `realhost'. It must be
3655 * freed by the caller.
3657 static const char *connect_to_host(Ssh ssh, const char *host, int port,
3658 char **realhost, int nodelay, int keepalive)
3660 static const struct plug_function_table fn_table = {
3671 int addressfamily, sshprot;
3673 ssh_hostport_setup(host, port, ssh->conf,
3674 &ssh->savedhost, &ssh->savedport, &loghost);
3676 ssh->fn = &fn_table; /* make 'ssh' usable as a Plug */
3679 * Try connection-sharing, in case that means we don't open a
3680 * socket after all. ssh_connection_sharing_init will connect to a
3681 * previously established upstream if it can, and failing that,
3682 * establish a listening socket for _us_ to be the upstream. In
3683 * the latter case it will return NULL just as if it had done
3684 * nothing, because here we only need to care if we're a
3685 * downstream and need to do our connection setup differently.
3687 ssh->connshare = NULL;
3688 ssh->attempting_connshare = TRUE; /* affects socket logging behaviour */
3689 ssh->s = ssh_connection_sharing_init(ssh->savedhost, ssh->savedport,
3690 ssh->conf, ssh, &ssh->connshare);
3691 ssh->attempting_connshare = FALSE;
3692 if (ssh->s != NULL) {
3694 * We are a downstream.
3696 ssh->bare_connection = TRUE;
3697 ssh->do_ssh_init = do_ssh_connection_init;
3698 ssh->fullhostname = NULL;
3699 *realhost = dupstr(host); /* best we can do */
3702 * We're not a downstream, so open a normal socket.
3704 ssh->do_ssh_init = do_ssh_init;
3709 addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
3710 addr = name_lookup(host, port, realhost, ssh->conf, addressfamily,
3711 ssh->frontend, "SSH connection");
3712 if ((err = sk_addr_error(addr)) != NULL) {
3716 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
3718 ssh->s = new_connection(addr, *realhost, port,
3719 0, 1, nodelay, keepalive,
3720 (Plug) ssh, ssh->conf);
3721 if ((err = sk_socket_error(ssh->s)) != NULL) {
3723 notify_remote_exit(ssh->frontend);
3729 * The SSH version number is always fixed (since we no longer support
3730 * fallback between versions), so set it now, and if it's SSH-2,
3731 * send the version string now too.
3733 sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3734 assert(sshprot == 0 || sshprot == 3);
3738 if (sshprot == 3 && !ssh->bare_connection) {
3741 ssh_send_verstring(ssh, "SSH-", NULL);
3745 * loghost, if configured, overrides realhost.
3749 *realhost = dupstr(loghost);
3756 * Throttle or unthrottle the SSH connection.
3758 static void ssh_throttle_conn(Ssh ssh, int adjust)
3760 int old_count = ssh->conn_throttle_count;
3761 ssh->conn_throttle_count += adjust;
3762 assert(ssh->conn_throttle_count >= 0);
3763 if (ssh->conn_throttle_count && !old_count) {
3764 ssh_set_frozen(ssh, 1);
3765 } else if (!ssh->conn_throttle_count && old_count) {
3766 ssh_set_frozen(ssh, 0);
3771 * Throttle or unthrottle _all_ local data streams (for when sends
3772 * on the SSH connection itself back up).
3774 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3777 struct ssh_channel *c;
3779 if (enable == ssh->throttled_all)
3781 ssh->throttled_all = enable;
3782 ssh->overall_bufsize = bufsize;
3785 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3787 case CHAN_MAINSESSION:
3789 * This is treated separately, outside the switch.
3793 x11_override_throttle(c->u.x11.xconn, enable);
3796 /* Agent channels require no buffer management. */
3799 pfd_override_throttle(c->u.pfd.pf, enable);
3805 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3807 Ssh ssh = (Ssh) sshv;
3809 ssh->agent_response = reply;
3810 ssh->agent_response_len = replylen;
3812 if (ssh->version == 1)
3813 do_ssh1_login(ssh, NULL, -1, NULL);
3815 do_ssh2_authconn(ssh, NULL, -1, NULL);
3818 static void ssh_dialog_callback(void *sshv, int ret)
3820 Ssh ssh = (Ssh) sshv;
3822 ssh->user_response = ret;
3824 if (ssh->version == 1)
3825 do_ssh1_login(ssh, NULL, -1, NULL);
3827 do_ssh2_transport(ssh, NULL, -1, NULL);
3830 * This may have unfrozen the SSH connection, so do a
3833 ssh_process_queued_incoming_data(ssh);
3836 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3838 struct ssh_channel *c = (struct ssh_channel *)cv;
3839 const void *sentreply = reply;
3841 c->u.a.outstanding_requests--;
3843 /* Fake SSH_AGENT_FAILURE. */
3844 sentreply = "\0\0\0\1\5";
3847 ssh_send_channel_data(c, sentreply, replylen);
3851 * If we've already seen an incoming EOF but haven't sent an
3852 * outgoing one, this may be the moment to send it.
3854 if (c->u.a.outstanding_requests == 0 && (c->closes & CLOSES_RCVD_EOF))
3855 sshfwd_write_eof(c);
3859 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3860 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3861 * => log `wire_reason'.
3863 static void ssh_disconnect(Ssh ssh, const char *client_reason,
3864 const char *wire_reason,
3865 int code, int clean_exit)
3869 client_reason = wire_reason;
3871 error = dupprintf("Disconnected: %s", client_reason);
3873 error = dupstr("Disconnected");
3875 if (ssh->version == 1) {
3876 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3878 } else if (ssh->version == 2) {
3879 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3880 ssh2_pkt_adduint32(pktout, code);
3881 ssh2_pkt_addstring(pktout, wire_reason);
3882 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3883 ssh2_pkt_send_noqueue(ssh, pktout);
3886 ssh->close_expected = TRUE;
3887 ssh->clean_exit = clean_exit;
3888 ssh_closing((Plug)ssh, error, 0, 0);
3892 int verify_ssh_manual_host_key(Ssh ssh, const char *fingerprint,
3893 const struct ssh_signkey *ssh2keytype,
3896 if (!conf_get_str_nthstrkey(ssh->conf, CONF_ssh_manual_hostkeys, 0)) {
3897 return -1; /* no manual keys configured */
3902 * The fingerprint string we've been given will have things
3903 * like 'ssh-rsa 2048' at the front of it. Strip those off and
3904 * narrow down to just the colon-separated hex block at the
3905 * end of the string.
3907 const char *p = strrchr(fingerprint, ' ');
3908 fingerprint = p ? p+1 : fingerprint;
3909 /* Quick sanity checks, including making sure it's in lowercase */
3910 assert(strlen(fingerprint) == 16*3 - 1);
3911 assert(fingerprint[2] == ':');
3912 assert(fingerprint[strspn(fingerprint, "0123456789abcdef:")] == 0);
3914 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3916 return 1; /* success */
3921 * Construct the base64-encoded public key blob and see if
3924 unsigned char *binblob;
3926 int binlen, atoms, i;
3927 binblob = ssh2keytype->public_blob(ssh2keydata, &binlen);
3928 atoms = (binlen + 2) / 3;
3929 base64blob = snewn(atoms * 4 + 1, char);
3930 for (i = 0; i < atoms; i++)
3931 base64_encode_atom(binblob + 3*i, binlen - 3*i, base64blob + 4*i);
3932 base64blob[atoms * 4] = '\0';
3934 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3937 return 1; /* success */
3946 * Handle the key exchange and user authentication phases.
3948 static int do_ssh1_login(Ssh ssh, const unsigned char *in, int inlen,
3949 struct Packet *pktin)
3952 unsigned char cookie[8], *ptr;
3953 struct MD5Context md5c;
3954 struct do_ssh1_login_state {
3957 unsigned char *rsabuf;
3958 const unsigned char *keystr1, *keystr2;
3959 unsigned long supported_ciphers_mask, supported_auths_mask;
3960 int tried_publickey, tried_agent;
3961 int tis_auth_refused, ccard_auth_refused;
3962 unsigned char session_id[16];
3964 void *publickey_blob;
3965 int publickey_bloblen;
3966 char *publickey_comment;
3967 int privatekey_available, privatekey_encrypted;
3968 prompts_t *cur_prompt;
3971 unsigned char request[5], *response, *p;
3981 struct RSAKey servkey, hostkey;
3983 crState(do_ssh1_login_state);
3990 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3991 bombout(("Public key packet not received"));
3995 logevent("Received public keys");
3997 ptr = ssh_pkt_getdata(pktin, 8);
3999 bombout(("SSH-1 public key packet stopped before random cookie"));
4002 memcpy(cookie, ptr, 8);
4004 if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
4005 !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) {
4006 bombout(("Failed to read SSH-1 public keys from public key packet"));
4011 * Log the host key fingerprint.
4015 logevent("Host key fingerprint is:");
4016 strcpy(logmsg, " ");
4017 s->hostkey.comment = NULL;
4018 rsa_fingerprint(logmsg + strlen(logmsg),
4019 sizeof(logmsg) - strlen(logmsg), &s->hostkey);
4023 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
4024 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
4025 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
4026 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
4027 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
4029 ssh->v1_local_protoflags =
4030 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
4031 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
4034 MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
4035 MD5Update(&md5c, s->keystr1, s->servkey.bytes);
4036 MD5Update(&md5c, cookie, 8);
4037 MD5Final(s->session_id, &md5c);
4039 for (i = 0; i < 32; i++)
4040 ssh->session_key[i] = random_byte();
4043 * Verify that the `bits' and `bytes' parameters match.
4045 if (s->hostkey.bits > s->hostkey.bytes * 8 ||
4046 s->servkey.bits > s->servkey.bytes * 8) {
4047 bombout(("SSH-1 public keys were badly formatted"));
4051 s->len = (s->hostkey.bytes > s->servkey.bytes ?
4052 s->hostkey.bytes : s->servkey.bytes);
4054 s->rsabuf = snewn(s->len, unsigned char);
4057 * Verify the host key.
4061 * First format the key into a string.
4063 int len = rsastr_len(&s->hostkey);
4064 char fingerprint[100];
4065 char *keystr = snewn(len, char);
4066 rsastr_fmt(keystr, &s->hostkey);
4067 rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
4069 /* First check against manually configured host keys. */
4070 s->dlgret = verify_ssh_manual_host_key(ssh, fingerprint, NULL, NULL);
4071 if (s->dlgret == 0) { /* did not match */
4072 bombout(("Host key did not appear in manually configured list"));
4075 } else if (s->dlgret < 0) { /* none configured; use standard handling */
4076 ssh_set_frozen(ssh, 1);
4077 s->dlgret = verify_ssh_host_key(ssh->frontend,
4078 ssh->savedhost, ssh->savedport,
4079 "rsa", keystr, fingerprint,
4080 ssh_dialog_callback, ssh);
4085 if (s->dlgret < 0) {
4089 bombout(("Unexpected data from server while waiting"
4090 " for user host key response"));
4093 } while (pktin || inlen > 0);
4094 s->dlgret = ssh->user_response;
4096 ssh_set_frozen(ssh, 0);
4098 if (s->dlgret == 0) {
4099 ssh_disconnect(ssh, "User aborted at host key verification",
4108 for (i = 0; i < 32; i++) {
4109 s->rsabuf[i] = ssh->session_key[i];
4111 s->rsabuf[i] ^= s->session_id[i];
4114 if (s->hostkey.bytes > s->servkey.bytes) {
4115 ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
4117 ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
4119 ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
4121 ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
4124 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
4128 logevent("Encrypted session key");
4131 int cipher_chosen = 0, warn = 0;
4132 const char *cipher_string = NULL;
4134 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
4135 int next_cipher = conf_get_int_int(ssh->conf,
4136 CONF_ssh_cipherlist, i);
4137 if (next_cipher == CIPHER_WARN) {
4138 /* If/when we choose a cipher, warn about it */
4140 } else if (next_cipher == CIPHER_AES) {
4141 /* XXX Probably don't need to mention this. */
4142 logevent("AES not supported in SSH-1, skipping");
4144 switch (next_cipher) {
4145 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
4146 cipher_string = "3DES"; break;
4147 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
4148 cipher_string = "Blowfish"; break;
4149 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
4150 cipher_string = "single-DES"; break;
4152 if (s->supported_ciphers_mask & (1 << s->cipher_type))
4156 if (!cipher_chosen) {
4157 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
4158 bombout(("Server violates SSH-1 protocol by not "
4159 "supporting 3DES encryption"));
4161 /* shouldn't happen */
4162 bombout(("No supported ciphers found"));
4166 /* Warn about chosen cipher if necessary. */
4168 ssh_set_frozen(ssh, 1);
4169 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
4170 ssh_dialog_callback, ssh);
4171 if (s->dlgret < 0) {
4175 bombout(("Unexpected data from server while waiting"
4176 " for user response"));
4179 } while (pktin || inlen > 0);
4180 s->dlgret = ssh->user_response;
4182 ssh_set_frozen(ssh, 0);
4183 if (s->dlgret == 0) {
4184 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
4191 switch (s->cipher_type) {
4192 case SSH_CIPHER_3DES:
4193 logevent("Using 3DES encryption");
4195 case SSH_CIPHER_DES:
4196 logevent("Using single-DES encryption");
4198 case SSH_CIPHER_BLOWFISH:
4199 logevent("Using Blowfish encryption");
4203 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
4204 PKT_CHAR, s->cipher_type,
4205 PKT_DATA, cookie, 8,
4206 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
4207 PKT_DATA, s->rsabuf, s->len,
4208 PKT_INT, ssh->v1_local_protoflags, PKT_END);
4210 logevent("Trying to enable encryption...");
4214 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
4215 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
4217 ssh->v1_cipher_ctx = ssh->cipher->make_context();
4218 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
4219 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
4221 ssh->crcda_ctx = crcda_make_context();
4222 logevent("Installing CRC compensation attack detector");
4224 if (s->servkey.modulus) {
4225 sfree(s->servkey.modulus);
4226 s->servkey.modulus = NULL;
4228 if (s->servkey.exponent) {
4229 sfree(s->servkey.exponent);
4230 s->servkey.exponent = NULL;
4232 if (s->hostkey.modulus) {
4233 sfree(s->hostkey.modulus);
4234 s->hostkey.modulus = NULL;
4236 if (s->hostkey.exponent) {
4237 sfree(s->hostkey.exponent);
4238 s->hostkey.exponent = NULL;
4242 if (pktin->type != SSH1_SMSG_SUCCESS) {
4243 bombout(("Encryption not successfully enabled"));
4247 logevent("Successfully started encryption");
4249 fflush(stdout); /* FIXME eh? */
4251 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
4252 int ret; /* need not be kept over crReturn */
4253 s->cur_prompt = new_prompts(ssh->frontend);
4254 s->cur_prompt->to_server = TRUE;
4255 s->cur_prompt->name = dupstr("SSH login name");
4256 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
4257 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4260 crWaitUntil(!pktin);
4261 ret = get_userpass_input(s->cur_prompt, in, inlen);
4266 * Failed to get a username. Terminate.
4268 free_prompts(s->cur_prompt);
4269 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
4272 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
4273 free_prompts(s->cur_prompt);
4276 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
4278 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
4280 if (flags & FLAG_INTERACTIVE &&
4281 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
4282 c_write_str(ssh, userlog);
4283 c_write_str(ssh, "\r\n");
4291 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
4292 /* We must not attempt PK auth. Pretend we've already tried it. */
4293 s->tried_publickey = s->tried_agent = 1;
4295 s->tried_publickey = s->tried_agent = 0;
4297 s->tis_auth_refused = s->ccard_auth_refused = 0;
4299 * Load the public half of any configured keyfile for later use.
4301 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4302 if (!filename_is_null(s->keyfile)) {
4304 logeventf(ssh, "Reading key file \"%.150s\"",
4305 filename_to_str(s->keyfile));
4306 keytype = key_type(s->keyfile);
4307 if (keytype == SSH_KEYTYPE_SSH1 ||
4308 keytype == SSH_KEYTYPE_SSH1_PUBLIC) {
4310 if (rsakey_pubblob(s->keyfile,
4311 &s->publickey_blob, &s->publickey_bloblen,
4312 &s->publickey_comment, &error)) {
4313 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH1);
4314 if (!s->privatekey_available)
4315 logeventf(ssh, "Key file contains public key only");
4316 s->privatekey_encrypted = rsakey_encrypted(s->keyfile,
4320 logeventf(ssh, "Unable to load key (%s)", error);
4321 msgbuf = dupprintf("Unable to load key file "
4322 "\"%.150s\" (%s)\r\n",
4323 filename_to_str(s->keyfile),
4325 c_write_str(ssh, msgbuf);
4327 s->publickey_blob = NULL;
4331 logeventf(ssh, "Unable to use this key file (%s)",
4332 key_type_to_str(keytype));
4333 msgbuf = dupprintf("Unable to use key file \"%.150s\""
4335 filename_to_str(s->keyfile),
4336 key_type_to_str(keytype));
4337 c_write_str(ssh, msgbuf);
4339 s->publickey_blob = NULL;
4342 s->publickey_blob = NULL;
4344 while (pktin->type == SSH1_SMSG_FAILURE) {
4345 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
4347 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
4349 * Attempt RSA authentication using Pageant.
4355 logevent("Pageant is running. Requesting keys.");
4357 /* Request the keys held by the agent. */
4358 PUT_32BIT(s->request, 1);
4359 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
4360 if (!agent_query(s->request, 5, &r, &s->responselen,
4361 ssh_agent_callback, ssh)) {
4365 bombout(("Unexpected data from server while waiting"
4366 " for agent response"));
4369 } while (pktin || inlen > 0);
4370 r = ssh->agent_response;
4371 s->responselen = ssh->agent_response_len;
4373 s->response = (unsigned char *) r;
4374 if (s->response && s->responselen >= 5 &&
4375 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
4376 s->p = s->response + 5;
4377 s->nkeys = toint(GET_32BIT(s->p));
4379 logeventf(ssh, "Pageant reported negative key count %d",
4384 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
4385 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
4386 unsigned char *pkblob = s->p;
4390 do { /* do while (0) to make breaking easy */
4391 n = ssh1_read_bignum
4392 (s->p, toint(s->responselen-(s->p-s->response)),
4397 n = ssh1_read_bignum
4398 (s->p, toint(s->responselen-(s->p-s->response)),
4403 if (s->responselen - (s->p-s->response) < 4)
4405 s->commentlen = toint(GET_32BIT(s->p));
4407 if (s->commentlen < 0 ||
4408 toint(s->responselen - (s->p-s->response)) <
4411 s->commentp = (char *)s->p;
4412 s->p += s->commentlen;
4416 logevent("Pageant key list packet was truncated");
4420 if (s->publickey_blob) {
4421 if (!memcmp(pkblob, s->publickey_blob,
4422 s->publickey_bloblen)) {
4423 logeventf(ssh, "Pageant key #%d matches "
4424 "configured key file", s->keyi);
4425 s->tried_publickey = 1;
4427 /* Skip non-configured key */
4430 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
4431 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4432 PKT_BIGNUM, s->key.modulus, PKT_END);
4434 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4435 logevent("Key refused");
4438 logevent("Received RSA challenge");
4439 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4440 bombout(("Server's RSA challenge was badly formatted"));
4445 char *agentreq, *q, *ret;
4448 len = 1 + 4; /* message type, bit count */
4449 len += ssh1_bignum_length(s->key.exponent);
4450 len += ssh1_bignum_length(s->key.modulus);
4451 len += ssh1_bignum_length(s->challenge);
4452 len += 16; /* session id */
4453 len += 4; /* response format */
4454 agentreq = snewn(4 + len, char);
4455 PUT_32BIT(agentreq, len);
4457 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
4458 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
4460 q += ssh1_write_bignum(q, s->key.exponent);
4461 q += ssh1_write_bignum(q, s->key.modulus);
4462 q += ssh1_write_bignum(q, s->challenge);
4463 memcpy(q, s->session_id, 16);
4465 PUT_32BIT(q, 1); /* response format */
4466 if (!agent_query(agentreq, len + 4, &vret, &retlen,
4467 ssh_agent_callback, ssh)) {
4472 bombout(("Unexpected data from server"
4473 " while waiting for agent"
4477 } while (pktin || inlen > 0);
4478 vret = ssh->agent_response;
4479 retlen = ssh->agent_response_len;
4484 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
4485 logevent("Sending Pageant's response");
4486 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4487 PKT_DATA, ret + 5, 16,
4491 if (pktin->type == SSH1_SMSG_SUCCESS) {
4493 ("Pageant's response accepted");
4494 if (flags & FLAG_VERBOSE) {
4495 c_write_str(ssh, "Authenticated using"
4497 c_write(ssh, s->commentp,
4499 c_write_str(ssh, "\" from agent\r\n");
4504 ("Pageant's response not accepted");
4507 ("Pageant failed to answer challenge");
4511 logevent("No reply received from Pageant");
4514 freebn(s->key.exponent);
4515 freebn(s->key.modulus);
4516 freebn(s->challenge);
4521 if (s->publickey_blob && !s->tried_publickey)
4522 logevent("Configured key file not in Pageant");
4524 logevent("Failed to get reply from Pageant");
4529 if (s->publickey_blob && s->privatekey_available &&
4530 !s->tried_publickey) {
4532 * Try public key authentication with the specified
4535 int got_passphrase; /* need not be kept over crReturn */
4536 if (flags & FLAG_VERBOSE)
4537 c_write_str(ssh, "Trying public key authentication.\r\n");
4538 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4539 logeventf(ssh, "Trying public key \"%s\"",
4540 filename_to_str(s->keyfile));
4541 s->tried_publickey = 1;
4542 got_passphrase = FALSE;
4543 while (!got_passphrase) {
4545 * Get a passphrase, if necessary.
4547 char *passphrase = NULL; /* only written after crReturn */
4549 if (!s->privatekey_encrypted) {
4550 if (flags & FLAG_VERBOSE)
4551 c_write_str(ssh, "No passphrase required.\r\n");
4554 int ret; /* need not be kept over crReturn */
4555 s->cur_prompt = new_prompts(ssh->frontend);
4556 s->cur_prompt->to_server = FALSE;
4557 s->cur_prompt->name = dupstr("SSH key passphrase");
4558 add_prompt(s->cur_prompt,
4559 dupprintf("Passphrase for key \"%.100s\": ",
4560 s->publickey_comment), FALSE);
4561 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4564 crWaitUntil(!pktin);
4565 ret = get_userpass_input(s->cur_prompt, in, inlen);
4569 /* Failed to get a passphrase. Terminate. */
4570 free_prompts(s->cur_prompt);
4571 ssh_disconnect(ssh, NULL, "Unable to authenticate",
4575 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
4576 free_prompts(s->cur_prompt);
4579 * Try decrypting key with passphrase.
4581 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4582 ret = loadrsakey(s->keyfile, &s->key, passphrase,
4585 smemclr(passphrase, strlen(passphrase));
4589 /* Correct passphrase. */
4590 got_passphrase = TRUE;
4591 } else if (ret == 0) {
4592 c_write_str(ssh, "Couldn't load private key from ");
4593 c_write_str(ssh, filename_to_str(s->keyfile));
4594 c_write_str(ssh, " (");
4595 c_write_str(ssh, error);
4596 c_write_str(ssh, ").\r\n");
4597 got_passphrase = FALSE;
4598 break; /* go and try something else */
4599 } else if (ret == -1) {
4600 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
4601 got_passphrase = FALSE;
4604 assert(0 && "unexpected return from loadrsakey()");
4605 got_passphrase = FALSE; /* placate optimisers */
4609 if (got_passphrase) {
4612 * Send a public key attempt.
4614 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4615 PKT_BIGNUM, s->key.modulus, PKT_END);
4618 if (pktin->type == SSH1_SMSG_FAILURE) {
4619 c_write_str(ssh, "Server refused our public key.\r\n");
4620 continue; /* go and try something else */
4622 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4623 bombout(("Bizarre response to offer of public key"));
4629 unsigned char buffer[32];
4630 Bignum challenge, response;
4632 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4633 bombout(("Server's RSA challenge was badly formatted"));
4636 response = rsadecrypt(challenge, &s->key);
4637 freebn(s->key.private_exponent);/* burn the evidence */
4639 for (i = 0; i < 32; i++) {
4640 buffer[i] = bignum_byte(response, 31 - i);
4644 MD5Update(&md5c, buffer, 32);
4645 MD5Update(&md5c, s->session_id, 16);
4646 MD5Final(buffer, &md5c);
4648 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4649 PKT_DATA, buffer, 16, PKT_END);
4656 if (pktin->type == SSH1_SMSG_FAILURE) {
4657 if (flags & FLAG_VERBOSE)
4658 c_write_str(ssh, "Failed to authenticate with"
4659 " our public key.\r\n");
4660 continue; /* go and try something else */
4661 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4662 bombout(("Bizarre response to RSA authentication response"));
4666 break; /* we're through! */
4672 * Otherwise, try various forms of password-like authentication.
4674 s->cur_prompt = new_prompts(ssh->frontend);
4676 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4677 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
4678 !s->tis_auth_refused) {
4679 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
4680 logevent("Requested TIS authentication");
4681 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
4683 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
4684 logevent("TIS authentication declined");
4685 if (flags & FLAG_INTERACTIVE)
4686 c_write_str(ssh, "TIS authentication refused.\r\n");
4687 s->tis_auth_refused = 1;
4692 char *instr_suf, *prompt;
4694 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4696 bombout(("TIS challenge packet was badly formed"));
4699 logevent("Received TIS challenge");
4700 s->cur_prompt->to_server = TRUE;
4701 s->cur_prompt->name = dupstr("SSH TIS authentication");
4702 /* Prompt heuristic comes from OpenSSH */
4703 if (memchr(challenge, '\n', challengelen)) {
4704 instr_suf = dupstr("");
4705 prompt = dupprintf("%.*s", challengelen, challenge);
4707 instr_suf = dupprintf("%.*s", challengelen, challenge);
4708 prompt = dupstr("Response: ");
4710 s->cur_prompt->instruction =
4711 dupprintf("Using TIS authentication.%s%s",
4712 (*instr_suf) ? "\n" : "",
4714 s->cur_prompt->instr_reqd = TRUE;
4715 add_prompt(s->cur_prompt, prompt, FALSE);
4719 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4720 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
4721 !s->ccard_auth_refused) {
4722 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
4723 logevent("Requested CryptoCard authentication");
4724 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
4726 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
4727 logevent("CryptoCard authentication declined");
4728 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
4729 s->ccard_auth_refused = 1;
4734 char *instr_suf, *prompt;
4736 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4738 bombout(("CryptoCard challenge packet was badly formed"));
4741 logevent("Received CryptoCard challenge");
4742 s->cur_prompt->to_server = TRUE;
4743 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4744 s->cur_prompt->name_reqd = FALSE;
4745 /* Prompt heuristic comes from OpenSSH */
4746 if (memchr(challenge, '\n', challengelen)) {
4747 instr_suf = dupstr("");
4748 prompt = dupprintf("%.*s", challengelen, challenge);
4750 instr_suf = dupprintf("%.*s", challengelen, challenge);
4751 prompt = dupstr("Response: ");
4753 s->cur_prompt->instruction =
4754 dupprintf("Using CryptoCard authentication.%s%s",
4755 (*instr_suf) ? "\n" : "",
4757 s->cur_prompt->instr_reqd = TRUE;
4758 add_prompt(s->cur_prompt, prompt, FALSE);
4762 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4763 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4764 bombout(("No supported authentication methods available"));
4767 s->cur_prompt->to_server = TRUE;
4768 s->cur_prompt->name = dupstr("SSH password");
4769 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4770 ssh->username, ssh->savedhost),
4775 * Show password prompt, having first obtained it via a TIS
4776 * or CryptoCard exchange if we're doing TIS or CryptoCard
4780 int ret; /* need not be kept over crReturn */
4781 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4784 crWaitUntil(!pktin);
4785 ret = get_userpass_input(s->cur_prompt, in, inlen);
4790 * Failed to get a password (for example
4791 * because one was supplied on the command line
4792 * which has already failed to work). Terminate.
4794 free_prompts(s->cur_prompt);
4795 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4800 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4802 * Defence against traffic analysis: we send a
4803 * whole bunch of packets containing strings of
4804 * different lengths. One of these strings is the
4805 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4806 * The others are all random data in
4807 * SSH1_MSG_IGNORE packets. This way a passive
4808 * listener can't tell which is the password, and
4809 * hence can't deduce the password length.
4811 * Anybody with a password length greater than 16
4812 * bytes is going to have enough entropy in their
4813 * password that a listener won't find it _that_
4814 * much help to know how long it is. So what we'll
4817 * - if password length < 16, we send 15 packets
4818 * containing string lengths 1 through 15
4820 * - otherwise, we let N be the nearest multiple
4821 * of 8 below the password length, and send 8
4822 * packets containing string lengths N through
4823 * N+7. This won't obscure the order of
4824 * magnitude of the password length, but it will
4825 * introduce a bit of extra uncertainty.
4827 * A few servers can't deal with SSH1_MSG_IGNORE, at
4828 * least in this context. For these servers, we need
4829 * an alternative defence. We make use of the fact
4830 * that the password is interpreted as a C string:
4831 * so we can append a NUL, then some random data.
4833 * A few servers can deal with neither SSH1_MSG_IGNORE
4834 * here _nor_ a padded password string.
4835 * For these servers we are left with no defences
4836 * against password length sniffing.
4838 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4839 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4841 * The server can deal with SSH1_MSG_IGNORE, so
4842 * we can use the primary defence.
4844 int bottom, top, pwlen, i;
4847 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4849 bottom = 0; /* zero length passwords are OK! :-) */
4852 bottom = pwlen & ~7;
4856 assert(pwlen >= bottom && pwlen <= top);
4858 randomstr = snewn(top + 1, char);
4860 for (i = bottom; i <= top; i++) {
4862 defer_packet(ssh, s->pwpkt_type,
4863 PKT_STR,s->cur_prompt->prompts[0]->result,
4866 for (j = 0; j < i; j++) {
4868 randomstr[j] = random_byte();
4869 } while (randomstr[j] == '\0');
4871 randomstr[i] = '\0';
4872 defer_packet(ssh, SSH1_MSG_IGNORE,
4873 PKT_STR, randomstr, PKT_END);
4876 logevent("Sending password with camouflage packets");
4877 ssh_pkt_defersend(ssh);
4880 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4882 * The server can't deal with SSH1_MSG_IGNORE
4883 * but can deal with padded passwords, so we
4884 * can use the secondary defence.
4890 len = strlen(s->cur_prompt->prompts[0]->result);
4891 if (len < sizeof(string)) {
4893 strcpy(string, s->cur_prompt->prompts[0]->result);
4894 len++; /* cover the zero byte */
4895 while (len < sizeof(string)) {
4896 string[len++] = (char) random_byte();
4899 ss = s->cur_prompt->prompts[0]->result;
4901 logevent("Sending length-padded password");
4902 send_packet(ssh, s->pwpkt_type,
4903 PKT_INT, len, PKT_DATA, ss, len,
4907 * The server is believed unable to cope with
4908 * any of our password camouflage methods.
4911 len = strlen(s->cur_prompt->prompts[0]->result);
4912 logevent("Sending unpadded password");
4913 send_packet(ssh, s->pwpkt_type,
4915 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4919 send_packet(ssh, s->pwpkt_type,
4920 PKT_STR, s->cur_prompt->prompts[0]->result,
4923 logevent("Sent password");
4924 free_prompts(s->cur_prompt);
4926 if (pktin->type == SSH1_SMSG_FAILURE) {
4927 if (flags & FLAG_VERBOSE)
4928 c_write_str(ssh, "Access denied\r\n");
4929 logevent("Authentication refused");
4930 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4931 bombout(("Strange packet received, type %d", pktin->type));
4937 if (s->publickey_blob) {
4938 sfree(s->publickey_blob);
4939 sfree(s->publickey_comment);
4942 logevent("Authentication successful");
4947 static void ssh_channel_try_eof(struct ssh_channel *c)
4950 assert(c->pending_eof); /* precondition for calling us */
4952 return; /* can't close: not even opened yet */
4953 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4954 return; /* can't send EOF: pending outgoing data */
4956 c->pending_eof = FALSE; /* we're about to send it */
4957 if (ssh->version == 1) {
4958 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4960 c->closes |= CLOSES_SENT_EOF;
4962 struct Packet *pktout;
4963 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4964 ssh2_pkt_adduint32(pktout, c->remoteid);
4965 ssh2_pkt_send(ssh, pktout);
4966 c->closes |= CLOSES_SENT_EOF;
4967 ssh2_channel_check_close(c);
4971 Conf *sshfwd_get_conf(struct ssh_channel *c)
4977 void sshfwd_write_eof(struct ssh_channel *c)
4981 if (ssh->state == SSH_STATE_CLOSED)
4984 if (c->closes & CLOSES_SENT_EOF)
4987 c->pending_eof = TRUE;
4988 ssh_channel_try_eof(c);
4991 void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
4995 if (ssh->state == SSH_STATE_CLOSED)
5000 x11_close(c->u.x11.xconn);
5001 logeventf(ssh, "Forwarded X11 connection terminated due to local "
5005 case CHAN_SOCKDATA_DORMANT:
5006 pfd_close(c->u.pfd.pf);
5007 logeventf(ssh, "Forwarded port closed due to local error: %s", err);
5010 c->type = CHAN_ZOMBIE;
5011 c->pending_eof = FALSE; /* this will confuse a zombie channel */
5013 ssh2_channel_check_close(c);
5016 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
5020 if (ssh->state == SSH_STATE_CLOSED)
5023 return ssh_send_channel_data(c, buf, len);
5026 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
5031 if (ssh->state == SSH_STATE_CLOSED)
5034 if (ssh->version == 1) {
5035 buflimit = SSH1_BUFFER_LIMIT;
5037 buflimit = c->v.v2.locmaxwin;
5038 ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
5040 if (c->throttling_conn && bufsize <= buflimit) {
5041 c->throttling_conn = 0;
5042 ssh_throttle_conn(ssh, -1);
5046 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
5048 struct queued_handler *qh = ssh->qhead;
5052 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
5055 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
5056 ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
5059 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
5060 ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
5064 ssh->qhead = qh->next;
5066 if (ssh->qhead->msg1 > 0) {
5067 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5068 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
5070 if (ssh->qhead->msg2 > 0) {
5071 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5072 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
5075 ssh->qhead = ssh->qtail = NULL;
5078 qh->handler(ssh, pktin, qh->ctx);
5083 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
5084 chandler_fn_t handler, void *ctx)
5086 struct queued_handler *qh;
5088 qh = snew(struct queued_handler);
5091 qh->handler = handler;
5095 if (ssh->qtail == NULL) {
5099 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5100 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
5103 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5104 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
5107 ssh->qtail->next = qh;
5112 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
5114 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
5116 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
5117 SSH2_MSG_REQUEST_SUCCESS)) {
5118 logeventf(ssh, "Remote port forwarding from %s enabled",
5121 logeventf(ssh, "Remote port forwarding from %s refused",
5124 rpf = del234(ssh->rportfwds, pf);
5126 pf->pfrec->remote = NULL;
5131 int ssh_alloc_sharing_rportfwd(Ssh ssh, const char *shost, int sport,
5134 struct ssh_rportfwd *pf = snew(struct ssh_rportfwd);
5137 pf->share_ctx = share_ctx;
5138 pf->shost = dupstr(shost);
5140 pf->sportdesc = NULL;
5141 if (!ssh->rportfwds) {
5142 assert(ssh->version == 2);
5143 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5145 if (add234(ssh->rportfwds, pf) != pf) {
5153 static void ssh_sharing_global_request_response(Ssh ssh, struct Packet *pktin,
5156 share_got_pkt_from_server(ctx, pktin->type,
5157 pktin->body, pktin->length);
5160 void ssh_sharing_queue_global_request(Ssh ssh, void *share_ctx)
5162 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE,
5163 ssh_sharing_global_request_response, share_ctx);
5166 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
5168 struct ssh_portfwd *epf;
5172 if (!ssh->portfwds) {
5173 ssh->portfwds = newtree234(ssh_portcmp);
5176 * Go through the existing port forwardings and tag them
5177 * with status==DESTROY. Any that we want to keep will be
5178 * re-enabled (status==KEEP) as we go through the
5179 * configuration and find out which bits are the same as
5182 struct ssh_portfwd *epf;
5184 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5185 epf->status = DESTROY;
5188 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
5190 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
5191 char *kp, *kp2, *vp, *vp2;
5192 char address_family, type;
5193 int sport,dport,sserv,dserv;
5194 char *sports, *dports, *saddr, *host;
5198 address_family = 'A';
5200 if (*kp == 'A' || *kp == '4' || *kp == '6')
5201 address_family = *kp++;
5202 if (*kp == 'L' || *kp == 'R')
5205 if ((kp2 = host_strchr(kp, ':')) != NULL) {
5207 * There's a colon in the middle of the source port
5208 * string, which means that the part before it is
5209 * actually a source address.
5211 char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp);
5212 saddr = host_strduptrim(saddr_tmp);
5219 sport = atoi(sports);
5223 sport = net_service_lookup(sports);
5225 logeventf(ssh, "Service lookup failed for source"
5226 " port \"%s\"", sports);
5230 if (type == 'L' && !strcmp(val, "D")) {
5231 /* dynamic forwarding */
5238 /* ordinary forwarding */
5240 vp2 = vp + host_strcspn(vp, ":");
5241 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
5245 dport = atoi(dports);
5249 dport = net_service_lookup(dports);
5251 logeventf(ssh, "Service lookup failed for destination"
5252 " port \"%s\"", dports);
5257 if (sport && dport) {
5258 /* Set up a description of the source port. */
5259 struct ssh_portfwd *pfrec, *epfrec;
5261 pfrec = snew(struct ssh_portfwd);
5263 pfrec->saddr = saddr;
5264 pfrec->sserv = sserv ? dupstr(sports) : NULL;
5265 pfrec->sport = sport;
5266 pfrec->daddr = host;
5267 pfrec->dserv = dserv ? dupstr(dports) : NULL;
5268 pfrec->dport = dport;
5269 pfrec->local = NULL;
5270 pfrec->remote = NULL;
5271 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
5272 address_family == '6' ? ADDRTYPE_IPV6 :
5275 epfrec = add234(ssh->portfwds, pfrec);
5276 if (epfrec != pfrec) {
5277 if (epfrec->status == DESTROY) {
5279 * We already have a port forwarding up and running
5280 * with precisely these parameters. Hence, no need
5281 * to do anything; simply re-tag the existing one
5284 epfrec->status = KEEP;
5287 * Anything else indicates that there was a duplicate
5288 * in our input, which we'll silently ignore.
5290 free_portfwd(pfrec);
5292 pfrec->status = CREATE;
5301 * Now go through and destroy any port forwardings which were
5304 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5305 if (epf->status == DESTROY) {
5308 message = dupprintf("%s port forwarding from %s%s%d",
5309 epf->type == 'L' ? "local" :
5310 epf->type == 'R' ? "remote" : "dynamic",
5311 epf->saddr ? epf->saddr : "",
5312 epf->saddr ? ":" : "",
5315 if (epf->type != 'D') {
5316 char *msg2 = dupprintf("%s to %s:%d", message,
5317 epf->daddr, epf->dport);
5322 logeventf(ssh, "Cancelling %s", message);
5325 /* epf->remote or epf->local may be NULL if setting up a
5326 * forwarding failed. */
5328 struct ssh_rportfwd *rpf = epf->remote;
5329 struct Packet *pktout;
5332 * Cancel the port forwarding at the server
5335 if (ssh->version == 1) {
5337 * We cannot cancel listening ports on the
5338 * server side in SSH-1! There's no message
5339 * to support it. Instead, we simply remove
5340 * the rportfwd record from the local end
5341 * so that any connections the server tries
5342 * to make on it are rejected.
5345 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5346 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
5347 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
5349 ssh2_pkt_addstring(pktout, epf->saddr);
5350 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5351 /* XXX: rport_acceptall may not represent
5352 * what was used to open the original connection,
5353 * since it's reconfigurable. */
5354 ssh2_pkt_addstring(pktout, "");
5356 ssh2_pkt_addstring(pktout, "localhost");
5358 ssh2_pkt_adduint32(pktout, epf->sport);
5359 ssh2_pkt_send(ssh, pktout);
5362 del234(ssh->rportfwds, rpf);
5364 } else if (epf->local) {
5365 pfl_terminate(epf->local);
5368 delpos234(ssh->portfwds, i);
5370 i--; /* so we don't skip one in the list */
5374 * And finally, set up any new port forwardings (status==CREATE).
5376 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5377 if (epf->status == CREATE) {
5378 char *sportdesc, *dportdesc;
5379 sportdesc = dupprintf("%s%s%s%s%d%s",
5380 epf->saddr ? epf->saddr : "",
5381 epf->saddr ? ":" : "",
5382 epf->sserv ? epf->sserv : "",
5383 epf->sserv ? "(" : "",
5385 epf->sserv ? ")" : "");
5386 if (epf->type == 'D') {
5389 dportdesc = dupprintf("%s:%s%s%d%s",
5391 epf->dserv ? epf->dserv : "",
5392 epf->dserv ? "(" : "",
5394 epf->dserv ? ")" : "");
5397 if (epf->type == 'L') {
5398 char *err = pfl_listen(epf->daddr, epf->dport,
5399 epf->saddr, epf->sport,
5400 ssh, conf, &epf->local,
5401 epf->addressfamily);
5403 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
5404 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5405 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5406 sportdesc, dportdesc,
5407 err ? " failed: " : "", err ? err : "");
5410 } else if (epf->type == 'D') {
5411 char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport,
5412 ssh, conf, &epf->local,
5413 epf->addressfamily);
5415 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
5416 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5417 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5419 err ? " failed: " : "", err ? err : "");
5424 struct ssh_rportfwd *pf;
5427 * Ensure the remote port forwardings tree exists.
5429 if (!ssh->rportfwds) {
5430 if (ssh->version == 1)
5431 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
5433 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5436 pf = snew(struct ssh_rportfwd);
5437 pf->share_ctx = NULL;
5438 pf->dhost = dupstr(epf->daddr);
5439 pf->dport = epf->dport;
5441 pf->shost = dupstr(epf->saddr);
5442 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5443 pf->shost = dupstr("");
5445 pf->shost = dupstr("localhost");
5447 pf->sport = epf->sport;
5448 if (add234(ssh->rportfwds, pf) != pf) {
5449 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
5450 epf->daddr, epf->dport);
5453 logeventf(ssh, "Requesting remote port %s"
5454 " forward to %s", sportdesc, dportdesc);
5456 pf->sportdesc = sportdesc;
5461 if (ssh->version == 1) {
5462 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
5463 PKT_INT, epf->sport,
5464 PKT_STR, epf->daddr,
5465 PKT_INT, epf->dport,
5467 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
5469 ssh_rportfwd_succfail, pf);
5471 struct Packet *pktout;
5472 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5473 ssh2_pkt_addstring(pktout, "tcpip-forward");
5474 ssh2_pkt_addbool(pktout, 1);/* want reply */
5475 ssh2_pkt_addstring(pktout, pf->shost);
5476 ssh2_pkt_adduint32(pktout, pf->sport);
5477 ssh2_pkt_send(ssh, pktout);
5479 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
5480 SSH2_MSG_REQUEST_FAILURE,
5481 ssh_rportfwd_succfail, pf);
5490 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
5493 int stringlen, bufsize;
5495 ssh_pkt_getstring(pktin, &string, &stringlen);
5496 if (string == NULL) {
5497 bombout(("Incoming terminal data packet was badly formed"));
5501 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
5503 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
5504 ssh->v1_stdout_throttling = 1;
5505 ssh_throttle_conn(ssh, +1);
5509 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
5511 /* Remote side is trying to open a channel to talk to our
5512 * X-Server. Give them back a local channel number. */
5513 struct ssh_channel *c;
5514 int remoteid = ssh_pkt_getuint32(pktin);
5516 logevent("Received X11 connect request");
5517 /* Refuse if X11 forwarding is disabled. */
5518 if (!ssh->X11_fwd_enabled) {
5519 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5520 PKT_INT, remoteid, PKT_END);
5521 logevent("Rejected X11 connect request");
5523 c = snew(struct ssh_channel);
5526 c->u.x11.xconn = x11_init(ssh->x11authtree, c, NULL, -1);
5527 c->remoteid = remoteid;
5528 c->halfopen = FALSE;
5529 c->localid = alloc_channel_id(ssh);
5531 c->pending_eof = FALSE;
5532 c->throttling_conn = 0;
5533 c->type = CHAN_X11; /* identify channel type */
5534 add234(ssh->channels, c);
5535 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5536 PKT_INT, c->remoteid, PKT_INT,
5537 c->localid, PKT_END);
5538 logevent("Opened X11 forward channel");
5542 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
5544 /* Remote side is trying to open a channel to talk to our
5545 * agent. Give them back a local channel number. */
5546 struct ssh_channel *c;
5547 int remoteid = ssh_pkt_getuint32(pktin);
5549 /* Refuse if agent forwarding is disabled. */
5550 if (!ssh->agentfwd_enabled) {
5551 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5552 PKT_INT, remoteid, PKT_END);
5554 c = snew(struct ssh_channel);
5556 c->remoteid = remoteid;
5557 c->halfopen = FALSE;
5558 c->localid = alloc_channel_id(ssh);
5560 c->pending_eof = FALSE;
5561 c->throttling_conn = 0;
5562 c->type = CHAN_AGENT; /* identify channel type */
5563 c->u.a.lensofar = 0;
5564 c->u.a.message = NULL;
5565 c->u.a.outstanding_requests = 0;
5566 add234(ssh->channels, c);
5567 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5568 PKT_INT, c->remoteid, PKT_INT, c->localid,
5573 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
5575 /* Remote side is trying to open a channel to talk to a
5576 * forwarded port. Give them back a local channel number. */
5577 struct ssh_rportfwd pf, *pfp;
5583 remoteid = ssh_pkt_getuint32(pktin);
5584 ssh_pkt_getstring(pktin, &host, &hostsize);
5585 port = ssh_pkt_getuint32(pktin);
5587 pf.dhost = dupprintf("%.*s", hostsize, NULLTOEMPTY(host));
5589 pfp = find234(ssh->rportfwds, &pf, NULL);
5592 logeventf(ssh, "Rejected remote port open request for %s:%d",
5594 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5595 PKT_INT, remoteid, PKT_END);
5597 struct ssh_channel *c = snew(struct ssh_channel);
5600 logeventf(ssh, "Received remote port open request for %s:%d",
5602 err = pfd_connect(&c->u.pfd.pf, pf.dhost, port,
5603 c, ssh->conf, pfp->pfrec->addressfamily);
5605 logeventf(ssh, "Port open failed: %s", err);
5608 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5609 PKT_INT, remoteid, PKT_END);
5611 c->remoteid = remoteid;
5612 c->halfopen = FALSE;
5613 c->localid = alloc_channel_id(ssh);
5615 c->pending_eof = FALSE;
5616 c->throttling_conn = 0;
5617 c->type = CHAN_SOCKDATA; /* identify channel type */
5618 add234(ssh->channels, c);
5619 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5620 PKT_INT, c->remoteid, PKT_INT,
5621 c->localid, PKT_END);
5622 logevent("Forwarded port opened successfully");
5629 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
5631 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5632 unsigned int localid = ssh_pkt_getuint32(pktin);
5633 struct ssh_channel *c;
5635 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5636 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5637 c->remoteid = localid;
5638 c->halfopen = FALSE;
5639 c->type = CHAN_SOCKDATA;
5640 c->throttling_conn = 0;
5641 pfd_confirm(c->u.pfd.pf);
5644 if (c && c->pending_eof) {
5646 * We have a pending close on this channel,
5647 * which we decided on before the server acked
5648 * the channel open. So now we know the
5649 * remoteid, we can close it again.
5651 ssh_channel_try_eof(c);
5655 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
5657 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5658 struct ssh_channel *c;
5660 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5661 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5662 logevent("Forwarded connection refused by server");
5663 pfd_close(c->u.pfd.pf);
5664 del234(ssh->channels, c);
5669 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
5671 /* Remote side closes a channel. */
5672 unsigned i = ssh_pkt_getuint32(pktin);
5673 struct ssh_channel *c;
5674 c = find234(ssh->channels, &i, ssh_channelfind);
5675 if (c && !c->halfopen) {
5677 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
5678 !(c->closes & CLOSES_RCVD_EOF)) {
5680 * Received CHANNEL_CLOSE, which we translate into
5683 int send_close = FALSE;
5685 c->closes |= CLOSES_RCVD_EOF;
5690 x11_send_eof(c->u.x11.xconn);
5696 pfd_send_eof(c->u.pfd.pf);
5705 if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
5706 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
5708 c->closes |= CLOSES_SENT_EOF;
5712 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
5713 !(c->closes & CLOSES_RCVD_CLOSE)) {
5715 if (!(c->closes & CLOSES_SENT_EOF)) {
5716 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %d"
5717 " for which we never sent CHANNEL_CLOSE\n", i));
5720 c->closes |= CLOSES_RCVD_CLOSE;
5723 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
5724 !(c->closes & CLOSES_SENT_CLOSE)) {
5725 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
5726 PKT_INT, c->remoteid, PKT_END);
5727 c->closes |= CLOSES_SENT_CLOSE;
5730 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
5731 ssh_channel_destroy(c);
5733 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
5734 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
5735 "_CONFIRMATION", c ? "half-open" : "nonexistent",
5741 * Handle incoming data on an SSH-1 or SSH-2 agent-forwarding channel.
5743 static int ssh_agent_channel_data(struct ssh_channel *c, char *data,
5746 while (length > 0) {
5747 if (c->u.a.lensofar < 4) {
5748 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)length);
5749 memcpy(c->u.a.msglen + c->u.a.lensofar, data, l);
5752 c->u.a.lensofar += l;
5754 if (c->u.a.lensofar == 4) {
5755 c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
5756 c->u.a.message = snewn(c->u.a.totallen, unsigned char);
5757 memcpy(c->u.a.message, c->u.a.msglen, 4);
5759 if (c->u.a.lensofar >= 4 && length > 0) {
5760 unsigned int l = min(c->u.a.totallen - c->u.a.lensofar,
5762 memcpy(c->u.a.message + c->u.a.lensofar, data, l);
5765 c->u.a.lensofar += l;
5767 if (c->u.a.lensofar == c->u.a.totallen) {
5770 c->u.a.outstanding_requests++;
5771 if (agent_query(c->u.a.message, c->u.a.totallen, &reply, &replylen,
5772 ssh_agentf_callback, c))
5773 ssh_agentf_callback(c, reply, replylen);
5774 sfree(c->u.a.message);
5775 c->u.a.message = NULL;
5776 c->u.a.lensofar = 0;
5779 return 0; /* agent channels never back up */
5782 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
5784 /* Data sent down one of our channels. */
5785 int i = ssh_pkt_getuint32(pktin);
5788 struct ssh_channel *c;
5790 ssh_pkt_getstring(pktin, &p, &len);
5792 c = find234(ssh->channels, &i, ssh_channelfind);
5797 bufsize = x11_send(c->u.x11.xconn, p, len);
5800 bufsize = pfd_send(c->u.pfd.pf, p, len);
5803 bufsize = ssh_agent_channel_data(c, p, len);
5806 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5807 c->throttling_conn = 1;
5808 ssh_throttle_conn(ssh, +1);
5813 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5815 ssh->exitcode = ssh_pkt_getuint32(pktin);
5816 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5817 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5819 * In case `helpful' firewalls or proxies tack
5820 * extra human-readable text on the end of the
5821 * session which we might mistake for another
5822 * encrypted packet, we close the session once
5823 * we've sent EXIT_CONFIRMATION.
5825 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5828 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5829 static void ssh1_send_ttymode(void *data,
5830 const struct ssh_ttymode *mode, char *val)
5832 struct Packet *pktout = (struct Packet *)data;
5833 unsigned int arg = 0;
5835 switch (mode->type) {
5837 arg = ssh_tty_parse_specchar(val);
5840 arg = ssh_tty_parse_boolean(val);
5843 ssh2_pkt_addbyte(pktout, mode->opcode);
5844 ssh2_pkt_addbyte(pktout, arg);
5847 int ssh_agent_forwarding_permitted(Ssh ssh)
5849 return conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists();
5852 static void do_ssh1_connection(Ssh ssh, const unsigned char *in, int inlen,
5853 struct Packet *pktin)
5855 crBegin(ssh->do_ssh1_connection_crstate);
5857 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5858 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5859 ssh1_smsg_stdout_stderr_data;
5861 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5862 ssh1_msg_channel_open_confirmation;
5863 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5864 ssh1_msg_channel_open_failure;
5865 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5866 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5867 ssh1_msg_channel_close;
5868 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5869 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5871 if (ssh_agent_forwarding_permitted(ssh)) {
5872 logevent("Requesting agent forwarding");
5873 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5877 if (pktin->type != SSH1_SMSG_SUCCESS
5878 && pktin->type != SSH1_SMSG_FAILURE) {
5879 bombout(("Protocol confusion"));
5881 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5882 logevent("Agent forwarding refused");
5884 logevent("Agent forwarding enabled");
5885 ssh->agentfwd_enabled = TRUE;
5886 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5890 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
5892 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5894 if (!ssh->x11disp) {
5895 /* FIXME: return an error message from x11_setup_display */
5896 logevent("X11 forwarding not enabled: unable to"
5897 " initialise X display");
5899 ssh->x11auth = x11_invent_fake_auth
5900 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
5901 ssh->x11auth->disp = ssh->x11disp;
5903 logevent("Requesting X11 forwarding");
5904 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5905 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5906 PKT_STR, ssh->x11auth->protoname,
5907 PKT_STR, ssh->x11auth->datastring,
5908 PKT_INT, ssh->x11disp->screennum,
5911 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5912 PKT_STR, ssh->x11auth->protoname,
5913 PKT_STR, ssh->x11auth->datastring,
5919 if (pktin->type != SSH1_SMSG_SUCCESS
5920 && pktin->type != SSH1_SMSG_FAILURE) {
5921 bombout(("Protocol confusion"));
5923 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5924 logevent("X11 forwarding refused");
5926 logevent("X11 forwarding enabled");
5927 ssh->X11_fwd_enabled = TRUE;
5928 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5933 ssh_setup_portfwd(ssh, ssh->conf);
5934 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5936 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5938 /* Unpick the terminal-speed string. */
5939 /* XXX perhaps we should allow no speeds to be sent. */
5940 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5941 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5942 /* Send the pty request. */
5943 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5944 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5945 ssh_pkt_adduint32(pkt, ssh->term_height);
5946 ssh_pkt_adduint32(pkt, ssh->term_width);
5947 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5948 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5949 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5950 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5951 ssh_pkt_adduint32(pkt, ssh->ispeed);
5952 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5953 ssh_pkt_adduint32(pkt, ssh->ospeed);
5954 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5956 ssh->state = SSH_STATE_INTERMED;
5960 if (pktin->type != SSH1_SMSG_SUCCESS
5961 && pktin->type != SSH1_SMSG_FAILURE) {
5962 bombout(("Protocol confusion"));
5964 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5965 c_write_str(ssh, "Server refused to allocate pty\r\n");
5966 ssh->editing = ssh->echoing = 1;
5968 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5969 ssh->ospeed, ssh->ispeed);
5970 ssh->got_pty = TRUE;
5973 ssh->editing = ssh->echoing = 1;
5976 if (conf_get_int(ssh->conf, CONF_compression)) {
5977 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5981 if (pktin->type != SSH1_SMSG_SUCCESS
5982 && pktin->type != SSH1_SMSG_FAILURE) {
5983 bombout(("Protocol confusion"));
5985 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5986 c_write_str(ssh, "Server refused to compress\r\n");
5988 logevent("Started compression");
5989 ssh->v1_compressing = TRUE;
5990 ssh->cs_comp_ctx = zlib_compress_init();
5991 logevent("Initialised zlib (RFC1950) compression");
5992 ssh->sc_comp_ctx = zlib_decompress_init();
5993 logevent("Initialised zlib (RFC1950) decompression");
5997 * Start the shell or command.
5999 * Special case: if the first-choice command is an SSH-2
6000 * subsystem (hence not usable here) and the second choice
6001 * exists, we fall straight back to that.
6004 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
6006 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
6007 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
6008 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
6009 ssh->fallback_cmd = TRUE;
6012 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
6014 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
6015 logevent("Started session");
6018 ssh->state = SSH_STATE_SESSION;
6019 if (ssh->size_needed)
6020 ssh_size(ssh, ssh->term_width, ssh->term_height);
6021 if (ssh->eof_needed)
6022 ssh_special(ssh, TS_EOF);
6025 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
6027 ssh->channels = newtree234(ssh_channelcmp);
6031 * By this point, most incoming packets are already being
6032 * handled by the dispatch table, and we need only pay
6033 * attention to the unusual ones.
6038 if (pktin->type == SSH1_SMSG_SUCCESS) {
6039 /* may be from EXEC_SHELL on some servers */
6040 } else if (pktin->type == SSH1_SMSG_FAILURE) {
6041 /* may be from EXEC_SHELL on some servers
6042 * if no pty is available or in other odd cases. Ignore */
6044 bombout(("Strange packet received: type %d", pktin->type));
6049 int len = min(inlen, 512);
6050 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
6051 PKT_INT, len, PKT_DATA, in, len,
6063 * Handle the top-level SSH-2 protocol.
6065 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
6070 ssh_pkt_getstring(pktin, &msg, &msglen);
6071 logeventf(ssh, "Remote debug message: %.*s", msglen, NULLTOEMPTY(msg));
6074 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
6076 /* log reason code in disconnect message */
6080 ssh_pkt_getstring(pktin, &msg, &msglen);
6081 bombout(("Server sent disconnect message:\n\"%.*s\"",
6082 msglen, NULLTOEMPTY(msg)));
6085 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
6087 /* Do nothing, because we're ignoring it! Duhh. */
6090 static void ssh1_protocol_setup(Ssh ssh)
6095 * Most messages are handled by the coroutines.
6097 for (i = 0; i < 256; i++)
6098 ssh->packet_dispatch[i] = NULL;
6101 * These special message types we install handlers for.
6103 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
6104 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
6105 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
6108 static void ssh1_protocol(Ssh ssh, const void *vin, int inlen,
6109 struct Packet *pktin)
6111 const unsigned char *in = (const unsigned char *)vin;
6112 if (ssh->state == SSH_STATE_CLOSED)
6115 if (pktin && ssh->packet_dispatch[pktin->type]) {
6116 ssh->packet_dispatch[pktin->type](ssh, pktin);
6120 if (!ssh->protocol_initial_phase_done) {
6121 if (do_ssh1_login(ssh, in, inlen, pktin))
6122 ssh->protocol_initial_phase_done = TRUE;
6127 do_ssh1_connection(ssh, in, inlen, pktin);
6131 * Utility routines for decoding comma-separated strings in KEXINIT.
6133 static int first_in_commasep_string(char const *needle, char const *haystack,
6137 if (!needle || !haystack) /* protect against null pointers */
6139 needlen = strlen(needle);
6141 if (haylen >= needlen && /* haystack is long enough */
6142 !memcmp(needle, haystack, needlen) && /* initial match */
6143 (haylen == needlen || haystack[needlen] == ',')
6144 /* either , or EOS follows */
6150 static int in_commasep_string(char const *needle, char const *haystack,
6155 if (!needle || !haystack) /* protect against null pointers */
6158 * Is it at the start of the string?
6160 if (first_in_commasep_string(needle, haystack, haylen))
6163 * If not, search for the next comma and resume after that.
6164 * If no comma found, terminate.
6166 p = memchr(haystack, ',', haylen);
6168 /* + 1 to skip over comma */
6169 return in_commasep_string(needle, p + 1, haylen - (p + 1 - haystack));
6173 * Add a value to the comma-separated string at the end of the packet.
6175 static void ssh2_pkt_addstring_commasep(struct Packet *pkt, const char *data)
6177 if (pkt->length - pkt->savedpos > 0)
6178 ssh_pkt_addstring_str(pkt, ",");
6179 ssh_pkt_addstring_str(pkt, data);
6184 * SSH-2 key derivation (RFC 4253 section 7.2).
6186 static unsigned char *ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H,
6187 char chr, int keylen)
6189 const struct ssh_hash *h = ssh->kex->hash;
6197 /* Round up to the next multiple of hash length. */
6198 keylen_padded = ((keylen + h->hlen - 1) / h->hlen) * h->hlen;
6200 key = snewn(keylen_padded, unsigned char);
6202 /* First hlen bytes. */
6204 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6205 hash_mpint(h, s, K);
6206 h->bytes(s, H, h->hlen);
6207 h->bytes(s, &chr, 1);
6208 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
6211 /* Subsequent blocks of hlen bytes. */
6212 if (keylen_padded > h->hlen) {
6216 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6217 hash_mpint(h, s, K);
6218 h->bytes(s, H, h->hlen);
6220 for (offset = h->hlen; offset < keylen_padded; offset += h->hlen) {
6221 h->bytes(s, key + offset - h->hlen, h->hlen);
6223 h->final(s2, key + offset);
6229 /* Now clear any extra bytes of key material beyond the length
6230 * we're officially returning, because the caller won't know to
6232 if (keylen_padded > keylen)
6233 smemclr(key + keylen, keylen_padded - keylen);
6239 * Structure for constructing KEXINIT algorithm lists.
6241 #define MAXKEXLIST 16
6242 struct kexinit_algorithm {
6246 const struct ssh_kex *kex;
6250 const struct ssh_signkey *hostkey;
6254 const struct ssh2_cipher *cipher;
6258 const struct ssh_mac *mac;
6261 const struct ssh_compress *comp;
6266 * Find a slot in a KEXINIT algorithm list to use for a new algorithm.
6267 * If the algorithm is already in the list, return a pointer to its
6268 * entry, otherwise return an entry from the end of the list.
6269 * This assumes that every time a particular name is passed in, it
6270 * comes from the same string constant. If this isn't true, this
6271 * function may need to be rewritten to use strcmp() instead.
6273 static struct kexinit_algorithm *ssh2_kexinit_addalg(struct kexinit_algorithm
6274 *list, const char *name)
6278 for (i = 0; i < MAXKEXLIST; i++)
6279 if (list[i].name == NULL || list[i].name == name) {
6280 list[i].name = name;
6283 assert(!"No space in KEXINIT list");
6288 * Handle the SSH-2 transport layer.
6290 static void do_ssh2_transport(Ssh ssh, const void *vin, int inlen,
6291 struct Packet *pktin)
6293 const unsigned char *in = (const unsigned char *)vin;
6295 KEXLIST_KEX, KEXLIST_HOSTKEY, KEXLIST_CSCIPHER, KEXLIST_SCCIPHER,
6296 KEXLIST_CSMAC, KEXLIST_SCMAC, KEXLIST_CSCOMP, KEXLIST_SCCOMP,
6299 const char * kexlist_descr[NKEXLIST] = {
6300 "key exchange algorithm", "host key algorithm",
6301 "client-to-server cipher", "server-to-client cipher",
6302 "client-to-server MAC", "server-to-client MAC",
6303 "client-to-server compression method",
6304 "server-to-client compression method" };
6305 struct do_ssh2_transport_state {
6307 int nbits, pbits, warn_kex, warn_hk, warn_cscipher, warn_sccipher;
6308 Bignum p, g, e, f, K;
6311 int kex_init_value, kex_reply_value;
6312 const struct ssh_mac *const *maclist;
6314 const struct ssh2_cipher *cscipher_tobe;
6315 const struct ssh2_cipher *sccipher_tobe;
6316 const struct ssh_mac *csmac_tobe;
6317 const struct ssh_mac *scmac_tobe;
6318 int csmac_etm_tobe, scmac_etm_tobe;
6319 const struct ssh_compress *cscomp_tobe;
6320 const struct ssh_compress *sccomp_tobe;
6321 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
6322 int hostkeylen, siglen, rsakeylen;
6323 void *hkey; /* actual host key */
6324 void *rsakey; /* for RSA kex */
6325 void *eckey; /* for ECDH kex */
6326 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
6327 int n_preferred_kex;
6328 const struct ssh_kexes *preferred_kex[KEX_MAX];
6330 int preferred_hk[HK_MAX];
6331 int n_preferred_ciphers;
6332 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
6333 const struct ssh_compress *preferred_comp;
6334 int userauth_succeeded; /* for delayed compression */
6335 int pending_compression;
6336 int got_session_id, activated_authconn;
6337 struct Packet *pktout;
6341 struct kexinit_algorithm kexlists[NKEXLIST][MAXKEXLIST];
6343 crState(do_ssh2_transport_state);
6345 assert(!ssh->bare_connection);
6346 assert(ssh->version == 2);
6350 s->cscipher_tobe = s->sccipher_tobe = NULL;
6351 s->csmac_tobe = s->scmac_tobe = NULL;
6352 s->cscomp_tobe = s->sccomp_tobe = NULL;
6354 s->got_session_id = s->activated_authconn = FALSE;
6355 s->userauth_succeeded = FALSE;
6356 s->pending_compression = FALSE;
6359 * Be prepared to work around the buggy MAC problem.
6361 if (ssh->remote_bugs & BUG_SSH2_HMAC)
6362 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
6364 s->maclist = macs, s->nmacs = lenof(macs);
6367 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
6370 struct kexinit_algorithm *alg;
6373 * Set up the preferred key exchange. (NULL => warn below here)
6375 s->n_preferred_kex = 0;
6376 for (i = 0; i < KEX_MAX; i++) {
6377 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
6379 s->preferred_kex[s->n_preferred_kex++] =
6380 &ssh_diffiehellman_gex;
6383 s->preferred_kex[s->n_preferred_kex++] =
6384 &ssh_diffiehellman_group14;
6387 s->preferred_kex[s->n_preferred_kex++] =
6388 &ssh_diffiehellman_group1;
6391 s->preferred_kex[s->n_preferred_kex++] =
6395 s->preferred_kex[s->n_preferred_kex++] =
6399 /* Flag for later. Don't bother if it's the last in
6401 if (i < KEX_MAX - 1) {
6402 s->preferred_kex[s->n_preferred_kex++] = NULL;
6409 * Set up the preferred host key types. These are just the ids
6410 * in the enum in putty.h, so 'warn below here' is indicated
6413 s->n_preferred_hk = 0;
6414 for (i = 0; i < HK_MAX; i++) {
6415 int id = conf_get_int_int(ssh->conf, CONF_ssh_hklist, i);
6416 /* As above, don't bother with HK_WARN if it's last in the
6418 if (id != HK_WARN || i < HK_MAX - 1)
6419 s->preferred_hk[s->n_preferred_hk++] = id;
6423 * Set up the preferred ciphers. (NULL => warn below here)
6425 s->n_preferred_ciphers = 0;
6426 for (i = 0; i < CIPHER_MAX; i++) {
6427 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
6428 case CIPHER_BLOWFISH:
6429 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
6432 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
6433 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
6437 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
6440 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
6442 case CIPHER_ARCFOUR:
6443 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
6445 case CIPHER_CHACHA20:
6446 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_ccp;
6449 /* Flag for later. Don't bother if it's the last in
6451 if (i < CIPHER_MAX - 1) {
6452 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
6459 * Set up preferred compression.
6461 if (conf_get_int(ssh->conf, CONF_compression))
6462 s->preferred_comp = &ssh_zlib;
6464 s->preferred_comp = &ssh_comp_none;
6467 * Enable queueing of outgoing auth- or connection-layer
6468 * packets while we are in the middle of a key exchange.
6470 ssh->queueing = TRUE;
6473 * Flag that KEX is in progress.
6475 ssh->kex_in_progress = TRUE;
6477 for (i = 0; i < NKEXLIST; i++)
6478 for (j = 0; j < MAXKEXLIST; j++)
6479 s->kexlists[i][j].name = NULL;
6480 /* List key exchange algorithms. */
6482 for (i = 0; i < s->n_preferred_kex; i++) {
6483 const struct ssh_kexes *k = s->preferred_kex[i];
6484 if (!k) warn = TRUE;
6485 else for (j = 0; j < k->nkexes; j++) {
6486 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_KEX],
6488 alg->u.kex.kex = k->list[j];
6489 alg->u.kex.warn = warn;
6492 /* List server host key algorithms. */
6493 if (!s->got_session_id) {
6495 * In the first key exchange, we list all the algorithms
6496 * we're prepared to cope with, but prefer those algorithms
6497 * for which we have a host key for this host.
6499 * If the host key algorithm is below the warning
6500 * threshold, we warn even if we did already have a key
6501 * for it, on the basis that if the user has just
6502 * reconfigured that host key type to be warned about,
6503 * they surely _do_ want to be alerted that a server
6504 * they're actually connecting to is using it.
6507 for (i = 0; i < s->n_preferred_hk; i++) {
6508 if (s->preferred_hk[i] == HK_WARN)
6510 for (j = 0; j < lenof(hostkey_algs); j++) {
6511 if (hostkey_algs[j].id != s->preferred_hk[i])
6513 if (have_ssh_host_key(ssh->savedhost, ssh->savedport,
6514 hostkey_algs[j].alg->keytype)) {
6515 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6516 hostkey_algs[j].alg->name);
6517 alg->u.hk.hostkey = hostkey_algs[j].alg;
6518 alg->u.hk.warn = warn;
6523 for (i = 0; i < s->n_preferred_hk; i++) {
6524 if (s->preferred_hk[i] == HK_WARN)
6526 for (j = 0; j < lenof(hostkey_algs); j++) {
6527 if (hostkey_algs[j].id != s->preferred_hk[i])
6529 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6530 hostkey_algs[j].alg->name);
6531 alg->u.hk.hostkey = hostkey_algs[j].alg;
6532 alg->u.hk.warn = warn;
6537 * In subsequent key exchanges, we list only the kex
6538 * algorithm that was selected in the first key exchange,
6539 * so that we keep getting the same host key and hence
6540 * don't have to interrupt the user's session to ask for
6544 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6545 ssh->hostkey->name);
6546 alg->u.hk.hostkey = ssh->hostkey;
6547 alg->u.hk.warn = FALSE;
6549 /* List encryption algorithms (client->server then server->client). */
6550 for (k = KEXLIST_CSCIPHER; k <= KEXLIST_SCCIPHER; k++) {
6553 alg = ssh2_kexinit_addalg(s->kexlists[k], "none");
6554 alg->u.cipher.cipher = NULL;
6555 alg->u.cipher.warn = warn;
6556 #endif /* FUZZING */
6557 for (i = 0; i < s->n_preferred_ciphers; i++) {
6558 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6559 if (!c) warn = TRUE;
6560 else for (j = 0; j < c->nciphers; j++) {
6561 alg = ssh2_kexinit_addalg(s->kexlists[k],
6563 alg->u.cipher.cipher = c->list[j];
6564 alg->u.cipher.warn = warn;
6568 /* List MAC algorithms (client->server then server->client). */
6569 for (j = KEXLIST_CSMAC; j <= KEXLIST_SCMAC; j++) {
6571 alg = ssh2_kexinit_addalg(s->kexlists[j], "none");
6572 alg->u.mac.mac = NULL;
6573 alg->u.mac.etm = FALSE;
6574 #endif /* FUZZING */
6575 for (i = 0; i < s->nmacs; i++) {
6576 alg = ssh2_kexinit_addalg(s->kexlists[j], s->maclist[i]->name);
6577 alg->u.mac.mac = s->maclist[i];
6578 alg->u.mac.etm = FALSE;
6580 for (i = 0; i < s->nmacs; i++)
6581 /* For each MAC, there may also be an ETM version,
6582 * which we list second. */
6583 if (s->maclist[i]->etm_name) {
6584 alg = ssh2_kexinit_addalg(s->kexlists[j],
6585 s->maclist[i]->etm_name);
6586 alg->u.mac.mac = s->maclist[i];
6587 alg->u.mac.etm = TRUE;
6590 /* List client->server compression algorithms,
6591 * then server->client compression algorithms. (We use the
6592 * same set twice.) */
6593 for (j = KEXLIST_CSCOMP; j <= KEXLIST_SCCOMP; j++) {
6594 assert(lenof(compressions) > 1);
6595 /* Prefer non-delayed versions */
6596 alg = ssh2_kexinit_addalg(s->kexlists[j], s->preferred_comp->name);
6597 alg->u.comp = s->preferred_comp;
6598 /* We don't even list delayed versions of algorithms until
6599 * they're allowed to be used, to avoid a race. See the end of
6601 if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
6602 alg = ssh2_kexinit_addalg(s->kexlists[j],
6603 s->preferred_comp->delayed_name);
6604 alg->u.comp = s->preferred_comp;
6606 for (i = 0; i < lenof(compressions); i++) {
6607 const struct ssh_compress *c = compressions[i];
6608 alg = ssh2_kexinit_addalg(s->kexlists[j], c->name);
6610 if (s->userauth_succeeded && c->delayed_name) {
6611 alg = ssh2_kexinit_addalg(s->kexlists[j], c->delayed_name);
6617 * Construct and send our key exchange packet.
6619 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
6620 for (i = 0; i < 16; i++)
6621 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
6622 for (i = 0; i < NKEXLIST; i++) {
6623 ssh2_pkt_addstring_start(s->pktout);
6624 for (j = 0; j < MAXKEXLIST; j++) {
6625 if (s->kexlists[i][j].name == NULL) break;
6626 ssh2_pkt_addstring_commasep(s->pktout, s->kexlists[i][j].name);
6629 /* List client->server languages. Empty list. */
6630 ssh2_pkt_addstring_start(s->pktout);
6631 /* List server->client languages. Empty list. */
6632 ssh2_pkt_addstring_start(s->pktout);
6633 /* First KEX packet does _not_ follow, because we're not that brave. */
6634 ssh2_pkt_addbool(s->pktout, FALSE);
6636 ssh2_pkt_adduint32(s->pktout, 0);
6639 s->our_kexinitlen = s->pktout->length - 5;
6640 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
6641 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
6643 ssh2_pkt_send_noqueue(ssh, s->pktout);
6646 crWaitUntilV(pktin);
6649 * Now examine the other side's KEXINIT to see what we're up
6656 if (pktin->type != SSH2_MSG_KEXINIT) {
6657 bombout(("expected key exchange packet from server"));
6661 ssh->hostkey = NULL;
6662 s->cscipher_tobe = NULL;
6663 s->sccipher_tobe = NULL;
6664 s->csmac_tobe = NULL;
6665 s->scmac_tobe = NULL;
6666 s->cscomp_tobe = NULL;
6667 s->sccomp_tobe = NULL;
6668 s->warn_kex = s->warn_hk = FALSE;
6669 s->warn_cscipher = s->warn_sccipher = FALSE;
6671 pktin->savedpos += 16; /* skip garbage cookie */
6674 for (i = 0; i < NKEXLIST; i++) {
6675 ssh_pkt_getstring(pktin, &str, &len);
6677 bombout(("KEXINIT packet was incomplete"));
6681 /* If we've already selected a cipher which requires a
6682 * particular MAC, then just select that, and don't even
6683 * bother looking through the server's KEXINIT string for
6685 if (i == KEXLIST_CSMAC && s->cscipher_tobe &&
6686 s->cscipher_tobe->required_mac) {
6687 s->csmac_tobe = s->cscipher_tobe->required_mac;
6688 s->csmac_etm_tobe = !!(s->csmac_tobe->etm_name);
6691 if (i == KEXLIST_SCMAC && s->sccipher_tobe &&
6692 s->sccipher_tobe->required_mac) {
6693 s->scmac_tobe = s->sccipher_tobe->required_mac;
6694 s->scmac_etm_tobe = !!(s->scmac_tobe->etm_name);
6698 for (j = 0; j < MAXKEXLIST; j++) {
6699 struct kexinit_algorithm *alg = &s->kexlists[i][j];
6700 if (alg->name == NULL) break;
6701 if (in_commasep_string(alg->name, str, len)) {
6702 /* We've found a matching algorithm. */
6703 if (i == KEXLIST_KEX || i == KEXLIST_HOSTKEY) {
6704 /* Check if we might need to ignore first kex pkt */
6706 !first_in_commasep_string(alg->name, str, len))
6709 if (i == KEXLIST_KEX) {
6710 ssh->kex = alg->u.kex.kex;
6711 s->warn_kex = alg->u.kex.warn;
6712 } else if (i == KEXLIST_HOSTKEY) {
6713 ssh->hostkey = alg->u.hk.hostkey;
6714 s->warn_hk = alg->u.hk.warn;
6715 } else if (i == KEXLIST_CSCIPHER) {
6716 s->cscipher_tobe = alg->u.cipher.cipher;
6717 s->warn_cscipher = alg->u.cipher.warn;
6718 } else if (i == KEXLIST_SCCIPHER) {
6719 s->sccipher_tobe = alg->u.cipher.cipher;
6720 s->warn_sccipher = alg->u.cipher.warn;
6721 } else if (i == KEXLIST_CSMAC) {
6722 s->csmac_tobe = alg->u.mac.mac;
6723 s->csmac_etm_tobe = alg->u.mac.etm;
6724 } else if (i == KEXLIST_SCMAC) {
6725 s->scmac_tobe = alg->u.mac.mac;
6726 s->scmac_etm_tobe = alg->u.mac.etm;
6727 } else if (i == KEXLIST_CSCOMP) {
6728 s->cscomp_tobe = alg->u.comp;
6729 } else if (i == KEXLIST_SCCOMP) {
6730 s->sccomp_tobe = alg->u.comp;
6734 if ((i == KEXLIST_CSCOMP || i == KEXLIST_SCCOMP) &&
6735 in_commasep_string(alg->u.comp->delayed_name, str, len))
6736 s->pending_compression = TRUE; /* try this later */
6738 bombout(("Couldn't agree a %s (available: %.*s)",
6739 kexlist_descr[i], len, str));
6743 if (i == KEXLIST_HOSTKEY) {
6747 * In addition to deciding which host key we're
6748 * actually going to use, we should make a list of the
6749 * host keys offered by the server which we _don't_
6750 * have cached. These will be offered as cross-
6751 * certification options by ssh_get_specials.
6753 * We also count the key we're currently using for KEX
6754 * as one we've already got, because by the time this
6755 * menu becomes visible, it will be.
6757 ssh->n_uncert_hostkeys = 0;
6759 for (j = 0; j < lenof(hostkey_algs); j++) {
6760 if (hostkey_algs[j].alg != ssh->hostkey &&
6761 in_commasep_string(hostkey_algs[j].alg->name,
6763 !have_ssh_host_key(ssh->savedhost, ssh->savedport,
6764 hostkey_algs[j].alg->keytype)) {
6765 ssh->uncert_hostkeys[ssh->n_uncert_hostkeys++] = j;
6771 if (s->pending_compression) {
6772 logevent("Server supports delayed compression; "
6773 "will try this later");
6775 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
6776 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
6777 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
6779 ssh->exhash = ssh->kex->hash->init();
6780 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
6781 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
6782 hash_string(ssh->kex->hash, ssh->exhash,
6783 s->our_kexinit, s->our_kexinitlen);
6784 sfree(s->our_kexinit);
6785 /* Include the type byte in the hash of server's KEXINIT */
6786 hash_string(ssh->kex->hash, ssh->exhash,
6787 pktin->body - 1, pktin->length + 1);
6790 ssh_set_frozen(ssh, 1);
6791 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
6793 ssh_dialog_callback, ssh);
6794 if (s->dlgret < 0) {
6798 bombout(("Unexpected data from server while"
6799 " waiting for user response"));
6802 } while (pktin || inlen > 0);
6803 s->dlgret = ssh->user_response;
6805 ssh_set_frozen(ssh, 0);
6806 if (s->dlgret == 0) {
6807 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
6817 ssh_set_frozen(ssh, 1);
6820 * Change warning box wording depending on why we chose a
6821 * warning-level host key algorithm. If it's because
6822 * that's all we have *cached*, use the askhk mechanism,
6823 * and list the host keys we could usefully cross-certify.
6824 * Otherwise, use askalg for the standard wording.
6827 for (j = 0; j < ssh->n_uncert_hostkeys; j++) {
6828 const struct ssh_signkey_with_user_pref_id *hktype =
6829 &hostkey_algs[ssh->uncert_hostkeys[j]];
6831 for (k = 0; k < HK_MAX; k++) {
6832 int id = conf_get_int_int(ssh->conf, CONF_ssh_hklist, k);
6833 if (id == HK_WARN) {
6835 } else if (id == hktype->id) {
6842 char *old_ba = betteralgs;
6843 betteralgs = dupcat(betteralgs, ",",
6845 (const char *)NULL);
6848 betteralgs = dupstr(hktype->alg->name);
6853 s->dlgret = askhk(ssh->frontend, ssh->hostkey->name,
6854 betteralgs, ssh_dialog_callback, ssh);
6857 s->dlgret = askalg(ssh->frontend, "host key type",
6859 ssh_dialog_callback, ssh);
6861 if (s->dlgret < 0) {
6865 bombout(("Unexpected data from server while"
6866 " waiting for user response"));
6869 } while (pktin || inlen > 0);
6870 s->dlgret = ssh->user_response;
6872 ssh_set_frozen(ssh, 0);
6873 if (s->dlgret == 0) {
6874 ssh_disconnect(ssh, "User aborted at host key warning", NULL,
6880 if (s->warn_cscipher) {
6881 ssh_set_frozen(ssh, 1);
6882 s->dlgret = askalg(ssh->frontend,
6883 "client-to-server cipher",
6884 s->cscipher_tobe->name,
6885 ssh_dialog_callback, ssh);
6886 if (s->dlgret < 0) {
6890 bombout(("Unexpected data from server while"
6891 " waiting for user response"));
6894 } while (pktin || inlen > 0);
6895 s->dlgret = ssh->user_response;
6897 ssh_set_frozen(ssh, 0);
6898 if (s->dlgret == 0) {
6899 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6905 if (s->warn_sccipher) {
6906 ssh_set_frozen(ssh, 1);
6907 s->dlgret = askalg(ssh->frontend,
6908 "server-to-client cipher",
6909 s->sccipher_tobe->name,
6910 ssh_dialog_callback, ssh);
6911 if (s->dlgret < 0) {
6915 bombout(("Unexpected data from server while"
6916 " waiting for user response"));
6919 } while (pktin || inlen > 0);
6920 s->dlgret = ssh->user_response;
6922 ssh_set_frozen(ssh, 0);
6923 if (s->dlgret == 0) {
6924 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6930 if (s->ignorepkt) /* first_kex_packet_follows */
6931 crWaitUntilV(pktin); /* Ignore packet */
6934 if (ssh->kex->main_type == KEXTYPE_DH) {
6936 * Work out the number of bits of key we will need from the
6937 * key exchange. We start with the maximum key length of
6943 csbits = s->cscipher_tobe ? s->cscipher_tobe->real_keybits : 0;
6944 scbits = s->sccipher_tobe ? s->sccipher_tobe->real_keybits : 0;
6945 s->nbits = (csbits > scbits ? csbits : scbits);
6947 /* The keys only have hlen-bit entropy, since they're based on
6948 * a hash. So cap the key size at hlen bits. */
6949 if (s->nbits > ssh->kex->hash->hlen * 8)
6950 s->nbits = ssh->kex->hash->hlen * 8;
6953 * If we're doing Diffie-Hellman group exchange, start by
6954 * requesting a group.
6956 if (dh_is_gex(ssh->kex)) {
6957 logevent("Doing Diffie-Hellman group exchange");
6958 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
6960 * Work out how big a DH group we will need to allow that
6963 s->pbits = 512 << ((s->nbits - 1) / 64);
6964 if (s->pbits < DH_MIN_SIZE)
6965 s->pbits = DH_MIN_SIZE;
6966 if (s->pbits > DH_MAX_SIZE)
6967 s->pbits = DH_MAX_SIZE;
6968 if ((ssh->remote_bugs & BUG_SSH2_OLDGEX)) {
6969 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD);
6970 ssh2_pkt_adduint32(s->pktout, s->pbits);
6972 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
6973 ssh2_pkt_adduint32(s->pktout, DH_MIN_SIZE);
6974 ssh2_pkt_adduint32(s->pktout, s->pbits);
6975 ssh2_pkt_adduint32(s->pktout, DH_MAX_SIZE);
6977 ssh2_pkt_send_noqueue(ssh, s->pktout);
6979 crWaitUntilV(pktin);
6980 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
6981 bombout(("expected key exchange group packet from server"));
6984 s->p = ssh2_pkt_getmp(pktin);
6985 s->g = ssh2_pkt_getmp(pktin);
6986 if (!s->p || !s->g) {
6987 bombout(("unable to read mp-ints from incoming group packet"));
6990 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
6991 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
6992 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
6994 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
6995 ssh->kex_ctx = dh_setup_group(ssh->kex);
6996 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
6997 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
6998 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
6999 ssh->kex->groupname);
7002 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
7003 ssh->kex->hash->text_name);
7005 * Now generate and send e for Diffie-Hellman.
7007 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
7008 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
7009 s->pktout = ssh2_pkt_init(s->kex_init_value);
7010 ssh2_pkt_addmp(s->pktout, s->e);
7011 ssh2_pkt_send_noqueue(ssh, s->pktout);
7013 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
7014 crWaitUntilV(pktin);
7015 if (pktin->type != s->kex_reply_value) {
7016 bombout(("expected key exchange reply packet from server"));
7019 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
7020 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7021 if (!s->hostkeydata) {
7022 bombout(("unable to parse key exchange reply packet"));
7025 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7026 s->hostkeydata, s->hostkeylen);
7027 s->f = ssh2_pkt_getmp(pktin);
7029 bombout(("unable to parse key exchange reply packet"));
7032 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7034 bombout(("unable to parse key exchange reply packet"));
7039 const char *err = dh_validate_f(ssh->kex_ctx, s->f);
7041 bombout(("key exchange reply failed validation: %s", err));
7045 s->K = dh_find_K(ssh->kex_ctx, s->f);
7047 /* We assume everything from now on will be quick, and it might
7048 * involve user interaction. */
7049 set_busy_status(ssh->frontend, BUSY_NOT);
7051 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
7052 if (dh_is_gex(ssh->kex)) {
7053 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
7054 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MIN_SIZE);
7055 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
7056 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
7057 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MAX_SIZE);
7058 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
7059 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
7061 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
7062 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
7064 dh_cleanup(ssh->kex_ctx);
7066 if (dh_is_gex(ssh->kex)) {
7070 } else if (ssh->kex->main_type == KEXTYPE_ECDH) {
7072 logeventf(ssh, "Doing ECDH key exchange with curve %s and hash %s",
7073 ssh_ecdhkex_curve_textname(ssh->kex),
7074 ssh->kex->hash->text_name);
7075 ssh->pkt_kctx = SSH2_PKTCTX_ECDHKEX;
7077 s->eckey = ssh_ecdhkex_newkey(ssh->kex);
7079 bombout(("Unable to generate key for ECDH"));
7085 int publicPointLength;
7086 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
7088 ssh_ecdhkex_freekey(s->eckey);
7089 bombout(("Unable to encode public key for ECDH"));
7092 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_ECDH_INIT);
7093 ssh2_pkt_addstring_start(s->pktout);
7094 ssh2_pkt_addstring_data(s->pktout, publicPoint, publicPointLength);
7098 ssh2_pkt_send_noqueue(ssh, s->pktout);
7100 crWaitUntilV(pktin);
7101 if (pktin->type != SSH2_MSG_KEX_ECDH_REPLY) {
7102 ssh_ecdhkex_freekey(s->eckey);
7103 bombout(("expected ECDH reply packet from server"));
7107 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7108 if (!s->hostkeydata) {
7109 bombout(("unable to parse ECDH reply packet"));
7112 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
7113 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7114 s->hostkeydata, s->hostkeylen);
7118 int publicPointLength;
7119 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
7121 ssh_ecdhkex_freekey(s->eckey);
7122 bombout(("Unable to encode public key for ECDH hash"));
7125 hash_string(ssh->kex->hash, ssh->exhash,
7126 publicPoint, publicPointLength);
7133 ssh_pkt_getstring(pktin, &keydata, &keylen);
7135 bombout(("unable to parse ECDH reply packet"));
7138 hash_string(ssh->kex->hash, ssh->exhash, keydata, keylen);
7139 s->K = ssh_ecdhkex_getkey(s->eckey, keydata, keylen);
7141 ssh_ecdhkex_freekey(s->eckey);
7142 bombout(("point received in ECDH was not valid"));
7147 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7149 bombout(("unable to parse key exchange reply packet"));
7153 ssh_ecdhkex_freekey(s->eckey);
7155 logeventf(ssh, "Doing RSA key exchange with hash %s",
7156 ssh->kex->hash->text_name);
7157 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
7159 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
7162 crWaitUntilV(pktin);
7163 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
7164 bombout(("expected RSA public key packet from server"));
7168 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7169 if (!s->hostkeydata) {
7170 bombout(("unable to parse RSA public key packet"));
7173 hash_string(ssh->kex->hash, ssh->exhash,
7174 s->hostkeydata, s->hostkeylen);
7175 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7176 s->hostkeydata, s->hostkeylen);
7180 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
7182 bombout(("unable to parse RSA public key packet"));
7185 s->rsakeydata = snewn(s->rsakeylen, char);
7186 memcpy(s->rsakeydata, keydata, s->rsakeylen);
7189 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
7191 sfree(s->rsakeydata);
7192 bombout(("unable to parse RSA public key from server"));
7196 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
7199 * Next, set up a shared secret K, of precisely KLEN -
7200 * 2*HLEN - 49 bits, where KLEN is the bit length of the
7201 * RSA key modulus and HLEN is the bit length of the hash
7205 int klen = ssh_rsakex_klen(s->rsakey);
7206 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
7208 unsigned char *kstr1, *kstr2, *outstr;
7209 int kstr1len, kstr2len, outstrlen;
7211 s->K = bn_power_2(nbits - 1);
7213 for (i = 0; i < nbits; i++) {
7215 byte = random_byte();
7217 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
7221 * Encode this as an mpint.
7223 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
7224 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
7225 PUT_32BIT(kstr2, kstr1len);
7226 memcpy(kstr2 + 4, kstr1, kstr1len);
7229 * Encrypt it with the given RSA key.
7231 outstrlen = (klen + 7) / 8;
7232 outstr = snewn(outstrlen, unsigned char);
7233 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
7234 outstr, outstrlen, s->rsakey);
7237 * And send it off in a return packet.
7239 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
7240 ssh2_pkt_addstring_start(s->pktout);
7241 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
7242 ssh2_pkt_send_noqueue(ssh, s->pktout);
7244 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
7251 ssh_rsakex_freekey(s->rsakey);
7253 crWaitUntilV(pktin);
7254 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
7255 sfree(s->rsakeydata);
7256 bombout(("expected signature packet from server"));
7260 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7262 bombout(("unable to parse signature packet"));
7266 sfree(s->rsakeydata);
7269 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
7270 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
7271 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
7273 ssh->kex_ctx = NULL;
7276 debug(("Exchange hash is:\n"));
7277 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
7281 bombout(("Server's host key is invalid"));
7285 if (!ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
7286 (char *)s->exchange_hash,
7287 ssh->kex->hash->hlen)) {
7289 bombout(("Server's host key did not match the signature supplied"));
7294 s->keystr = ssh->hostkey->fmtkey(s->hkey);
7295 if (!s->got_session_id) {
7297 * Make a note of any other host key formats that are available.
7300 int i, j, nkeys = 0;
7302 for (i = 0; i < lenof(hostkey_algs); i++) {
7303 if (hostkey_algs[i].alg == ssh->hostkey)
7306 for (j = 0; j < ssh->n_uncert_hostkeys; j++)
7307 if (ssh->uncert_hostkeys[j] == i)
7310 if (j < ssh->n_uncert_hostkeys) {
7313 newlist = dupprintf("%s/%s", list,
7314 hostkey_algs[i].alg->name);
7316 newlist = dupprintf("%s", hostkey_algs[i].alg->name);
7324 "Server also has %s host key%s, but we "
7325 "don't know %s", list,
7326 nkeys > 1 ? "s" : "",
7327 nkeys > 1 ? "any of them" : "it");
7333 * Authenticate remote host: verify host key. (We've already
7334 * checked the signature of the exchange hash.)
7336 s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
7337 logevent("Host key fingerprint is:");
7338 logevent(s->fingerprint);
7339 /* First check against manually configured host keys. */
7340 s->dlgret = verify_ssh_manual_host_key(ssh, s->fingerprint,
7341 ssh->hostkey, s->hkey);
7342 if (s->dlgret == 0) { /* did not match */
7343 bombout(("Host key did not appear in manually configured list"));
7345 } else if (s->dlgret < 0) { /* none configured; use standard handling */
7346 ssh_set_frozen(ssh, 1);
7347 s->dlgret = verify_ssh_host_key(ssh->frontend,
7348 ssh->savedhost, ssh->savedport,
7349 ssh->hostkey->keytype, s->keystr,
7351 ssh_dialog_callback, ssh);
7355 if (s->dlgret < 0) {
7359 bombout(("Unexpected data from server while waiting"
7360 " for user host key response"));
7363 } while (pktin || inlen > 0);
7364 s->dlgret = ssh->user_response;
7366 ssh_set_frozen(ssh, 0);
7367 if (s->dlgret == 0) {
7368 ssh_disconnect(ssh, "Aborted at host key verification", NULL,
7373 sfree(s->fingerprint);
7375 * Save this host key, to check against the one presented in
7376 * subsequent rekeys.
7378 ssh->hostkey_str = s->keystr;
7379 } else if (ssh->cross_certifying) {
7380 s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
7381 logevent("Storing additional host key for this host:");
7382 logevent(s->fingerprint);
7383 store_host_key(ssh->savedhost, ssh->savedport,
7384 ssh->hostkey->keytype, s->keystr);
7385 ssh->cross_certifying = FALSE;
7387 * Don't forget to store the new key as the one we'll be
7388 * re-checking in future normal rekeys.
7390 ssh->hostkey_str = s->keystr;
7393 * In a rekey, we never present an interactive host key
7394 * verification request to the user. Instead, we simply
7395 * enforce that the key we're seeing this time is identical to
7396 * the one we saw before.
7398 if (strcmp(ssh->hostkey_str, s->keystr)) {
7400 bombout(("Host key was different in repeat key exchange"));
7406 ssh->hostkey->freekey(s->hkey);
7409 * The exchange hash from the very first key exchange is also
7410 * the session id, used in session key construction and
7413 if (!s->got_session_id) {
7414 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
7415 memcpy(ssh->v2_session_id, s->exchange_hash,
7416 sizeof(s->exchange_hash));
7417 ssh->v2_session_id_len = ssh->kex->hash->hlen;
7418 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
7419 s->got_session_id = TRUE;
7423 * Send SSH2_MSG_NEWKEYS.
7425 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
7426 ssh2_pkt_send_noqueue(ssh, s->pktout);
7427 ssh->outgoing_data_size = 0; /* start counting from here */
7430 * We've sent client NEWKEYS, so create and initialise
7431 * client-to-server session keys.
7433 if (ssh->cs_cipher_ctx)
7434 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
7435 ssh->cscipher = s->cscipher_tobe;
7436 if (ssh->cscipher) ssh->cs_cipher_ctx = ssh->cscipher->make_context();
7438 if (ssh->cs_mac_ctx)
7439 ssh->csmac->free_context(ssh->cs_mac_ctx);
7440 ssh->csmac = s->csmac_tobe;
7441 ssh->csmac_etm = s->csmac_etm_tobe;
7443 ssh->cs_mac_ctx = ssh->csmac->make_context(ssh->cs_cipher_ctx);
7445 if (ssh->cs_comp_ctx)
7446 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
7447 ssh->cscomp = s->cscomp_tobe;
7448 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
7451 * Set IVs on client-to-server keys. Here we use the exchange
7452 * hash from the _first_ key exchange.
7454 if (ssh->cscipher) {
7457 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'C',
7458 ssh->cscipher->padded_keybytes);
7459 ssh->cscipher->setkey(ssh->cs_cipher_ctx, key);
7460 smemclr(key, ssh->cscipher->padded_keybytes);
7463 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'A',
7464 ssh->cscipher->blksize);
7465 ssh->cscipher->setiv(ssh->cs_cipher_ctx, key);
7466 smemclr(key, ssh->cscipher->blksize);
7472 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'E',
7473 ssh->csmac->keylen);
7474 ssh->csmac->setkey(ssh->cs_mac_ctx, key);
7475 smemclr(key, ssh->csmac->keylen);
7480 logeventf(ssh, "Initialised %.200s client->server encryption",
7481 ssh->cscipher->text_name);
7483 logeventf(ssh, "Initialised %.200s client->server MAC algorithm%s%s",
7484 ssh->csmac->text_name,
7485 ssh->csmac_etm ? " (in ETM mode)" : "",
7486 ssh->cscipher->required_mac ? " (required by cipher)" : "");
7487 if (ssh->cscomp->text_name)
7488 logeventf(ssh, "Initialised %s compression",
7489 ssh->cscomp->text_name);
7492 * Now our end of the key exchange is complete, we can send all
7493 * our queued higher-layer packets.
7495 ssh->queueing = FALSE;
7496 ssh2_pkt_queuesend(ssh);
7499 * Expect SSH2_MSG_NEWKEYS from server.
7501 crWaitUntilV(pktin);
7502 if (pktin->type != SSH2_MSG_NEWKEYS) {
7503 bombout(("expected new-keys packet from server"));
7506 ssh->incoming_data_size = 0; /* start counting from here */
7509 * We've seen server NEWKEYS, so create and initialise
7510 * server-to-client session keys.
7512 if (ssh->sc_cipher_ctx)
7513 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
7514 if (s->sccipher_tobe) {
7515 ssh->sccipher = s->sccipher_tobe;
7516 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
7519 if (ssh->sc_mac_ctx)
7520 ssh->scmac->free_context(ssh->sc_mac_ctx);
7521 if (s->scmac_tobe) {
7522 ssh->scmac = s->scmac_tobe;
7523 ssh->scmac_etm = s->scmac_etm_tobe;
7524 ssh->sc_mac_ctx = ssh->scmac->make_context(ssh->sc_cipher_ctx);
7527 if (ssh->sc_comp_ctx)
7528 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
7529 ssh->sccomp = s->sccomp_tobe;
7530 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
7533 * Set IVs on server-to-client keys. Here we use the exchange
7534 * hash from the _first_ key exchange.
7536 if (ssh->sccipher) {
7539 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'D',
7540 ssh->sccipher->padded_keybytes);
7541 ssh->sccipher->setkey(ssh->sc_cipher_ctx, key);
7542 smemclr(key, ssh->sccipher->padded_keybytes);
7545 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'B',
7546 ssh->sccipher->blksize);
7547 ssh->sccipher->setiv(ssh->sc_cipher_ctx, key);
7548 smemclr(key, ssh->sccipher->blksize);
7554 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'F',
7555 ssh->scmac->keylen);
7556 ssh->scmac->setkey(ssh->sc_mac_ctx, key);
7557 smemclr(key, ssh->scmac->keylen);
7561 logeventf(ssh, "Initialised %.200s server->client encryption",
7562 ssh->sccipher->text_name);
7564 logeventf(ssh, "Initialised %.200s server->client MAC algorithm%s%s",
7565 ssh->scmac->text_name,
7566 ssh->scmac_etm ? " (in ETM mode)" : "",
7567 ssh->sccipher->required_mac ? " (required by cipher)" : "");
7568 if (ssh->sccomp->text_name)
7569 logeventf(ssh, "Initialised %s decompression",
7570 ssh->sccomp->text_name);
7573 * Free shared secret.
7578 * Update the specials menu to list the remaining uncertified host
7581 update_specials_menu(ssh->frontend);
7584 * Key exchange is over. Loop straight back round if we have a
7585 * deferred rekey reason.
7587 if (ssh->deferred_rekey_reason) {
7588 logevent(ssh->deferred_rekey_reason);
7590 ssh->deferred_rekey_reason = NULL;
7591 goto begin_key_exchange;
7595 * Otherwise, schedule a timer for our next rekey.
7597 ssh->kex_in_progress = FALSE;
7598 ssh->last_rekey = GETTICKCOUNT();
7599 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
7600 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7604 * Now we're encrypting. Begin returning 1 to the protocol main
7605 * function so that other things can run on top of the
7606 * transport. If we ever see a KEXINIT, we must go back to the
7609 * We _also_ go back to the start if we see pktin==NULL and
7610 * inlen negative, because this is a special signal meaning
7611 * `initiate client-driven rekey', and `in' contains a message
7612 * giving the reason for the rekey.
7614 * inlen==-1 means always initiate a rekey;
7615 * inlen==-2 means that userauth has completed successfully and
7616 * we should consider rekeying (for delayed compression).
7618 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
7619 (!pktin && inlen < 0))) {
7621 if (!ssh->protocol_initial_phase_done) {
7622 ssh->protocol_initial_phase_done = TRUE;
7624 * Allow authconn to initialise itself.
7626 do_ssh2_authconn(ssh, NULL, 0, NULL);
7631 logevent("Server initiated key re-exchange");
7635 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
7636 * delayed compression, if it's available.
7638 * draft-miller-secsh-compression-delayed-00 says that you
7639 * negotiate delayed compression in the first key exchange, and
7640 * both sides start compressing when the server has sent
7641 * USERAUTH_SUCCESS. This has a race condition -- the server
7642 * can't know when the client has seen it, and thus which incoming
7643 * packets it should treat as compressed.
7645 * Instead, we do the initial key exchange without offering the
7646 * delayed methods, but note if the server offers them; when we
7647 * get here, if a delayed method was available that was higher
7648 * on our list than what we got, we initiate a rekey in which we
7649 * _do_ list the delayed methods (and hopefully get it as a
7650 * result). Subsequent rekeys will do the same.
7652 assert(!s->userauth_succeeded); /* should only happen once */
7653 s->userauth_succeeded = TRUE;
7654 if (!s->pending_compression)
7655 /* Can't see any point rekeying. */
7656 goto wait_for_rekey; /* this is utterly horrid */
7657 /* else fall through to rekey... */
7658 s->pending_compression = FALSE;
7661 * Now we've decided to rekey.
7663 * Special case: if the server bug is set that doesn't
7664 * allow rekeying, we give a different log message and
7665 * continue waiting. (If such a server _initiates_ a rekey,
7666 * we process it anyway!)
7668 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
7669 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
7671 /* Reset the counters, so that at least this message doesn't
7672 * hit the event log _too_ often. */
7673 ssh->outgoing_data_size = 0;
7674 ssh->incoming_data_size = 0;
7675 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
7677 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7680 goto wait_for_rekey; /* this is still utterly horrid */
7682 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
7685 goto begin_key_exchange;
7691 * Send data on an SSH channel. In SSH-2, this involves buffering it
7694 static int ssh_send_channel_data(struct ssh_channel *c, const char *buf,
7697 if (c->ssh->version == 2) {
7698 bufchain_add(&c->v.v2.outbuffer, buf, len);
7699 return ssh2_try_send(c);
7701 send_packet(c->ssh, SSH1_MSG_CHANNEL_DATA,
7702 PKT_INT, c->remoteid,
7707 * In SSH-1 we can return 0 here - implying that channels are
7708 * never individually throttled - because the only
7709 * circumstance that can cause throttling will be the whole
7710 * SSH connection backing up, in which case _everything_ will
7711 * be throttled as a whole.
7718 * Attempt to send data on an SSH-2 channel.
7720 static int ssh2_try_send(struct ssh_channel *c)
7723 struct Packet *pktout;
7726 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
7729 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
7730 if ((unsigned)len > c->v.v2.remwindow)
7731 len = c->v.v2.remwindow;
7732 if ((unsigned)len > c->v.v2.remmaxpkt)
7733 len = c->v.v2.remmaxpkt;
7734 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
7735 ssh2_pkt_adduint32(pktout, c->remoteid);
7736 ssh2_pkt_addstring_start(pktout);
7737 ssh2_pkt_addstring_data(pktout, data, len);
7738 ssh2_pkt_send(ssh, pktout);
7739 bufchain_consume(&c->v.v2.outbuffer, len);
7740 c->v.v2.remwindow -= len;
7744 * After having sent as much data as we can, return the amount
7747 ret = bufchain_size(&c->v.v2.outbuffer);
7750 * And if there's no data pending but we need to send an EOF, send
7753 if (!ret && c->pending_eof)
7754 ssh_channel_try_eof(c);
7759 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
7762 if (c->closes & CLOSES_SENT_EOF)
7763 return; /* don't send on channels we've EOFed */
7764 bufsize = ssh2_try_send(c);
7767 case CHAN_MAINSESSION:
7768 /* stdin need not receive an unthrottle
7769 * notification since it will be polled */
7772 x11_unthrottle(c->u.x11.xconn);
7775 /* agent sockets are request/response and need no
7776 * buffer management */
7779 pfd_unthrottle(c->u.pfd.pf);
7785 static int ssh_is_simple(Ssh ssh)
7788 * We use the 'simple' variant of the SSH protocol if we're asked
7789 * to, except not if we're also doing connection-sharing (either
7790 * tunnelling our packets over an upstream or expecting to be
7791 * tunnelled over ourselves), since then the assumption that we
7792 * have only one channel to worry about is not true after all.
7794 return (conf_get_int(ssh->conf, CONF_ssh_simple) &&
7795 !ssh->bare_connection && !ssh->connshare);
7799 * Set up most of a new ssh_channel for SSH-2.
7801 static void ssh2_channel_init(struct ssh_channel *c)
7804 c->localid = alloc_channel_id(ssh);
7806 c->pending_eof = FALSE;
7807 c->throttling_conn = FALSE;
7808 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
7809 ssh_is_simple(ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
7810 c->v.v2.chanreq_head = NULL;
7811 c->v.v2.throttle_state = UNTHROTTLED;
7812 bufchain_init(&c->v.v2.outbuffer);
7816 * Construct the common parts of a CHANNEL_OPEN.
7818 static struct Packet *ssh2_chanopen_init(struct ssh_channel *c,
7821 struct Packet *pktout;
7823 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7824 ssh2_pkt_addstring(pktout, type);
7825 ssh2_pkt_adduint32(pktout, c->localid);
7826 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
7827 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7832 * CHANNEL_FAILURE doesn't come with any indication of what message
7833 * caused it, so we have to keep track of the outstanding
7834 * CHANNEL_REQUESTs ourselves.
7836 static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
7837 cchandler_fn_t handler, void *ctx)
7839 struct outstanding_channel_request *ocr =
7840 snew(struct outstanding_channel_request);
7842 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7843 ocr->handler = handler;
7846 if (!c->v.v2.chanreq_head)
7847 c->v.v2.chanreq_head = ocr;
7849 c->v.v2.chanreq_tail->next = ocr;
7850 c->v.v2.chanreq_tail = ocr;
7854 * Construct the common parts of a CHANNEL_REQUEST. If handler is not
7855 * NULL then a reply will be requested and the handler will be called
7856 * when it arrives. The returned packet is ready to have any
7857 * request-specific data added and be sent. Note that if a handler is
7858 * provided, it's essential that the request actually be sent.
7860 * The handler will usually be passed the response packet in pktin. If
7861 * pktin is NULL, this means that no reply will ever be forthcoming
7862 * (e.g. because the entire connection is being destroyed, or because
7863 * the server initiated channel closure before we saw the response)
7864 * and the handler should free any storage it's holding.
7866 static struct Packet *ssh2_chanreq_init(struct ssh_channel *c,
7868 cchandler_fn_t handler, void *ctx)
7870 struct Packet *pktout;
7872 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7873 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7874 ssh2_pkt_adduint32(pktout, c->remoteid);
7875 ssh2_pkt_addstring(pktout, type);
7876 ssh2_pkt_addbool(pktout, handler != NULL);
7877 if (handler != NULL)
7878 ssh2_queue_chanreq_handler(c, handler, ctx);
7883 * Potentially enlarge the window on an SSH-2 channel.
7885 static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
7887 static void ssh2_set_window(struct ssh_channel *c, int newwin)
7892 * Never send WINDOW_ADJUST for a channel that the remote side has
7893 * already sent EOF on; there's no point, since it won't be
7894 * sending any more data anyway. Ditto if _we've_ already sent
7897 if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
7901 * Also, never widen the window for an X11 channel when we're
7902 * still waiting to see its initial auth and may yet hand it off
7905 if (c->type == CHAN_X11 && c->u.x11.initial)
7909 * If the remote end has a habit of ignoring maxpkt, limit the
7910 * window so that it has no choice (assuming it doesn't ignore the
7913 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
7914 newwin = OUR_V2_MAXPKT;
7917 * Only send a WINDOW_ADJUST if there's significantly more window
7918 * available than the other end thinks there is. This saves us
7919 * sending a WINDOW_ADJUST for every character in a shell session.
7921 * "Significant" is arbitrarily defined as half the window size.
7923 if (newwin / 2 >= c->v.v2.locwindow) {
7924 struct Packet *pktout;
7928 * In order to keep track of how much window the client
7929 * actually has available, we'd like it to acknowledge each
7930 * WINDOW_ADJUST. We can't do that directly, so we accompany
7931 * it with a CHANNEL_REQUEST that has to be acknowledged.
7933 * This is only necessary if we're opening the window wide.
7934 * If we're not, then throughput is being constrained by
7935 * something other than the maximum window size anyway.
7937 if (newwin == c->v.v2.locmaxwin &&
7938 !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
7939 up = snew(unsigned);
7940 *up = newwin - c->v.v2.locwindow;
7941 pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org",
7942 ssh2_handle_winadj_response, up);
7943 ssh2_pkt_send(ssh, pktout);
7945 if (c->v.v2.throttle_state != UNTHROTTLED)
7946 c->v.v2.throttle_state = UNTHROTTLING;
7948 /* Pretend the WINDOW_ADJUST was acked immediately. */
7949 c->v.v2.remlocwin = newwin;
7950 c->v.v2.throttle_state = THROTTLED;
7952 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
7953 ssh2_pkt_adduint32(pktout, c->remoteid);
7954 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
7955 ssh2_pkt_send(ssh, pktout);
7956 c->v.v2.locwindow = newwin;
7961 * Find the channel associated with a message. If there's no channel,
7962 * or it's not properly open, make a noise about it and return NULL.
7964 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
7966 unsigned localid = ssh_pkt_getuint32(pktin);
7967 struct ssh_channel *c;
7969 c = find234(ssh->channels, &localid, ssh_channelfind);
7971 (c->type != CHAN_SHARING && c->halfopen &&
7972 pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
7973 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
7974 char *buf = dupprintf("Received %s for %s channel %u",
7975 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
7977 c ? "half-open" : "nonexistent", localid);
7978 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
7985 static void ssh2_handle_winadj_response(struct ssh_channel *c,
7986 struct Packet *pktin, void *ctx)
7988 unsigned *sizep = ctx;
7991 * Winadj responses should always be failures. However, at least
7992 * one server ("boks_sshd") is known to return SUCCESS for channel
7993 * requests it's never heard of, such as "winadj@putty". Raised
7994 * with foxt.com as bug 090916-090424, but for the sake of a quiet
7995 * life, we don't worry about what kind of response we got.
7998 c->v.v2.remlocwin += *sizep;
8001 * winadj messages are only sent when the window is fully open, so
8002 * if we get an ack of one, we know any pending unthrottle is
8005 if (c->v.v2.throttle_state == UNTHROTTLING)
8006 c->v.v2.throttle_state = UNTHROTTLED;
8009 static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
8011 struct ssh_channel *c = ssh2_channel_msg(ssh, pktin);
8012 struct outstanding_channel_request *ocr;
8015 if (c->type == CHAN_SHARING) {
8016 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8017 pktin->body, pktin->length);
8020 ocr = c->v.v2.chanreq_head;
8022 ssh2_msg_unexpected(ssh, pktin);
8025 ocr->handler(c, pktin, ocr->ctx);
8026 c->v.v2.chanreq_head = ocr->next;
8029 * We may now initiate channel-closing procedures, if that
8030 * CHANNEL_REQUEST was the last thing outstanding before we send
8033 ssh2_channel_check_close(c);
8036 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
8038 struct ssh_channel *c;
8039 c = ssh2_channel_msg(ssh, pktin);
8042 if (c->type == CHAN_SHARING) {
8043 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8044 pktin->body, pktin->length);
8047 if (!(c->closes & CLOSES_SENT_EOF)) {
8048 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
8049 ssh2_try_send_and_unthrottle(ssh, c);
8053 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
8057 struct ssh_channel *c;
8058 c = ssh2_channel_msg(ssh, pktin);
8061 if (c->type == CHAN_SHARING) {
8062 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8063 pktin->body, pktin->length);
8066 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
8067 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
8068 return; /* extended but not stderr */
8069 ssh_pkt_getstring(pktin, &data, &length);
8072 c->v.v2.locwindow -= length;
8073 c->v.v2.remlocwin -= length;
8075 case CHAN_MAINSESSION:
8077 from_backend(ssh->frontend, pktin->type ==
8078 SSH2_MSG_CHANNEL_EXTENDED_DATA,
8082 bufsize = x11_send(c->u.x11.xconn, data, length);
8085 bufsize = pfd_send(c->u.pfd.pf, data, length);
8088 bufsize = ssh_agent_channel_data(c, data, length);
8092 * If it looks like the remote end hit the end of its window,
8093 * and we didn't want it to do that, think about using a
8096 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
8097 c->v.v2.locmaxwin < 0x40000000)
8098 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
8100 * If we are not buffering too much data,
8101 * enlarge the window again at the remote side.
8102 * If we are buffering too much, we may still
8103 * need to adjust the window if the server's
8106 ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
8107 c->v.v2.locmaxwin - bufsize : 0);
8109 * If we're either buffering way too much data, or if we're
8110 * buffering anything at all and we're in "simple" mode,
8111 * throttle the whole channel.
8113 if ((bufsize > c->v.v2.locmaxwin || (ssh_is_simple(ssh) && bufsize>0))
8114 && !c->throttling_conn) {
8115 c->throttling_conn = 1;
8116 ssh_throttle_conn(ssh, +1);
8121 static void ssh_check_termination(Ssh ssh)
8123 if (ssh->version == 2 &&
8124 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
8125 (ssh->channels && count234(ssh->channels) == 0) &&
8126 !(ssh->connshare && share_ndownstreams(ssh->connshare) > 0)) {
8128 * We used to send SSH_MSG_DISCONNECT here, because I'd
8129 * believed that _every_ conforming SSH-2 connection had to
8130 * end with a disconnect being sent by at least one side;
8131 * apparently I was wrong and it's perfectly OK to
8132 * unceremoniously slam the connection shut when you're done,
8133 * and indeed OpenSSH feels this is more polite than sending a
8134 * DISCONNECT. So now we don't.
8136 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
8140 void ssh_sharing_downstream_connected(Ssh ssh, unsigned id,
8141 const char *peerinfo)
8144 logeventf(ssh, "Connection sharing downstream #%u connected from %s",
8147 logeventf(ssh, "Connection sharing downstream #%u connected", id);
8150 void ssh_sharing_downstream_disconnected(Ssh ssh, unsigned id)
8152 logeventf(ssh, "Connection sharing downstream #%u disconnected", id);
8153 ssh_check_termination(ssh);
8156 void ssh_sharing_logf(Ssh ssh, unsigned id, const char *logfmt, ...)
8161 va_start(ap, logfmt);
8162 buf = dupvprintf(logfmt, ap);
8165 logeventf(ssh, "Connection sharing downstream #%u: %s", id, buf);
8167 logeventf(ssh, "Connection sharing: %s", buf);
8171 static void ssh_channel_destroy(struct ssh_channel *c)
8176 case CHAN_MAINSESSION:
8177 ssh->mainchan = NULL;
8178 update_specials_menu(ssh->frontend);
8181 if (c->u.x11.xconn != NULL)
8182 x11_close(c->u.x11.xconn);
8183 logevent("Forwarded X11 connection terminated");
8186 sfree(c->u.a.message);
8189 if (c->u.pfd.pf != NULL)
8190 pfd_close(c->u.pfd.pf);
8191 logevent("Forwarded port closed");
8195 del234(ssh->channels, c);
8196 if (ssh->version == 2) {
8197 bufchain_clear(&c->v.v2.outbuffer);
8198 assert(c->v.v2.chanreq_head == NULL);
8203 * If that was the last channel left open, we might need to
8206 ssh_check_termination(ssh);
8209 static void ssh2_channel_check_close(struct ssh_channel *c)
8212 struct Packet *pktout;
8216 * If we've sent out our own CHANNEL_OPEN but not yet seen
8217 * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
8218 * it's too early to be sending close messages of any kind.
8223 if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
8224 c->type == CHAN_ZOMBIE) &&
8225 !c->v.v2.chanreq_head &&
8226 !(c->closes & CLOSES_SENT_CLOSE)) {
8228 * We have both sent and received EOF (or the channel is a
8229 * zombie), and we have no outstanding channel requests, which
8230 * means the channel is in final wind-up. But we haven't sent
8231 * CLOSE, so let's do so now.
8233 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
8234 ssh2_pkt_adduint32(pktout, c->remoteid);
8235 ssh2_pkt_send(ssh, pktout);
8236 c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
8239 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
8240 assert(c->v.v2.chanreq_head == NULL);
8242 * We have both sent and received CLOSE, which means we're
8243 * completely done with the channel.
8245 ssh_channel_destroy(c);
8249 static void ssh2_channel_got_eof(struct ssh_channel *c)
8251 if (c->closes & CLOSES_RCVD_EOF)
8252 return; /* already seen EOF */
8253 c->closes |= CLOSES_RCVD_EOF;
8255 if (c->type == CHAN_X11) {
8256 x11_send_eof(c->u.x11.xconn);
8257 } else if (c->type == CHAN_AGENT) {
8258 if (c->u.a.outstanding_requests == 0) {
8259 /* Manufacture an outgoing EOF in response to the incoming one. */
8260 sshfwd_write_eof(c);
8262 } else if (c->type == CHAN_SOCKDATA) {
8263 pfd_send_eof(c->u.pfd.pf);
8264 } else if (c->type == CHAN_MAINSESSION) {
8267 if (!ssh->sent_console_eof &&
8268 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
8270 * Either from_backend_eof told us that the front end
8271 * wants us to close the outgoing side of the connection
8272 * as soon as we see EOF from the far end, or else we've
8273 * unilaterally decided to do that because we've allocated
8274 * a remote pty and hence EOF isn't a particularly
8275 * meaningful concept.
8277 sshfwd_write_eof(c);
8279 ssh->sent_console_eof = TRUE;
8282 ssh2_channel_check_close(c);
8285 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
8287 struct ssh_channel *c;
8289 c = ssh2_channel_msg(ssh, pktin);
8292 if (c->type == CHAN_SHARING) {
8293 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8294 pktin->body, pktin->length);
8297 ssh2_channel_got_eof(c);
8300 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
8302 struct ssh_channel *c;
8304 c = ssh2_channel_msg(ssh, pktin);
8307 if (c->type == CHAN_SHARING) {
8308 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8309 pktin->body, pktin->length);
8314 * When we receive CLOSE on a channel, we assume it comes with an
8315 * implied EOF if we haven't seen EOF yet.
8317 ssh2_channel_got_eof(c);
8319 if (!(ssh->remote_bugs & BUG_SENDS_LATE_REQUEST_REPLY)) {
8321 * It also means we stop expecting to see replies to any
8322 * outstanding channel requests, so clean those up too.
8323 * (ssh_chanreq_init will enforce by assertion that we don't
8324 * subsequently put anything back on this list.)
8326 while (c->v.v2.chanreq_head) {
8327 struct outstanding_channel_request *ocr = c->v.v2.chanreq_head;
8328 ocr->handler(c, NULL, ocr->ctx);
8329 c->v.v2.chanreq_head = ocr->next;
8335 * And we also send an outgoing EOF, if we haven't already, on the
8336 * assumption that CLOSE is a pretty forceful announcement that
8337 * the remote side is doing away with the entire channel. (If it
8338 * had wanted to send us EOF and continue receiving data from us,
8339 * it would have just sent CHANNEL_EOF.)
8341 if (!(c->closes & CLOSES_SENT_EOF)) {
8343 * Make sure we don't read any more from whatever our local
8344 * data source is for this channel.
8347 case CHAN_MAINSESSION:
8348 ssh->send_ok = 0; /* stop trying to read from stdin */
8351 x11_override_throttle(c->u.x11.xconn, 1);
8354 pfd_override_throttle(c->u.pfd.pf, 1);
8359 * Abandon any buffered data we still wanted to send to this
8360 * channel. Receiving a CHANNEL_CLOSE is an indication that
8361 * the server really wants to get on and _destroy_ this
8362 * channel, and it isn't going to send us any further
8363 * WINDOW_ADJUSTs to permit us to send pending stuff.
8365 bufchain_clear(&c->v.v2.outbuffer);
8368 * Send outgoing EOF.
8370 sshfwd_write_eof(c);
8374 * Now process the actual close.
8376 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
8377 c->closes |= CLOSES_RCVD_CLOSE;
8378 ssh2_channel_check_close(c);
8382 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
8384 struct ssh_channel *c;
8386 c = ssh2_channel_msg(ssh, pktin);
8389 if (c->type == CHAN_SHARING) {
8390 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8391 pktin->body, pktin->length);
8394 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
8395 c->remoteid = ssh_pkt_getuint32(pktin);
8396 c->halfopen = FALSE;
8397 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8398 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8400 if (c->type == CHAN_SOCKDATA_DORMANT) {
8401 c->type = CHAN_SOCKDATA;
8403 pfd_confirm(c->u.pfd.pf);
8404 } else if (c->type == CHAN_ZOMBIE) {
8406 * This case can occur if a local socket error occurred
8407 * between us sending out CHANNEL_OPEN and receiving
8408 * OPEN_CONFIRMATION. In this case, all we can do is
8409 * immediately initiate close proceedings now that we know the
8410 * server's id to put in the close message.
8412 ssh2_channel_check_close(c);
8415 * We never expect to receive OPEN_CONFIRMATION for any
8416 * *other* channel type (since only local-to-remote port
8417 * forwardings cause us to send CHANNEL_OPEN after the main
8418 * channel is live - all other auxiliary channel types are
8419 * initiated from the server end). It's safe to enforce this
8420 * by assertion rather than by ssh_disconnect, because the
8421 * real point is that we never constructed a half-open channel
8422 * structure in the first place with any type other than the
8425 assert(!"Funny channel type in ssh2_msg_channel_open_confirmation");
8429 ssh_channel_try_eof(c); /* in case we had a pending EOF */
8432 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
8434 static const char *const reasons[] = {
8435 "<unknown reason code>",
8436 "Administratively prohibited",
8438 "Unknown channel type",
8439 "Resource shortage",
8441 unsigned reason_code;
8442 char *reason_string;
8444 struct ssh_channel *c;
8446 c = ssh2_channel_msg(ssh, pktin);
8449 if (c->type == CHAN_SHARING) {
8450 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8451 pktin->body, pktin->length);
8454 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
8456 if (c->type == CHAN_SOCKDATA_DORMANT) {
8457 reason_code = ssh_pkt_getuint32(pktin);
8458 if (reason_code >= lenof(reasons))
8459 reason_code = 0; /* ensure reasons[reason_code] in range */
8460 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
8461 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
8462 reasons[reason_code], reason_length,
8463 NULLTOEMPTY(reason_string));
8465 pfd_close(c->u.pfd.pf);
8466 } else if (c->type == CHAN_ZOMBIE) {
8468 * This case can occur if a local socket error occurred
8469 * between us sending out CHANNEL_OPEN and receiving
8470 * OPEN_FAILURE. In this case, we need do nothing except allow
8471 * the code below to throw the half-open channel away.
8475 * We never expect to receive OPEN_FAILURE for any *other*
8476 * channel type (since only local-to-remote port forwardings
8477 * cause us to send CHANNEL_OPEN after the main channel is
8478 * live - all other auxiliary channel types are initiated from
8479 * the server end). It's safe to enforce this by assertion
8480 * rather than by ssh_disconnect, because the real point is
8481 * that we never constructed a half-open channel structure in
8482 * the first place with any type other than the above.
8484 assert(!"Funny channel type in ssh2_msg_channel_open_failure");
8487 del234(ssh->channels, c);
8491 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
8494 int typelen, want_reply;
8495 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
8496 struct ssh_channel *c;
8497 struct Packet *pktout;
8499 c = ssh2_channel_msg(ssh, pktin);
8502 if (c->type == CHAN_SHARING) {
8503 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8504 pktin->body, pktin->length);
8507 ssh_pkt_getstring(pktin, &type, &typelen);
8508 want_reply = ssh2_pkt_getbool(pktin);
8510 if (c->closes & CLOSES_SENT_CLOSE) {
8512 * We don't reply to channel requests after we've sent
8513 * CHANNEL_CLOSE for the channel, because our reply might
8514 * cross in the network with the other side's CHANNEL_CLOSE
8515 * and arrive after they have wound the channel up completely.
8521 * Having got the channel number, we now look at
8522 * the request type string to see if it's something
8525 if (c == ssh->mainchan) {
8527 * We recognise "exit-status" and "exit-signal" on
8528 * the primary channel.
8530 if (typelen == 11 &&
8531 !memcmp(type, "exit-status", 11)) {
8533 ssh->exitcode = ssh_pkt_getuint32(pktin);
8534 logeventf(ssh, "Server sent command exit status %d",
8536 reply = SSH2_MSG_CHANNEL_SUCCESS;
8538 } else if (typelen == 11 &&
8539 !memcmp(type, "exit-signal", 11)) {
8541 int is_plausible = TRUE, is_int = FALSE;
8542 char *fmt_sig = NULL, *fmt_msg = NULL;
8544 int msglen = 0, core = FALSE;
8545 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
8546 * provide an `int' for the signal, despite its
8547 * having been a `string' in the drafts of RFC 4254 since at
8548 * least 2001. (Fixed in session.c 1.147.) Try to
8549 * infer which we can safely parse it as. */
8551 unsigned char *p = pktin->body +
8553 long len = pktin->length - pktin->savedpos;
8554 unsigned long num = GET_32BIT(p); /* what is it? */
8555 /* If it's 0, it hardly matters; assume string */
8559 int maybe_int = FALSE, maybe_str = FALSE;
8560 #define CHECK_HYPOTHESIS(offset, result) \
8563 int q = toint(offset); \
8564 if (q >= 0 && q+4 <= len) { \
8565 q = toint(q + 4 + GET_32BIT(p+q)); \
8566 if (q >= 0 && q+4 <= len && \
8567 ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
8572 CHECK_HYPOTHESIS(4+1, maybe_int);
8573 CHECK_HYPOTHESIS(4+num+1, maybe_str);
8574 #undef CHECK_HYPOTHESIS
8575 if (maybe_int && !maybe_str)
8577 else if (!maybe_int && maybe_str)
8580 /* Crikey. Either or neither. Panic. */
8581 is_plausible = FALSE;
8584 ssh->exitcode = 128; /* means `unknown signal' */
8587 /* Old non-standard OpenSSH. */
8588 int signum = ssh_pkt_getuint32(pktin);
8589 fmt_sig = dupprintf(" %d", signum);
8590 ssh->exitcode = 128 + signum;
8592 /* As per RFC 4254. */
8595 ssh_pkt_getstring(pktin, &sig, &siglen);
8596 /* Signal name isn't supposed to be blank, but
8597 * let's cope gracefully if it is. */
8599 fmt_sig = dupprintf(" \"%.*s\"",
8604 * Really hideous method of translating the
8605 * signal description back into a locally
8606 * meaningful number.
8611 #define TRANSLATE_SIGNAL(s) \
8612 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
8613 ssh->exitcode = 128 + SIG ## s
8615 TRANSLATE_SIGNAL(ABRT);
8618 TRANSLATE_SIGNAL(ALRM);
8621 TRANSLATE_SIGNAL(FPE);
8624 TRANSLATE_SIGNAL(HUP);
8627 TRANSLATE_SIGNAL(ILL);
8630 TRANSLATE_SIGNAL(INT);
8633 TRANSLATE_SIGNAL(KILL);
8636 TRANSLATE_SIGNAL(PIPE);
8639 TRANSLATE_SIGNAL(QUIT);
8642 TRANSLATE_SIGNAL(SEGV);
8645 TRANSLATE_SIGNAL(TERM);
8648 TRANSLATE_SIGNAL(USR1);
8651 TRANSLATE_SIGNAL(USR2);
8653 #undef TRANSLATE_SIGNAL
8655 ssh->exitcode = 128;
8657 core = ssh2_pkt_getbool(pktin);
8658 ssh_pkt_getstring(pktin, &msg, &msglen);
8660 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
8662 /* ignore lang tag */
8663 } /* else don't attempt to parse */
8664 logeventf(ssh, "Server exited on signal%s%s%s",
8665 fmt_sig ? fmt_sig : "",
8666 core ? " (core dumped)" : "",
8667 fmt_msg ? fmt_msg : "");
8670 reply = SSH2_MSG_CHANNEL_SUCCESS;
8675 * This is a channel request we don't know
8676 * about, so we now either ignore the request
8677 * or respond with CHANNEL_FAILURE, depending
8680 reply = SSH2_MSG_CHANNEL_FAILURE;
8683 pktout = ssh2_pkt_init(reply);
8684 ssh2_pkt_adduint32(pktout, c->remoteid);
8685 ssh2_pkt_send(ssh, pktout);
8689 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
8692 int typelen, want_reply;
8693 struct Packet *pktout;
8695 ssh_pkt_getstring(pktin, &type, &typelen);
8696 want_reply = ssh2_pkt_getbool(pktin);
8699 * We currently don't support any global requests
8700 * at all, so we either ignore the request or
8701 * respond with REQUEST_FAILURE, depending on
8705 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
8706 ssh2_pkt_send(ssh, pktout);
8710 struct X11FakeAuth *ssh_sharing_add_x11_display(Ssh ssh, int authtype,
8714 struct X11FakeAuth *auth;
8717 * Make up a new set of fake X11 auth data, and add it to the tree
8718 * of currently valid ones with an indication of the sharing
8719 * context that it's relevant to.
8721 auth = x11_invent_fake_auth(ssh->x11authtree, authtype);
8722 auth->share_cs = share_cs;
8723 auth->share_chan = share_chan;
8728 void ssh_sharing_remove_x11_display(Ssh ssh, struct X11FakeAuth *auth)
8730 del234(ssh->x11authtree, auth);
8731 x11_free_fake_auth(auth);
8734 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
8741 const char *error = NULL;
8742 struct ssh_channel *c;
8743 unsigned remid, winsize, pktsize;
8744 unsigned our_winsize_override = 0;
8745 struct Packet *pktout;
8747 ssh_pkt_getstring(pktin, &type, &typelen);
8748 c = snew(struct ssh_channel);
8751 remid = ssh_pkt_getuint32(pktin);
8752 winsize = ssh_pkt_getuint32(pktin);
8753 pktsize = ssh_pkt_getuint32(pktin);
8755 if (typelen == 3 && !memcmp(type, "x11", 3)) {
8758 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8759 addrstr = dupprintf("%.*s", peeraddrlen, NULLTOEMPTY(peeraddr));
8760 peerport = ssh_pkt_getuint32(pktin);
8762 logeventf(ssh, "Received X11 connect request from %s:%d",
8765 if (!ssh->X11_fwd_enabled && !ssh->connshare)
8766 error = "X11 forwarding is not enabled";
8768 c->u.x11.xconn = x11_init(ssh->x11authtree, c,
8771 c->u.x11.initial = TRUE;
8774 * If we are a connection-sharing upstream, then we should
8775 * initially present a very small window, adequate to take
8776 * the X11 initial authorisation packet but not much more.
8777 * Downstream will then present us a larger window (by
8778 * fiat of the connection-sharing protocol) and we can
8779 * guarantee to send a positive-valued WINDOW_ADJUST.
8782 our_winsize_override = 128;
8784 logevent("Opened X11 forward channel");
8788 } else if (typelen == 15 &&
8789 !memcmp(type, "forwarded-tcpip", 15)) {
8790 struct ssh_rportfwd pf, *realpf;
8793 ssh_pkt_getstring(pktin, &shost, &shostlen);/* skip address */
8794 pf.shost = dupprintf("%.*s", shostlen, NULLTOEMPTY(shost));
8795 pf.sport = ssh_pkt_getuint32(pktin);
8796 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8797 peerport = ssh_pkt_getuint32(pktin);
8798 realpf = find234(ssh->rportfwds, &pf, NULL);
8799 logeventf(ssh, "Received remote port %s:%d open request "
8800 "from %.*s:%d", pf.shost, pf.sport,
8801 peeraddrlen, NULLTOEMPTY(peeraddr), peerport);
8804 if (realpf == NULL) {
8805 error = "Remote port is not recognised";
8809 if (realpf->share_ctx) {
8811 * This port forwarding is on behalf of a
8812 * connection-sharing downstream, so abandon our own
8813 * channel-open procedure and just pass the message on
8816 share_got_pkt_from_server(realpf->share_ctx, pktin->type,
8817 pktin->body, pktin->length);
8822 err = pfd_connect(&c->u.pfd.pf, realpf->dhost, realpf->dport,
8823 c, ssh->conf, realpf->pfrec->addressfamily);
8824 logeventf(ssh, "Attempting to forward remote port to "
8825 "%s:%d", realpf->dhost, realpf->dport);
8827 logeventf(ssh, "Port open failed: %s", err);
8829 error = "Port open failed";
8831 logevent("Forwarded port opened successfully");
8832 c->type = CHAN_SOCKDATA;
8835 } else if (typelen == 22 &&
8836 !memcmp(type, "auth-agent@openssh.com", 22)) {
8837 if (!ssh->agentfwd_enabled)
8838 error = "Agent forwarding is not enabled";
8840 c->type = CHAN_AGENT; /* identify channel type */
8841 c->u.a.lensofar = 0;
8842 c->u.a.message = NULL;
8843 c->u.a.outstanding_requests = 0;
8846 error = "Unsupported channel type requested";
8849 c->remoteid = remid;
8850 c->halfopen = FALSE;
8852 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
8853 ssh2_pkt_adduint32(pktout, c->remoteid);
8854 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
8855 ssh2_pkt_addstring(pktout, error);
8856 ssh2_pkt_addstring(pktout, "en"); /* language tag */
8857 ssh2_pkt_send(ssh, pktout);
8858 logeventf(ssh, "Rejected channel open: %s", error);
8861 ssh2_channel_init(c);
8862 c->v.v2.remwindow = winsize;
8863 c->v.v2.remmaxpkt = pktsize;
8864 if (our_winsize_override) {
8865 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
8866 our_winsize_override;
8868 add234(ssh->channels, c);
8869 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
8870 ssh2_pkt_adduint32(pktout, c->remoteid);
8871 ssh2_pkt_adduint32(pktout, c->localid);
8872 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
8873 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
8874 ssh2_pkt_send(ssh, pktout);
8878 void sshfwd_x11_sharing_handover(struct ssh_channel *c,
8879 void *share_cs, void *share_chan,
8880 const char *peer_addr, int peer_port,
8881 int endian, int protomajor, int protominor,
8882 const void *initial_data, int initial_len)
8885 * This function is called when we've just discovered that an X
8886 * forwarding channel on which we'd been handling the initial auth
8887 * ourselves turns out to be destined for a connection-sharing
8888 * downstream. So we turn the channel into a CHAN_SHARING, meaning
8889 * that we completely stop tracking windows and buffering data and
8890 * just pass more or less unmodified SSH messages back and forth.
8892 c->type = CHAN_SHARING;
8893 c->u.sharing.ctx = share_cs;
8894 share_setup_x11_channel(share_cs, share_chan,
8895 c->localid, c->remoteid, c->v.v2.remwindow,
8896 c->v.v2.remmaxpkt, c->v.v2.locwindow,
8897 peer_addr, peer_port, endian,
8898 protomajor, protominor,
8899 initial_data, initial_len);
8902 void sshfwd_x11_is_local(struct ssh_channel *c)
8905 * This function is called when we've just discovered that an X
8906 * forwarding channel is _not_ destined for a connection-sharing
8907 * downstream but we're going to handle it ourselves. We stop
8908 * presenting a cautiously small window and go into ordinary data
8911 c->u.x11.initial = FALSE;
8912 ssh2_set_window(c, ssh_is_simple(c->ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE);
8916 * Buffer banner messages for later display at some convenient point,
8917 * if we're going to display them.
8919 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
8921 /* Arbitrary limit to prevent unbounded inflation of buffer */
8922 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
8923 bufchain_size(&ssh->banner) <= 131072) {
8924 char *banner = NULL;
8926 ssh_pkt_getstring(pktin, &banner, &size);
8928 bufchain_add(&ssh->banner, banner, size);
8932 /* Helper function to deal with sending tty modes for "pty-req" */
8933 static void ssh2_send_ttymode(void *data,
8934 const struct ssh_ttymode *mode, char *val)
8936 struct Packet *pktout = (struct Packet *)data;
8937 unsigned int arg = 0;
8939 switch (mode->type) {
8941 arg = ssh_tty_parse_specchar(val);
8944 arg = ssh_tty_parse_boolean(val);
8947 ssh2_pkt_addbyte(pktout, mode->opcode);
8948 ssh2_pkt_adduint32(pktout, arg);
8951 static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
8954 struct ssh2_setup_x11_state {
8958 struct Packet *pktout;
8959 crStateP(ssh2_setup_x11_state, ctx);
8963 logevent("Requesting X11 forwarding");
8964 pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
8966 ssh2_pkt_addbool(pktout, 0); /* many connections */
8967 ssh2_pkt_addstring(pktout, ssh->x11auth->protoname);
8968 ssh2_pkt_addstring(pktout, ssh->x11auth->datastring);
8969 ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
8970 ssh2_pkt_send(ssh, pktout);
8972 /* Wait to be called back with either a response packet, or NULL
8973 * meaning clean up and free our data */
8977 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8978 logevent("X11 forwarding enabled");
8979 ssh->X11_fwd_enabled = TRUE;
8981 logevent("X11 forwarding refused");
8987 static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
8990 struct ssh2_setup_agent_state {
8994 struct Packet *pktout;
8995 crStateP(ssh2_setup_agent_state, ctx);
8999 logevent("Requesting OpenSSH-style agent forwarding");
9000 pktout = ssh2_chanreq_init(ssh->mainchan, "auth-agent-req@openssh.com",
9001 ssh2_setup_agent, s);
9002 ssh2_pkt_send(ssh, pktout);
9004 /* Wait to be called back with either a response packet, or NULL
9005 * meaning clean up and free our data */
9009 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
9010 logevent("Agent forwarding enabled");
9011 ssh->agentfwd_enabled = TRUE;
9013 logevent("Agent forwarding refused");
9019 static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
9022 struct ssh2_setup_pty_state {
9026 struct Packet *pktout;
9027 crStateP(ssh2_setup_pty_state, ctx);
9031 /* Unpick the terminal-speed string. */
9032 /* XXX perhaps we should allow no speeds to be sent. */
9033 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
9034 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
9035 /* Build the pty request. */
9036 pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
9038 ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
9039 ssh2_pkt_adduint32(pktout, ssh->term_width);
9040 ssh2_pkt_adduint32(pktout, ssh->term_height);
9041 ssh2_pkt_adduint32(pktout, 0); /* pixel width */
9042 ssh2_pkt_adduint32(pktout, 0); /* pixel height */
9043 ssh2_pkt_addstring_start(pktout);
9044 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
9045 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
9046 ssh2_pkt_adduint32(pktout, ssh->ispeed);
9047 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
9048 ssh2_pkt_adduint32(pktout, ssh->ospeed);
9049 ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
9050 ssh2_pkt_send(ssh, pktout);
9051 ssh->state = SSH_STATE_INTERMED;
9053 /* Wait to be called back with either a response packet, or NULL
9054 * meaning clean up and free our data */
9058 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
9059 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
9060 ssh->ospeed, ssh->ispeed);
9061 ssh->got_pty = TRUE;
9063 c_write_str(ssh, "Server refused to allocate pty\r\n");
9064 ssh->editing = ssh->echoing = 1;
9071 static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
9074 struct ssh2_setup_env_state {
9076 int num_env, env_left, env_ok;
9079 struct Packet *pktout;
9080 crStateP(ssh2_setup_env_state, ctx);
9085 * Send environment variables.
9087 * Simplest thing here is to send all the requests at once, and
9088 * then wait for a whole bunch of successes or failures.
9094 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
9096 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
9097 pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
9098 ssh2_pkt_addstring(pktout, key);
9099 ssh2_pkt_addstring(pktout, val);
9100 ssh2_pkt_send(ssh, pktout);
9105 logeventf(ssh, "Sent %d environment variables", s->num_env);
9110 s->env_left = s->num_env;
9112 while (s->env_left > 0) {
9113 /* Wait to be called back with either a response packet,
9114 * or NULL meaning clean up and free our data */
9116 if (!pktin) goto out;
9117 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
9122 if (s->env_ok == s->num_env) {
9123 logevent("All environment variables successfully set");
9124 } else if (s->env_ok == 0) {
9125 logevent("All environment variables refused");
9126 c_write_str(ssh, "Server refused to set environment variables\r\n");
9128 logeventf(ssh, "%d environment variables refused",
9129 s->num_env - s->env_ok);
9130 c_write_str(ssh, "Server refused to set all environment variables\r\n");
9138 * Handle the SSH-2 userauth and connection layers.
9140 static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
9142 do_ssh2_authconn(ssh, NULL, 0, pktin);
9145 static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
9149 do_ssh2_authconn(c->ssh, NULL, 0, pktin);
9152 static void do_ssh2_authconn(Ssh ssh, const unsigned char *in, int inlen,
9153 struct Packet *pktin)
9155 struct do_ssh2_authconn_state {
9159 AUTH_TYPE_PUBLICKEY,
9160 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
9161 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
9163 AUTH_TYPE_GSSAPI, /* always QUIET */
9164 AUTH_TYPE_KEYBOARD_INTERACTIVE,
9165 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
9167 int done_service_req;
9168 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
9169 int tried_pubkey_config, done_agent;
9174 int kbd_inter_refused;
9175 int we_are_in, userauth_success;
9176 prompts_t *cur_prompt;
9181 void *publickey_blob;
9182 int publickey_bloblen;
9183 int privatekey_available, privatekey_encrypted;
9184 char *publickey_algorithm;
9185 char *publickey_comment;
9186 unsigned char agent_request[5], *agent_response, *agentp;
9187 int agent_responselen;
9188 unsigned char *pkblob_in_agent;
9190 char *pkblob, *alg, *commentp;
9191 int pklen, alglen, commentlen;
9192 int siglen, retlen, len;
9193 char *q, *agentreq, *ret;
9194 struct Packet *pktout;
9197 struct ssh_gss_library *gsslib;
9198 Ssh_gss_ctx gss_ctx;
9199 Ssh_gss_buf gss_buf;
9200 Ssh_gss_buf gss_rcvtok, gss_sndtok;
9201 Ssh_gss_name gss_srv_name;
9202 Ssh_gss_stat gss_stat;
9205 crState(do_ssh2_authconn_state);
9209 /* Register as a handler for all the messages this coroutine handles. */
9210 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
9211 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
9212 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
9213 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
9214 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
9215 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
9216 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
9217 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
9218 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
9219 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
9220 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
9221 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
9222 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
9223 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
9224 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
9225 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
9226 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
9227 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
9228 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
9229 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
9231 s->done_service_req = FALSE;
9232 s->we_are_in = s->userauth_success = FALSE;
9233 s->agent_response = NULL;
9235 s->tried_gssapi = FALSE;
9238 if (!ssh->bare_connection) {
9239 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
9241 * Request userauth protocol, and await a response to it.
9243 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
9244 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
9245 ssh2_pkt_send(ssh, s->pktout);
9246 crWaitUntilV(pktin);
9247 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
9248 s->done_service_req = TRUE;
9250 if (!s->done_service_req) {
9252 * Request connection protocol directly, without authentication.
9254 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
9255 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9256 ssh2_pkt_send(ssh, s->pktout);
9257 crWaitUntilV(pktin);
9258 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
9259 s->we_are_in = TRUE; /* no auth required */
9261 bombout(("Server refused service request"));
9266 s->we_are_in = TRUE;
9269 /* Arrange to be able to deal with any BANNERs that come in.
9270 * (We do this now as packets may come in during the next bit.) */
9271 bufchain_init(&ssh->banner);
9272 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
9273 ssh2_msg_userauth_banner;
9276 * Misc one-time setup for authentication.
9278 s->publickey_blob = NULL;
9279 if (!s->we_are_in) {
9282 * Load the public half of any configured public key file
9285 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9286 if (!filename_is_null(s->keyfile)) {
9288 logeventf(ssh, "Reading key file \"%.150s\"",
9289 filename_to_str(s->keyfile));
9290 keytype = key_type(s->keyfile);
9291 if (keytype == SSH_KEYTYPE_SSH2 ||
9292 keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 ||
9293 keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
9296 ssh2_userkey_loadpub(s->keyfile,
9297 &s->publickey_algorithm,
9298 &s->publickey_bloblen,
9299 &s->publickey_comment, &error);
9300 if (s->publickey_blob) {
9301 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH2);
9302 if (!s->privatekey_available)
9303 logeventf(ssh, "Key file contains public key only");
9304 s->privatekey_encrypted =
9305 ssh2_userkey_encrypted(s->keyfile, NULL);
9308 logeventf(ssh, "Unable to load key (%s)",
9310 msgbuf = dupprintf("Unable to load key file "
9311 "\"%.150s\" (%s)\r\n",
9312 filename_to_str(s->keyfile),
9314 c_write_str(ssh, msgbuf);
9319 logeventf(ssh, "Unable to use this key file (%s)",
9320 key_type_to_str(keytype));
9321 msgbuf = dupprintf("Unable to use key file \"%.150s\""
9323 filename_to_str(s->keyfile),
9324 key_type_to_str(keytype));
9325 c_write_str(ssh, msgbuf);
9327 s->publickey_blob = NULL;
9332 * Find out about any keys Pageant has (but if there's a
9333 * public key configured, filter out all others).
9336 s->agent_response = NULL;
9337 s->pkblob_in_agent = NULL;
9338 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
9342 logevent("Pageant is running. Requesting keys.");
9344 /* Request the keys held by the agent. */
9345 PUT_32BIT(s->agent_request, 1);
9346 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
9347 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
9348 ssh_agent_callback, ssh)) {
9352 bombout(("Unexpected data from server while"
9353 " waiting for agent response"));
9356 } while (pktin || inlen > 0);
9357 r = ssh->agent_response;
9358 s->agent_responselen = ssh->agent_response_len;
9360 s->agent_response = (unsigned char *) r;
9361 if (s->agent_response && s->agent_responselen >= 5 &&
9362 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
9365 p = s->agent_response + 5;
9366 s->nkeys = toint(GET_32BIT(p));
9369 * Vet the Pageant response to ensure that the key
9370 * count and blob lengths make sense.
9373 logeventf(ssh, "Pageant response contained a negative"
9374 " key count %d", s->nkeys);
9376 goto done_agent_query;
9378 unsigned char *q = p + 4;
9379 int lenleft = s->agent_responselen - 5 - 4;
9381 for (keyi = 0; keyi < s->nkeys; keyi++) {
9382 int bloblen, commentlen;
9384 logeventf(ssh, "Pageant response was truncated");
9386 goto done_agent_query;
9388 bloblen = toint(GET_32BIT(q));
9389 if (bloblen < 0 || bloblen > lenleft) {
9390 logeventf(ssh, "Pageant response was truncated");
9392 goto done_agent_query;
9394 lenleft -= 4 + bloblen;
9396 commentlen = toint(GET_32BIT(q));
9397 if (commentlen < 0 || commentlen > lenleft) {
9398 logeventf(ssh, "Pageant response was truncated");
9400 goto done_agent_query;
9402 lenleft -= 4 + commentlen;
9403 q += 4 + commentlen;
9408 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
9409 if (s->publickey_blob) {
9410 /* See if configured key is in agent. */
9411 for (keyi = 0; keyi < s->nkeys; keyi++) {
9412 s->pklen = toint(GET_32BIT(p));
9413 if (s->pklen == s->publickey_bloblen &&
9414 !memcmp(p+4, s->publickey_blob,
9415 s->publickey_bloblen)) {
9416 logeventf(ssh, "Pageant key #%d matches "
9417 "configured key file", keyi);
9419 s->pkblob_in_agent = p;
9423 p += toint(GET_32BIT(p)) + 4; /* comment */
9425 if (!s->pkblob_in_agent) {
9426 logevent("Configured key file not in Pageant");
9431 logevent("Failed to get reply from Pageant");
9439 * We repeat this whole loop, including the username prompt,
9440 * until we manage a successful authentication. If the user
9441 * types the wrong _password_, they can be sent back to the
9442 * beginning to try another username, if this is configured on.
9443 * (If they specify a username in the config, they are never
9444 * asked, even if they do give a wrong password.)
9446 * I think this best serves the needs of
9448 * - the people who have no configuration, no keys, and just
9449 * want to try repeated (username,password) pairs until they
9450 * type both correctly
9452 * - people who have keys and configuration but occasionally
9453 * need to fall back to passwords
9455 * - people with a key held in Pageant, who might not have
9456 * logged in to a particular machine before; so they want to
9457 * type a username, and then _either_ their key will be
9458 * accepted, _or_ they will type a password. If they mistype
9459 * the username they will want to be able to get back and
9462 s->got_username = FALSE;
9463 while (!s->we_are_in) {
9467 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
9469 * We got a username last time round this loop, and
9470 * with change_username turned off we don't try to get
9473 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
9474 int ret; /* need not be kept over crReturn */
9475 s->cur_prompt = new_prompts(ssh->frontend);
9476 s->cur_prompt->to_server = TRUE;
9477 s->cur_prompt->name = dupstr("SSH login name");
9478 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
9479 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9482 crWaitUntilV(!pktin);
9483 ret = get_userpass_input(s->cur_prompt, in, inlen);
9488 * get_userpass_input() failed to get a username.
9491 free_prompts(s->cur_prompt);
9492 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
9495 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
9496 free_prompts(s->cur_prompt);
9499 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
9500 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
9501 c_write_str(ssh, stuff);
9505 s->got_username = TRUE;
9508 * Send an authentication request using method "none": (a)
9509 * just in case it succeeds, and (b) so that we know what
9510 * authentication methods we can usefully try next.
9512 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9514 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9515 ssh2_pkt_addstring(s->pktout, ssh->username);
9516 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
9517 ssh2_pkt_addstring(s->pktout, "none"); /* method */
9518 ssh2_pkt_send(ssh, s->pktout);
9519 s->type = AUTH_TYPE_NONE;
9521 s->we_are_in = FALSE;
9523 s->tried_pubkey_config = FALSE;
9524 s->kbd_inter_refused = FALSE;
9526 /* Reset agent request state. */
9527 s->done_agent = FALSE;
9528 if (s->agent_response) {
9529 if (s->pkblob_in_agent) {
9530 s->agentp = s->pkblob_in_agent;
9532 s->agentp = s->agent_response + 5 + 4;
9538 char *methods = NULL;
9542 * Wait for the result of the last authentication request.
9545 crWaitUntilV(pktin);
9547 * Now is a convenient point to spew any banner material
9548 * that we've accumulated. (This should ensure that when
9549 * we exit the auth loop, we haven't any left to deal
9553 int size = bufchain_size(&ssh->banner);
9555 * Don't show the banner if we're operating in
9556 * non-verbose non-interactive mode. (It's probably
9557 * a script, which means nobody will read the
9558 * banner _anyway_, and moreover the printing of
9559 * the banner will screw up processing on the
9560 * output of (say) plink.)
9562 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
9563 char *banner = snewn(size, char);
9564 bufchain_fetch(&ssh->banner, banner, size);
9565 c_write_untrusted(ssh, banner, size);
9568 bufchain_clear(&ssh->banner);
9570 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
9571 logevent("Access granted");
9572 s->we_are_in = s->userauth_success = TRUE;
9576 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
9577 bombout(("Strange packet received during authentication: "
9578 "type %d", pktin->type));
9585 * OK, we're now sitting on a USERAUTH_FAILURE message, so
9586 * we can look at the string in it and know what we can
9587 * helpfully try next.
9589 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
9590 ssh_pkt_getstring(pktin, &methods, &methlen);
9591 if (!ssh2_pkt_getbool(pktin)) {
9593 * We have received an unequivocal Access
9594 * Denied. This can translate to a variety of
9595 * messages, or no message at all.
9597 * For forms of authentication which are attempted
9598 * implicitly, by which I mean without printing
9599 * anything in the window indicating that we're
9600 * trying them, we should never print 'Access
9603 * If we do print a message saying that we're
9604 * attempting some kind of authentication, it's OK
9605 * to print a followup message saying it failed -
9606 * but the message may sometimes be more specific
9607 * than simply 'Access denied'.
9609 * Additionally, if we'd just tried password
9610 * authentication, we should break out of this
9611 * whole loop so as to go back to the username
9612 * prompt (iff we're configured to allow
9613 * username change attempts).
9615 if (s->type == AUTH_TYPE_NONE) {
9617 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
9618 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
9619 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
9620 c_write_str(ssh, "Server refused our key\r\n");
9621 logevent("Server refused our key");
9622 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
9623 /* This _shouldn't_ happen except by a
9624 * protocol bug causing client and server to
9625 * disagree on what is a correct signature. */
9626 c_write_str(ssh, "Server refused public-key signature"
9627 " despite accepting key!\r\n");
9628 logevent("Server refused public-key signature"
9629 " despite accepting key!");
9630 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
9631 /* quiet, so no c_write */
9632 logevent("Server refused keyboard-interactive authentication");
9633 } else if (s->type==AUTH_TYPE_GSSAPI) {
9634 /* always quiet, so no c_write */
9635 /* also, the code down in the GSSAPI block has
9636 * already logged this in the Event Log */
9637 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
9638 logevent("Keyboard-interactive authentication failed");
9639 c_write_str(ssh, "Access denied\r\n");
9641 assert(s->type == AUTH_TYPE_PASSWORD);
9642 logevent("Password authentication failed");
9643 c_write_str(ssh, "Access denied\r\n");
9645 if (conf_get_int(ssh->conf, CONF_change_username)) {
9646 /* XXX perhaps we should allow
9647 * keyboard-interactive to do this too? */
9648 s->we_are_in = FALSE;
9653 c_write_str(ssh, "Further authentication required\r\n");
9654 logevent("Further authentication required");
9658 in_commasep_string("publickey", methods, methlen);
9660 in_commasep_string("password", methods, methlen);
9661 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
9662 in_commasep_string("keyboard-interactive", methods, methlen);
9664 if (conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
9665 in_commasep_string("gssapi-with-mic", methods, methlen)) {
9666 /* Try loading the GSS libraries and see if we
9669 ssh->gsslibs = ssh_gss_setup(ssh->conf);
9670 s->can_gssapi = (ssh->gsslibs->nlibraries > 0);
9672 /* No point in even bothering to try to load the
9673 * GSS libraries, if the user configuration and
9674 * server aren't both prepared to attempt GSSAPI
9675 * auth in the first place. */
9676 s->can_gssapi = FALSE;
9681 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9683 if (s->can_pubkey && !s->done_agent && s->nkeys) {
9686 * Attempt public-key authentication using a key from Pageant.
9689 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9691 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
9693 /* Unpack key from agent response */
9694 s->pklen = toint(GET_32BIT(s->agentp));
9696 s->pkblob = (char *)s->agentp;
9697 s->agentp += s->pklen;
9698 s->alglen = toint(GET_32BIT(s->pkblob));
9699 s->alg = s->pkblob + 4;
9700 s->commentlen = toint(GET_32BIT(s->agentp));
9702 s->commentp = (char *)s->agentp;
9703 s->agentp += s->commentlen;
9704 /* s->agentp now points at next key, if any */
9706 /* See if server will accept it */
9707 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9708 ssh2_pkt_addstring(s->pktout, ssh->username);
9709 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9710 /* service requested */
9711 ssh2_pkt_addstring(s->pktout, "publickey");
9713 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
9714 ssh2_pkt_addstring_start(s->pktout);
9715 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9716 ssh2_pkt_addstring_start(s->pktout);
9717 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9718 ssh2_pkt_send(ssh, s->pktout);
9719 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
9721 crWaitUntilV(pktin);
9722 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9724 /* Offer of key refused. */
9731 if (flags & FLAG_VERBOSE) {
9732 c_write_str(ssh, "Authenticating with "
9734 c_write(ssh, s->commentp, s->commentlen);
9735 c_write_str(ssh, "\" from agent\r\n");
9739 * Server is willing to accept the key.
9740 * Construct a SIGN_REQUEST.
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, TRUE); /* 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);
9754 /* Ask agent for signature. */
9755 s->siglen = s->pktout->length - 5 + 4 +
9756 ssh->v2_session_id_len;
9757 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9759 s->len = 1; /* message type */
9760 s->len += 4 + s->pklen; /* key blob */
9761 s->len += 4 + s->siglen; /* data to sign */
9762 s->len += 4; /* flags */
9763 s->agentreq = snewn(4 + s->len, char);
9764 PUT_32BIT(s->agentreq, s->len);
9765 s->q = s->agentreq + 4;
9766 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
9767 PUT_32BIT(s->q, s->pklen);
9769 memcpy(s->q, s->pkblob, s->pklen);
9771 PUT_32BIT(s->q, s->siglen);
9773 /* Now the data to be signed... */
9774 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9775 PUT_32BIT(s->q, ssh->v2_session_id_len);
9778 memcpy(s->q, ssh->v2_session_id,
9779 ssh->v2_session_id_len);
9780 s->q += ssh->v2_session_id_len;
9781 memcpy(s->q, s->pktout->data + 5,
9782 s->pktout->length - 5);
9783 s->q += s->pktout->length - 5;
9784 /* And finally the (zero) flags word. */
9786 if (!agent_query(s->agentreq, s->len + 4,
9788 ssh_agent_callback, ssh)) {
9792 bombout(("Unexpected data from server"
9793 " while waiting for agent"
9797 } while (pktin || inlen > 0);
9798 vret = ssh->agent_response;
9799 s->retlen = ssh->agent_response_len;
9804 if (s->retlen >= 9 &&
9805 s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
9806 GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
9807 logevent("Sending Pageant's response");
9808 ssh2_add_sigblob(ssh, s->pktout,
9809 s->pkblob, s->pklen,
9811 GET_32BIT(s->ret + 5));
9812 ssh2_pkt_send(ssh, s->pktout);
9813 s->type = AUTH_TYPE_PUBLICKEY;
9815 /* FIXME: less drastic response */
9816 bombout(("Pageant failed to answer challenge"));
9822 /* Do we have any keys left to try? */
9823 if (s->pkblob_in_agent) {
9824 s->done_agent = TRUE;
9825 s->tried_pubkey_config = TRUE;
9828 if (s->keyi >= s->nkeys)
9829 s->done_agent = TRUE;
9832 } else if (s->can_pubkey && s->publickey_blob &&
9833 s->privatekey_available && !s->tried_pubkey_config) {
9835 struct ssh2_userkey *key; /* not live over crReturn */
9836 char *passphrase; /* not live over crReturn */
9838 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9840 s->tried_pubkey_config = TRUE;
9843 * Try the public key supplied in the configuration.
9845 * First, offer the public blob to see if the server is
9846 * willing to accept it.
9848 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9849 ssh2_pkt_addstring(s->pktout, ssh->username);
9850 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9851 /* service requested */
9852 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
9853 ssh2_pkt_addbool(s->pktout, FALSE);
9854 /* no signature included */
9855 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
9856 ssh2_pkt_addstring_start(s->pktout);
9857 ssh2_pkt_addstring_data(s->pktout,
9858 (char *)s->publickey_blob,
9859 s->publickey_bloblen);
9860 ssh2_pkt_send(ssh, s->pktout);
9861 logevent("Offered public key");
9863 crWaitUntilV(pktin);
9864 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9865 /* Key refused. Give up. */
9866 s->gotit = TRUE; /* reconsider message next loop */
9867 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
9868 continue; /* process this new message */
9870 logevent("Offer of public key accepted");
9873 * Actually attempt a serious authentication using
9876 if (flags & FLAG_VERBOSE) {
9877 c_write_str(ssh, "Authenticating with public key \"");
9878 c_write_str(ssh, s->publickey_comment);
9879 c_write_str(ssh, "\"\r\n");
9883 const char *error; /* not live over crReturn */
9884 if (s->privatekey_encrypted) {
9886 * Get a passphrase from the user.
9888 int ret; /* need not be kept over crReturn */
9889 s->cur_prompt = new_prompts(ssh->frontend);
9890 s->cur_prompt->to_server = FALSE;
9891 s->cur_prompt->name = dupstr("SSH key passphrase");
9892 add_prompt(s->cur_prompt,
9893 dupprintf("Passphrase for key \"%.100s\": ",
9894 s->publickey_comment),
9896 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9899 crWaitUntilV(!pktin);
9900 ret = get_userpass_input(s->cur_prompt,
9905 /* Failed to get a passphrase. Terminate. */
9906 free_prompts(s->cur_prompt);
9907 ssh_disconnect(ssh, NULL,
9908 "Unable to authenticate",
9909 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9914 dupstr(s->cur_prompt->prompts[0]->result);
9915 free_prompts(s->cur_prompt);
9917 passphrase = NULL; /* no passphrase needed */
9921 * Try decrypting the key.
9923 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9924 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
9926 /* burn the evidence */
9927 smemclr(passphrase, strlen(passphrase));
9930 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
9932 (key == SSH2_WRONG_PASSPHRASE)) {
9933 c_write_str(ssh, "Wrong passphrase\r\n");
9935 /* and loop again */
9937 c_write_str(ssh, "Unable to load private key (");
9938 c_write_str(ssh, error);
9939 c_write_str(ssh, ")\r\n");
9941 break; /* try something else */
9947 unsigned char *pkblob, *sigblob, *sigdata;
9948 int pkblob_len, sigblob_len, sigdata_len;
9952 * We have loaded the private key and the server
9953 * has announced that it's willing to accept it.
9954 * Hallelujah. Generate a signature and send it.
9956 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9957 ssh2_pkt_addstring(s->pktout, ssh->username);
9958 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9959 /* service requested */
9960 ssh2_pkt_addstring(s->pktout, "publickey");
9962 ssh2_pkt_addbool(s->pktout, TRUE);
9963 /* signature follows */
9964 ssh2_pkt_addstring(s->pktout, key->alg->name);
9965 pkblob = key->alg->public_blob(key->data,
9967 ssh2_pkt_addstring_start(s->pktout);
9968 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
9972 * The data to be signed is:
9976 * followed by everything so far placed in the
9979 sigdata_len = s->pktout->length - 5 + 4 +
9980 ssh->v2_session_id_len;
9981 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9983 sigdata = snewn(sigdata_len, unsigned char);
9985 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9986 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
9989 memcpy(sigdata+p, ssh->v2_session_id,
9990 ssh->v2_session_id_len);
9991 p += ssh->v2_session_id_len;
9992 memcpy(sigdata+p, s->pktout->data + 5,
9993 s->pktout->length - 5);
9994 p += s->pktout->length - 5;
9995 assert(p == sigdata_len);
9996 sigblob = key->alg->sign(key->data, (char *)sigdata,
9997 sigdata_len, &sigblob_len);
9998 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
9999 sigblob, sigblob_len);
10004 ssh2_pkt_send(ssh, s->pktout);
10005 logevent("Sent public key signature");
10006 s->type = AUTH_TYPE_PUBLICKEY;
10007 key->alg->freekey(key->data);
10008 sfree(key->comment);
10013 } else if (s->can_gssapi && !s->tried_gssapi) {
10015 /* GSSAPI Authentication */
10017 int micoffset, len;
10020 s->type = AUTH_TYPE_GSSAPI;
10021 s->tried_gssapi = TRUE;
10023 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
10026 * Pick the highest GSS library on the preference
10032 for (i = 0; i < ngsslibs; i++) {
10033 int want_id = conf_get_int_int(ssh->conf,
10034 CONF_ssh_gsslist, i);
10035 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
10036 if (ssh->gsslibs->libraries[j].id == want_id) {
10037 s->gsslib = &ssh->gsslibs->libraries[j];
10038 goto got_gsslib; /* double break */
10043 * We always expect to have found something in
10044 * the above loop: we only came here if there
10045 * was at least one viable GSS library, and the
10046 * preference list should always mention
10047 * everything and only change the order.
10052 if (s->gsslib->gsslogmsg)
10053 logevent(s->gsslib->gsslogmsg);
10055 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
10056 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10057 ssh2_pkt_addstring(s->pktout, ssh->username);
10058 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10059 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
10060 logevent("Attempting GSSAPI authentication");
10062 /* add mechanism info */
10063 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
10065 /* number of GSSAPI mechanisms */
10066 ssh2_pkt_adduint32(s->pktout,1);
10068 /* length of OID + 2 */
10069 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
10070 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
10072 /* length of OID */
10073 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
10075 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
10076 s->gss_buf.length);
10077 ssh2_pkt_send(ssh, s->pktout);
10078 crWaitUntilV(pktin);
10079 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
10080 logevent("GSSAPI authentication request refused");
10084 /* check returned packet ... */
10086 ssh_pkt_getstring(pktin, &data, &len);
10087 s->gss_rcvtok.value = data;
10088 s->gss_rcvtok.length = len;
10089 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
10090 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
10091 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
10092 memcmp((char *)s->gss_rcvtok.value + 2,
10093 s->gss_buf.value,s->gss_buf.length) ) {
10094 logevent("GSSAPI authentication - wrong response from server");
10098 /* now start running */
10099 s->gss_stat = s->gsslib->import_name(s->gsslib,
10102 if (s->gss_stat != SSH_GSS_OK) {
10103 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
10104 logevent("GSSAPI import name failed - Bad service name");
10106 logevent("GSSAPI import name failed");
10110 /* fetch TGT into GSS engine */
10111 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
10113 if (s->gss_stat != SSH_GSS_OK) {
10114 logevent("GSSAPI authentication failed to get credentials");
10115 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10119 /* initial tokens are empty */
10120 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
10121 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
10123 /* now enter the loop */
10125 s->gss_stat = s->gsslib->init_sec_context
10129 conf_get_int(ssh->conf, CONF_gssapifwd),
10133 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
10134 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
10135 logevent("GSSAPI authentication initialisation failed");
10137 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
10138 &s->gss_buf) == SSH_GSS_OK) {
10139 logevent(s->gss_buf.value);
10140 sfree(s->gss_buf.value);
10145 logevent("GSSAPI authentication initialised");
10147 /* Client and server now exchange tokens until GSSAPI
10148 * no longer says CONTINUE_NEEDED */
10150 if (s->gss_sndtok.length != 0) {
10151 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
10152 ssh_pkt_addstring_start(s->pktout);
10153 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
10154 ssh2_pkt_send(ssh, s->pktout);
10155 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
10158 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
10159 crWaitUntilV(pktin);
10160 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
10161 logevent("GSSAPI authentication - bad server response");
10162 s->gss_stat = SSH_GSS_FAILURE;
10165 ssh_pkt_getstring(pktin, &data, &len);
10166 s->gss_rcvtok.value = data;
10167 s->gss_rcvtok.length = len;
10169 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
10171 if (s->gss_stat != SSH_GSS_OK) {
10172 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10173 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
10176 logevent("GSSAPI authentication loop finished OK");
10178 /* Now send the MIC */
10180 s->pktout = ssh2_pkt_init(0);
10181 micoffset = s->pktout->length;
10182 ssh_pkt_addstring_start(s->pktout);
10183 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
10184 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
10185 ssh_pkt_addstring(s->pktout, ssh->username);
10186 ssh_pkt_addstring(s->pktout, "ssh-connection");
10187 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
10189 s->gss_buf.value = (char *)s->pktout->data + micoffset;
10190 s->gss_buf.length = s->pktout->length - micoffset;
10192 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
10193 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
10194 ssh_pkt_addstring_start(s->pktout);
10195 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
10196 ssh2_pkt_send(ssh, s->pktout);
10197 s->gsslib->free_mic(s->gsslib, &mic);
10201 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10202 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
10205 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
10208 * Keyboard-interactive authentication.
10211 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
10213 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
10215 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10216 ssh2_pkt_addstring(s->pktout, ssh->username);
10217 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10218 /* service requested */
10219 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
10221 ssh2_pkt_addstring(s->pktout, ""); /* lang */
10222 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
10223 ssh2_pkt_send(ssh, s->pktout);
10225 logevent("Attempting keyboard-interactive authentication");
10227 crWaitUntilV(pktin);
10228 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
10229 /* Server is not willing to do keyboard-interactive
10230 * at all (or, bizarrely but legally, accepts the
10231 * user without actually issuing any prompts).
10232 * Give up on it entirely. */
10234 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
10235 s->kbd_inter_refused = TRUE; /* don't try it again */
10240 * Loop while the server continues to send INFO_REQUESTs.
10242 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
10244 char *name, *inst, *lang;
10245 int name_len, inst_len, lang_len;
10249 * We've got a fresh USERAUTH_INFO_REQUEST.
10250 * Get the preamble and start building a prompt.
10252 ssh_pkt_getstring(pktin, &name, &name_len);
10253 ssh_pkt_getstring(pktin, &inst, &inst_len);
10254 ssh_pkt_getstring(pktin, &lang, &lang_len);
10255 s->cur_prompt = new_prompts(ssh->frontend);
10256 s->cur_prompt->to_server = TRUE;
10259 * Get any prompt(s) from the packet.
10261 s->num_prompts = ssh_pkt_getuint32(pktin);
10262 for (i = 0; i < s->num_prompts; i++) {
10266 static char noprompt[] =
10267 "<server failed to send prompt>: ";
10269 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10270 echo = ssh2_pkt_getbool(pktin);
10273 prompt_len = lenof(noprompt)-1;
10275 add_prompt(s->cur_prompt,
10276 dupprintf("%.*s", prompt_len, prompt),
10281 /* FIXME: better prefix to distinguish from
10282 * local prompts? */
10283 s->cur_prompt->name =
10284 dupprintf("SSH server: %.*s", name_len, name);
10285 s->cur_prompt->name_reqd = TRUE;
10287 s->cur_prompt->name =
10288 dupstr("SSH server authentication");
10289 s->cur_prompt->name_reqd = FALSE;
10291 /* We add a prefix to try to make it clear that a prompt
10292 * has come from the server.
10293 * FIXME: ugly to print "Using..." in prompt _every_
10294 * time round. Can this be done more subtly? */
10295 /* Special case: for reasons best known to themselves,
10296 * some servers send k-i requests with no prompts and
10297 * nothing to display. Keep quiet in this case. */
10298 if (s->num_prompts || name_len || inst_len) {
10299 s->cur_prompt->instruction =
10300 dupprintf("Using keyboard-interactive authentication.%s%.*s",
10301 inst_len ? "\n" : "", inst_len, inst);
10302 s->cur_prompt->instr_reqd = TRUE;
10304 s->cur_prompt->instr_reqd = FALSE;
10308 * Display any instructions, and get the user's
10312 int ret; /* not live over crReturn */
10313 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10316 crWaitUntilV(!pktin);
10317 ret = get_userpass_input(s->cur_prompt, in, inlen);
10322 * Failed to get responses. Terminate.
10324 free_prompts(s->cur_prompt);
10325 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10326 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10333 * Send the response(s) to the server.
10335 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
10336 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
10337 for (i=0; i < s->num_prompts; i++) {
10338 ssh2_pkt_addstring(s->pktout,
10339 s->cur_prompt->prompts[i]->result);
10341 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10344 * Free the prompts structure from this iteration.
10345 * If there's another, a new one will be allocated
10346 * when we return to the top of this while loop.
10348 free_prompts(s->cur_prompt);
10351 * Get the next packet in case it's another
10354 crWaitUntilV(pktin);
10359 * We should have SUCCESS or FAILURE now.
10363 } else if (s->can_passwd) {
10366 * Plain old password authentication.
10368 int ret; /* not live over crReturn */
10369 int changereq_first_time; /* not live over crReturn */
10371 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
10373 s->cur_prompt = new_prompts(ssh->frontend);
10374 s->cur_prompt->to_server = TRUE;
10375 s->cur_prompt->name = dupstr("SSH password");
10376 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
10381 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10384 crWaitUntilV(!pktin);
10385 ret = get_userpass_input(s->cur_prompt, in, inlen);
10390 * Failed to get responses. Terminate.
10392 free_prompts(s->cur_prompt);
10393 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10394 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10399 * Squirrel away the password. (We may need it later if
10400 * asked to change it.)
10402 s->password = dupstr(s->cur_prompt->prompts[0]->result);
10403 free_prompts(s->cur_prompt);
10406 * Send the password packet.
10408 * We pad out the password packet to 256 bytes to make
10409 * it harder for an attacker to find the length of the
10412 * Anyone using a password longer than 256 bytes
10413 * probably doesn't have much to worry about from
10414 * people who find out how long their password is!
10416 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10417 ssh2_pkt_addstring(s->pktout, ssh->username);
10418 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10419 /* service requested */
10420 ssh2_pkt_addstring(s->pktout, "password");
10421 ssh2_pkt_addbool(s->pktout, FALSE);
10422 ssh2_pkt_addstring(s->pktout, s->password);
10423 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10424 logevent("Sent password");
10425 s->type = AUTH_TYPE_PASSWORD;
10428 * Wait for next packet, in case it's a password change
10431 crWaitUntilV(pktin);
10432 changereq_first_time = TRUE;
10434 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
10437 * We're being asked for a new password
10438 * (perhaps not for the first time).
10439 * Loop until the server accepts it.
10442 int got_new = FALSE; /* not live over crReturn */
10443 char *prompt; /* not live over crReturn */
10444 int prompt_len; /* not live over crReturn */
10448 if (changereq_first_time)
10449 msg = "Server requested password change";
10451 msg = "Server rejected new password";
10453 c_write_str(ssh, msg);
10454 c_write_str(ssh, "\r\n");
10457 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10459 s->cur_prompt = new_prompts(ssh->frontend);
10460 s->cur_prompt->to_server = TRUE;
10461 s->cur_prompt->name = dupstr("New SSH password");
10462 s->cur_prompt->instruction =
10463 dupprintf("%.*s", prompt_len, NULLTOEMPTY(prompt));
10464 s->cur_prompt->instr_reqd = TRUE;
10466 * There's no explicit requirement in the protocol
10467 * for the "old" passwords in the original and
10468 * password-change messages to be the same, and
10469 * apparently some Cisco kit supports password change
10470 * by the user entering a blank password originally
10471 * and the real password subsequently, so,
10472 * reluctantly, we prompt for the old password again.
10474 * (On the other hand, some servers don't even bother
10475 * to check this field.)
10477 add_prompt(s->cur_prompt,
10478 dupstr("Current password (blank for previously entered password): "),
10480 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
10482 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
10486 * Loop until the user manages to enter the same
10491 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10494 crWaitUntilV(!pktin);
10495 ret = get_userpass_input(s->cur_prompt, in, inlen);
10500 * Failed to get responses. Terminate.
10502 /* burn the evidence */
10503 free_prompts(s->cur_prompt);
10504 smemclr(s->password, strlen(s->password));
10505 sfree(s->password);
10506 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10507 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10513 * If the user specified a new original password
10514 * (IYSWIM), overwrite any previously specified
10516 * (A side effect is that the user doesn't have to
10517 * re-enter it if they louse up the new password.)
10519 if (s->cur_prompt->prompts[0]->result[0]) {
10520 smemclr(s->password, strlen(s->password));
10521 /* burn the evidence */
10522 sfree(s->password);
10524 dupstr(s->cur_prompt->prompts[0]->result);
10528 * Check the two new passwords match.
10530 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
10531 s->cur_prompt->prompts[2]->result)
10534 /* They don't. Silly user. */
10535 c_write_str(ssh, "Passwords do not match\r\n");
10540 * Send the new password (along with the old one).
10541 * (see above for padding rationale)
10543 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10544 ssh2_pkt_addstring(s->pktout, ssh->username);
10545 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10546 /* service requested */
10547 ssh2_pkt_addstring(s->pktout, "password");
10548 ssh2_pkt_addbool(s->pktout, TRUE);
10549 ssh2_pkt_addstring(s->pktout, s->password);
10550 ssh2_pkt_addstring(s->pktout,
10551 s->cur_prompt->prompts[1]->result);
10552 free_prompts(s->cur_prompt);
10553 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10554 logevent("Sent new password");
10557 * Now see what the server has to say about it.
10558 * (If it's CHANGEREQ again, it's not happy with the
10561 crWaitUntilV(pktin);
10562 changereq_first_time = FALSE;
10567 * We need to reexamine the current pktin at the top
10568 * of the loop. Either:
10569 * - we weren't asked to change password at all, in
10570 * which case it's a SUCCESS or FAILURE with the
10572 * - we sent a new password, and the server was
10573 * either OK with it (SUCCESS or FAILURE w/partial
10574 * success) or unhappy with the _old_ password
10575 * (FAILURE w/o partial success)
10576 * In any of these cases, we go back to the top of
10577 * the loop and start again.
10582 * We don't need the old password any more, in any
10583 * case. Burn the evidence.
10585 smemclr(s->password, strlen(s->password));
10586 sfree(s->password);
10589 char *str = dupprintf("No supported authentication methods available"
10590 " (server sent: %.*s)",
10593 ssh_disconnect(ssh, str,
10594 "No supported authentication methods available",
10595 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
10605 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
10607 /* Clear up various bits and pieces from authentication. */
10608 if (s->publickey_blob) {
10609 sfree(s->publickey_algorithm);
10610 sfree(s->publickey_blob);
10611 sfree(s->publickey_comment);
10613 if (s->agent_response)
10614 sfree(s->agent_response);
10616 if (s->userauth_success && !ssh->bare_connection) {
10618 * We've just received USERAUTH_SUCCESS, and we haven't sent any
10619 * packets since. Signal the transport layer to consider enacting
10620 * delayed compression.
10622 * (Relying on we_are_in is not sufficient, as
10623 * draft-miller-secsh-compression-delayed is quite clear that it
10624 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
10625 * become set for other reasons.)
10627 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
10630 ssh->channels = newtree234(ssh_channelcmp);
10633 * Set up handlers for some connection protocol messages, so we
10634 * don't have to handle them repeatedly in this coroutine.
10636 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
10637 ssh2_msg_channel_window_adjust;
10638 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
10639 ssh2_msg_global_request;
10642 * Create the main session channel.
10644 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
10645 ssh->mainchan = NULL;
10647 ssh->mainchan = snew(struct ssh_channel);
10648 ssh->mainchan->ssh = ssh;
10649 ssh2_channel_init(ssh->mainchan);
10651 if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
10653 * Just start a direct-tcpip channel and use it as the main
10656 ssh_send_port_open(ssh->mainchan,
10657 conf_get_str(ssh->conf, CONF_ssh_nc_host),
10658 conf_get_int(ssh->conf, CONF_ssh_nc_port),
10660 ssh->ncmode = TRUE;
10662 s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
10663 logevent("Opening session as main channel");
10664 ssh2_pkt_send(ssh, s->pktout);
10665 ssh->ncmode = FALSE;
10667 crWaitUntilV(pktin);
10668 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
10669 bombout(("Server refused to open channel"));
10671 /* FIXME: error data comes back in FAILURE packet */
10673 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
10674 bombout(("Server's channel confirmation cited wrong channel"));
10677 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
10678 ssh->mainchan->halfopen = FALSE;
10679 ssh->mainchan->type = CHAN_MAINSESSION;
10680 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
10681 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
10682 add234(ssh->channels, ssh->mainchan);
10683 update_specials_menu(ssh->frontend);
10684 logevent("Opened main channel");
10688 * Now we have a channel, make dispatch table entries for
10689 * general channel-based messages.
10691 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
10692 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
10693 ssh2_msg_channel_data;
10694 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
10695 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
10696 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
10697 ssh2_msg_channel_open_confirmation;
10698 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
10699 ssh2_msg_channel_open_failure;
10700 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
10701 ssh2_msg_channel_request;
10702 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
10703 ssh2_msg_channel_open;
10704 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
10705 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
10708 * Now the connection protocol is properly up and running, with
10709 * all those dispatch table entries, so it's safe to let
10710 * downstreams start trying to open extra channels through us.
10712 if (ssh->connshare)
10713 share_activate(ssh->connshare, ssh->v_s);
10715 if (ssh->mainchan && ssh_is_simple(ssh)) {
10717 * This message indicates to the server that we promise
10718 * not to try to run any other channel in parallel with
10719 * this one, so it's safe for it to advertise a very large
10720 * window and leave the flow control to TCP.
10722 s->pktout = ssh2_chanreq_init(ssh->mainchan,
10723 "simple@putty.projects.tartarus.org",
10725 ssh2_pkt_send(ssh, s->pktout);
10729 * Enable port forwardings.
10731 ssh_setup_portfwd(ssh, ssh->conf);
10733 if (ssh->mainchan && !ssh->ncmode) {
10735 * Send the CHANNEL_REQUESTS for the main session channel.
10736 * Each one is handled by its own little asynchronous
10740 /* Potentially enable X11 forwarding. */
10741 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
10743 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
10745 if (!ssh->x11disp) {
10746 /* FIXME: return an error message from x11_setup_display */
10747 logevent("X11 forwarding not enabled: unable to"
10748 " initialise X display");
10750 ssh->x11auth = x11_invent_fake_auth
10751 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
10752 ssh->x11auth->disp = ssh->x11disp;
10754 ssh2_setup_x11(ssh->mainchan, NULL, NULL);
10758 /* Potentially enable agent forwarding. */
10759 if (ssh_agent_forwarding_permitted(ssh))
10760 ssh2_setup_agent(ssh->mainchan, NULL, NULL);
10762 /* Now allocate a pty for the session. */
10763 if (!conf_get_int(ssh->conf, CONF_nopty))
10764 ssh2_setup_pty(ssh->mainchan, NULL, NULL);
10766 /* Send environment variables. */
10767 ssh2_setup_env(ssh->mainchan, NULL, NULL);
10770 * Start a shell or a remote command. We may have to attempt
10771 * this twice if the config data has provided a second choice
10778 if (ssh->fallback_cmd) {
10779 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
10780 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
10782 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
10783 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
10787 s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
10788 ssh2_response_authconn, NULL);
10789 ssh2_pkt_addstring(s->pktout, cmd);
10791 s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
10792 ssh2_response_authconn, NULL);
10793 ssh2_pkt_addstring(s->pktout, cmd);
10795 s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
10796 ssh2_response_authconn, NULL);
10798 ssh2_pkt_send(ssh, s->pktout);
10800 crWaitUntilV(pktin);
10802 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
10803 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
10804 bombout(("Unexpected response to shell/command request:"
10805 " packet type %d", pktin->type));
10809 * We failed to start the command. If this is the
10810 * fallback command, we really are finished; if it's
10811 * not, and if the fallback command exists, try falling
10812 * back to it before complaining.
10814 if (!ssh->fallback_cmd &&
10815 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
10816 logevent("Primary command failed; attempting fallback");
10817 ssh->fallback_cmd = TRUE;
10820 bombout(("Server refused to start a shell/command"));
10823 logevent("Started a shell/command");
10828 ssh->editing = ssh->echoing = TRUE;
10831 ssh->state = SSH_STATE_SESSION;
10832 if (ssh->size_needed)
10833 ssh_size(ssh, ssh->term_width, ssh->term_height);
10834 if (ssh->eof_needed)
10835 ssh_special(ssh, TS_EOF);
10841 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
10849 * _All_ the connection-layer packets we expect to
10850 * receive are now handled by the dispatch table.
10851 * Anything that reaches here must be bogus.
10854 bombout(("Strange packet received: type %d", pktin->type));
10856 } else if (ssh->mainchan) {
10858 * We have spare data. Add it to the channel buffer.
10860 ssh_send_channel_data(ssh->mainchan, (char *)in, inlen);
10868 * Handlers for SSH-2 messages that might arrive at any moment.
10870 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
10872 /* log reason code in disconnect message */
10874 int reason, msglen;
10876 reason = ssh_pkt_getuint32(pktin);
10877 ssh_pkt_getstring(pktin, &msg, &msglen);
10879 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
10880 buf = dupprintf("Received disconnect message (%s)",
10881 ssh2_disconnect_reasons[reason]);
10883 buf = dupprintf("Received disconnect message (unknown"
10884 " type %d)", reason);
10888 buf = dupprintf("Disconnection message text: %.*s",
10889 msglen, NULLTOEMPTY(msg));
10891 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
10893 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
10894 ssh2_disconnect_reasons[reason] : "unknown",
10895 msglen, NULLTOEMPTY(msg)));
10899 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
10901 /* log the debug message */
10905 /* XXX maybe we should actually take notice of the return value */
10906 ssh2_pkt_getbool(pktin);
10907 ssh_pkt_getstring(pktin, &msg, &msglen);
10909 logeventf(ssh, "Remote debug message: %.*s", msglen, NULLTOEMPTY(msg));
10912 static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
10914 do_ssh2_transport(ssh, NULL, 0, pktin);
10918 * Called if we receive a packet that isn't allowed by the protocol.
10919 * This only applies to packets whose meaning PuTTY understands.
10920 * Entirely unknown packets are handled below.
10922 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
10924 char *buf = dupprintf("Server protocol violation: unexpected %s packet",
10925 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
10927 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
10931 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
10933 struct Packet *pktout;
10934 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
10935 ssh2_pkt_adduint32(pktout, pktin->sequence);
10937 * UNIMPLEMENTED messages MUST appear in the same order as the
10938 * messages they respond to. Hence, never queue them.
10940 ssh2_pkt_send_noqueue(ssh, pktout);
10944 * Handle the top-level SSH-2 protocol.
10946 static void ssh2_protocol_setup(Ssh ssh)
10951 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10953 for (i = 0; i < 256; i++)
10954 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10957 * Initially, we only accept transport messages (and a few generic
10958 * ones). do_ssh2_authconn will add more when it starts.
10959 * Messages that are understood but not currently acceptable go to
10960 * ssh2_msg_unexpected.
10962 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10963 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
10964 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
10965 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
10966 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
10967 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
10968 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
10969 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
10970 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
10971 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
10972 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
10973 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
10974 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
10975 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
10976 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
10977 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
10978 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
10979 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
10980 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
10981 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10982 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10983 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10984 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10985 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10986 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10987 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10988 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10989 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10990 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10991 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10992 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10993 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10994 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10997 * These messages have a special handler from the start.
10999 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
11000 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
11001 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
11004 static void ssh2_bare_connection_protocol_setup(Ssh ssh)
11009 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
11011 for (i = 0; i < 256; i++)
11012 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
11015 * Initially, we set all ssh-connection messages to 'unexpected';
11016 * do_ssh2_authconn will fill things in properly. We also handle a
11017 * couple of messages from the transport protocol which aren't
11018 * related to key exchange (UNIMPLEMENTED, IGNORE, DEBUG,
11021 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
11022 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
11023 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
11024 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
11025 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
11026 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
11027 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
11028 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
11029 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
11030 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
11031 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
11032 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
11033 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
11034 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
11036 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
11039 * These messages have a special handler from the start.
11041 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
11042 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore;
11043 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
11046 static void ssh2_timer(void *ctx, unsigned long now)
11048 Ssh ssh = (Ssh)ctx;
11050 if (ssh->state == SSH_STATE_CLOSED)
11053 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11054 conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
11055 now == ssh->next_rekey) {
11056 do_ssh2_transport(ssh, "timeout", -1, NULL);
11060 static void ssh2_protocol(Ssh ssh, const void *vin, int inlen,
11061 struct Packet *pktin)
11063 const unsigned char *in = (const unsigned char *)vin;
11064 if (ssh->state == SSH_STATE_CLOSED)
11068 ssh->incoming_data_size += pktin->encrypted_len;
11069 if (!ssh->kex_in_progress &&
11070 ssh->max_data_size != 0 &&
11071 ssh->incoming_data_size > ssh->max_data_size)
11072 do_ssh2_transport(ssh, "too much data received", -1, NULL);
11076 ssh->packet_dispatch[pktin->type](ssh, pktin);
11077 else if (!ssh->protocol_initial_phase_done)
11078 do_ssh2_transport(ssh, in, inlen, pktin);
11080 do_ssh2_authconn(ssh, in, inlen, pktin);
11083 static void ssh2_bare_connection_protocol(Ssh ssh, const void *vin, int inlen,
11084 struct Packet *pktin)
11086 const unsigned char *in = (const unsigned char *)vin;
11087 if (ssh->state == SSH_STATE_CLOSED)
11091 ssh->packet_dispatch[pktin->type](ssh, pktin);
11093 do_ssh2_authconn(ssh, in, inlen, pktin);
11096 static void ssh_cache_conf_values(Ssh ssh)
11098 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
11102 * Called to set up the connection.
11104 * Returns an error message, or NULL on success.
11106 static const char *ssh_init(void *frontend_handle, void **backend_handle,
11108 const char *host, int port, char **realhost,
11109 int nodelay, int keepalive)
11114 ssh = snew(struct ssh_tag);
11115 ssh->conf = conf_copy(conf);
11116 ssh_cache_conf_values(ssh);
11117 ssh->version = 0; /* when not ready yet */
11119 ssh->cipher = NULL;
11120 ssh->v1_cipher_ctx = NULL;
11121 ssh->crcda_ctx = NULL;
11122 ssh->cscipher = NULL;
11123 ssh->cs_cipher_ctx = NULL;
11124 ssh->sccipher = NULL;
11125 ssh->sc_cipher_ctx = NULL;
11127 ssh->cs_mac_ctx = NULL;
11129 ssh->sc_mac_ctx = NULL;
11130 ssh->cscomp = NULL;
11131 ssh->cs_comp_ctx = NULL;
11132 ssh->sccomp = NULL;
11133 ssh->sc_comp_ctx = NULL;
11135 ssh->kex_ctx = NULL;
11136 ssh->hostkey = NULL;
11137 ssh->hostkey_str = NULL;
11138 ssh->exitcode = -1;
11139 ssh->close_expected = FALSE;
11140 ssh->clean_exit = FALSE;
11141 ssh->state = SSH_STATE_PREPACKET;
11142 ssh->size_needed = FALSE;
11143 ssh->eof_needed = FALSE;
11145 ssh->logctx = NULL;
11146 ssh->deferred_send_data = NULL;
11147 ssh->deferred_len = 0;
11148 ssh->deferred_size = 0;
11149 ssh->fallback_cmd = 0;
11150 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
11151 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
11152 ssh->x11disp = NULL;
11153 ssh->x11auth = NULL;
11154 ssh->x11authtree = newtree234(x11_authcmp);
11155 ssh->v1_compressing = FALSE;
11156 ssh->v2_outgoing_sequence = 0;
11157 ssh->ssh1_rdpkt_crstate = 0;
11158 ssh->ssh2_rdpkt_crstate = 0;
11159 ssh->ssh2_bare_rdpkt_crstate = 0;
11160 ssh->ssh_gotdata_crstate = 0;
11161 ssh->do_ssh1_connection_crstate = 0;
11162 ssh->do_ssh_init_state = NULL;
11163 ssh->do_ssh_connection_init_state = NULL;
11164 ssh->do_ssh1_login_state = NULL;
11165 ssh->do_ssh2_transport_state = NULL;
11166 ssh->do_ssh2_authconn_state = NULL;
11169 ssh->mainchan = NULL;
11170 ssh->throttled_all = 0;
11171 ssh->v1_stdout_throttling = 0;
11173 ssh->queuelen = ssh->queuesize = 0;
11174 ssh->queueing = FALSE;
11175 ssh->qhead = ssh->qtail = NULL;
11176 ssh->deferred_rekey_reason = NULL;
11177 bufchain_init(&ssh->queued_incoming_data);
11178 ssh->frozen = FALSE;
11179 ssh->username = NULL;
11180 ssh->sent_console_eof = FALSE;
11181 ssh->got_pty = FALSE;
11182 ssh->bare_connection = FALSE;
11183 ssh->X11_fwd_enabled = FALSE;
11184 ssh->connshare = NULL;
11185 ssh->attempting_connshare = FALSE;
11186 ssh->session_started = FALSE;
11187 ssh->specials = NULL;
11188 ssh->n_uncert_hostkeys = 0;
11189 ssh->cross_certifying = FALSE;
11191 *backend_handle = ssh;
11194 if (crypto_startup() == 0)
11195 return "Microsoft high encryption pack not installed!";
11198 ssh->frontend = frontend_handle;
11199 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
11200 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
11202 ssh->channels = NULL;
11203 ssh->rportfwds = NULL;
11204 ssh->portfwds = NULL;
11209 ssh->conn_throttle_count = 0;
11210 ssh->overall_bufsize = 0;
11211 ssh->fallback_cmd = 0;
11213 ssh->protocol = NULL;
11215 ssh->protocol_initial_phase_done = FALSE;
11217 ssh->pinger = NULL;
11219 ssh->incoming_data_size = ssh->outgoing_data_size =
11220 ssh->deferred_data_size = 0L;
11221 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11222 CONF_ssh_rekey_data));
11223 ssh->kex_in_progress = FALSE;
11226 ssh->gsslibs = NULL;
11229 random_ref(); /* do this now - may be needed by sharing setup code */
11231 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
11240 static void ssh_free(void *handle)
11242 Ssh ssh = (Ssh) handle;
11243 struct ssh_channel *c;
11244 struct ssh_rportfwd *pf;
11245 struct X11FakeAuth *auth;
11247 if (ssh->v1_cipher_ctx)
11248 ssh->cipher->free_context(ssh->v1_cipher_ctx);
11249 if (ssh->cs_cipher_ctx)
11250 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
11251 if (ssh->sc_cipher_ctx)
11252 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
11253 if (ssh->cs_mac_ctx)
11254 ssh->csmac->free_context(ssh->cs_mac_ctx);
11255 if (ssh->sc_mac_ctx)
11256 ssh->scmac->free_context(ssh->sc_mac_ctx);
11257 if (ssh->cs_comp_ctx) {
11259 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
11261 zlib_compress_cleanup(ssh->cs_comp_ctx);
11263 if (ssh->sc_comp_ctx) {
11265 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
11267 zlib_decompress_cleanup(ssh->sc_comp_ctx);
11270 dh_cleanup(ssh->kex_ctx);
11271 sfree(ssh->savedhost);
11273 while (ssh->queuelen-- > 0)
11274 ssh_free_packet(ssh->queue[ssh->queuelen]);
11277 while (ssh->qhead) {
11278 struct queued_handler *qh = ssh->qhead;
11279 ssh->qhead = qh->next;
11282 ssh->qhead = ssh->qtail = NULL;
11284 if (ssh->channels) {
11285 while ((c = delpos234(ssh->channels, 0)) != NULL) {
11288 if (c->u.x11.xconn != NULL)
11289 x11_close(c->u.x11.xconn);
11291 case CHAN_SOCKDATA:
11292 case CHAN_SOCKDATA_DORMANT:
11293 if (c->u.pfd.pf != NULL)
11294 pfd_close(c->u.pfd.pf);
11297 if (ssh->version == 2) {
11298 struct outstanding_channel_request *ocr, *nocr;
11299 ocr = c->v.v2.chanreq_head;
11301 ocr->handler(c, NULL, ocr->ctx);
11306 bufchain_clear(&c->v.v2.outbuffer);
11310 freetree234(ssh->channels);
11311 ssh->channels = NULL;
11314 if (ssh->connshare)
11315 sharestate_free(ssh->connshare);
11317 if (ssh->rportfwds) {
11318 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
11320 freetree234(ssh->rportfwds);
11321 ssh->rportfwds = NULL;
11323 sfree(ssh->deferred_send_data);
11325 x11_free_display(ssh->x11disp);
11326 while ((auth = delpos234(ssh->x11authtree, 0)) != NULL)
11327 x11_free_fake_auth(auth);
11328 freetree234(ssh->x11authtree);
11329 sfree(ssh->do_ssh_init_state);
11330 sfree(ssh->do_ssh1_login_state);
11331 sfree(ssh->do_ssh2_transport_state);
11332 sfree(ssh->do_ssh2_authconn_state);
11335 sfree(ssh->fullhostname);
11336 sfree(ssh->hostkey_str);
11337 sfree(ssh->specials);
11338 if (ssh->crcda_ctx) {
11339 crcda_free_context(ssh->crcda_ctx);
11340 ssh->crcda_ctx = NULL;
11343 ssh_do_close(ssh, TRUE);
11344 expire_timer_context(ssh);
11346 pinger_free(ssh->pinger);
11347 bufchain_clear(&ssh->queued_incoming_data);
11348 sfree(ssh->username);
11349 conf_free(ssh->conf);
11352 ssh_gss_cleanup(ssh->gsslibs);
11360 * Reconfigure the SSH backend.
11362 static void ssh_reconfig(void *handle, Conf *conf)
11364 Ssh ssh = (Ssh) handle;
11365 const char *rekeying = NULL;
11366 int rekey_mandatory = FALSE;
11367 unsigned long old_max_data_size;
11370 pinger_reconfig(ssh->pinger, ssh->conf, conf);
11372 ssh_setup_portfwd(ssh, conf);
11374 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
11375 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
11377 unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
11378 unsigned long now = GETTICKCOUNT();
11380 if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
11381 rekeying = "timeout shortened";
11383 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
11387 old_max_data_size = ssh->max_data_size;
11388 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11389 CONF_ssh_rekey_data));
11390 if (old_max_data_size != ssh->max_data_size &&
11391 ssh->max_data_size != 0) {
11392 if (ssh->outgoing_data_size > ssh->max_data_size ||
11393 ssh->incoming_data_size > ssh->max_data_size)
11394 rekeying = "data limit lowered";
11397 if (conf_get_int(ssh->conf, CONF_compression) !=
11398 conf_get_int(conf, CONF_compression)) {
11399 rekeying = "compression setting changed";
11400 rekey_mandatory = TRUE;
11403 for (i = 0; i < CIPHER_MAX; i++)
11404 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
11405 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
11406 rekeying = "cipher settings changed";
11407 rekey_mandatory = TRUE;
11409 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
11410 conf_get_int(conf, CONF_ssh2_des_cbc)) {
11411 rekeying = "cipher settings changed";
11412 rekey_mandatory = TRUE;
11415 conf_free(ssh->conf);
11416 ssh->conf = conf_copy(conf);
11417 ssh_cache_conf_values(ssh);
11419 if (!ssh->bare_connection && rekeying) {
11420 if (!ssh->kex_in_progress) {
11421 do_ssh2_transport(ssh, rekeying, -1, NULL);
11422 } else if (rekey_mandatory) {
11423 ssh->deferred_rekey_reason = rekeying;
11429 * Called to send data down the SSH connection.
11431 static int ssh_send(void *handle, const char *buf, int len)
11433 Ssh ssh = (Ssh) handle;
11435 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11438 ssh->protocol(ssh, (const unsigned char *)buf, len, 0);
11440 return ssh_sendbuffer(ssh);
11444 * Called to query the current amount of buffered stdin data.
11446 static int ssh_sendbuffer(void *handle)
11448 Ssh ssh = (Ssh) handle;
11449 int override_value;
11451 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11455 * If the SSH socket itself has backed up, add the total backup
11456 * size on that to any individual buffer on the stdin channel.
11458 override_value = 0;
11459 if (ssh->throttled_all)
11460 override_value = ssh->overall_bufsize;
11462 if (ssh->version == 1) {
11463 return override_value;
11464 } else if (ssh->version == 2) {
11465 if (!ssh->mainchan)
11466 return override_value;
11468 return (override_value +
11469 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
11476 * Called to set the size of the window from SSH's POV.
11478 static void ssh_size(void *handle, int width, int height)
11480 Ssh ssh = (Ssh) handle;
11481 struct Packet *pktout;
11483 ssh->term_width = width;
11484 ssh->term_height = height;
11486 switch (ssh->state) {
11487 case SSH_STATE_BEFORE_SIZE:
11488 case SSH_STATE_PREPACKET:
11489 case SSH_STATE_CLOSED:
11490 break; /* do nothing */
11491 case SSH_STATE_INTERMED:
11492 ssh->size_needed = TRUE; /* buffer for later */
11494 case SSH_STATE_SESSION:
11495 if (!conf_get_int(ssh->conf, CONF_nopty)) {
11496 if (ssh->version == 1) {
11497 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
11498 PKT_INT, ssh->term_height,
11499 PKT_INT, ssh->term_width,
11500 PKT_INT, 0, PKT_INT, 0, PKT_END);
11501 } else if (ssh->mainchan) {
11502 pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
11504 ssh2_pkt_adduint32(pktout, ssh->term_width);
11505 ssh2_pkt_adduint32(pktout, ssh->term_height);
11506 ssh2_pkt_adduint32(pktout, 0);
11507 ssh2_pkt_adduint32(pktout, 0);
11508 ssh2_pkt_send(ssh, pktout);
11516 * Return a list of the special codes that make sense in this
11519 static const struct telnet_special *ssh_get_specials(void *handle)
11521 static const struct telnet_special ssh1_ignore_special[] = {
11522 {"IGNORE message", TS_NOP}
11524 static const struct telnet_special ssh2_ignore_special[] = {
11525 {"IGNORE message", TS_NOP},
11527 static const struct telnet_special ssh2_rekey_special[] = {
11528 {"Repeat key exchange", TS_REKEY},
11530 static const struct telnet_special ssh2_session_specials[] = {
11533 /* These are the signal names defined by RFC 4254.
11534 * They include all the ISO C signals, but are a subset of the POSIX
11535 * required signals. */
11536 {"SIGINT (Interrupt)", TS_SIGINT},
11537 {"SIGTERM (Terminate)", TS_SIGTERM},
11538 {"SIGKILL (Kill)", TS_SIGKILL},
11539 {"SIGQUIT (Quit)", TS_SIGQUIT},
11540 {"SIGHUP (Hangup)", TS_SIGHUP},
11541 {"More signals", TS_SUBMENU},
11542 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
11543 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
11544 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
11545 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
11546 {NULL, TS_EXITMENU}
11548 static const struct telnet_special specials_end[] = {
11549 {NULL, TS_EXITMENU}
11552 struct telnet_special *specials = NULL;
11553 int nspecials = 0, specialsize = 0;
11555 Ssh ssh = (Ssh) handle;
11557 sfree(ssh->specials);
11559 #define ADD_SPECIALS(name) do \
11561 int len = lenof(name); \
11562 if (nspecials + len > specialsize) { \
11563 specialsize = (nspecials + len) * 5 / 4 + 32; \
11564 specials = sresize(specials, specialsize, struct telnet_special); \
11566 memcpy(specials+nspecials, name, len*sizeof(struct telnet_special)); \
11567 nspecials += len; \
11570 if (ssh->version == 1) {
11571 /* Don't bother offering IGNORE if we've decided the remote
11572 * won't cope with it, since we wouldn't bother sending it if
11574 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11575 ADD_SPECIALS(ssh1_ignore_special);
11576 } else if (ssh->version == 2) {
11577 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
11578 ADD_SPECIALS(ssh2_ignore_special);
11579 if (!(ssh->remote_bugs & BUG_SSH2_REKEY) && !ssh->bare_connection)
11580 ADD_SPECIALS(ssh2_rekey_special);
11582 ADD_SPECIALS(ssh2_session_specials);
11584 if (ssh->n_uncert_hostkeys) {
11585 static const struct telnet_special uncert_start[] = {
11587 {"Cache new host key type", TS_SUBMENU},
11589 static const struct telnet_special uncert_end[] = {
11590 {NULL, TS_EXITMENU},
11594 ADD_SPECIALS(uncert_start);
11595 for (i = 0; i < ssh->n_uncert_hostkeys; i++) {
11596 struct telnet_special uncert[1];
11597 const struct ssh_signkey *alg =
11598 hostkey_algs[ssh->uncert_hostkeys[i]].alg;
11599 uncert[0].name = alg->name;
11600 uncert[0].code = TS_LOCALSTART + ssh->uncert_hostkeys[i];
11601 ADD_SPECIALS(uncert);
11603 ADD_SPECIALS(uncert_end);
11605 } /* else we're not ready yet */
11608 ADD_SPECIALS(specials_end);
11610 ssh->specials = specials;
11617 #undef ADD_SPECIALS
11621 * Send special codes. TS_EOF is useful for `plink', so you
11622 * can send an EOF and collect resulting output (e.g. `plink
11625 static void ssh_special(void *handle, Telnet_Special code)
11627 Ssh ssh = (Ssh) handle;
11628 struct Packet *pktout;
11630 if (code == TS_EOF) {
11631 if (ssh->state != SSH_STATE_SESSION) {
11633 * Buffer the EOF in case we are pre-SESSION, so we can
11634 * send it as soon as we reach SESSION.
11636 if (code == TS_EOF)
11637 ssh->eof_needed = TRUE;
11640 if (ssh->version == 1) {
11641 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
11642 } else if (ssh->mainchan) {
11643 sshfwd_write_eof(ssh->mainchan);
11644 ssh->send_ok = 0; /* now stop trying to read from stdin */
11646 logevent("Sent EOF message");
11647 } else if (code == TS_PING || code == TS_NOP) {
11648 if (ssh->state == SSH_STATE_CLOSED
11649 || ssh->state == SSH_STATE_PREPACKET) return;
11650 if (ssh->version == 1) {
11651 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11652 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
11654 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
11655 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
11656 ssh2_pkt_addstring_start(pktout);
11657 ssh2_pkt_send_noqueue(ssh, pktout);
11660 } else if (code == TS_REKEY) {
11661 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11662 ssh->version == 2) {
11663 do_ssh2_transport(ssh, "at user request", -1, NULL);
11665 } else if (code >= TS_LOCALSTART) {
11666 ssh->hostkey = hostkey_algs[code - TS_LOCALSTART].alg;
11667 ssh->cross_certifying = TRUE;
11668 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11669 ssh->version == 2) {
11670 do_ssh2_transport(ssh, "cross-certifying new host key", -1, NULL);
11672 } else if (code == TS_BRK) {
11673 if (ssh->state == SSH_STATE_CLOSED
11674 || ssh->state == SSH_STATE_PREPACKET) return;
11675 if (ssh->version == 1) {
11676 logevent("Unable to send BREAK signal in SSH-1");
11677 } else if (ssh->mainchan) {
11678 pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
11679 ssh2_pkt_adduint32(pktout, 0); /* default break length */
11680 ssh2_pkt_send(ssh, pktout);
11683 /* Is is a POSIX signal? */
11684 const char *signame = NULL;
11685 if (code == TS_SIGABRT) signame = "ABRT";
11686 if (code == TS_SIGALRM) signame = "ALRM";
11687 if (code == TS_SIGFPE) signame = "FPE";
11688 if (code == TS_SIGHUP) signame = "HUP";
11689 if (code == TS_SIGILL) signame = "ILL";
11690 if (code == TS_SIGINT) signame = "INT";
11691 if (code == TS_SIGKILL) signame = "KILL";
11692 if (code == TS_SIGPIPE) signame = "PIPE";
11693 if (code == TS_SIGQUIT) signame = "QUIT";
11694 if (code == TS_SIGSEGV) signame = "SEGV";
11695 if (code == TS_SIGTERM) signame = "TERM";
11696 if (code == TS_SIGUSR1) signame = "USR1";
11697 if (code == TS_SIGUSR2) signame = "USR2";
11698 /* The SSH-2 protocol does in principle support arbitrary named
11699 * signals, including signame@domain, but we don't support those. */
11701 /* It's a signal. */
11702 if (ssh->version == 2 && ssh->mainchan) {
11703 pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
11704 ssh2_pkt_addstring(pktout, signame);
11705 ssh2_pkt_send(ssh, pktout);
11706 logeventf(ssh, "Sent signal SIG%s", signame);
11709 /* Never heard of it. Do nothing */
11714 void *new_sock_channel(void *handle, struct PortForwarding *pf)
11716 Ssh ssh = (Ssh) handle;
11717 struct ssh_channel *c;
11718 c = snew(struct ssh_channel);
11721 ssh2_channel_init(c);
11722 c->halfopen = TRUE;
11723 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
11725 add234(ssh->channels, c);
11729 unsigned ssh_alloc_sharing_channel(Ssh ssh, void *sharing_ctx)
11731 struct ssh_channel *c;
11732 c = snew(struct ssh_channel);
11735 ssh2_channel_init(c);
11736 c->type = CHAN_SHARING;
11737 c->u.sharing.ctx = sharing_ctx;
11738 add234(ssh->channels, c);
11742 void ssh_delete_sharing_channel(Ssh ssh, unsigned localid)
11744 struct ssh_channel *c;
11746 c = find234(ssh->channels, &localid, ssh_channelfind);
11748 ssh_channel_destroy(c);
11751 void ssh_send_packet_from_downstream(Ssh ssh, unsigned id, int type,
11752 const void *data, int datalen,
11753 const char *additional_log_text)
11755 struct Packet *pkt;
11757 pkt = ssh2_pkt_init(type);
11758 pkt->downstream_id = id;
11759 pkt->additional_log_text = additional_log_text;
11760 ssh2_pkt_adddata(pkt, data, datalen);
11761 ssh2_pkt_send(ssh, pkt);
11765 * This is called when stdout/stderr (the entity to which
11766 * from_backend sends data) manages to clear some backlog.
11768 static void ssh_unthrottle(void *handle, int bufsize)
11770 Ssh ssh = (Ssh) handle;
11773 if (ssh->version == 1) {
11774 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
11775 ssh->v1_stdout_throttling = 0;
11776 ssh_throttle_conn(ssh, -1);
11779 if (ssh->mainchan) {
11780 ssh2_set_window(ssh->mainchan,
11781 bufsize < ssh->mainchan->v.v2.locmaxwin ?
11782 ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
11783 if (ssh_is_simple(ssh))
11786 buflimit = ssh->mainchan->v.v2.locmaxwin;
11787 if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
11788 ssh->mainchan->throttling_conn = 0;
11789 ssh_throttle_conn(ssh, -1);
11795 * Now process any SSH connection data that was stashed in our
11796 * queue while we were frozen.
11798 ssh_process_queued_incoming_data(ssh);
11801 void ssh_send_port_open(void *channel, const char *hostname, int port,
11804 struct ssh_channel *c = (struct ssh_channel *)channel;
11806 struct Packet *pktout;
11808 logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
11810 if (ssh->version == 1) {
11811 send_packet(ssh, SSH1_MSG_PORT_OPEN,
11812 PKT_INT, c->localid,
11815 /* PKT_STR, <org:orgport>, */
11818 pktout = ssh2_chanopen_init(c, "direct-tcpip");
11820 char *trimmed_host = host_strduptrim(hostname);
11821 ssh2_pkt_addstring(pktout, trimmed_host);
11822 sfree(trimmed_host);
11824 ssh2_pkt_adduint32(pktout, port);
11826 * We make up values for the originator data; partly it's
11827 * too much hassle to keep track, and partly I'm not
11828 * convinced the server should be told details like that
11829 * about my local network configuration.
11830 * The "originator IP address" is syntactically a numeric
11831 * IP address, and some servers (e.g., Tectia) get upset
11832 * if it doesn't match this syntax.
11834 ssh2_pkt_addstring(pktout, "0.0.0.0");
11835 ssh2_pkt_adduint32(pktout, 0);
11836 ssh2_pkt_send(ssh, pktout);
11840 static int ssh_connected(void *handle)
11842 Ssh ssh = (Ssh) handle;
11843 return ssh->s != NULL;
11846 static int ssh_sendok(void *handle)
11848 Ssh ssh = (Ssh) handle;
11849 return ssh->send_ok;
11852 static int ssh_ldisc(void *handle, int option)
11854 Ssh ssh = (Ssh) handle;
11855 if (option == LD_ECHO)
11856 return ssh->echoing;
11857 if (option == LD_EDIT)
11858 return ssh->editing;
11862 static void ssh_provide_ldisc(void *handle, void *ldisc)
11864 Ssh ssh = (Ssh) handle;
11865 ssh->ldisc = ldisc;
11868 static void ssh_provide_logctx(void *handle, void *logctx)
11870 Ssh ssh = (Ssh) handle;
11871 ssh->logctx = logctx;
11874 static int ssh_return_exitcode(void *handle)
11876 Ssh ssh = (Ssh) handle;
11877 if (ssh->s != NULL)
11880 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
11884 * cfg_info for SSH is the protocol running in this session.
11885 * (1 or 2 for the full SSH-1 or SSH-2 protocol; -1 for the bare
11886 * SSH-2 connection protocol, i.e. a downstream; 0 for not-decided-yet.)
11888 static int ssh_cfg_info(void *handle)
11890 Ssh ssh = (Ssh) handle;
11891 if (ssh->version == 0)
11892 return 0; /* don't know yet */
11893 else if (ssh->bare_connection)
11896 return ssh->version;
11900 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
11901 * that fails. This variable is the means by which scp.c can reach
11902 * into the SSH code and find out which one it got.
11904 extern int ssh_fallback_cmd(void *handle)
11906 Ssh ssh = (Ssh) handle;
11907 return ssh->fallback_cmd;
11910 Backend ssh_backend = {
11920 ssh_return_exitcode,
11924 ssh_provide_logctx,
11927 ssh_test_for_upstream,