29 * Packet type contexts, so that ssh2_pkt_type can correctly decode
30 * the ambiguous type numbers back into the correct type strings.
41 SSH2_PKTCTX_PUBLICKEY,
47 static const char *const ssh2_disconnect_reasons[] = {
49 "host not allowed to connect",
51 "key exchange failed",
52 "host authentication failed",
55 "service not available",
56 "protocol version not supported",
57 "host key not verifiable",
60 "too many connections",
61 "auth cancelled by user",
62 "no more auth methods available",
67 * Various remote-bug flags.
69 #define BUG_CHOKES_ON_SSH1_IGNORE 1
70 #define BUG_SSH2_HMAC 2
71 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
72 #define BUG_CHOKES_ON_RSA 8
73 #define BUG_SSH2_RSA_PADDING 16
74 #define BUG_SSH2_DERIVEKEY 32
75 #define BUG_SSH2_REKEY 64
76 #define BUG_SSH2_PK_SESSIONID 128
77 #define BUG_SSH2_MAXPKT 256
78 #define BUG_CHOKES_ON_SSH2_IGNORE 512
79 #define BUG_CHOKES_ON_WINADJ 1024
80 #define BUG_SENDS_LATE_REQUEST_REPLY 2048
81 #define BUG_SSH2_OLDGEX 4096
83 #define DH_MIN_SIZE 1024
84 #define DH_MAX_SIZE 8192
87 * Codes for terminal modes.
88 * Most of these are the same in SSH-1 and SSH-2.
89 * This list is derived from RFC 4254 and
93 const char* const mode;
95 enum { TTY_OP_CHAR, TTY_OP_BOOL } type;
97 /* "V" prefix discarded for special characters relative to SSH specs */
98 { "INTR", 1, TTY_OP_CHAR },
99 { "QUIT", 2, TTY_OP_CHAR },
100 { "ERASE", 3, TTY_OP_CHAR },
101 { "KILL", 4, TTY_OP_CHAR },
102 { "EOF", 5, TTY_OP_CHAR },
103 { "EOL", 6, TTY_OP_CHAR },
104 { "EOL2", 7, TTY_OP_CHAR },
105 { "START", 8, TTY_OP_CHAR },
106 { "STOP", 9, TTY_OP_CHAR },
107 { "SUSP", 10, TTY_OP_CHAR },
108 { "DSUSP", 11, TTY_OP_CHAR },
109 { "REPRINT", 12, TTY_OP_CHAR },
110 { "WERASE", 13, TTY_OP_CHAR },
111 { "LNEXT", 14, TTY_OP_CHAR },
112 { "FLUSH", 15, TTY_OP_CHAR },
113 { "SWTCH", 16, TTY_OP_CHAR },
114 { "STATUS", 17, TTY_OP_CHAR },
115 { "DISCARD", 18, TTY_OP_CHAR },
116 { "IGNPAR", 30, TTY_OP_BOOL },
117 { "PARMRK", 31, TTY_OP_BOOL },
118 { "INPCK", 32, TTY_OP_BOOL },
119 { "ISTRIP", 33, TTY_OP_BOOL },
120 { "INLCR", 34, TTY_OP_BOOL },
121 { "IGNCR", 35, TTY_OP_BOOL },
122 { "ICRNL", 36, TTY_OP_BOOL },
123 { "IUCLC", 37, TTY_OP_BOOL },
124 { "IXON", 38, TTY_OP_BOOL },
125 { "IXANY", 39, TTY_OP_BOOL },
126 { "IXOFF", 40, TTY_OP_BOOL },
127 { "IMAXBEL", 41, TTY_OP_BOOL },
128 { "ISIG", 50, TTY_OP_BOOL },
129 { "ICANON", 51, TTY_OP_BOOL },
130 { "XCASE", 52, TTY_OP_BOOL },
131 { "ECHO", 53, TTY_OP_BOOL },
132 { "ECHOE", 54, TTY_OP_BOOL },
133 { "ECHOK", 55, TTY_OP_BOOL },
134 { "ECHONL", 56, TTY_OP_BOOL },
135 { "NOFLSH", 57, TTY_OP_BOOL },
136 { "TOSTOP", 58, TTY_OP_BOOL },
137 { "IEXTEN", 59, TTY_OP_BOOL },
138 { "ECHOCTL", 60, TTY_OP_BOOL },
139 { "ECHOKE", 61, TTY_OP_BOOL },
140 { "PENDIN", 62, TTY_OP_BOOL }, /* XXX is this a real mode? */
141 { "OPOST", 70, TTY_OP_BOOL },
142 { "OLCUC", 71, TTY_OP_BOOL },
143 { "ONLCR", 72, TTY_OP_BOOL },
144 { "OCRNL", 73, TTY_OP_BOOL },
145 { "ONOCR", 74, TTY_OP_BOOL },
146 { "ONLRET", 75, TTY_OP_BOOL },
147 { "CS7", 90, TTY_OP_BOOL },
148 { "CS8", 91, TTY_OP_BOOL },
149 { "PARENB", 92, TTY_OP_BOOL },
150 { "PARODD", 93, TTY_OP_BOOL }
153 /* Miscellaneous other tty-related constants. */
154 #define SSH_TTY_OP_END 0
155 /* The opcodes for ISPEED/OSPEED differ between SSH-1 and SSH-2. */
156 #define SSH1_TTY_OP_ISPEED 192
157 #define SSH1_TTY_OP_OSPEED 193
158 #define SSH2_TTY_OP_ISPEED 128
159 #define SSH2_TTY_OP_OSPEED 129
161 /* Helper functions for parsing tty-related config. */
162 static unsigned int ssh_tty_parse_specchar(char *s)
167 ret = ctrlparse(s, &next);
168 if (!next) ret = s[0];
170 ret = 255; /* special value meaning "don't set" */
174 static unsigned int ssh_tty_parse_boolean(char *s)
176 if (stricmp(s, "yes") == 0 ||
177 stricmp(s, "on") == 0 ||
178 stricmp(s, "true") == 0 ||
179 stricmp(s, "+") == 0)
181 else if (stricmp(s, "no") == 0 ||
182 stricmp(s, "off") == 0 ||
183 stricmp(s, "false") == 0 ||
184 stricmp(s, "-") == 0)
185 return 0; /* false */
187 return (atoi(s) != 0);
190 #define translate(x) if (type == x) return #x
191 #define translatek(x,ctx) if (type == x && (pkt_kctx == ctx)) return #x
192 #define translatea(x,ctx) if (type == x && (pkt_actx == ctx)) return #x
193 static const char *ssh1_pkt_type(int type)
195 translate(SSH1_MSG_DISCONNECT);
196 translate(SSH1_SMSG_PUBLIC_KEY);
197 translate(SSH1_CMSG_SESSION_KEY);
198 translate(SSH1_CMSG_USER);
199 translate(SSH1_CMSG_AUTH_RSA);
200 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
201 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
202 translate(SSH1_CMSG_AUTH_PASSWORD);
203 translate(SSH1_CMSG_REQUEST_PTY);
204 translate(SSH1_CMSG_WINDOW_SIZE);
205 translate(SSH1_CMSG_EXEC_SHELL);
206 translate(SSH1_CMSG_EXEC_CMD);
207 translate(SSH1_SMSG_SUCCESS);
208 translate(SSH1_SMSG_FAILURE);
209 translate(SSH1_CMSG_STDIN_DATA);
210 translate(SSH1_SMSG_STDOUT_DATA);
211 translate(SSH1_SMSG_STDERR_DATA);
212 translate(SSH1_CMSG_EOF);
213 translate(SSH1_SMSG_EXIT_STATUS);
214 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
215 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
216 translate(SSH1_MSG_CHANNEL_DATA);
217 translate(SSH1_MSG_CHANNEL_CLOSE);
218 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
219 translate(SSH1_SMSG_X11_OPEN);
220 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
221 translate(SSH1_MSG_PORT_OPEN);
222 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
223 translate(SSH1_SMSG_AGENT_OPEN);
224 translate(SSH1_MSG_IGNORE);
225 translate(SSH1_CMSG_EXIT_CONFIRMATION);
226 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
227 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
228 translate(SSH1_MSG_DEBUG);
229 translate(SSH1_CMSG_REQUEST_COMPRESSION);
230 translate(SSH1_CMSG_AUTH_TIS);
231 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
232 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
233 translate(SSH1_CMSG_AUTH_CCARD);
234 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
235 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
238 static const char *ssh2_pkt_type(Pkt_KCtx pkt_kctx, Pkt_ACtx pkt_actx,
241 translatea(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE,SSH2_PKTCTX_GSSAPI);
242 translatea(SSH2_MSG_USERAUTH_GSSAPI_TOKEN,SSH2_PKTCTX_GSSAPI);
243 translatea(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE,SSH2_PKTCTX_GSSAPI);
244 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERROR,SSH2_PKTCTX_GSSAPI);
245 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK,SSH2_PKTCTX_GSSAPI);
246 translatea(SSH2_MSG_USERAUTH_GSSAPI_MIC, SSH2_PKTCTX_GSSAPI);
247 translate(SSH2_MSG_DISCONNECT);
248 translate(SSH2_MSG_IGNORE);
249 translate(SSH2_MSG_UNIMPLEMENTED);
250 translate(SSH2_MSG_DEBUG);
251 translate(SSH2_MSG_SERVICE_REQUEST);
252 translate(SSH2_MSG_SERVICE_ACCEPT);
253 translate(SSH2_MSG_KEXINIT);
254 translate(SSH2_MSG_NEWKEYS);
255 translatek(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP);
256 translatek(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP);
257 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD, SSH2_PKTCTX_DHGEX);
258 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
259 translatek(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
260 translatek(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
261 translatek(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
262 translatek(SSH2_MSG_KEXRSA_PUBKEY, SSH2_PKTCTX_RSAKEX);
263 translatek(SSH2_MSG_KEXRSA_SECRET, SSH2_PKTCTX_RSAKEX);
264 translatek(SSH2_MSG_KEXRSA_DONE, SSH2_PKTCTX_RSAKEX);
265 translatek(SSH2_MSG_KEX_ECDH_INIT, SSH2_PKTCTX_ECDHKEX);
266 translatek(SSH2_MSG_KEX_ECDH_REPLY, SSH2_PKTCTX_ECDHKEX);
267 translate(SSH2_MSG_USERAUTH_REQUEST);
268 translate(SSH2_MSG_USERAUTH_FAILURE);
269 translate(SSH2_MSG_USERAUTH_SUCCESS);
270 translate(SSH2_MSG_USERAUTH_BANNER);
271 translatea(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
272 translatea(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
273 translatea(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
274 translatea(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
275 translate(SSH2_MSG_GLOBAL_REQUEST);
276 translate(SSH2_MSG_REQUEST_SUCCESS);
277 translate(SSH2_MSG_REQUEST_FAILURE);
278 translate(SSH2_MSG_CHANNEL_OPEN);
279 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
280 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
281 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
282 translate(SSH2_MSG_CHANNEL_DATA);
283 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
284 translate(SSH2_MSG_CHANNEL_EOF);
285 translate(SSH2_MSG_CHANNEL_CLOSE);
286 translate(SSH2_MSG_CHANNEL_REQUEST);
287 translate(SSH2_MSG_CHANNEL_SUCCESS);
288 translate(SSH2_MSG_CHANNEL_FAILURE);
294 /* Enumeration values for fields in SSH-1 packets */
296 PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
300 * Coroutine mechanics for the sillier bits of the code. If these
301 * macros look impenetrable to you, you might find it helpful to
304 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
306 * which explains the theory behind these macros.
308 * In particular, if you are getting `case expression not constant'
309 * errors when building with MS Visual Studio, this is because MS's
310 * Edit and Continue debugging feature causes their compiler to
311 * violate ANSI C. To disable Edit and Continue debugging:
313 * - right-click ssh.c in the FileView
315 * - select the C/C++ tab and the General category
316 * - under `Debug info:', select anything _other_ than `Program
317 * Database for Edit and Continue'.
319 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
320 #define crBeginState crBegin(s->crLine)
321 #define crStateP(t, v) \
323 if (!(v)) { s = (v) = snew(struct t); s->crLine = 0; } \
325 #define crState(t) crStateP(t, ssh->t)
326 #define crFinish(z) } *crLine = 0; return (z); }
327 #define crFinishV } *crLine = 0; return; }
328 #define crFinishFree(z) } sfree(s); return (z); }
329 #define crFinishFreeV } sfree(s); return; }
330 #define crReturn(z) \
332 *crLine =__LINE__; return (z); case __LINE__:;\
336 *crLine=__LINE__; return; case __LINE__:;\
338 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
339 #define crStopV do{ *crLine = 0; return; }while(0)
340 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
341 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
345 static struct Packet *ssh1_pkt_init(int pkt_type);
346 static struct Packet *ssh2_pkt_init(int pkt_type);
347 static void ssh_pkt_ensure(struct Packet *, int length);
348 static void ssh_pkt_adddata(struct Packet *, const void *data, int len);
349 static void ssh_pkt_addbyte(struct Packet *, unsigned char value);
350 static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
351 static void ssh_pkt_adduint32(struct Packet *, unsigned long value);
352 static void ssh_pkt_addstring_start(struct Packet *);
353 static void ssh_pkt_addstring_str(struct Packet *, const char *data);
354 static void ssh_pkt_addstring_data(struct Packet *, const char *data, int len);
355 static void ssh_pkt_addstring(struct Packet *, const char *data);
356 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
357 static void ssh1_pkt_addmp(struct Packet *, Bignum b);
358 static void ssh2_pkt_addmp(struct Packet *, Bignum b);
359 static int ssh2_pkt_construct(Ssh, struct Packet *);
360 static void ssh2_pkt_send(Ssh, struct Packet *);
361 static void ssh2_pkt_send_noqueue(Ssh, struct Packet *);
362 static int do_ssh1_login(Ssh ssh, const unsigned char *in, int inlen,
363 struct Packet *pktin);
364 static void do_ssh2_authconn(Ssh ssh, const unsigned char *in, int inlen,
365 struct Packet *pktin);
366 static void ssh2_channel_check_close(struct ssh_channel *c);
367 static void ssh_channel_destroy(struct ssh_channel *c);
368 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin);
371 * Buffer management constants. There are several of these for
372 * various different purposes:
374 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
375 * on a local data stream before we throttle the whole SSH
376 * connection (in SSH-1 only). Throttling the whole connection is
377 * pretty drastic so we set this high in the hope it won't
380 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
381 * on the SSH connection itself before we defensively throttle
382 * _all_ local data streams. This is pretty drastic too (though
383 * thankfully unlikely in SSH-2 since the window mechanism should
384 * ensure that the server never has any need to throttle its end
385 * of the connection), so we set this high as well.
387 * - OUR_V2_WINSIZE is the 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, char *mode, char *val),
1017 for (val = conf_get_str_strs(ssh->conf, CONF_ttymodes, NULL, &key);
1019 val = conf_get_str_strs(ssh->conf, CONF_ttymodes, key, &key)) {
1021 * val[0] is either 'V', indicating that an explicit value
1022 * follows it, or 'A' indicating that we should pass the
1023 * value through from the local environment via get_ttymode.
1025 if (val[0] == 'A') {
1026 val = get_ttymode(ssh->frontend, key);
1028 do_mode(data, key, val);
1032 do_mode(data, key, val + 1); /* skip the 'V' */
1036 static int ssh_channelcmp(void *av, void *bv)
1038 struct ssh_channel *a = (struct ssh_channel *) av;
1039 struct ssh_channel *b = (struct ssh_channel *) bv;
1040 if (a->localid < b->localid)
1042 if (a->localid > b->localid)
1046 static int ssh_channelfind(void *av, void *bv)
1048 unsigned *a = (unsigned *) av;
1049 struct ssh_channel *b = (struct ssh_channel *) bv;
1050 if (*a < b->localid)
1052 if (*a > b->localid)
1057 static int ssh_rportcmp_ssh1(void *av, void *bv)
1059 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1060 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1062 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
1063 return i < 0 ? -1 : +1;
1064 if (a->dport > b->dport)
1066 if (a->dport < b->dport)
1071 static int ssh_rportcmp_ssh2(void *av, void *bv)
1073 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1074 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1076 if ( (i = strcmp(a->shost, b->shost)) != 0)
1077 return i < 0 ? -1 : +1;
1078 if (a->sport > b->sport)
1080 if (a->sport < b->sport)
1086 * Special form of strcmp which can cope with NULL inputs. NULL is
1087 * defined to sort before even the empty string.
1089 static int nullstrcmp(const char *a, const char *b)
1091 if (a == NULL && b == NULL)
1097 return strcmp(a, b);
1100 static int ssh_portcmp(void *av, void *bv)
1102 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1103 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1105 if (a->type > b->type)
1107 if (a->type < b->type)
1109 if (a->addressfamily > b->addressfamily)
1111 if (a->addressfamily < b->addressfamily)
1113 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1114 return i < 0 ? -1 : +1;
1115 if (a->sport > b->sport)
1117 if (a->sport < b->sport)
1119 if (a->type != 'D') {
1120 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1121 return i < 0 ? -1 : +1;
1122 if (a->dport > b->dport)
1124 if (a->dport < b->dport)
1130 static int alloc_channel_id(Ssh ssh)
1132 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1133 unsigned low, high, mid;
1135 struct ssh_channel *c;
1138 * First-fit allocation of channel numbers: always pick the
1139 * lowest unused one. To do this, binary-search using the
1140 * counted B-tree to find the largest channel ID which is in a
1141 * contiguous sequence from the beginning. (Precisely
1142 * everything in that sequence must have ID equal to its tree
1143 * index plus CHANNEL_NUMBER_OFFSET.)
1145 tsize = count234(ssh->channels);
1149 while (high - low > 1) {
1150 mid = (high + low) / 2;
1151 c = index234(ssh->channels, mid);
1152 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1153 low = mid; /* this one is fine */
1155 high = mid; /* this one is past it */
1158 * Now low points to either -1, or the tree index of the
1159 * largest ID in the initial sequence.
1162 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1163 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1165 return low + 1 + CHANNEL_NUMBER_OFFSET;
1168 static void c_write_stderr(int trusted, const char *buf, int len)
1171 for (i = 0; i < len; i++)
1172 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1173 fputc(buf[i], stderr);
1176 static void c_write(Ssh ssh, const char *buf, int len)
1178 if (flags & FLAG_STDERR)
1179 c_write_stderr(1, buf, len);
1181 from_backend(ssh->frontend, 1, buf, len);
1184 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1186 if (flags & FLAG_STDERR)
1187 c_write_stderr(0, buf, len);
1189 from_backend_untrusted(ssh->frontend, buf, len);
1192 static void c_write_str(Ssh ssh, const char *buf)
1194 c_write(ssh, buf, strlen(buf));
1197 static void ssh_free_packet(struct Packet *pkt)
1202 static struct Packet *ssh_new_packet(void)
1204 struct Packet *pkt = snew(struct Packet);
1206 pkt->body = pkt->data = NULL;
1212 static void ssh1_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1215 struct logblank_t blanks[4];
1221 if (ssh->logomitdata &&
1222 (pkt->type == SSH1_SMSG_STDOUT_DATA ||
1223 pkt->type == SSH1_SMSG_STDERR_DATA ||
1224 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1225 /* "Session data" packets - omit the data string. */
1226 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1227 ssh_pkt_getuint32(pkt); /* skip channel id */
1228 blanks[nblanks].offset = pkt->savedpos + 4;
1229 blanks[nblanks].type = PKTLOG_OMIT;
1230 ssh_pkt_getstring(pkt, &str, &slen);
1232 blanks[nblanks].len = slen;
1236 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1237 ssh1_pkt_type(pkt->type),
1238 pkt->body, pkt->length, nblanks, blanks, NULL,
1242 static void ssh1_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1245 struct logblank_t blanks[4];
1250 * For outgoing packets, pkt->length represents the length of the
1251 * whole packet starting at pkt->data (including some header), and
1252 * pkt->body refers to the point within that where the log-worthy
1253 * payload begins. However, incoming packets expect pkt->length to
1254 * represent only the payload length (that is, it's measured from
1255 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1256 * packet to conform to the incoming-packet semantics, so that we
1257 * can analyse it with the ssh_pkt_get functions.
1259 pkt->length -= (pkt->body - pkt->data);
1262 if (ssh->logomitdata &&
1263 (pkt->type == SSH1_CMSG_STDIN_DATA ||
1264 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1265 /* "Session data" packets - omit the data string. */
1266 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1267 ssh_pkt_getuint32(pkt); /* skip channel id */
1268 blanks[nblanks].offset = pkt->savedpos + 4;
1269 blanks[nblanks].type = PKTLOG_OMIT;
1270 ssh_pkt_getstring(pkt, &str, &slen);
1272 blanks[nblanks].len = slen;
1277 if ((pkt->type == SSH1_CMSG_AUTH_PASSWORD ||
1278 pkt->type == SSH1_CMSG_AUTH_TIS_RESPONSE ||
1279 pkt->type == SSH1_CMSG_AUTH_CCARD_RESPONSE) &&
1280 conf_get_int(ssh->conf, CONF_logomitpass)) {
1281 /* If this is a password or similar packet, blank the password(s). */
1282 blanks[nblanks].offset = 0;
1283 blanks[nblanks].len = pkt->length;
1284 blanks[nblanks].type = PKTLOG_BLANK;
1286 } else if (pkt->type == SSH1_CMSG_X11_REQUEST_FORWARDING &&
1287 conf_get_int(ssh->conf, CONF_logomitpass)) {
1289 * If this is an X forwarding request packet, blank the fake
1292 * Note that while we blank the X authentication data here, we
1293 * don't take any special action to blank the start of an X11
1294 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1295 * an X connection without having session blanking enabled is
1296 * likely to leak your cookie into the log.
1299 ssh_pkt_getstring(pkt, &str, &slen);
1300 blanks[nblanks].offset = pkt->savedpos;
1301 blanks[nblanks].type = PKTLOG_BLANK;
1302 ssh_pkt_getstring(pkt, &str, &slen);
1304 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1309 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1310 ssh1_pkt_type(pkt->data[12]),
1311 pkt->body, pkt->length,
1312 nblanks, blanks, NULL, 0, NULL);
1315 * Undo the above adjustment of pkt->length, to put the packet
1316 * back in the state we found it.
1318 pkt->length += (pkt->body - pkt->data);
1322 * Collect incoming data in the incoming packet buffer.
1323 * Decipher and verify the packet when it is completely read.
1324 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1325 * Update the *data and *datalen variables.
1326 * Return a Packet structure when a packet is completed.
1328 static struct Packet *ssh1_rdpkt(Ssh ssh, const unsigned char **data,
1331 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1333 crBegin(ssh->ssh1_rdpkt_crstate);
1335 st->pktin = ssh_new_packet();
1337 st->pktin->type = 0;
1338 st->pktin->length = 0;
1340 for (st->i = st->len = 0; st->i < 4; st->i++) {
1341 while ((*datalen) == 0)
1343 st->len = (st->len << 8) + **data;
1344 (*data)++, (*datalen)--;
1347 st->pad = 8 - (st->len % 8);
1348 st->biglen = st->len + st->pad;
1349 st->pktin->length = st->len - 5;
1351 if (st->biglen < 0) {
1352 bombout(("Extremely large packet length from server suggests"
1353 " data stream corruption"));
1354 ssh_free_packet(st->pktin);
1358 st->pktin->maxlen = st->biglen;
1359 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1361 st->to_read = st->biglen;
1362 st->p = st->pktin->data;
1363 while (st->to_read > 0) {
1364 st->chunk = st->to_read;
1365 while ((*datalen) == 0)
1367 if (st->chunk > (*datalen))
1368 st->chunk = (*datalen);
1369 memcpy(st->p, *data, st->chunk);
1371 *datalen -= st->chunk;
1373 st->to_read -= st->chunk;
1376 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1377 st->biglen, NULL)) {
1378 bombout(("Network attack (CRC compensation) detected!"));
1379 ssh_free_packet(st->pktin);
1384 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1386 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1387 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1388 if (st->gotcrc != st->realcrc) {
1389 bombout(("Incorrect CRC received on packet"));
1390 ssh_free_packet(st->pktin);
1394 st->pktin->body = st->pktin->data + st->pad + 1;
1396 if (ssh->v1_compressing) {
1397 unsigned char *decompblk;
1399 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1400 st->pktin->body - 1, st->pktin->length + 1,
1401 &decompblk, &decomplen)) {
1402 bombout(("Zlib decompression encountered invalid data"));
1403 ssh_free_packet(st->pktin);
1407 if (st->pktin->maxlen < st->pad + decomplen) {
1408 st->pktin->maxlen = st->pad + decomplen;
1409 st->pktin->data = sresize(st->pktin->data,
1410 st->pktin->maxlen + APIEXTRA,
1412 st->pktin->body = st->pktin->data + st->pad + 1;
1415 memcpy(st->pktin->body - 1, decompblk, decomplen);
1417 st->pktin->length = decomplen - 1;
1420 st->pktin->type = st->pktin->body[-1];
1423 * Now pktin->body and pktin->length identify the semantic content
1424 * of the packet, excluding the initial type byte.
1428 ssh1_log_incoming_packet(ssh, st->pktin);
1430 st->pktin->savedpos = 0;
1432 crFinish(st->pktin);
1435 static void ssh2_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1438 struct logblank_t blanks[4];
1444 if (ssh->logomitdata &&
1445 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1446 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1447 /* "Session data" packets - omit the data string. */
1448 ssh_pkt_getuint32(pkt); /* skip channel id */
1449 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1450 ssh_pkt_getuint32(pkt); /* skip extended data type */
1451 blanks[nblanks].offset = pkt->savedpos + 4;
1452 blanks[nblanks].type = PKTLOG_OMIT;
1453 ssh_pkt_getstring(pkt, &str, &slen);
1455 blanks[nblanks].len = slen;
1460 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1461 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->type),
1462 pkt->body, pkt->length, nblanks, blanks, &pkt->sequence,
1466 static void ssh2_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1469 struct logblank_t blanks[4];
1474 * For outgoing packets, pkt->length represents the length of the
1475 * whole packet starting at pkt->data (including some header), and
1476 * pkt->body refers to the point within that where the log-worthy
1477 * payload begins. However, incoming packets expect pkt->length to
1478 * represent only the payload length (that is, it's measured from
1479 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1480 * packet to conform to the incoming-packet semantics, so that we
1481 * can analyse it with the ssh_pkt_get functions.
1483 pkt->length -= (pkt->body - pkt->data);
1486 if (ssh->logomitdata &&
1487 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1488 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1489 /* "Session data" packets - omit the data string. */
1490 ssh_pkt_getuint32(pkt); /* skip channel id */
1491 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1492 ssh_pkt_getuint32(pkt); /* skip extended data type */
1493 blanks[nblanks].offset = pkt->savedpos + 4;
1494 blanks[nblanks].type = PKTLOG_OMIT;
1495 ssh_pkt_getstring(pkt, &str, &slen);
1497 blanks[nblanks].len = slen;
1502 if (pkt->type == SSH2_MSG_USERAUTH_REQUEST &&
1503 conf_get_int(ssh->conf, CONF_logomitpass)) {
1504 /* If this is a password packet, blank the password(s). */
1506 ssh_pkt_getstring(pkt, &str, &slen);
1507 ssh_pkt_getstring(pkt, &str, &slen);
1508 ssh_pkt_getstring(pkt, &str, &slen);
1509 if (slen == 8 && !memcmp(str, "password", 8)) {
1510 ssh2_pkt_getbool(pkt);
1511 /* Blank the password field. */
1512 blanks[nblanks].offset = pkt->savedpos;
1513 blanks[nblanks].type = PKTLOG_BLANK;
1514 ssh_pkt_getstring(pkt, &str, &slen);
1516 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1518 /* If there's another password field beyond it (change of
1519 * password), blank that too. */
1520 ssh_pkt_getstring(pkt, &str, &slen);
1522 blanks[nblanks-1].len =
1523 pkt->savedpos - blanks[nblanks].offset;
1526 } else if (ssh->pkt_actx == SSH2_PKTCTX_KBDINTER &&
1527 pkt->type == SSH2_MSG_USERAUTH_INFO_RESPONSE &&
1528 conf_get_int(ssh->conf, CONF_logomitpass)) {
1529 /* If this is a keyboard-interactive response packet, blank
1532 ssh_pkt_getuint32(pkt);
1533 blanks[nblanks].offset = pkt->savedpos;
1534 blanks[nblanks].type = PKTLOG_BLANK;
1536 ssh_pkt_getstring(pkt, &str, &slen);
1540 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1542 } else if (pkt->type == SSH2_MSG_CHANNEL_REQUEST &&
1543 conf_get_int(ssh->conf, CONF_logomitpass)) {
1545 * If this is an X forwarding request packet, blank the fake
1548 * Note that while we blank the X authentication data here, we
1549 * don't take any special action to blank the start of an X11
1550 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1551 * an X connection without having session blanking enabled is
1552 * likely to leak your cookie into the log.
1555 ssh_pkt_getuint32(pkt);
1556 ssh_pkt_getstring(pkt, &str, &slen);
1557 if (slen == 7 && !memcmp(str, "x11-req", 0)) {
1558 ssh2_pkt_getbool(pkt);
1559 ssh2_pkt_getbool(pkt);
1560 ssh_pkt_getstring(pkt, &str, &slen);
1561 blanks[nblanks].offset = pkt->savedpos;
1562 blanks[nblanks].type = PKTLOG_BLANK;
1563 ssh_pkt_getstring(pkt, &str, &slen);
1565 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1571 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1572 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1573 pkt->body, pkt->length, nblanks, blanks,
1574 &ssh->v2_outgoing_sequence,
1575 pkt->downstream_id, pkt->additional_log_text);
1578 * Undo the above adjustment of pkt->length, to put the packet
1579 * back in the state we found it.
1581 pkt->length += (pkt->body - pkt->data);
1584 static struct Packet *ssh2_rdpkt(Ssh ssh, const unsigned char **data,
1587 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1589 crBegin(ssh->ssh2_rdpkt_crstate);
1591 st->pktin = ssh_new_packet();
1593 st->pktin->type = 0;
1594 st->pktin->length = 0;
1596 st->cipherblk = ssh->sccipher->blksize;
1599 if (st->cipherblk < 8)
1601 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1603 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1604 ssh->scmac && !ssh->scmac_etm) {
1606 * When dealing with a CBC-mode cipher, we want to avoid the
1607 * possibility of an attacker's tweaking the ciphertext stream
1608 * so as to cause us to feed the same block to the block
1609 * cipher more than once and thus leak information
1610 * (VU#958563). The way we do this is not to take any
1611 * decisions on the basis of anything we've decrypted until
1612 * we've verified it with a MAC. That includes the packet
1613 * length, so we just read data and check the MAC repeatedly,
1614 * and when the MAC passes, see if the length we've got is
1617 * This defence is unnecessary in OpenSSH ETM mode, because
1618 * the whole point of ETM mode is that the attacker can't
1619 * tweak the ciphertext stream at all without the MAC
1620 * detecting it before we decrypt anything.
1623 /* May as well allocate the whole lot now. */
1624 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1627 /* Read an amount corresponding to the MAC. */
1628 for (st->i = 0; st->i < st->maclen; st->i++) {
1629 while ((*datalen) == 0)
1631 st->pktin->data[st->i] = *(*data)++;
1637 unsigned char seq[4];
1638 ssh->scmac->start(ssh->sc_mac_ctx);
1639 PUT_32BIT(seq, st->incoming_sequence);
1640 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1643 for (;;) { /* Once around this loop per cipher block. */
1644 /* Read another cipher-block's worth, and tack it onto the end. */
1645 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1646 while ((*datalen) == 0)
1648 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1651 /* Decrypt one more block (a little further back in the stream). */
1652 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1653 st->pktin->data + st->packetlen,
1655 /* Feed that block to the MAC. */
1656 ssh->scmac->bytes(ssh->sc_mac_ctx,
1657 st->pktin->data + st->packetlen, st->cipherblk);
1658 st->packetlen += st->cipherblk;
1659 /* See if that gives us a valid packet. */
1660 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1661 st->pktin->data + st->packetlen) &&
1662 ((st->len = toint(GET_32BIT(st->pktin->data))) ==
1665 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1666 bombout(("No valid incoming packet found"));
1667 ssh_free_packet(st->pktin);
1671 st->pktin->maxlen = st->packetlen + st->maclen;
1672 st->pktin->data = sresize(st->pktin->data,
1673 st->pktin->maxlen + APIEXTRA,
1675 } else if (ssh->scmac && ssh->scmac_etm) {
1676 st->pktin->data = snewn(4 + APIEXTRA, unsigned char);
1679 * OpenSSH encrypt-then-MAC mode: the packet length is
1680 * unencrypted, unless the cipher supports length encryption.
1682 for (st->i = st->len = 0; st->i < 4; st->i++) {
1683 while ((*datalen) == 0)
1685 st->pktin->data[st->i] = *(*data)++;
1688 /* Cipher supports length decryption, so do it */
1689 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_SEPARATE_LENGTH)) {
1690 /* Keep the packet the same though, so the MAC passes */
1691 unsigned char len[4];
1692 memcpy(len, st->pktin->data, 4);
1693 ssh->sccipher->decrypt_length(ssh->sc_cipher_ctx, len, 4, st->incoming_sequence);
1694 st->len = toint(GET_32BIT(len));
1696 st->len = toint(GET_32BIT(st->pktin->data));
1700 * _Completely_ silly lengths should be stomped on before they
1701 * do us any more damage.
1703 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1704 st->len % st->cipherblk != 0) {
1705 bombout(("Incoming packet length field was garbled"));
1706 ssh_free_packet(st->pktin);
1711 * So now we can work out the total packet length.
1713 st->packetlen = st->len + 4;
1716 * Allocate memory for the rest of the packet.
1718 st->pktin->maxlen = st->packetlen + st->maclen;
1719 st->pktin->data = sresize(st->pktin->data,
1720 st->pktin->maxlen + APIEXTRA,
1724 * Read the remainder of the packet.
1726 for (st->i = 4; st->i < st->packetlen + st->maclen; st->i++) {
1727 while ((*datalen) == 0)
1729 st->pktin->data[st->i] = *(*data)++;
1737 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1738 st->len + 4, st->incoming_sequence)) {
1739 bombout(("Incorrect MAC received on packet"));
1740 ssh_free_packet(st->pktin);
1744 /* Decrypt everything between the length field and the MAC. */
1746 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1747 st->pktin->data + 4,
1750 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1753 * Acquire and decrypt the first block of the packet. This will
1754 * contain the length and padding details.
1756 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1757 while ((*datalen) == 0)
1759 st->pktin->data[st->i] = *(*data)++;
1764 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1765 st->pktin->data, st->cipherblk);
1768 * Now get the length figure.
1770 st->len = toint(GET_32BIT(st->pktin->data));
1773 * _Completely_ silly lengths should be stomped on before they
1774 * do us any more damage.
1776 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1777 (st->len + 4) % st->cipherblk != 0) {
1778 bombout(("Incoming packet was garbled on decryption"));
1779 ssh_free_packet(st->pktin);
1784 * So now we can work out the total packet length.
1786 st->packetlen = st->len + 4;
1789 * Allocate memory for the rest of the packet.
1791 st->pktin->maxlen = st->packetlen + st->maclen;
1792 st->pktin->data = sresize(st->pktin->data,
1793 st->pktin->maxlen + APIEXTRA,
1797 * Read and decrypt the remainder of the packet.
1799 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1801 while ((*datalen) == 0)
1803 st->pktin->data[st->i] = *(*data)++;
1806 /* Decrypt everything _except_ the MAC. */
1808 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1809 st->pktin->data + st->cipherblk,
1810 st->packetlen - st->cipherblk);
1816 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1817 st->len + 4, st->incoming_sequence)) {
1818 bombout(("Incorrect MAC received on packet"));
1819 ssh_free_packet(st->pktin);
1823 /* Get and sanity-check the amount of random padding. */
1824 st->pad = st->pktin->data[4];
1825 if (st->pad < 4 || st->len - st->pad < 1) {
1826 bombout(("Invalid padding length on received packet"));
1827 ssh_free_packet(st->pktin);
1831 * This enables us to deduce the payload length.
1833 st->payload = st->len - st->pad - 1;
1835 st->pktin->length = st->payload + 5;
1836 st->pktin->encrypted_len = st->packetlen;
1838 st->pktin->sequence = st->incoming_sequence++;
1840 st->pktin->length = st->packetlen - st->pad;
1841 assert(st->pktin->length >= 0);
1844 * Decompress packet payload.
1847 unsigned char *newpayload;
1850 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1851 st->pktin->data + 5, st->pktin->length - 5,
1852 &newpayload, &newlen)) {
1853 if (st->pktin->maxlen < newlen + 5) {
1854 st->pktin->maxlen = newlen + 5;
1855 st->pktin->data = sresize(st->pktin->data,
1856 st->pktin->maxlen + APIEXTRA,
1859 st->pktin->length = 5 + newlen;
1860 memcpy(st->pktin->data + 5, newpayload, newlen);
1866 * RFC 4253 doesn't explicitly say that completely empty packets
1867 * with no type byte are forbidden, so treat them as deserving
1868 * an SSH_MSG_UNIMPLEMENTED.
1870 if (st->pktin->length <= 5) { /* == 5 we hope, but robustness */
1871 ssh2_msg_something_unimplemented(ssh, st->pktin);
1875 * pktin->body and pktin->length should identify the semantic
1876 * content of the packet, excluding the initial type byte.
1878 st->pktin->type = st->pktin->data[5];
1879 st->pktin->body = st->pktin->data + 6;
1880 st->pktin->length -= 6;
1881 assert(st->pktin->length >= 0); /* one last double-check */
1884 ssh2_log_incoming_packet(ssh, st->pktin);
1886 st->pktin->savedpos = 0;
1888 crFinish(st->pktin);
1891 static struct Packet *ssh2_bare_connection_rdpkt(Ssh ssh,
1892 const unsigned char **data,
1895 struct rdpkt2_bare_state_tag *st = &ssh->rdpkt2_bare_state;
1897 crBegin(ssh->ssh2_bare_rdpkt_crstate);
1900 * Read the packet length field.
1902 for (st->i = 0; st->i < 4; st->i++) {
1903 while ((*datalen) == 0)
1905 st->length[st->i] = *(*data)++;
1909 st->packetlen = toint(GET_32BIT_MSB_FIRST(st->length));
1910 if (st->packetlen <= 0 || st->packetlen >= OUR_V2_PACKETLIMIT) {
1911 bombout(("Invalid packet length received"));
1915 st->pktin = ssh_new_packet();
1916 st->pktin->data = snewn(st->packetlen, unsigned char);
1918 st->pktin->encrypted_len = st->packetlen;
1920 st->pktin->sequence = st->incoming_sequence++;
1923 * Read the remainder of the packet.
1925 for (st->i = 0; st->i < st->packetlen; st->i++) {
1926 while ((*datalen) == 0)
1928 st->pktin->data[st->i] = *(*data)++;
1933 * pktin->body and pktin->length should identify the semantic
1934 * content of the packet, excluding the initial type byte.
1936 st->pktin->type = st->pktin->data[0];
1937 st->pktin->body = st->pktin->data + 1;
1938 st->pktin->length = st->packetlen - 1;
1941 * Log incoming packet, possibly omitting sensitive fields.
1944 ssh2_log_incoming_packet(ssh, st->pktin);
1946 st->pktin->savedpos = 0;
1948 crFinish(st->pktin);
1951 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1953 int pad, biglen, i, pktoffs;
1957 * XXX various versions of SC (including 8.8.4) screw up the
1958 * register allocation in this function and use the same register
1959 * (D6) for len and as a temporary, with predictable results. The
1960 * following sledgehammer prevents this.
1967 ssh1_log_outgoing_packet(ssh, pkt);
1969 if (ssh->v1_compressing) {
1970 unsigned char *compblk;
1972 zlib_compress_block(ssh->cs_comp_ctx,
1973 pkt->data + 12, pkt->length - 12,
1974 &compblk, &complen);
1975 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1976 memcpy(pkt->data + 12, compblk, complen);
1978 pkt->length = complen + 12;
1981 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1983 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1984 pad = 8 - (len % 8);
1986 biglen = len + pad; /* len(padding+type+data+CRC) */
1988 for (i = pktoffs; i < 4+8; i++)
1989 pkt->data[i] = random_byte();
1990 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
1991 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
1992 PUT_32BIT(pkt->data + pktoffs, len);
1995 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
1996 pkt->data + pktoffs + 4, biglen);
1998 if (offset_p) *offset_p = pktoffs;
1999 return biglen + 4; /* len(length+padding+type+data+CRC) */
2002 static int s_write(Ssh ssh, void *data, int len)
2005 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
2006 0, NULL, NULL, 0, NULL);
2009 return sk_write(ssh->s, (char *)data, len);
2012 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
2014 int len, backlog, offset;
2015 len = s_wrpkt_prepare(ssh, pkt, &offset);
2016 backlog = s_write(ssh, pkt->data + offset, len);
2017 if (backlog > SSH_MAX_BACKLOG)
2018 ssh_throttle_all(ssh, 1, backlog);
2019 ssh_free_packet(pkt);
2022 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
2025 len = s_wrpkt_prepare(ssh, pkt, &offset);
2026 if (ssh->deferred_len + len > ssh->deferred_size) {
2027 ssh->deferred_size = ssh->deferred_len + len + 128;
2028 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2032 memcpy(ssh->deferred_send_data + ssh->deferred_len,
2033 pkt->data + offset, len);
2034 ssh->deferred_len += len;
2035 ssh_free_packet(pkt);
2039 * Construct a SSH-1 packet with the specified contents.
2040 * (This all-at-once interface used to be the only one, but now SSH-1
2041 * packets can also be constructed incrementally.)
2043 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
2049 pkt = ssh1_pkt_init(pkttype);
2051 while ((argtype = va_arg(ap, int)) != PKT_END) {
2052 unsigned char *argp, argchar;
2054 unsigned long argint;
2057 /* Actual fields in the packet */
2059 argint = va_arg(ap, int);
2060 ssh_pkt_adduint32(pkt, argint);
2063 argchar = (unsigned char) va_arg(ap, int);
2064 ssh_pkt_addbyte(pkt, argchar);
2067 argp = va_arg(ap, unsigned char *);
2068 arglen = va_arg(ap, int);
2069 ssh_pkt_adddata(pkt, argp, arglen);
2072 sargp = va_arg(ap, char *);
2073 ssh_pkt_addstring(pkt, sargp);
2076 bn = va_arg(ap, Bignum);
2077 ssh1_pkt_addmp(pkt, bn);
2085 static void send_packet(Ssh ssh, int pkttype, ...)
2089 va_start(ap, pkttype);
2090 pkt = construct_packet(ssh, pkttype, ap);
2095 static void defer_packet(Ssh ssh, int pkttype, ...)
2099 va_start(ap, pkttype);
2100 pkt = construct_packet(ssh, pkttype, ap);
2102 s_wrpkt_defer(ssh, pkt);
2105 static int ssh_versioncmp(const char *a, const char *b)
2108 unsigned long av, bv;
2110 av = strtoul(a, &ae, 10);
2111 bv = strtoul(b, &be, 10);
2113 return (av < bv ? -1 : +1);
2118 av = strtoul(ae, &ae, 10);
2119 bv = strtoul(be, &be, 10);
2121 return (av < bv ? -1 : +1);
2126 * Utility routines for putting an SSH-protocol `string' and
2127 * `uint32' into a hash state.
2129 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
2131 unsigned char lenblk[4];
2132 PUT_32BIT(lenblk, len);
2133 h->bytes(s, lenblk, 4);
2134 h->bytes(s, str, len);
2137 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
2139 unsigned char intblk[4];
2140 PUT_32BIT(intblk, i);
2141 h->bytes(s, intblk, 4);
2145 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
2147 static void ssh_pkt_ensure(struct Packet *pkt, int length)
2149 if (pkt->maxlen < length) {
2150 unsigned char *body = pkt->body;
2151 int offset = body ? body - pkt->data : 0;
2152 pkt->maxlen = length + 256;
2153 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
2154 if (body) pkt->body = pkt->data + offset;
2157 static void ssh_pkt_adddata(struct Packet *pkt, const void *data, int len)
2160 ssh_pkt_ensure(pkt, pkt->length);
2161 memcpy(pkt->data + pkt->length - len, data, len);
2163 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
2165 ssh_pkt_adddata(pkt, &byte, 1);
2167 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
2169 ssh_pkt_adddata(pkt, &value, 1);
2171 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
2174 PUT_32BIT(x, value);
2175 ssh_pkt_adddata(pkt, x, 4);
2177 static void ssh_pkt_addstring_start(struct Packet *pkt)
2179 ssh_pkt_adduint32(pkt, 0);
2180 pkt->savedpos = pkt->length;
2182 static void ssh_pkt_addstring_data(struct Packet *pkt, const char *data,
2185 ssh_pkt_adddata(pkt, data, len);
2186 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
2188 static void ssh_pkt_addstring_str(struct Packet *pkt, const char *data)
2190 ssh_pkt_addstring_data(pkt, data, strlen(data));
2192 static void ssh_pkt_addstring(struct Packet *pkt, const char *data)
2194 ssh_pkt_addstring_start(pkt);
2195 ssh_pkt_addstring_str(pkt, data);
2197 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
2199 int len = ssh1_bignum_length(b);
2200 unsigned char *data = snewn(len, unsigned char);
2201 (void) ssh1_write_bignum(data, b);
2202 ssh_pkt_adddata(pkt, data, len);
2205 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
2208 int i, n = (bignum_bitcount(b) + 7) / 8;
2209 p = snewn(n + 1, unsigned char);
2211 for (i = 1; i <= n; i++)
2212 p[i] = bignum_byte(b, n - i);
2214 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
2216 memmove(p, p + i, n + 1 - i);
2220 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
2224 p = ssh2_mpint_fmt(b, &len);
2225 ssh_pkt_addstring_start(pkt);
2226 ssh_pkt_addstring_data(pkt, (char *)p, len);
2230 static struct Packet *ssh1_pkt_init(int pkt_type)
2232 struct Packet *pkt = ssh_new_packet();
2233 pkt->length = 4 + 8; /* space for length + max padding */
2234 ssh_pkt_addbyte(pkt, pkt_type);
2235 pkt->body = pkt->data + pkt->length;
2236 pkt->type = pkt_type;
2237 pkt->downstream_id = 0;
2238 pkt->additional_log_text = NULL;
2242 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
2243 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
2244 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
2245 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
2246 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
2247 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
2248 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
2249 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
2250 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
2252 static struct Packet *ssh2_pkt_init(int pkt_type)
2254 struct Packet *pkt = ssh_new_packet();
2255 pkt->length = 5; /* space for packet length + padding length */
2257 pkt->type = pkt_type;
2258 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
2259 pkt->body = pkt->data + pkt->length; /* after packet type */
2260 pkt->downstream_id = 0;
2261 pkt->additional_log_text = NULL;
2266 * Construct an SSH-2 final-form packet: compress it, encrypt it,
2267 * put the MAC on it. Final packet, ready to be sent, is stored in
2268 * pkt->data. Total length is returned.
2270 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
2272 int cipherblk, maclen, padding, unencrypted_prefix, i;
2275 ssh2_log_outgoing_packet(ssh, pkt);
2277 if (ssh->bare_connection) {
2279 * Trivial packet construction for the bare connection
2282 PUT_32BIT(pkt->data + 1, pkt->length - 5);
2283 pkt->body = pkt->data + 1;
2284 ssh->v2_outgoing_sequence++; /* only for diagnostics, really */
2285 return pkt->length - 1;
2289 * Compress packet payload.
2292 unsigned char *newpayload;
2295 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
2297 &newpayload, &newlen)) {
2299 ssh2_pkt_adddata(pkt, newpayload, newlen);
2305 * Add padding. At least four bytes, and must also bring total
2306 * length (minus MAC) up to a multiple of the block size.
2307 * If pkt->forcepad is set, make sure the packet is at least that size
2310 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
2311 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
2313 unencrypted_prefix = (ssh->csmac && ssh->csmac_etm) ? 4 : 0;
2314 if (pkt->length + padding < pkt->forcepad)
2315 padding = pkt->forcepad - pkt->length;
2317 (cipherblk - (pkt->length - unencrypted_prefix + padding) % cipherblk)
2319 assert(padding <= 255);
2320 maclen = ssh->csmac ? ssh->csmac->len : 0;
2321 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
2322 pkt->data[4] = padding;
2323 for (i = 0; i < padding; i++)
2324 pkt->data[pkt->length + i] = random_byte();
2325 PUT_32BIT(pkt->data, pkt->length + padding - 4);
2327 /* Encrypt length if the scheme requires it */
2328 if (ssh->cscipher && (ssh->cscipher->flags & SSH_CIPHER_SEPARATE_LENGTH)) {
2329 ssh->cscipher->encrypt_length(ssh->cs_cipher_ctx, pkt->data, 4,
2330 ssh->v2_outgoing_sequence);
2333 if (ssh->csmac && ssh->csmac_etm) {
2335 * OpenSSH-defined encrypt-then-MAC protocol.
2338 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2339 pkt->data + 4, pkt->length + padding - 4);
2340 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2341 pkt->length + padding,
2342 ssh->v2_outgoing_sequence);
2345 * SSH-2 standard protocol.
2348 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2349 pkt->length + padding,
2350 ssh->v2_outgoing_sequence);
2352 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2353 pkt->data, pkt->length + padding);
2356 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
2357 pkt->encrypted_len = pkt->length + padding;
2359 /* Ready-to-send packet starts at pkt->data. We return length. */
2360 pkt->body = pkt->data;
2361 return pkt->length + padding + maclen;
2365 * Routines called from the main SSH code to send packets. There
2366 * are quite a few of these, because we have two separate
2367 * mechanisms for delaying the sending of packets:
2369 * - In order to send an IGNORE message and a password message in
2370 * a single fixed-length blob, we require the ability to
2371 * concatenate the encrypted forms of those two packets _into_ a
2372 * single blob and then pass it to our <network.h> transport
2373 * layer in one go. Hence, there's a deferment mechanism which
2374 * works after packet encryption.
2376 * - In order to avoid sending any connection-layer messages
2377 * during repeat key exchange, we have to queue up any such
2378 * outgoing messages _before_ they are encrypted (and in
2379 * particular before they're allocated sequence numbers), and
2380 * then send them once we've finished.
2382 * I call these mechanisms `defer' and `queue' respectively, so as
2383 * to distinguish them reasonably easily.
2385 * The functions send_noqueue() and defer_noqueue() free the packet
2386 * structure they are passed. Every outgoing packet goes through
2387 * precisely one of these functions in its life; packets passed to
2388 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
2389 * these or get queued, and then when the queue is later emptied
2390 * the packets are all passed to defer_noqueue().
2392 * When using a CBC-mode cipher, it's necessary to ensure that an
2393 * attacker can't provide data to be encrypted using an IV that they
2394 * know. We ensure this by prefixing each packet that might contain
2395 * user data with an SSH_MSG_IGNORE. This is done using the deferral
2396 * mechanism, so in this case send_noqueue() ends up redirecting to
2397 * defer_noqueue(). If you don't like this inefficiency, don't use
2401 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
2402 static void ssh_pkt_defersend(Ssh);
2405 * Send an SSH-2 packet immediately, without queuing or deferring.
2407 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
2411 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
2412 /* We need to send two packets, so use the deferral mechanism. */
2413 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2414 ssh_pkt_defersend(ssh);
2417 len = ssh2_pkt_construct(ssh, pkt);
2418 backlog = s_write(ssh, pkt->body, len);
2419 if (backlog > SSH_MAX_BACKLOG)
2420 ssh_throttle_all(ssh, 1, backlog);
2422 ssh->outgoing_data_size += pkt->encrypted_len;
2423 if (!ssh->kex_in_progress &&
2424 !ssh->bare_connection &&
2425 ssh->max_data_size != 0 &&
2426 ssh->outgoing_data_size > ssh->max_data_size)
2427 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2429 ssh_free_packet(pkt);
2433 * Defer an SSH-2 packet.
2435 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2438 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2439 ssh->deferred_len == 0 && !noignore &&
2440 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2442 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2443 * get encrypted with a known IV.
2445 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2446 ssh2_pkt_addstring_start(ipkt);
2447 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2449 len = ssh2_pkt_construct(ssh, pkt);
2450 if (ssh->deferred_len + len > ssh->deferred_size) {
2451 ssh->deferred_size = ssh->deferred_len + len + 128;
2452 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2456 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->body, len);
2457 ssh->deferred_len += len;
2458 ssh->deferred_data_size += pkt->encrypted_len;
2459 ssh_free_packet(pkt);
2463 * Queue an SSH-2 packet.
2465 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2467 assert(ssh->queueing);
2469 if (ssh->queuelen >= ssh->queuesize) {
2470 ssh->queuesize = ssh->queuelen + 32;
2471 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2474 ssh->queue[ssh->queuelen++] = pkt;
2478 * Either queue or send a packet, depending on whether queueing is
2481 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2484 ssh2_pkt_queue(ssh, pkt);
2486 ssh2_pkt_send_noqueue(ssh, pkt);
2490 * Either queue or defer a packet, depending on whether queueing is
2493 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2496 ssh2_pkt_queue(ssh, pkt);
2498 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2502 * Send the whole deferred data block constructed by
2503 * ssh2_pkt_defer() or SSH-1's defer_packet().
2505 * The expected use of the defer mechanism is that you call
2506 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2507 * not currently queueing, this simply sets up deferred_send_data
2508 * and then sends it. If we _are_ currently queueing, the calls to
2509 * ssh2_pkt_defer() put the deferred packets on to the queue
2510 * instead, and therefore ssh_pkt_defersend() has no deferred data
2511 * to send. Hence, there's no need to make it conditional on
2514 static void ssh_pkt_defersend(Ssh ssh)
2517 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2518 ssh->deferred_len = ssh->deferred_size = 0;
2519 sfree(ssh->deferred_send_data);
2520 ssh->deferred_send_data = NULL;
2521 if (backlog > SSH_MAX_BACKLOG)
2522 ssh_throttle_all(ssh, 1, backlog);
2524 if (ssh->version == 2) {
2525 ssh->outgoing_data_size += ssh->deferred_data_size;
2526 ssh->deferred_data_size = 0;
2527 if (!ssh->kex_in_progress &&
2528 !ssh->bare_connection &&
2529 ssh->max_data_size != 0 &&
2530 ssh->outgoing_data_size > ssh->max_data_size)
2531 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2536 * Send a packet whose length needs to be disguised (typically
2537 * passwords or keyboard-interactive responses).
2539 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2545 * The simplest way to do this is to adjust the
2546 * variable-length padding field in the outgoing packet.
2548 * Currently compiled out, because some Cisco SSH servers
2549 * don't like excessively padded packets (bah, why's it
2552 pkt->forcepad = padsize;
2553 ssh2_pkt_send(ssh, pkt);
2558 * If we can't do that, however, an alternative approach is
2559 * to use the pkt_defer mechanism to bundle the packet
2560 * tightly together with an SSH_MSG_IGNORE such that their
2561 * combined length is a constant. So first we construct the
2562 * final form of this packet and defer its sending.
2564 ssh2_pkt_defer(ssh, pkt);
2567 * Now construct an SSH_MSG_IGNORE which includes a string
2568 * that's an exact multiple of the cipher block size. (If
2569 * the cipher is NULL so that the block size is
2570 * unavailable, we don't do this trick at all, because we
2571 * gain nothing by it.)
2573 if (ssh->cscipher &&
2574 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2577 stringlen = (256 - ssh->deferred_len);
2578 stringlen += ssh->cscipher->blksize - 1;
2579 stringlen -= (stringlen % ssh->cscipher->blksize);
2582 * Temporarily disable actual compression, so we
2583 * can guarantee to get this string exactly the
2584 * length we want it. The compression-disabling
2585 * routine should return an integer indicating how
2586 * many bytes we should adjust our string length
2590 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2592 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2593 ssh2_pkt_addstring_start(pkt);
2594 for (i = 0; i < stringlen; i++) {
2595 char c = (char) random_byte();
2596 ssh2_pkt_addstring_data(pkt, &c, 1);
2598 ssh2_pkt_defer(ssh, pkt);
2600 ssh_pkt_defersend(ssh);
2605 * Send all queued SSH-2 packets. We send them by means of
2606 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2607 * packets that needed to be lumped together.
2609 static void ssh2_pkt_queuesend(Ssh ssh)
2613 assert(!ssh->queueing);
2615 for (i = 0; i < ssh->queuelen; i++)
2616 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2619 ssh_pkt_defersend(ssh);
2623 void bndebug(char *string, Bignum b)
2627 p = ssh2_mpint_fmt(b, &len);
2628 debug(("%s", string));
2629 for (i = 0; i < len; i++)
2630 debug((" %02x", p[i]));
2636 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2640 p = ssh2_mpint_fmt(b, &len);
2641 hash_string(h, s, p, len);
2646 * Packet decode functions for both SSH-1 and SSH-2.
2648 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2650 unsigned long value;
2651 if (pkt->length - pkt->savedpos < 4)
2652 return 0; /* arrgh, no way to decline (FIXME?) */
2653 value = GET_32BIT(pkt->body + pkt->savedpos);
2657 static int ssh2_pkt_getbool(struct Packet *pkt)
2659 unsigned long value;
2660 if (pkt->length - pkt->savedpos < 1)
2661 return 0; /* arrgh, no way to decline (FIXME?) */
2662 value = pkt->body[pkt->savedpos] != 0;
2666 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2671 if (pkt->length - pkt->savedpos < 4)
2673 len = toint(GET_32BIT(pkt->body + pkt->savedpos));
2678 if (pkt->length - pkt->savedpos < *length)
2680 *p = (char *)(pkt->body + pkt->savedpos);
2681 pkt->savedpos += *length;
2683 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2685 if (pkt->length - pkt->savedpos < length)
2687 pkt->savedpos += length;
2688 return pkt->body + (pkt->savedpos - length);
2690 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2691 const unsigned char **keystr)
2695 j = makekey(pkt->body + pkt->savedpos,
2696 pkt->length - pkt->savedpos,
2703 assert(pkt->savedpos < pkt->length);
2707 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2712 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2713 pkt->length - pkt->savedpos, &b);
2721 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2727 ssh_pkt_getstring(pkt, &p, &length);
2732 b = bignum_from_bytes((unsigned char *)p, length);
2737 * Helper function to add an SSH-2 signature blob to a packet.
2738 * Expects to be shown the public key blob as well as the signature
2739 * blob. Normally works just like ssh2_pkt_addstring, but will
2740 * fiddle with the signature packet if necessary for
2741 * BUG_SSH2_RSA_PADDING.
2743 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2744 void *pkblob_v, int pkblob_len,
2745 void *sigblob_v, int sigblob_len)
2747 unsigned char *pkblob = (unsigned char *)pkblob_v;
2748 unsigned char *sigblob = (unsigned char *)sigblob_v;
2750 /* dmemdump(pkblob, pkblob_len); */
2751 /* dmemdump(sigblob, sigblob_len); */
2754 * See if this is in fact an ssh-rsa signature and a buggy
2755 * server; otherwise we can just do this the easy way.
2757 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) && pkblob_len > 4+7+4 &&
2758 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2759 int pos, len, siglen;
2762 * Find the byte length of the modulus.
2765 pos = 4+7; /* skip over "ssh-rsa" */
2766 len = toint(GET_32BIT(pkblob+pos)); /* get length of exponent */
2767 if (len < 0 || len > pkblob_len - pos - 4)
2769 pos += 4 + len; /* skip over exponent */
2770 if (pkblob_len - pos < 4)
2772 len = toint(GET_32BIT(pkblob+pos)); /* find length of modulus */
2773 if (len < 0 || len > pkblob_len - pos - 4)
2775 pos += 4; /* find modulus itself */
2776 while (len > 0 && pkblob[pos] == 0)
2778 /* debug(("modulus length is %d\n", len)); */
2781 * Now find the signature integer.
2783 pos = 4+7; /* skip over "ssh-rsa" */
2784 if (sigblob_len < pos+4)
2786 siglen = toint(GET_32BIT(sigblob+pos));
2787 if (siglen != sigblob_len - pos - 4)
2789 /* debug(("signature length is %d\n", siglen)); */
2791 if (len != siglen) {
2792 unsigned char newlen[4];
2793 ssh2_pkt_addstring_start(pkt);
2794 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2795 /* dmemdump(sigblob, pos); */
2796 pos += 4; /* point to start of actual sig */
2797 PUT_32BIT(newlen, len);
2798 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2799 /* dmemdump(newlen, 4); */
2801 while (len-- > siglen) {
2802 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2803 /* dmemdump(newlen, 1); */
2805 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2806 /* dmemdump(sigblob+pos, siglen); */
2810 /* Otherwise fall through and do it the easy way. We also come
2811 * here as a fallback if we discover above that the key blob
2812 * is misformatted in some way. */
2816 ssh2_pkt_addstring_start(pkt);
2817 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2821 * Examine the remote side's version string and compare it against
2822 * a list of known buggy implementations.
2824 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2826 char *imp; /* pointer to implementation part */
2828 imp += strcspn(imp, "-");
2830 imp += strcspn(imp, "-");
2833 ssh->remote_bugs = 0;
2836 * General notes on server version strings:
2837 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2838 * here -- in particular, we've heard of one that's perfectly happy
2839 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2840 * so we can't distinguish them.
2842 if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
2843 (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
2844 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2845 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2846 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2847 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2849 * These versions don't support SSH1_MSG_IGNORE, so we have
2850 * to use a different defence against password length
2853 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2854 logevent("We believe remote version has SSH-1 ignore bug");
2857 if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
2858 (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
2859 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2861 * These versions need a plain password sent; they can't
2862 * handle having a null and a random length of data after
2865 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2866 logevent("We believe remote version needs a plain SSH-1 password");
2869 if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
2870 (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
2871 (!strcmp(imp, "Cisco-1.25")))) {
2873 * These versions apparently have no clue whatever about
2874 * RSA authentication and will panic and die if they see
2875 * an AUTH_RSA message.
2877 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2878 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2881 if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
2882 (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
2883 !wc_match("* VShell", imp) &&
2884 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2885 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2886 wc_match("2.1 *", imp)))) {
2888 * These versions have the HMAC bug.
2890 ssh->remote_bugs |= BUG_SSH2_HMAC;
2891 logevent("We believe remote version has SSH-2 HMAC bug");
2894 if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
2895 (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
2896 !wc_match("* VShell", imp) &&
2897 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2899 * These versions have the key-derivation bug (failing to
2900 * include the literal shared secret in the hashes that
2901 * generate the keys).
2903 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2904 logevent("We believe remote version has SSH-2 key-derivation bug");
2907 if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
2908 (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
2909 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2910 wc_match("OpenSSH_3.[0-2]*", imp) ||
2911 wc_match("mod_sftp/0.[0-8]*", imp) ||
2912 wc_match("mod_sftp/0.9.[0-8]", imp)))) {
2914 * These versions have the SSH-2 RSA padding bug.
2916 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2917 logevent("We believe remote version has SSH-2 RSA padding bug");
2920 if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
2921 (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
2922 wc_match("OpenSSH_2.[0-2]*", imp))) {
2924 * These versions have the SSH-2 session-ID bug in
2925 * public-key authentication.
2927 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2928 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2931 if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
2932 (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
2933 (wc_match("DigiSSH_2.0", imp) ||
2934 wc_match("OpenSSH_2.[0-4]*", imp) ||
2935 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2936 wc_match("Sun_SSH_1.0", imp) ||
2937 wc_match("Sun_SSH_1.0.1", imp) ||
2938 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2939 wc_match("WeOnlyDo-*", imp)))) {
2941 * These versions have the SSH-2 rekey bug.
2943 ssh->remote_bugs |= BUG_SSH2_REKEY;
2944 logevent("We believe remote version has SSH-2 rekey bug");
2947 if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
2948 (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
2949 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2950 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2952 * This version ignores our makpkt and needs to be throttled.
2954 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2955 logevent("We believe remote version ignores SSH-2 maximum packet size");
2958 if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
2960 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2961 * none detected automatically.
2963 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2964 logevent("We believe remote version has SSH-2 ignore bug");
2967 if (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == FORCE_ON ||
2968 (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == AUTO &&
2969 (wc_match("OpenSSH_2.[235]*", imp)))) {
2971 * These versions only support the original (pre-RFC4419)
2972 * SSH-2 GEX request, and disconnect with a protocol error if
2973 * we use the newer version.
2975 ssh->remote_bugs |= BUG_SSH2_OLDGEX;
2976 logevent("We believe remote version has outdated SSH-2 GEX");
2979 if (conf_get_int(ssh->conf, CONF_sshbug_winadj) == FORCE_ON) {
2981 * Servers that don't support our winadj request for one
2982 * reason or another. Currently, none detected automatically.
2984 ssh->remote_bugs |= BUG_CHOKES_ON_WINADJ;
2985 logevent("We believe remote version has winadj bug");
2988 if (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == FORCE_ON ||
2989 (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == AUTO &&
2990 (wc_match("OpenSSH_[2-5].*", imp) ||
2991 wc_match("OpenSSH_6.[0-6]*", imp) ||
2992 wc_match("dropbear_0.[2-4][0-9]*", imp) ||
2993 wc_match("dropbear_0.5[01]*", imp)))) {
2995 * These versions have the SSH-2 channel request bug.
2996 * OpenSSH 6.7 and above do not:
2997 * https://bugzilla.mindrot.org/show_bug.cgi?id=1818
2998 * dropbear_0.52 and above do not:
2999 * https://secure.ucc.asn.au/hg/dropbear/rev/cd02449b709c
3001 ssh->remote_bugs |= BUG_SENDS_LATE_REQUEST_REPLY;
3002 logevent("We believe remote version has SSH-2 channel request bug");
3007 * The `software version' part of an SSH version string is required
3008 * to contain no spaces or minus signs.
3010 static void ssh_fix_verstring(char *str)
3012 /* Eat "<protoversion>-". */
3013 while (*str && *str != '-') str++;
3014 assert(*str == '-'); str++;
3016 /* Convert minus signs and spaces in the remaining string into
3019 if (*str == '-' || *str == ' ')
3026 * Send an appropriate SSH version string.
3028 static void ssh_send_verstring(Ssh ssh, const char *protoname, char *svers)
3032 if (ssh->version == 2) {
3034 * Construct a v2 version string.
3036 verstring = dupprintf("%s2.0-%s\015\012", protoname, sshver);
3039 * Construct a v1 version string.
3041 assert(!strcmp(protoname, "SSH-")); /* no v1 bare connection protocol */
3042 verstring = dupprintf("SSH-%s-%s\012",
3043 (ssh_versioncmp(svers, "1.5") <= 0 ?
3048 ssh_fix_verstring(verstring + strlen(protoname));
3050 /* FUZZING make PuTTY insecure, so make live use difficult. */
3054 if (ssh->version == 2) {
3057 * Record our version string.
3059 len = strcspn(verstring, "\015\012");
3060 ssh->v_c = snewn(len + 1, char);
3061 memcpy(ssh->v_c, verstring, len);
3065 logeventf(ssh, "We claim version: %.*s",
3066 strcspn(verstring, "\015\012"), verstring);
3067 s_write(ssh, verstring, strlen(verstring));
3071 static int do_ssh_init(Ssh ssh, unsigned char c)
3073 static const char protoname[] = "SSH-";
3075 struct do_ssh_init_state {
3084 crState(do_ssh_init_state);
3088 /* Search for a line beginning with the protocol name prefix in
3091 for (s->i = 0; protoname[s->i]; s->i++) {
3092 if ((char)c != protoname[s->i]) goto no;
3102 ssh->session_started = TRUE;
3104 s->vstrsize = sizeof(protoname) + 16;
3105 s->vstring = snewn(s->vstrsize, char);
3106 strcpy(s->vstring, protoname);
3107 s->vslen = strlen(protoname);
3110 if (s->vslen >= s->vstrsize - 1) {
3112 s->vstring = sresize(s->vstring, s->vstrsize, char);
3114 s->vstring[s->vslen++] = c;
3117 s->version[s->i] = '\0';
3119 } else if (s->i < sizeof(s->version) - 1)
3120 s->version[s->i++] = c;
3121 } else if (c == '\012')
3123 crReturn(1); /* get another char */
3126 ssh->agentfwd_enabled = FALSE;
3127 ssh->rdpkt2_state.incoming_sequence = 0;
3129 s->vstring[s->vslen] = 0;
3130 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3131 logeventf(ssh, "Server version: %s", s->vstring);
3132 ssh_detect_bugs(ssh, s->vstring);
3135 * Decide which SSH protocol version to support.
3138 /* Anything strictly below "2.0" means protocol 1 is supported. */
3139 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
3140 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
3141 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
3143 if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
3145 bombout(("SSH protocol version 1 required by our configuration "
3146 "but not provided by server"));
3149 } else if (conf_get_int(ssh->conf, CONF_sshprot) == 3) {
3151 bombout(("SSH protocol version 2 required by our configuration "
3152 "but server only provides (old, insecure) SSH-1"));
3156 /* No longer support values 1 or 2 for CONF_sshprot */
3157 assert(!"Unexpected value for CONF_sshprot");
3160 if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
3165 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
3167 /* Send the version string, if we haven't already */
3168 if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
3169 ssh_send_verstring(ssh, protoname, s->version);
3171 if (ssh->version == 2) {
3174 * Record their version string.
3176 len = strcspn(s->vstring, "\015\012");
3177 ssh->v_s = snewn(len + 1, char);
3178 memcpy(ssh->v_s, s->vstring, len);
3182 * Initialise SSH-2 protocol.
3184 ssh->protocol = ssh2_protocol;
3185 ssh2_protocol_setup(ssh);
3186 ssh->s_rdpkt = ssh2_rdpkt;
3189 * Initialise SSH-1 protocol.
3191 ssh->protocol = ssh1_protocol;
3192 ssh1_protocol_setup(ssh);
3193 ssh->s_rdpkt = ssh1_rdpkt;
3195 if (ssh->version == 2)
3196 do_ssh2_transport(ssh, NULL, -1, NULL);
3198 update_specials_menu(ssh->frontend);
3199 ssh->state = SSH_STATE_BEFORE_SIZE;
3200 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3207 static int do_ssh_connection_init(Ssh ssh, unsigned char c)
3210 * Ordinary SSH begins with the banner "SSH-x.y-...". This is just
3211 * the ssh-connection part, extracted and given a trivial binary
3212 * packet protocol, so we replace 'SSH-' at the start with a new
3213 * name. In proper SSH style (though of course this part of the
3214 * proper SSH protocol _isn't_ subject to this kind of
3215 * DNS-domain-based extension), we define the new name in our
3218 static const char protoname[] =
3219 "SSHCONNECTION@putty.projects.tartarus.org-";
3221 struct do_ssh_connection_init_state {
3229 crState(do_ssh_connection_init_state);
3233 /* Search for a line beginning with the protocol name prefix in
3236 for (s->i = 0; protoname[s->i]; s->i++) {
3237 if ((char)c != protoname[s->i]) goto no;
3247 s->vstrsize = sizeof(protoname) + 16;
3248 s->vstring = snewn(s->vstrsize, char);
3249 strcpy(s->vstring, protoname);
3250 s->vslen = strlen(protoname);
3253 if (s->vslen >= s->vstrsize - 1) {
3255 s->vstring = sresize(s->vstring, s->vstrsize, char);
3257 s->vstring[s->vslen++] = c;
3260 s->version[s->i] = '\0';
3262 } else if (s->i < sizeof(s->version) - 1)
3263 s->version[s->i++] = c;
3264 } else if (c == '\012')
3266 crReturn(1); /* get another char */
3269 ssh->agentfwd_enabled = FALSE;
3270 ssh->rdpkt2_bare_state.incoming_sequence = 0;
3272 s->vstring[s->vslen] = 0;
3273 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3274 logeventf(ssh, "Server version: %s", s->vstring);
3275 ssh_detect_bugs(ssh, s->vstring);
3278 * Decide which SSH protocol version to support. This is easy in
3279 * bare ssh-connection mode: only 2.0 is legal.
3281 if (ssh_versioncmp(s->version, "2.0") < 0) {
3282 bombout(("Server announces compatibility with SSH-1 in bare ssh-connection protocol"));
3285 if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
3286 bombout(("Bare ssh-connection protocol cannot be run in SSH-1-only mode"));
3292 logeventf(ssh, "Using bare ssh-connection protocol");
3294 /* Send the version string, if we haven't already */
3295 ssh_send_verstring(ssh, protoname, s->version);
3298 * Initialise bare connection protocol.
3300 ssh->protocol = ssh2_bare_connection_protocol;
3301 ssh2_bare_connection_protocol_setup(ssh);
3302 ssh->s_rdpkt = ssh2_bare_connection_rdpkt;
3304 update_specials_menu(ssh->frontend);
3305 ssh->state = SSH_STATE_BEFORE_SIZE;
3306 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3309 * Get authconn (really just conn) under way.
3311 do_ssh2_authconn(ssh, NULL, 0, NULL);
3318 static void ssh_process_incoming_data(Ssh ssh,
3319 const unsigned char **data, int *datalen)
3321 struct Packet *pktin;
3323 pktin = ssh->s_rdpkt(ssh, data, datalen);
3325 ssh->protocol(ssh, NULL, 0, pktin);
3326 ssh_free_packet(pktin);
3330 static void ssh_queue_incoming_data(Ssh ssh,
3331 const unsigned char **data, int *datalen)
3333 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
3338 static void ssh_process_queued_incoming_data(Ssh ssh)
3341 const unsigned char *data;
3344 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
3345 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
3349 while (!ssh->frozen && len > 0)
3350 ssh_process_incoming_data(ssh, &data, &len);
3353 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
3357 static void ssh_set_frozen(Ssh ssh, int frozen)
3360 sk_set_frozen(ssh->s, frozen);
3361 ssh->frozen = frozen;
3364 static void ssh_gotdata(Ssh ssh, const unsigned char *data, int datalen)
3366 /* Log raw data, if we're in that mode. */
3368 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
3369 0, NULL, NULL, 0, NULL);
3371 crBegin(ssh->ssh_gotdata_crstate);
3374 * To begin with, feed the characters one by one to the
3375 * protocol initialisation / selection function do_ssh_init().
3376 * When that returns 0, we're done with the initial greeting
3377 * exchange and can move on to packet discipline.
3380 int ret; /* need not be kept across crReturn */
3382 crReturnV; /* more data please */
3383 ret = ssh->do_ssh_init(ssh, *data);
3391 * We emerge from that loop when the initial negotiation is
3392 * over and we have selected an s_rdpkt function. Now pass
3393 * everything to s_rdpkt, and then pass the resulting packets
3394 * to the proper protocol handler.
3398 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
3400 ssh_queue_incoming_data(ssh, &data, &datalen);
3401 /* This uses up all data and cannot cause anything interesting
3402 * to happen; indeed, for anything to happen at all, we must
3403 * return, so break out. */
3405 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
3406 /* This uses up some or all data, and may freeze the
3408 ssh_process_queued_incoming_data(ssh);
3410 /* This uses up some or all data, and may freeze the
3412 ssh_process_incoming_data(ssh, &data, &datalen);
3414 /* FIXME this is probably EBW. */
3415 if (ssh->state == SSH_STATE_CLOSED)
3418 /* We're out of data. Go and get some more. */
3424 static int ssh_do_close(Ssh ssh, int notify_exit)
3427 struct ssh_channel *c;
3429 ssh->state = SSH_STATE_CLOSED;
3430 expire_timer_context(ssh);
3435 notify_remote_exit(ssh->frontend);
3440 * Now we must shut down any port- and X-forwarded channels going
3441 * through this connection.
3443 if (ssh->channels) {
3444 while (NULL != (c = index234(ssh->channels, 0))) {
3447 x11_close(c->u.x11.xconn);
3450 case CHAN_SOCKDATA_DORMANT:
3451 pfd_close(c->u.pfd.pf);
3454 del234(ssh->channels, c); /* moving next one to index 0 */
3455 if (ssh->version == 2)
3456 bufchain_clear(&c->v.v2.outbuffer);
3461 * Go through port-forwardings, and close any associated
3462 * listening sockets.
3464 if (ssh->portfwds) {
3465 struct ssh_portfwd *pf;
3466 while (NULL != (pf = index234(ssh->portfwds, 0))) {
3467 /* Dispose of any listening socket. */
3469 pfl_terminate(pf->local);
3470 del234(ssh->portfwds, pf); /* moving next one to index 0 */
3473 freetree234(ssh->portfwds);
3474 ssh->portfwds = NULL;
3478 * Also stop attempting to connection-share.
3480 if (ssh->connshare) {
3481 sharestate_free(ssh->connshare);
3482 ssh->connshare = NULL;
3488 static void ssh_socket_log(Plug plug, int type, SockAddr addr, int port,
3489 const char *error_msg, int error_code)
3491 Ssh ssh = (Ssh) plug;
3494 * While we're attempting connection sharing, don't loudly log
3495 * everything that happens. Real TCP connections need to be logged
3496 * when we _start_ trying to connect, because it might be ages
3497 * before they respond if something goes wrong; but connection
3498 * sharing is local and quick to respond, and it's sufficient to
3499 * simply wait and see whether it worked afterwards.
3502 if (!ssh->attempting_connshare)
3503 backend_socket_log(ssh->frontend, type, addr, port,
3504 error_msg, error_code, ssh->conf,
3505 ssh->session_started);
3508 void ssh_connshare_log(Ssh ssh, int event, const char *logtext,
3509 const char *ds_err, const char *us_err)
3511 if (event == SHARE_NONE) {
3512 /* In this case, 'logtext' is an error message indicating a
3513 * reason why connection sharing couldn't be set up _at all_.
3514 * Failing that, ds_err and us_err indicate why we couldn't be
3515 * a downstream and an upstream respectively. */
3517 logeventf(ssh, "Could not set up connection sharing: %s", logtext);
3520 logeventf(ssh, "Could not set up connection sharing"
3521 " as downstream: %s", ds_err);
3523 logeventf(ssh, "Could not set up connection sharing"
3524 " as upstream: %s", us_err);
3526 } else if (event == SHARE_DOWNSTREAM) {
3527 /* In this case, 'logtext' is a local endpoint address */
3528 logeventf(ssh, "Using existing shared connection at %s", logtext);
3529 /* Also we should mention this in the console window to avoid
3530 * confusing users as to why this window doesn't behave the
3532 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
3533 c_write_str(ssh,"Reusing a shared connection to this server.\r\n");
3535 } else if (event == SHARE_UPSTREAM) {
3536 /* In this case, 'logtext' is a local endpoint address too */
3537 logeventf(ssh, "Sharing this connection at %s", logtext);
3541 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
3544 Ssh ssh = (Ssh) plug;
3545 int need_notify = ssh_do_close(ssh, FALSE);
3548 if (!ssh->close_expected)
3549 error_msg = "Server unexpectedly closed network connection";
3551 error_msg = "Server closed network connection";
3554 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
3558 notify_remote_exit(ssh->frontend);
3561 logevent(error_msg);
3562 if (!ssh->close_expected || !ssh->clean_exit)
3563 connection_fatal(ssh->frontend, "%s", error_msg);
3567 static int ssh_receive(Plug plug, int urgent, char *data, int len)
3569 Ssh ssh = (Ssh) plug;
3570 ssh_gotdata(ssh, (unsigned char *)data, len);
3571 if (ssh->state == SSH_STATE_CLOSED) {
3572 ssh_do_close(ssh, TRUE);
3578 static void ssh_sent(Plug plug, int bufsize)
3580 Ssh ssh = (Ssh) plug;
3582 * If the send backlog on the SSH socket itself clears, we
3583 * should unthrottle the whole world if it was throttled.
3585 if (bufsize < SSH_MAX_BACKLOG)
3586 ssh_throttle_all(ssh, 0, bufsize);
3589 static void ssh_hostport_setup(const char *host, int port, Conf *conf,
3590 char **savedhost, int *savedport,
3593 char *loghost = conf_get_str(conf, CONF_loghost);
3595 *loghost_ret = loghost;
3601 tmphost = dupstr(loghost);
3602 *savedport = 22; /* default ssh port */
3605 * A colon suffix on the hostname string also lets us affect
3606 * savedport. (Unless there are multiple colons, in which case
3607 * we assume this is an unbracketed IPv6 literal.)
3609 colon = host_strrchr(tmphost, ':');
3610 if (colon && colon == host_strchr(tmphost, ':')) {
3613 *savedport = atoi(colon);
3616 *savedhost = host_strduptrim(tmphost);
3619 *savedhost = host_strduptrim(host);
3621 port = 22; /* default ssh port */
3626 static int ssh_test_for_upstream(const char *host, int port, Conf *conf)
3632 random_ref(); /* platform may need this to determine share socket name */
3633 ssh_hostport_setup(host, port, conf, &savedhost, &savedport, NULL);
3634 ret = ssh_share_test_for_upstream(savedhost, savedport, conf);
3642 * Connect to specified host and port.
3643 * Returns an error message, or NULL on success.
3644 * Also places the canonical host name into `realhost'. It must be
3645 * freed by the caller.
3647 static const char *connect_to_host(Ssh ssh, const char *host, int port,
3648 char **realhost, int nodelay, int keepalive)
3650 static const struct plug_function_table fn_table = {
3661 int addressfamily, sshprot;
3663 ssh_hostport_setup(host, port, ssh->conf,
3664 &ssh->savedhost, &ssh->savedport, &loghost);
3666 ssh->fn = &fn_table; /* make 'ssh' usable as a Plug */
3669 * Try connection-sharing, in case that means we don't open a
3670 * socket after all. ssh_connection_sharing_init will connect to a
3671 * previously established upstream if it can, and failing that,
3672 * establish a listening socket for _us_ to be the upstream. In
3673 * the latter case it will return NULL just as if it had done
3674 * nothing, because here we only need to care if we're a
3675 * downstream and need to do our connection setup differently.
3677 ssh->connshare = NULL;
3678 ssh->attempting_connshare = TRUE; /* affects socket logging behaviour */
3679 ssh->s = ssh_connection_sharing_init(ssh->savedhost, ssh->savedport,
3680 ssh->conf, ssh, &ssh->connshare);
3681 ssh->attempting_connshare = FALSE;
3682 if (ssh->s != NULL) {
3684 * We are a downstream.
3686 ssh->bare_connection = TRUE;
3687 ssh->do_ssh_init = do_ssh_connection_init;
3688 ssh->fullhostname = NULL;
3689 *realhost = dupstr(host); /* best we can do */
3692 * We're not a downstream, so open a normal socket.
3694 ssh->do_ssh_init = do_ssh_init;
3699 addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
3700 addr = name_lookup(host, port, realhost, ssh->conf, addressfamily,
3701 ssh->frontend, "SSH connection");
3702 if ((err = sk_addr_error(addr)) != NULL) {
3706 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
3708 ssh->s = new_connection(addr, *realhost, port,
3709 0, 1, nodelay, keepalive,
3710 (Plug) ssh, ssh->conf);
3711 if ((err = sk_socket_error(ssh->s)) != NULL) {
3713 notify_remote_exit(ssh->frontend);
3719 * The SSH version number is always fixed (since we no longer support
3720 * fallback between versions), so set it now, and if it's SSH-2,
3721 * send the version string now too.
3723 sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3724 assert(sshprot == 0 || sshprot == 3);
3728 if (sshprot == 3 && !ssh->bare_connection) {
3731 ssh_send_verstring(ssh, "SSH-", NULL);
3735 * loghost, if configured, overrides realhost.
3739 *realhost = dupstr(loghost);
3746 * Throttle or unthrottle the SSH connection.
3748 static void ssh_throttle_conn(Ssh ssh, int adjust)
3750 int old_count = ssh->conn_throttle_count;
3751 ssh->conn_throttle_count += adjust;
3752 assert(ssh->conn_throttle_count >= 0);
3753 if (ssh->conn_throttle_count && !old_count) {
3754 ssh_set_frozen(ssh, 1);
3755 } else if (!ssh->conn_throttle_count && old_count) {
3756 ssh_set_frozen(ssh, 0);
3761 * Throttle or unthrottle _all_ local data streams (for when sends
3762 * on the SSH connection itself back up).
3764 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3767 struct ssh_channel *c;
3769 if (enable == ssh->throttled_all)
3771 ssh->throttled_all = enable;
3772 ssh->overall_bufsize = bufsize;
3775 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3777 case CHAN_MAINSESSION:
3779 * This is treated separately, outside the switch.
3783 x11_override_throttle(c->u.x11.xconn, enable);
3786 /* Agent channels require no buffer management. */
3789 pfd_override_throttle(c->u.pfd.pf, enable);
3795 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3797 Ssh ssh = (Ssh) sshv;
3799 ssh->agent_response = reply;
3800 ssh->agent_response_len = replylen;
3802 if (ssh->version == 1)
3803 do_ssh1_login(ssh, NULL, -1, NULL);
3805 do_ssh2_authconn(ssh, NULL, -1, NULL);
3808 static void ssh_dialog_callback(void *sshv, int ret)
3810 Ssh ssh = (Ssh) sshv;
3812 ssh->user_response = ret;
3814 if (ssh->version == 1)
3815 do_ssh1_login(ssh, NULL, -1, NULL);
3817 do_ssh2_transport(ssh, NULL, -1, NULL);
3820 * This may have unfrozen the SSH connection, so do a
3823 ssh_process_queued_incoming_data(ssh);
3826 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3828 struct ssh_channel *c = (struct ssh_channel *)cv;
3829 const void *sentreply = reply;
3831 c->u.a.outstanding_requests--;
3833 /* Fake SSH_AGENT_FAILURE. */
3834 sentreply = "\0\0\0\1\5";
3837 ssh_send_channel_data(c, sentreply, replylen);
3841 * If we've already seen an incoming EOF but haven't sent an
3842 * outgoing one, this may be the moment to send it.
3844 if (c->u.a.outstanding_requests == 0 && (c->closes & CLOSES_RCVD_EOF))
3845 sshfwd_write_eof(c);
3849 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3850 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3851 * => log `wire_reason'.
3853 static void ssh_disconnect(Ssh ssh, const char *client_reason,
3854 const char *wire_reason,
3855 int code, int clean_exit)
3859 client_reason = wire_reason;
3861 error = dupprintf("Disconnected: %s", client_reason);
3863 error = dupstr("Disconnected");
3865 if (ssh->version == 1) {
3866 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3868 } else if (ssh->version == 2) {
3869 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3870 ssh2_pkt_adduint32(pktout, code);
3871 ssh2_pkt_addstring(pktout, wire_reason);
3872 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3873 ssh2_pkt_send_noqueue(ssh, pktout);
3876 ssh->close_expected = TRUE;
3877 ssh->clean_exit = clean_exit;
3878 ssh_closing((Plug)ssh, error, 0, 0);
3882 int verify_ssh_manual_host_key(Ssh ssh, const char *fingerprint,
3883 const struct ssh_signkey *ssh2keytype,
3886 if (!conf_get_str_nthstrkey(ssh->conf, CONF_ssh_manual_hostkeys, 0)) {
3887 return -1; /* no manual keys configured */
3892 * The fingerprint string we've been given will have things
3893 * like 'ssh-rsa 2048' at the front of it. Strip those off and
3894 * narrow down to just the colon-separated hex block at the
3895 * end of the string.
3897 const char *p = strrchr(fingerprint, ' ');
3898 fingerprint = p ? p+1 : fingerprint;
3899 /* Quick sanity checks, including making sure it's in lowercase */
3900 assert(strlen(fingerprint) == 16*3 - 1);
3901 assert(fingerprint[2] == ':');
3902 assert(fingerprint[strspn(fingerprint, "0123456789abcdef:")] == 0);
3904 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3906 return 1; /* success */
3911 * Construct the base64-encoded public key blob and see if
3914 unsigned char *binblob;
3916 int binlen, atoms, i;
3917 binblob = ssh2keytype->public_blob(ssh2keydata, &binlen);
3918 atoms = (binlen + 2) / 3;
3919 base64blob = snewn(atoms * 4 + 1, char);
3920 for (i = 0; i < atoms; i++)
3921 base64_encode_atom(binblob + 3*i, binlen - 3*i, base64blob + 4*i);
3922 base64blob[atoms * 4] = '\0';
3924 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3927 return 1; /* success */
3936 * Handle the key exchange and user authentication phases.
3938 static int do_ssh1_login(Ssh ssh, const unsigned char *in, int inlen,
3939 struct Packet *pktin)
3942 unsigned char cookie[8], *ptr;
3943 struct MD5Context md5c;
3944 struct do_ssh1_login_state {
3947 unsigned char *rsabuf;
3948 const unsigned char *keystr1, *keystr2;
3949 unsigned long supported_ciphers_mask, supported_auths_mask;
3950 int tried_publickey, tried_agent;
3951 int tis_auth_refused, ccard_auth_refused;
3952 unsigned char session_id[16];
3954 void *publickey_blob;
3955 int publickey_bloblen;
3956 char *publickey_comment;
3957 int privatekey_available, privatekey_encrypted;
3958 prompts_t *cur_prompt;
3961 unsigned char request[5], *response, *p;
3971 struct RSAKey servkey, hostkey;
3973 crState(do_ssh1_login_state);
3980 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3981 bombout(("Public key packet not received"));
3985 logevent("Received public keys");
3987 ptr = ssh_pkt_getdata(pktin, 8);
3989 bombout(("SSH-1 public key packet stopped before random cookie"));
3992 memcpy(cookie, ptr, 8);
3994 if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
3995 !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) {
3996 bombout(("Failed to read SSH-1 public keys from public key packet"));
4001 * Log the host key fingerprint.
4005 logevent("Host key fingerprint is:");
4006 strcpy(logmsg, " ");
4007 s->hostkey.comment = NULL;
4008 rsa_fingerprint(logmsg + strlen(logmsg),
4009 sizeof(logmsg) - strlen(logmsg), &s->hostkey);
4013 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
4014 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
4015 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
4016 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
4017 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
4019 ssh->v1_local_protoflags =
4020 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
4021 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
4024 MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
4025 MD5Update(&md5c, s->keystr1, s->servkey.bytes);
4026 MD5Update(&md5c, cookie, 8);
4027 MD5Final(s->session_id, &md5c);
4029 for (i = 0; i < 32; i++)
4030 ssh->session_key[i] = random_byte();
4033 * Verify that the `bits' and `bytes' parameters match.
4035 if (s->hostkey.bits > s->hostkey.bytes * 8 ||
4036 s->servkey.bits > s->servkey.bytes * 8) {
4037 bombout(("SSH-1 public keys were badly formatted"));
4041 s->len = (s->hostkey.bytes > s->servkey.bytes ?
4042 s->hostkey.bytes : s->servkey.bytes);
4044 s->rsabuf = snewn(s->len, unsigned char);
4047 * Verify the host key.
4051 * First format the key into a string.
4053 int len = rsastr_len(&s->hostkey);
4054 char fingerprint[100];
4055 char *keystr = snewn(len, char);
4056 rsastr_fmt(keystr, &s->hostkey);
4057 rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
4059 /* First check against manually configured host keys. */
4060 s->dlgret = verify_ssh_manual_host_key(ssh, fingerprint, NULL, NULL);
4061 if (s->dlgret == 0) { /* did not match */
4062 bombout(("Host key did not appear in manually configured list"));
4065 } else if (s->dlgret < 0) { /* none configured; use standard handling */
4066 ssh_set_frozen(ssh, 1);
4067 s->dlgret = verify_ssh_host_key(ssh->frontend,
4068 ssh->savedhost, ssh->savedport,
4069 "rsa", keystr, fingerprint,
4070 ssh_dialog_callback, ssh);
4075 if (s->dlgret < 0) {
4079 bombout(("Unexpected data from server while waiting"
4080 " for user host key response"));
4083 } while (pktin || inlen > 0);
4084 s->dlgret = ssh->user_response;
4086 ssh_set_frozen(ssh, 0);
4088 if (s->dlgret == 0) {
4089 ssh_disconnect(ssh, "User aborted at host key verification",
4098 for (i = 0; i < 32; i++) {
4099 s->rsabuf[i] = ssh->session_key[i];
4101 s->rsabuf[i] ^= s->session_id[i];
4104 if (s->hostkey.bytes > s->servkey.bytes) {
4105 ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
4107 ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
4109 ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
4111 ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
4114 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
4118 logevent("Encrypted session key");
4121 int cipher_chosen = 0, warn = 0;
4122 const char *cipher_string = NULL;
4124 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
4125 int next_cipher = conf_get_int_int(ssh->conf,
4126 CONF_ssh_cipherlist, i);
4127 if (next_cipher == CIPHER_WARN) {
4128 /* If/when we choose a cipher, warn about it */
4130 } else if (next_cipher == CIPHER_AES) {
4131 /* XXX Probably don't need to mention this. */
4132 logevent("AES not supported in SSH-1, skipping");
4134 switch (next_cipher) {
4135 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
4136 cipher_string = "3DES"; break;
4137 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
4138 cipher_string = "Blowfish"; break;
4139 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
4140 cipher_string = "single-DES"; break;
4142 if (s->supported_ciphers_mask & (1 << s->cipher_type))
4146 if (!cipher_chosen) {
4147 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
4148 bombout(("Server violates SSH-1 protocol by not "
4149 "supporting 3DES encryption"));
4151 /* shouldn't happen */
4152 bombout(("No supported ciphers found"));
4156 /* Warn about chosen cipher if necessary. */
4158 ssh_set_frozen(ssh, 1);
4159 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
4160 ssh_dialog_callback, ssh);
4161 if (s->dlgret < 0) {
4165 bombout(("Unexpected data from server while waiting"
4166 " for user response"));
4169 } while (pktin || inlen > 0);
4170 s->dlgret = ssh->user_response;
4172 ssh_set_frozen(ssh, 0);
4173 if (s->dlgret == 0) {
4174 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
4181 switch (s->cipher_type) {
4182 case SSH_CIPHER_3DES:
4183 logevent("Using 3DES encryption");
4185 case SSH_CIPHER_DES:
4186 logevent("Using single-DES encryption");
4188 case SSH_CIPHER_BLOWFISH:
4189 logevent("Using Blowfish encryption");
4193 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
4194 PKT_CHAR, s->cipher_type,
4195 PKT_DATA, cookie, 8,
4196 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
4197 PKT_DATA, s->rsabuf, s->len,
4198 PKT_INT, ssh->v1_local_protoflags, PKT_END);
4200 logevent("Trying to enable encryption...");
4204 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
4205 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
4207 ssh->v1_cipher_ctx = ssh->cipher->make_context();
4208 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
4209 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
4211 ssh->crcda_ctx = crcda_make_context();
4212 logevent("Installing CRC compensation attack detector");
4214 if (s->servkey.modulus) {
4215 sfree(s->servkey.modulus);
4216 s->servkey.modulus = NULL;
4218 if (s->servkey.exponent) {
4219 sfree(s->servkey.exponent);
4220 s->servkey.exponent = NULL;
4222 if (s->hostkey.modulus) {
4223 sfree(s->hostkey.modulus);
4224 s->hostkey.modulus = NULL;
4226 if (s->hostkey.exponent) {
4227 sfree(s->hostkey.exponent);
4228 s->hostkey.exponent = NULL;
4232 if (pktin->type != SSH1_SMSG_SUCCESS) {
4233 bombout(("Encryption not successfully enabled"));
4237 logevent("Successfully started encryption");
4239 fflush(stdout); /* FIXME eh? */
4241 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
4242 int ret; /* need not be kept over crReturn */
4243 s->cur_prompt = new_prompts(ssh->frontend);
4244 s->cur_prompt->to_server = TRUE;
4245 s->cur_prompt->name = dupstr("SSH login name");
4246 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
4247 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4250 crWaitUntil(!pktin);
4251 ret = get_userpass_input(s->cur_prompt, in, inlen);
4256 * Failed to get a username. Terminate.
4258 free_prompts(s->cur_prompt);
4259 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
4262 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
4263 free_prompts(s->cur_prompt);
4266 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
4268 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
4270 if (flags & FLAG_INTERACTIVE &&
4271 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
4272 c_write_str(ssh, userlog);
4273 c_write_str(ssh, "\r\n");
4281 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
4282 /* We must not attempt PK auth. Pretend we've already tried it. */
4283 s->tried_publickey = s->tried_agent = 1;
4285 s->tried_publickey = s->tried_agent = 0;
4287 s->tis_auth_refused = s->ccard_auth_refused = 0;
4289 * Load the public half of any configured keyfile for later use.
4291 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4292 if (!filename_is_null(s->keyfile)) {
4294 logeventf(ssh, "Reading key file \"%.150s\"",
4295 filename_to_str(s->keyfile));
4296 keytype = key_type(s->keyfile);
4297 if (keytype == SSH_KEYTYPE_SSH1 ||
4298 keytype == SSH_KEYTYPE_SSH1_PUBLIC) {
4300 if (rsakey_pubblob(s->keyfile,
4301 &s->publickey_blob, &s->publickey_bloblen,
4302 &s->publickey_comment, &error)) {
4303 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH1);
4304 if (!s->privatekey_available)
4305 logeventf(ssh, "Key file contains public key only");
4306 s->privatekey_encrypted = rsakey_encrypted(s->keyfile,
4310 logeventf(ssh, "Unable to load key (%s)", error);
4311 msgbuf = dupprintf("Unable to load key file "
4312 "\"%.150s\" (%s)\r\n",
4313 filename_to_str(s->keyfile),
4315 c_write_str(ssh, msgbuf);
4317 s->publickey_blob = NULL;
4321 logeventf(ssh, "Unable to use this key file (%s)",
4322 key_type_to_str(keytype));
4323 msgbuf = dupprintf("Unable to use key file \"%.150s\""
4325 filename_to_str(s->keyfile),
4326 key_type_to_str(keytype));
4327 c_write_str(ssh, msgbuf);
4329 s->publickey_blob = NULL;
4332 s->publickey_blob = NULL;
4334 while (pktin->type == SSH1_SMSG_FAILURE) {
4335 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
4337 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
4339 * Attempt RSA authentication using Pageant.
4345 logevent("Pageant is running. Requesting keys.");
4347 /* Request the keys held by the agent. */
4348 PUT_32BIT(s->request, 1);
4349 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
4350 if (!agent_query(s->request, 5, &r, &s->responselen,
4351 ssh_agent_callback, ssh)) {
4355 bombout(("Unexpected data from server while waiting"
4356 " for agent response"));
4359 } while (pktin || inlen > 0);
4360 r = ssh->agent_response;
4361 s->responselen = ssh->agent_response_len;
4363 s->response = (unsigned char *) r;
4364 if (s->response && s->responselen >= 5 &&
4365 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
4366 s->p = s->response + 5;
4367 s->nkeys = toint(GET_32BIT(s->p));
4369 logeventf(ssh, "Pageant reported negative key count %d",
4374 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
4375 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
4376 unsigned char *pkblob = s->p;
4380 do { /* do while (0) to make breaking easy */
4381 n = ssh1_read_bignum
4382 (s->p, toint(s->responselen-(s->p-s->response)),
4387 n = ssh1_read_bignum
4388 (s->p, toint(s->responselen-(s->p-s->response)),
4393 if (s->responselen - (s->p-s->response) < 4)
4395 s->commentlen = toint(GET_32BIT(s->p));
4397 if (s->commentlen < 0 ||
4398 toint(s->responselen - (s->p-s->response)) <
4401 s->commentp = (char *)s->p;
4402 s->p += s->commentlen;
4406 logevent("Pageant key list packet was truncated");
4410 if (s->publickey_blob) {
4411 if (!memcmp(pkblob, s->publickey_blob,
4412 s->publickey_bloblen)) {
4413 logeventf(ssh, "Pageant key #%d matches "
4414 "configured key file", s->keyi);
4415 s->tried_publickey = 1;
4417 /* Skip non-configured key */
4420 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
4421 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4422 PKT_BIGNUM, s->key.modulus, PKT_END);
4424 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4425 logevent("Key refused");
4428 logevent("Received RSA challenge");
4429 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4430 bombout(("Server's RSA challenge was badly formatted"));
4435 char *agentreq, *q, *ret;
4438 len = 1 + 4; /* message type, bit count */
4439 len += ssh1_bignum_length(s->key.exponent);
4440 len += ssh1_bignum_length(s->key.modulus);
4441 len += ssh1_bignum_length(s->challenge);
4442 len += 16; /* session id */
4443 len += 4; /* response format */
4444 agentreq = snewn(4 + len, char);
4445 PUT_32BIT(agentreq, len);
4447 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
4448 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
4450 q += ssh1_write_bignum(q, s->key.exponent);
4451 q += ssh1_write_bignum(q, s->key.modulus);
4452 q += ssh1_write_bignum(q, s->challenge);
4453 memcpy(q, s->session_id, 16);
4455 PUT_32BIT(q, 1); /* response format */
4456 if (!agent_query(agentreq, len + 4, &vret, &retlen,
4457 ssh_agent_callback, ssh)) {
4462 bombout(("Unexpected data from server"
4463 " while waiting for agent"
4467 } while (pktin || inlen > 0);
4468 vret = ssh->agent_response;
4469 retlen = ssh->agent_response_len;
4474 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
4475 logevent("Sending Pageant's response");
4476 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4477 PKT_DATA, ret + 5, 16,
4481 if (pktin->type == SSH1_SMSG_SUCCESS) {
4483 ("Pageant's response accepted");
4484 if (flags & FLAG_VERBOSE) {
4485 c_write_str(ssh, "Authenticated using"
4487 c_write(ssh, s->commentp,
4489 c_write_str(ssh, "\" from agent\r\n");
4494 ("Pageant's response not accepted");
4497 ("Pageant failed to answer challenge");
4501 logevent("No reply received from Pageant");
4504 freebn(s->key.exponent);
4505 freebn(s->key.modulus);
4506 freebn(s->challenge);
4511 if (s->publickey_blob && !s->tried_publickey)
4512 logevent("Configured key file not in Pageant");
4514 logevent("Failed to get reply from Pageant");
4519 if (s->publickey_blob && s->privatekey_available &&
4520 !s->tried_publickey) {
4522 * Try public key authentication with the specified
4525 int got_passphrase; /* need not be kept over crReturn */
4526 if (flags & FLAG_VERBOSE)
4527 c_write_str(ssh, "Trying public key authentication.\r\n");
4528 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4529 logeventf(ssh, "Trying public key \"%s\"",
4530 filename_to_str(s->keyfile));
4531 s->tried_publickey = 1;
4532 got_passphrase = FALSE;
4533 while (!got_passphrase) {
4535 * Get a passphrase, if necessary.
4537 char *passphrase = NULL; /* only written after crReturn */
4539 if (!s->privatekey_encrypted) {
4540 if (flags & FLAG_VERBOSE)
4541 c_write_str(ssh, "No passphrase required.\r\n");
4544 int ret; /* need not be kept over crReturn */
4545 s->cur_prompt = new_prompts(ssh->frontend);
4546 s->cur_prompt->to_server = FALSE;
4547 s->cur_prompt->name = dupstr("SSH key passphrase");
4548 add_prompt(s->cur_prompt,
4549 dupprintf("Passphrase for key \"%.100s\": ",
4550 s->publickey_comment), FALSE);
4551 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4554 crWaitUntil(!pktin);
4555 ret = get_userpass_input(s->cur_prompt, in, inlen);
4559 /* Failed to get a passphrase. Terminate. */
4560 free_prompts(s->cur_prompt);
4561 ssh_disconnect(ssh, NULL, "Unable to authenticate",
4565 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
4566 free_prompts(s->cur_prompt);
4569 * Try decrypting key with passphrase.
4571 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4572 ret = loadrsakey(s->keyfile, &s->key, passphrase,
4575 smemclr(passphrase, strlen(passphrase));
4579 /* Correct passphrase. */
4580 got_passphrase = TRUE;
4581 } else if (ret == 0) {
4582 c_write_str(ssh, "Couldn't load private key from ");
4583 c_write_str(ssh, filename_to_str(s->keyfile));
4584 c_write_str(ssh, " (");
4585 c_write_str(ssh, error);
4586 c_write_str(ssh, ").\r\n");
4587 got_passphrase = FALSE;
4588 break; /* go and try something else */
4589 } else if (ret == -1) {
4590 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
4591 got_passphrase = FALSE;
4594 assert(0 && "unexpected return from loadrsakey()");
4595 got_passphrase = FALSE; /* placate optimisers */
4599 if (got_passphrase) {
4602 * Send a public key attempt.
4604 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4605 PKT_BIGNUM, s->key.modulus, PKT_END);
4608 if (pktin->type == SSH1_SMSG_FAILURE) {
4609 c_write_str(ssh, "Server refused our public key.\r\n");
4610 continue; /* go and try something else */
4612 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4613 bombout(("Bizarre response to offer of public key"));
4619 unsigned char buffer[32];
4620 Bignum challenge, response;
4622 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4623 bombout(("Server's RSA challenge was badly formatted"));
4626 response = rsadecrypt(challenge, &s->key);
4627 freebn(s->key.private_exponent);/* burn the evidence */
4629 for (i = 0; i < 32; i++) {
4630 buffer[i] = bignum_byte(response, 31 - i);
4634 MD5Update(&md5c, buffer, 32);
4635 MD5Update(&md5c, s->session_id, 16);
4636 MD5Final(buffer, &md5c);
4638 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4639 PKT_DATA, buffer, 16, PKT_END);
4646 if (pktin->type == SSH1_SMSG_FAILURE) {
4647 if (flags & FLAG_VERBOSE)
4648 c_write_str(ssh, "Failed to authenticate with"
4649 " our public key.\r\n");
4650 continue; /* go and try something else */
4651 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4652 bombout(("Bizarre response to RSA authentication response"));
4656 break; /* we're through! */
4662 * Otherwise, try various forms of password-like authentication.
4664 s->cur_prompt = new_prompts(ssh->frontend);
4666 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4667 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
4668 !s->tis_auth_refused) {
4669 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
4670 logevent("Requested TIS authentication");
4671 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
4673 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
4674 logevent("TIS authentication declined");
4675 if (flags & FLAG_INTERACTIVE)
4676 c_write_str(ssh, "TIS authentication refused.\r\n");
4677 s->tis_auth_refused = 1;
4682 char *instr_suf, *prompt;
4684 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4686 bombout(("TIS challenge packet was badly formed"));
4689 logevent("Received TIS challenge");
4690 s->cur_prompt->to_server = TRUE;
4691 s->cur_prompt->name = dupstr("SSH TIS authentication");
4692 /* Prompt heuristic comes from OpenSSH */
4693 if (memchr(challenge, '\n', challengelen)) {
4694 instr_suf = dupstr("");
4695 prompt = dupprintf("%.*s", challengelen, challenge);
4697 instr_suf = dupprintf("%.*s", challengelen, challenge);
4698 prompt = dupstr("Response: ");
4700 s->cur_prompt->instruction =
4701 dupprintf("Using TIS authentication.%s%s",
4702 (*instr_suf) ? "\n" : "",
4704 s->cur_prompt->instr_reqd = TRUE;
4705 add_prompt(s->cur_prompt, prompt, FALSE);
4709 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4710 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
4711 !s->ccard_auth_refused) {
4712 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
4713 logevent("Requested CryptoCard authentication");
4714 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
4716 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
4717 logevent("CryptoCard authentication declined");
4718 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
4719 s->ccard_auth_refused = 1;
4724 char *instr_suf, *prompt;
4726 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4728 bombout(("CryptoCard challenge packet was badly formed"));
4731 logevent("Received CryptoCard challenge");
4732 s->cur_prompt->to_server = TRUE;
4733 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4734 s->cur_prompt->name_reqd = FALSE;
4735 /* Prompt heuristic comes from OpenSSH */
4736 if (memchr(challenge, '\n', challengelen)) {
4737 instr_suf = dupstr("");
4738 prompt = dupprintf("%.*s", challengelen, challenge);
4740 instr_suf = dupprintf("%.*s", challengelen, challenge);
4741 prompt = dupstr("Response: ");
4743 s->cur_prompt->instruction =
4744 dupprintf("Using CryptoCard authentication.%s%s",
4745 (*instr_suf) ? "\n" : "",
4747 s->cur_prompt->instr_reqd = TRUE;
4748 add_prompt(s->cur_prompt, prompt, FALSE);
4752 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4753 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4754 bombout(("No supported authentication methods available"));
4757 s->cur_prompt->to_server = TRUE;
4758 s->cur_prompt->name = dupstr("SSH password");
4759 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4760 ssh->username, ssh->savedhost),
4765 * Show password prompt, having first obtained it via a TIS
4766 * or CryptoCard exchange if we're doing TIS or CryptoCard
4770 int ret; /* need not be kept over crReturn */
4771 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4774 crWaitUntil(!pktin);
4775 ret = get_userpass_input(s->cur_prompt, in, inlen);
4780 * Failed to get a password (for example
4781 * because one was supplied on the command line
4782 * which has already failed to work). Terminate.
4784 free_prompts(s->cur_prompt);
4785 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4790 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4792 * Defence against traffic analysis: we send a
4793 * whole bunch of packets containing strings of
4794 * different lengths. One of these strings is the
4795 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4796 * The others are all random data in
4797 * SSH1_MSG_IGNORE packets. This way a passive
4798 * listener can't tell which is the password, and
4799 * hence can't deduce the password length.
4801 * Anybody with a password length greater than 16
4802 * bytes is going to have enough entropy in their
4803 * password that a listener won't find it _that_
4804 * much help to know how long it is. So what we'll
4807 * - if password length < 16, we send 15 packets
4808 * containing string lengths 1 through 15
4810 * - otherwise, we let N be the nearest multiple
4811 * of 8 below the password length, and send 8
4812 * packets containing string lengths N through
4813 * N+7. This won't obscure the order of
4814 * magnitude of the password length, but it will
4815 * introduce a bit of extra uncertainty.
4817 * A few servers can't deal with SSH1_MSG_IGNORE, at
4818 * least in this context. For these servers, we need
4819 * an alternative defence. We make use of the fact
4820 * that the password is interpreted as a C string:
4821 * so we can append a NUL, then some random data.
4823 * A few servers can deal with neither SSH1_MSG_IGNORE
4824 * here _nor_ a padded password string.
4825 * For these servers we are left with no defences
4826 * against password length sniffing.
4828 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4829 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4831 * The server can deal with SSH1_MSG_IGNORE, so
4832 * we can use the primary defence.
4834 int bottom, top, pwlen, i;
4837 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4839 bottom = 0; /* zero length passwords are OK! :-) */
4842 bottom = pwlen & ~7;
4846 assert(pwlen >= bottom && pwlen <= top);
4848 randomstr = snewn(top + 1, char);
4850 for (i = bottom; i <= top; i++) {
4852 defer_packet(ssh, s->pwpkt_type,
4853 PKT_STR,s->cur_prompt->prompts[0]->result,
4856 for (j = 0; j < i; j++) {
4858 randomstr[j] = random_byte();
4859 } while (randomstr[j] == '\0');
4861 randomstr[i] = '\0';
4862 defer_packet(ssh, SSH1_MSG_IGNORE,
4863 PKT_STR, randomstr, PKT_END);
4866 logevent("Sending password with camouflage packets");
4867 ssh_pkt_defersend(ssh);
4870 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4872 * The server can't deal with SSH1_MSG_IGNORE
4873 * but can deal with padded passwords, so we
4874 * can use the secondary defence.
4880 len = strlen(s->cur_prompt->prompts[0]->result);
4881 if (len < sizeof(string)) {
4883 strcpy(string, s->cur_prompt->prompts[0]->result);
4884 len++; /* cover the zero byte */
4885 while (len < sizeof(string)) {
4886 string[len++] = (char) random_byte();
4889 ss = s->cur_prompt->prompts[0]->result;
4891 logevent("Sending length-padded password");
4892 send_packet(ssh, s->pwpkt_type,
4893 PKT_INT, len, PKT_DATA, ss, len,
4897 * The server is believed unable to cope with
4898 * any of our password camouflage methods.
4901 len = strlen(s->cur_prompt->prompts[0]->result);
4902 logevent("Sending unpadded password");
4903 send_packet(ssh, s->pwpkt_type,
4905 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4909 send_packet(ssh, s->pwpkt_type,
4910 PKT_STR, s->cur_prompt->prompts[0]->result,
4913 logevent("Sent password");
4914 free_prompts(s->cur_prompt);
4916 if (pktin->type == SSH1_SMSG_FAILURE) {
4917 if (flags & FLAG_VERBOSE)
4918 c_write_str(ssh, "Access denied\r\n");
4919 logevent("Authentication refused");
4920 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4921 bombout(("Strange packet received, type %d", pktin->type));
4927 if (s->publickey_blob) {
4928 sfree(s->publickey_blob);
4929 sfree(s->publickey_comment);
4932 logevent("Authentication successful");
4937 static void ssh_channel_try_eof(struct ssh_channel *c)
4940 assert(c->pending_eof); /* precondition for calling us */
4942 return; /* can't close: not even opened yet */
4943 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4944 return; /* can't send EOF: pending outgoing data */
4946 c->pending_eof = FALSE; /* we're about to send it */
4947 if (ssh->version == 1) {
4948 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4950 c->closes |= CLOSES_SENT_EOF;
4952 struct Packet *pktout;
4953 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4954 ssh2_pkt_adduint32(pktout, c->remoteid);
4955 ssh2_pkt_send(ssh, pktout);
4956 c->closes |= CLOSES_SENT_EOF;
4957 ssh2_channel_check_close(c);
4961 Conf *sshfwd_get_conf(struct ssh_channel *c)
4967 void sshfwd_write_eof(struct ssh_channel *c)
4971 if (ssh->state == SSH_STATE_CLOSED)
4974 if (c->closes & CLOSES_SENT_EOF)
4977 c->pending_eof = TRUE;
4978 ssh_channel_try_eof(c);
4981 void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
4985 if (ssh->state == SSH_STATE_CLOSED)
4990 x11_close(c->u.x11.xconn);
4991 logeventf(ssh, "Forwarded X11 connection terminated due to local "
4995 case CHAN_SOCKDATA_DORMANT:
4996 pfd_close(c->u.pfd.pf);
4997 logeventf(ssh, "Forwarded port closed due to local error: %s", err);
5000 c->type = CHAN_ZOMBIE;
5001 c->pending_eof = FALSE; /* this will confuse a zombie channel */
5003 ssh2_channel_check_close(c);
5006 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
5010 if (ssh->state == SSH_STATE_CLOSED)
5013 return ssh_send_channel_data(c, buf, len);
5016 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
5021 if (ssh->state == SSH_STATE_CLOSED)
5024 if (ssh->version == 1) {
5025 buflimit = SSH1_BUFFER_LIMIT;
5027 buflimit = c->v.v2.locmaxwin;
5028 ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
5030 if (c->throttling_conn && bufsize <= buflimit) {
5031 c->throttling_conn = 0;
5032 ssh_throttle_conn(ssh, -1);
5036 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
5038 struct queued_handler *qh = ssh->qhead;
5042 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
5045 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
5046 ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
5049 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
5050 ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
5054 ssh->qhead = qh->next;
5056 if (ssh->qhead->msg1 > 0) {
5057 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5058 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
5060 if (ssh->qhead->msg2 > 0) {
5061 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5062 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
5065 ssh->qhead = ssh->qtail = NULL;
5068 qh->handler(ssh, pktin, qh->ctx);
5073 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
5074 chandler_fn_t handler, void *ctx)
5076 struct queued_handler *qh;
5078 qh = snew(struct queued_handler);
5081 qh->handler = handler;
5085 if (ssh->qtail == NULL) {
5089 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5090 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
5093 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5094 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
5097 ssh->qtail->next = qh;
5102 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
5104 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
5106 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
5107 SSH2_MSG_REQUEST_SUCCESS)) {
5108 logeventf(ssh, "Remote port forwarding from %s enabled",
5111 logeventf(ssh, "Remote port forwarding from %s refused",
5114 rpf = del234(ssh->rportfwds, pf);
5116 pf->pfrec->remote = NULL;
5121 int ssh_alloc_sharing_rportfwd(Ssh ssh, const char *shost, int sport,
5124 struct ssh_rportfwd *pf = snew(struct ssh_rportfwd);
5127 pf->share_ctx = share_ctx;
5128 pf->shost = dupstr(shost);
5130 pf->sportdesc = NULL;
5131 if (!ssh->rportfwds) {
5132 assert(ssh->version == 2);
5133 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5135 if (add234(ssh->rportfwds, pf) != pf) {
5143 static void ssh_sharing_global_request_response(Ssh ssh, struct Packet *pktin,
5146 share_got_pkt_from_server(ctx, pktin->type,
5147 pktin->body, pktin->length);
5150 void ssh_sharing_queue_global_request(Ssh ssh, void *share_ctx)
5152 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE,
5153 ssh_sharing_global_request_response, share_ctx);
5156 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
5158 struct ssh_portfwd *epf;
5162 if (!ssh->portfwds) {
5163 ssh->portfwds = newtree234(ssh_portcmp);
5166 * Go through the existing port forwardings and tag them
5167 * with status==DESTROY. Any that we want to keep will be
5168 * re-enabled (status==KEEP) as we go through the
5169 * configuration and find out which bits are the same as
5172 struct ssh_portfwd *epf;
5174 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5175 epf->status = DESTROY;
5178 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
5180 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
5181 char *kp, *kp2, *vp, *vp2;
5182 char address_family, type;
5183 int sport,dport,sserv,dserv;
5184 char *sports, *dports, *saddr, *host;
5188 address_family = 'A';
5190 if (*kp == 'A' || *kp == '4' || *kp == '6')
5191 address_family = *kp++;
5192 if (*kp == 'L' || *kp == 'R')
5195 if ((kp2 = host_strchr(kp, ':')) != NULL) {
5197 * There's a colon in the middle of the source port
5198 * string, which means that the part before it is
5199 * actually a source address.
5201 char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp);
5202 saddr = host_strduptrim(saddr_tmp);
5209 sport = atoi(sports);
5213 sport = net_service_lookup(sports);
5215 logeventf(ssh, "Service lookup failed for source"
5216 " port \"%s\"", sports);
5220 if (type == 'L' && !strcmp(val, "D")) {
5221 /* dynamic forwarding */
5228 /* ordinary forwarding */
5230 vp2 = vp + host_strcspn(vp, ":");
5231 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
5235 dport = atoi(dports);
5239 dport = net_service_lookup(dports);
5241 logeventf(ssh, "Service lookup failed for destination"
5242 " port \"%s\"", dports);
5247 if (sport && dport) {
5248 /* Set up a description of the source port. */
5249 struct ssh_portfwd *pfrec, *epfrec;
5251 pfrec = snew(struct ssh_portfwd);
5253 pfrec->saddr = saddr;
5254 pfrec->sserv = sserv ? dupstr(sports) : NULL;
5255 pfrec->sport = sport;
5256 pfrec->daddr = host;
5257 pfrec->dserv = dserv ? dupstr(dports) : NULL;
5258 pfrec->dport = dport;
5259 pfrec->local = NULL;
5260 pfrec->remote = NULL;
5261 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
5262 address_family == '6' ? ADDRTYPE_IPV6 :
5265 epfrec = add234(ssh->portfwds, pfrec);
5266 if (epfrec != pfrec) {
5267 if (epfrec->status == DESTROY) {
5269 * We already have a port forwarding up and running
5270 * with precisely these parameters. Hence, no need
5271 * to do anything; simply re-tag the existing one
5274 epfrec->status = KEEP;
5277 * Anything else indicates that there was a duplicate
5278 * in our input, which we'll silently ignore.
5280 free_portfwd(pfrec);
5282 pfrec->status = CREATE;
5291 * Now go through and destroy any port forwardings which were
5294 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5295 if (epf->status == DESTROY) {
5298 message = dupprintf("%s port forwarding from %s%s%d",
5299 epf->type == 'L' ? "local" :
5300 epf->type == 'R' ? "remote" : "dynamic",
5301 epf->saddr ? epf->saddr : "",
5302 epf->saddr ? ":" : "",
5305 if (epf->type != 'D') {
5306 char *msg2 = dupprintf("%s to %s:%d", message,
5307 epf->daddr, epf->dport);
5312 logeventf(ssh, "Cancelling %s", message);
5315 /* epf->remote or epf->local may be NULL if setting up a
5316 * forwarding failed. */
5318 struct ssh_rportfwd *rpf = epf->remote;
5319 struct Packet *pktout;
5322 * Cancel the port forwarding at the server
5325 if (ssh->version == 1) {
5327 * We cannot cancel listening ports on the
5328 * server side in SSH-1! There's no message
5329 * to support it. Instead, we simply remove
5330 * the rportfwd record from the local end
5331 * so that any connections the server tries
5332 * to make on it are rejected.
5335 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5336 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
5337 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
5339 ssh2_pkt_addstring(pktout, epf->saddr);
5340 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5341 /* XXX: rport_acceptall may not represent
5342 * what was used to open the original connection,
5343 * since it's reconfigurable. */
5344 ssh2_pkt_addstring(pktout, "");
5346 ssh2_pkt_addstring(pktout, "localhost");
5348 ssh2_pkt_adduint32(pktout, epf->sport);
5349 ssh2_pkt_send(ssh, pktout);
5352 del234(ssh->rportfwds, rpf);
5354 } else if (epf->local) {
5355 pfl_terminate(epf->local);
5358 delpos234(ssh->portfwds, i);
5360 i--; /* so we don't skip one in the list */
5364 * And finally, set up any new port forwardings (status==CREATE).
5366 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5367 if (epf->status == CREATE) {
5368 char *sportdesc, *dportdesc;
5369 sportdesc = dupprintf("%s%s%s%s%d%s",
5370 epf->saddr ? epf->saddr : "",
5371 epf->saddr ? ":" : "",
5372 epf->sserv ? epf->sserv : "",
5373 epf->sserv ? "(" : "",
5375 epf->sserv ? ")" : "");
5376 if (epf->type == 'D') {
5379 dportdesc = dupprintf("%s:%s%s%d%s",
5381 epf->dserv ? epf->dserv : "",
5382 epf->dserv ? "(" : "",
5384 epf->dserv ? ")" : "");
5387 if (epf->type == 'L') {
5388 char *err = pfl_listen(epf->daddr, epf->dport,
5389 epf->saddr, epf->sport,
5390 ssh, conf, &epf->local,
5391 epf->addressfamily);
5393 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
5394 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5395 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5396 sportdesc, dportdesc,
5397 err ? " failed: " : "", err ? err : "");
5400 } else if (epf->type == 'D') {
5401 char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport,
5402 ssh, conf, &epf->local,
5403 epf->addressfamily);
5405 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
5406 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5407 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5409 err ? " failed: " : "", err ? err : "");
5414 struct ssh_rportfwd *pf;
5417 * Ensure the remote port forwardings tree exists.
5419 if (!ssh->rportfwds) {
5420 if (ssh->version == 1)
5421 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
5423 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5426 pf = snew(struct ssh_rportfwd);
5427 pf->share_ctx = NULL;
5428 pf->dhost = dupstr(epf->daddr);
5429 pf->dport = epf->dport;
5431 pf->shost = dupstr(epf->saddr);
5432 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5433 pf->shost = dupstr("");
5435 pf->shost = dupstr("localhost");
5437 pf->sport = epf->sport;
5438 if (add234(ssh->rportfwds, pf) != pf) {
5439 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
5440 epf->daddr, epf->dport);
5443 logeventf(ssh, "Requesting remote port %s"
5444 " forward to %s", sportdesc, dportdesc);
5446 pf->sportdesc = sportdesc;
5451 if (ssh->version == 1) {
5452 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
5453 PKT_INT, epf->sport,
5454 PKT_STR, epf->daddr,
5455 PKT_INT, epf->dport,
5457 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
5459 ssh_rportfwd_succfail, pf);
5461 struct Packet *pktout;
5462 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5463 ssh2_pkt_addstring(pktout, "tcpip-forward");
5464 ssh2_pkt_addbool(pktout, 1);/* want reply */
5465 ssh2_pkt_addstring(pktout, pf->shost);
5466 ssh2_pkt_adduint32(pktout, pf->sport);
5467 ssh2_pkt_send(ssh, pktout);
5469 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
5470 SSH2_MSG_REQUEST_FAILURE,
5471 ssh_rportfwd_succfail, pf);
5480 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
5483 int stringlen, bufsize;
5485 ssh_pkt_getstring(pktin, &string, &stringlen);
5486 if (string == NULL) {
5487 bombout(("Incoming terminal data packet was badly formed"));
5491 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
5493 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
5494 ssh->v1_stdout_throttling = 1;
5495 ssh_throttle_conn(ssh, +1);
5499 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
5501 /* Remote side is trying to open a channel to talk to our
5502 * X-Server. Give them back a local channel number. */
5503 struct ssh_channel *c;
5504 int remoteid = ssh_pkt_getuint32(pktin);
5506 logevent("Received X11 connect request");
5507 /* Refuse if X11 forwarding is disabled. */
5508 if (!ssh->X11_fwd_enabled) {
5509 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5510 PKT_INT, remoteid, PKT_END);
5511 logevent("Rejected X11 connect request");
5513 c = snew(struct ssh_channel);
5516 c->u.x11.xconn = x11_init(ssh->x11authtree, c, NULL, -1);
5517 c->remoteid = remoteid;
5518 c->halfopen = FALSE;
5519 c->localid = alloc_channel_id(ssh);
5521 c->pending_eof = FALSE;
5522 c->throttling_conn = 0;
5523 c->type = CHAN_X11; /* identify channel type */
5524 add234(ssh->channels, c);
5525 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5526 PKT_INT, c->remoteid, PKT_INT,
5527 c->localid, PKT_END);
5528 logevent("Opened X11 forward channel");
5532 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
5534 /* Remote side is trying to open a channel to talk to our
5535 * agent. Give them back a local channel number. */
5536 struct ssh_channel *c;
5537 int remoteid = ssh_pkt_getuint32(pktin);
5539 /* Refuse if agent forwarding is disabled. */
5540 if (!ssh->agentfwd_enabled) {
5541 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5542 PKT_INT, remoteid, PKT_END);
5544 c = snew(struct ssh_channel);
5546 c->remoteid = remoteid;
5547 c->halfopen = FALSE;
5548 c->localid = alloc_channel_id(ssh);
5550 c->pending_eof = FALSE;
5551 c->throttling_conn = 0;
5552 c->type = CHAN_AGENT; /* identify channel type */
5553 c->u.a.lensofar = 0;
5554 c->u.a.message = NULL;
5555 c->u.a.outstanding_requests = 0;
5556 add234(ssh->channels, c);
5557 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5558 PKT_INT, c->remoteid, PKT_INT, c->localid,
5563 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
5565 /* Remote side is trying to open a channel to talk to a
5566 * forwarded port. Give them back a local channel number. */
5567 struct ssh_rportfwd pf, *pfp;
5573 remoteid = ssh_pkt_getuint32(pktin);
5574 ssh_pkt_getstring(pktin, &host, &hostsize);
5575 port = ssh_pkt_getuint32(pktin);
5577 pf.dhost = dupprintf("%.*s", hostsize, NULLTOEMPTY(host));
5579 pfp = find234(ssh->rportfwds, &pf, NULL);
5582 logeventf(ssh, "Rejected remote port open request for %s:%d",
5584 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5585 PKT_INT, remoteid, PKT_END);
5587 struct ssh_channel *c = snew(struct ssh_channel);
5590 logeventf(ssh, "Received remote port open request for %s:%d",
5592 err = pfd_connect(&c->u.pfd.pf, pf.dhost, port,
5593 c, ssh->conf, pfp->pfrec->addressfamily);
5595 logeventf(ssh, "Port open failed: %s", err);
5598 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5599 PKT_INT, remoteid, PKT_END);
5601 c->remoteid = remoteid;
5602 c->halfopen = FALSE;
5603 c->localid = alloc_channel_id(ssh);
5605 c->pending_eof = FALSE;
5606 c->throttling_conn = 0;
5607 c->type = CHAN_SOCKDATA; /* identify channel type */
5608 add234(ssh->channels, c);
5609 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5610 PKT_INT, c->remoteid, PKT_INT,
5611 c->localid, PKT_END);
5612 logevent("Forwarded port opened successfully");
5619 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
5621 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5622 unsigned int localid = ssh_pkt_getuint32(pktin);
5623 struct ssh_channel *c;
5625 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5626 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5627 c->remoteid = localid;
5628 c->halfopen = FALSE;
5629 c->type = CHAN_SOCKDATA;
5630 c->throttling_conn = 0;
5631 pfd_confirm(c->u.pfd.pf);
5634 if (c && c->pending_eof) {
5636 * We have a pending close on this channel,
5637 * which we decided on before the server acked
5638 * the channel open. So now we know the
5639 * remoteid, we can close it again.
5641 ssh_channel_try_eof(c);
5645 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
5647 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5648 struct ssh_channel *c;
5650 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5651 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5652 logevent("Forwarded connection refused by server");
5653 pfd_close(c->u.pfd.pf);
5654 del234(ssh->channels, c);
5659 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
5661 /* Remote side closes a channel. */
5662 unsigned i = ssh_pkt_getuint32(pktin);
5663 struct ssh_channel *c;
5664 c = find234(ssh->channels, &i, ssh_channelfind);
5665 if (c && !c->halfopen) {
5667 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
5668 !(c->closes & CLOSES_RCVD_EOF)) {
5670 * Received CHANNEL_CLOSE, which we translate into
5673 int send_close = FALSE;
5675 c->closes |= CLOSES_RCVD_EOF;
5680 x11_send_eof(c->u.x11.xconn);
5686 pfd_send_eof(c->u.pfd.pf);
5695 if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
5696 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
5698 c->closes |= CLOSES_SENT_EOF;
5702 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
5703 !(c->closes & CLOSES_RCVD_CLOSE)) {
5705 if (!(c->closes & CLOSES_SENT_EOF)) {
5706 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %d"
5707 " for which we never sent CHANNEL_CLOSE\n", i));
5710 c->closes |= CLOSES_RCVD_CLOSE;
5713 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
5714 !(c->closes & CLOSES_SENT_CLOSE)) {
5715 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
5716 PKT_INT, c->remoteid, PKT_END);
5717 c->closes |= CLOSES_SENT_CLOSE;
5720 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
5721 ssh_channel_destroy(c);
5723 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
5724 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
5725 "_CONFIRMATION", c ? "half-open" : "nonexistent",
5731 * Handle incoming data on an SSH-1 or SSH-2 agent-forwarding channel.
5733 static int ssh_agent_channel_data(struct ssh_channel *c, char *data,
5736 while (length > 0) {
5737 if (c->u.a.lensofar < 4) {
5738 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)length);
5739 memcpy(c->u.a.msglen + c->u.a.lensofar, data, l);
5742 c->u.a.lensofar += l;
5744 if (c->u.a.lensofar == 4) {
5745 c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
5746 c->u.a.message = snewn(c->u.a.totallen, unsigned char);
5747 memcpy(c->u.a.message, c->u.a.msglen, 4);
5749 if (c->u.a.lensofar >= 4 && length > 0) {
5750 unsigned int l = min(c->u.a.totallen - c->u.a.lensofar,
5752 memcpy(c->u.a.message + c->u.a.lensofar, data, l);
5755 c->u.a.lensofar += l;
5757 if (c->u.a.lensofar == c->u.a.totallen) {
5760 c->u.a.outstanding_requests++;
5761 if (agent_query(c->u.a.message, c->u.a.totallen, &reply, &replylen,
5762 ssh_agentf_callback, c))
5763 ssh_agentf_callback(c, reply, replylen);
5764 sfree(c->u.a.message);
5765 c->u.a.message = NULL;
5766 c->u.a.lensofar = 0;
5769 return 0; /* agent channels never back up */
5772 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
5774 /* Data sent down one of our channels. */
5775 int i = ssh_pkt_getuint32(pktin);
5778 struct ssh_channel *c;
5780 ssh_pkt_getstring(pktin, &p, &len);
5782 c = find234(ssh->channels, &i, ssh_channelfind);
5787 bufsize = x11_send(c->u.x11.xconn, p, len);
5790 bufsize = pfd_send(c->u.pfd.pf, p, len);
5793 bufsize = ssh_agent_channel_data(c, p, len);
5796 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5797 c->throttling_conn = 1;
5798 ssh_throttle_conn(ssh, +1);
5803 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5805 ssh->exitcode = ssh_pkt_getuint32(pktin);
5806 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5807 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5809 * In case `helpful' firewalls or proxies tack
5810 * extra human-readable text on the end of the
5811 * session which we might mistake for another
5812 * encrypted packet, we close the session once
5813 * we've sent EXIT_CONFIRMATION.
5815 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5818 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5819 static void ssh1_send_ttymode(void *data, char *mode, char *val)
5821 struct Packet *pktout = (struct Packet *)data;
5823 unsigned int arg = 0;
5824 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
5825 if (i == lenof(ssh_ttymodes)) return;
5826 switch (ssh_ttymodes[i].type) {
5828 arg = ssh_tty_parse_specchar(val);
5831 arg = ssh_tty_parse_boolean(val);
5834 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
5835 ssh2_pkt_addbyte(pktout, arg);
5838 int ssh_agent_forwarding_permitted(Ssh ssh)
5840 return conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists();
5843 static void do_ssh1_connection(Ssh ssh, const unsigned char *in, int inlen,
5844 struct Packet *pktin)
5846 crBegin(ssh->do_ssh1_connection_crstate);
5848 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5849 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5850 ssh1_smsg_stdout_stderr_data;
5852 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5853 ssh1_msg_channel_open_confirmation;
5854 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5855 ssh1_msg_channel_open_failure;
5856 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5857 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5858 ssh1_msg_channel_close;
5859 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5860 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5862 if (ssh_agent_forwarding_permitted(ssh)) {
5863 logevent("Requesting agent forwarding");
5864 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5868 if (pktin->type != SSH1_SMSG_SUCCESS
5869 && pktin->type != SSH1_SMSG_FAILURE) {
5870 bombout(("Protocol confusion"));
5872 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5873 logevent("Agent forwarding refused");
5875 logevent("Agent forwarding enabled");
5876 ssh->agentfwd_enabled = TRUE;
5877 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5881 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
5883 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5885 if (!ssh->x11disp) {
5886 /* FIXME: return an error message from x11_setup_display */
5887 logevent("X11 forwarding not enabled: unable to"
5888 " initialise X display");
5890 ssh->x11auth = x11_invent_fake_auth
5891 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
5892 ssh->x11auth->disp = ssh->x11disp;
5894 logevent("Requesting X11 forwarding");
5895 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5896 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5897 PKT_STR, ssh->x11auth->protoname,
5898 PKT_STR, ssh->x11auth->datastring,
5899 PKT_INT, ssh->x11disp->screennum,
5902 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5903 PKT_STR, ssh->x11auth->protoname,
5904 PKT_STR, ssh->x11auth->datastring,
5910 if (pktin->type != SSH1_SMSG_SUCCESS
5911 && pktin->type != SSH1_SMSG_FAILURE) {
5912 bombout(("Protocol confusion"));
5914 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5915 logevent("X11 forwarding refused");
5917 logevent("X11 forwarding enabled");
5918 ssh->X11_fwd_enabled = TRUE;
5919 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5924 ssh_setup_portfwd(ssh, ssh->conf);
5925 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5927 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5929 /* Unpick the terminal-speed string. */
5930 /* XXX perhaps we should allow no speeds to be sent. */
5931 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5932 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5933 /* Send the pty request. */
5934 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5935 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5936 ssh_pkt_adduint32(pkt, ssh->term_height);
5937 ssh_pkt_adduint32(pkt, ssh->term_width);
5938 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5939 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5940 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5941 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5942 ssh_pkt_adduint32(pkt, ssh->ispeed);
5943 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5944 ssh_pkt_adduint32(pkt, ssh->ospeed);
5945 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5947 ssh->state = SSH_STATE_INTERMED;
5951 if (pktin->type != SSH1_SMSG_SUCCESS
5952 && pktin->type != SSH1_SMSG_FAILURE) {
5953 bombout(("Protocol confusion"));
5955 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5956 c_write_str(ssh, "Server refused to allocate pty\r\n");
5957 ssh->editing = ssh->echoing = 1;
5959 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5960 ssh->ospeed, ssh->ispeed);
5961 ssh->got_pty = TRUE;
5964 ssh->editing = ssh->echoing = 1;
5967 if (conf_get_int(ssh->conf, CONF_compression)) {
5968 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5972 if (pktin->type != SSH1_SMSG_SUCCESS
5973 && pktin->type != SSH1_SMSG_FAILURE) {
5974 bombout(("Protocol confusion"));
5976 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5977 c_write_str(ssh, "Server refused to compress\r\n");
5979 logevent("Started compression");
5980 ssh->v1_compressing = TRUE;
5981 ssh->cs_comp_ctx = zlib_compress_init();
5982 logevent("Initialised zlib (RFC1950) compression");
5983 ssh->sc_comp_ctx = zlib_decompress_init();
5984 logevent("Initialised zlib (RFC1950) decompression");
5988 * Start the shell or command.
5990 * Special case: if the first-choice command is an SSH-2
5991 * subsystem (hence not usable here) and the second choice
5992 * exists, we fall straight back to that.
5995 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
5997 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
5998 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
5999 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
6000 ssh->fallback_cmd = TRUE;
6003 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
6005 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
6006 logevent("Started session");
6009 ssh->state = SSH_STATE_SESSION;
6010 if (ssh->size_needed)
6011 ssh_size(ssh, ssh->term_width, ssh->term_height);
6012 if (ssh->eof_needed)
6013 ssh_special(ssh, TS_EOF);
6016 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
6018 ssh->channels = newtree234(ssh_channelcmp);
6022 * By this point, most incoming packets are already being
6023 * handled by the dispatch table, and we need only pay
6024 * attention to the unusual ones.
6029 if (pktin->type == SSH1_SMSG_SUCCESS) {
6030 /* may be from EXEC_SHELL on some servers */
6031 } else if (pktin->type == SSH1_SMSG_FAILURE) {
6032 /* may be from EXEC_SHELL on some servers
6033 * if no pty is available or in other odd cases. Ignore */
6035 bombout(("Strange packet received: type %d", pktin->type));
6040 int len = min(inlen, 512);
6041 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
6042 PKT_INT, len, PKT_DATA, in, len,
6054 * Handle the top-level SSH-2 protocol.
6056 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
6061 ssh_pkt_getstring(pktin, &msg, &msglen);
6062 logeventf(ssh, "Remote debug message: %.*s", msglen, NULLTOEMPTY(msg));
6065 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
6067 /* log reason code in disconnect message */
6071 ssh_pkt_getstring(pktin, &msg, &msglen);
6072 bombout(("Server sent disconnect message:\n\"%.*s\"",
6073 msglen, NULLTOEMPTY(msg)));
6076 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
6078 /* Do nothing, because we're ignoring it! Duhh. */
6081 static void ssh1_protocol_setup(Ssh ssh)
6086 * Most messages are handled by the coroutines.
6088 for (i = 0; i < 256; i++)
6089 ssh->packet_dispatch[i] = NULL;
6092 * These special message types we install handlers for.
6094 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
6095 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
6096 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
6099 static void ssh1_protocol(Ssh ssh, const void *vin, int inlen,
6100 struct Packet *pktin)
6102 const unsigned char *in = (const unsigned char *)vin;
6103 if (ssh->state == SSH_STATE_CLOSED)
6106 if (pktin && ssh->packet_dispatch[pktin->type]) {
6107 ssh->packet_dispatch[pktin->type](ssh, pktin);
6111 if (!ssh->protocol_initial_phase_done) {
6112 if (do_ssh1_login(ssh, in, inlen, pktin))
6113 ssh->protocol_initial_phase_done = TRUE;
6118 do_ssh1_connection(ssh, in, inlen, pktin);
6122 * Utility routines for decoding comma-separated strings in KEXINIT.
6124 static int first_in_commasep_string(char const *needle, char const *haystack,
6128 if (!needle || !haystack) /* protect against null pointers */
6130 needlen = strlen(needle);
6132 if (haylen >= needlen && /* haystack is long enough */
6133 !memcmp(needle, haystack, needlen) && /* initial match */
6134 (haylen == needlen || haystack[needlen] == ',')
6135 /* either , or EOS follows */
6141 static int in_commasep_string(char const *needle, char const *haystack,
6146 if (!needle || !haystack) /* protect against null pointers */
6149 * Is it at the start of the string?
6151 if (first_in_commasep_string(needle, haystack, haylen))
6154 * If not, search for the next comma and resume after that.
6155 * If no comma found, terminate.
6157 p = memchr(haystack, ',', haylen);
6159 /* + 1 to skip over comma */
6160 return in_commasep_string(needle, p + 1, haylen - (p + 1 - haystack));
6164 * Add a value to the comma-separated string at the end of the packet.
6166 static void ssh2_pkt_addstring_commasep(struct Packet *pkt, const char *data)
6168 if (pkt->length - pkt->savedpos > 0)
6169 ssh_pkt_addstring_str(pkt, ",");
6170 ssh_pkt_addstring_str(pkt, data);
6175 * SSH-2 key derivation (RFC 4253 section 7.2).
6177 static unsigned char *ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H,
6178 char chr, int keylen)
6180 const struct ssh_hash *h = ssh->kex->hash;
6188 /* Round up to the next multiple of hash length. */
6189 keylen_padded = ((keylen + h->hlen - 1) / h->hlen) * h->hlen;
6191 key = snewn(keylen_padded, unsigned char);
6193 /* First hlen bytes. */
6195 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6196 hash_mpint(h, s, K);
6197 h->bytes(s, H, h->hlen);
6198 h->bytes(s, &chr, 1);
6199 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
6202 /* Subsequent blocks of hlen bytes. */
6203 if (keylen_padded > h->hlen) {
6207 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6208 hash_mpint(h, s, K);
6209 h->bytes(s, H, h->hlen);
6211 for (offset = h->hlen; offset < keylen_padded; offset += h->hlen) {
6212 h->bytes(s, key + offset - h->hlen, h->hlen);
6214 h->final(s2, key + offset);
6220 /* Now clear any extra bytes of key material beyond the length
6221 * we're officially returning, because the caller won't know to
6223 if (keylen_padded > keylen)
6224 smemclr(key + keylen, keylen_padded - keylen);
6230 * Structure for constructing KEXINIT algorithm lists.
6232 #define MAXKEXLIST 16
6233 struct kexinit_algorithm {
6237 const struct ssh_kex *kex;
6241 const struct ssh_signkey *hostkey;
6245 const struct ssh2_cipher *cipher;
6249 const struct ssh_mac *mac;
6252 const struct ssh_compress *comp;
6257 * Find a slot in a KEXINIT algorithm list to use for a new algorithm.
6258 * If the algorithm is already in the list, return a pointer to its
6259 * entry, otherwise return an entry from the end of the list.
6260 * This assumes that every time a particular name is passed in, it
6261 * comes from the same string constant. If this isn't true, this
6262 * function may need to be rewritten to use strcmp() instead.
6264 static struct kexinit_algorithm *ssh2_kexinit_addalg(struct kexinit_algorithm
6265 *list, const char *name)
6269 for (i = 0; i < MAXKEXLIST; i++)
6270 if (list[i].name == NULL || list[i].name == name) {
6271 list[i].name = name;
6274 assert(!"No space in KEXINIT list");
6279 * Handle the SSH-2 transport layer.
6281 static void do_ssh2_transport(Ssh ssh, const void *vin, int inlen,
6282 struct Packet *pktin)
6284 const unsigned char *in = (const unsigned char *)vin;
6286 KEXLIST_KEX, KEXLIST_HOSTKEY, KEXLIST_CSCIPHER, KEXLIST_SCCIPHER,
6287 KEXLIST_CSMAC, KEXLIST_SCMAC, KEXLIST_CSCOMP, KEXLIST_SCCOMP,
6290 const char * kexlist_descr[NKEXLIST] = {
6291 "key exchange algorithm", "host key algorithm",
6292 "client-to-server cipher", "server-to-client cipher",
6293 "client-to-server MAC", "server-to-client MAC",
6294 "client-to-server compression method",
6295 "server-to-client compression method" };
6296 struct do_ssh2_transport_state {
6298 int nbits, pbits, warn_kex, warn_hk, warn_cscipher, warn_sccipher;
6299 Bignum p, g, e, f, K;
6302 int kex_init_value, kex_reply_value;
6303 const struct ssh_mac *const *maclist;
6305 const struct ssh2_cipher *cscipher_tobe;
6306 const struct ssh2_cipher *sccipher_tobe;
6307 const struct ssh_mac *csmac_tobe;
6308 const struct ssh_mac *scmac_tobe;
6309 int csmac_etm_tobe, scmac_etm_tobe;
6310 const struct ssh_compress *cscomp_tobe;
6311 const struct ssh_compress *sccomp_tobe;
6312 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
6313 int hostkeylen, siglen, rsakeylen;
6314 void *hkey; /* actual host key */
6315 void *rsakey; /* for RSA kex */
6316 void *eckey; /* for ECDH kex */
6317 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
6318 int n_preferred_kex;
6319 const struct ssh_kexes *preferred_kex[KEX_MAX];
6321 int preferred_hk[HK_MAX];
6322 int n_preferred_ciphers;
6323 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
6324 const struct ssh_compress *preferred_comp;
6325 int userauth_succeeded; /* for delayed compression */
6326 int pending_compression;
6327 int got_session_id, activated_authconn;
6328 struct Packet *pktout;
6332 struct kexinit_algorithm kexlists[NKEXLIST][MAXKEXLIST];
6334 crState(do_ssh2_transport_state);
6336 assert(!ssh->bare_connection);
6337 assert(ssh->version == 2);
6341 s->cscipher_tobe = s->sccipher_tobe = NULL;
6342 s->csmac_tobe = s->scmac_tobe = NULL;
6343 s->cscomp_tobe = s->sccomp_tobe = NULL;
6345 s->got_session_id = s->activated_authconn = FALSE;
6346 s->userauth_succeeded = FALSE;
6347 s->pending_compression = FALSE;
6350 * Be prepared to work around the buggy MAC problem.
6352 if (ssh->remote_bugs & BUG_SSH2_HMAC)
6353 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
6355 s->maclist = macs, s->nmacs = lenof(macs);
6358 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
6361 struct kexinit_algorithm *alg;
6364 * Set up the preferred key exchange. (NULL => warn below here)
6366 s->n_preferred_kex = 0;
6367 for (i = 0; i < KEX_MAX; i++) {
6368 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
6370 s->preferred_kex[s->n_preferred_kex++] =
6371 &ssh_diffiehellman_gex;
6374 s->preferred_kex[s->n_preferred_kex++] =
6375 &ssh_diffiehellman_group14;
6378 s->preferred_kex[s->n_preferred_kex++] =
6379 &ssh_diffiehellman_group1;
6382 s->preferred_kex[s->n_preferred_kex++] =
6386 s->preferred_kex[s->n_preferred_kex++] =
6390 /* Flag for later. Don't bother if it's the last in
6392 if (i < KEX_MAX - 1) {
6393 s->preferred_kex[s->n_preferred_kex++] = NULL;
6400 * Set up the preferred host key types. These are just the ids
6401 * in the enum in putty.h, so 'warn below here' is indicated
6404 s->n_preferred_hk = 0;
6405 for (i = 0; i < HK_MAX; i++) {
6406 int id = conf_get_int_int(ssh->conf, CONF_ssh_hklist, i);
6407 /* As above, don't bother with HK_WARN if it's last in the
6409 if (id != HK_WARN || i < HK_MAX - 1)
6410 s->preferred_hk[s->n_preferred_hk++] = id;
6414 * Set up the preferred ciphers. (NULL => warn below here)
6416 s->n_preferred_ciphers = 0;
6417 for (i = 0; i < CIPHER_MAX; i++) {
6418 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
6419 case CIPHER_BLOWFISH:
6420 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
6423 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
6424 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
6428 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
6431 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
6433 case CIPHER_ARCFOUR:
6434 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
6436 case CIPHER_CHACHA20:
6437 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_ccp;
6440 /* Flag for later. Don't bother if it's the last in
6442 if (i < CIPHER_MAX - 1) {
6443 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
6450 * Set up preferred compression.
6452 if (conf_get_int(ssh->conf, CONF_compression))
6453 s->preferred_comp = &ssh_zlib;
6455 s->preferred_comp = &ssh_comp_none;
6458 * Enable queueing of outgoing auth- or connection-layer
6459 * packets while we are in the middle of a key exchange.
6461 ssh->queueing = TRUE;
6464 * Flag that KEX is in progress.
6466 ssh->kex_in_progress = TRUE;
6468 for (i = 0; i < NKEXLIST; i++)
6469 for (j = 0; j < MAXKEXLIST; j++)
6470 s->kexlists[i][j].name = NULL;
6471 /* List key exchange algorithms. */
6473 for (i = 0; i < s->n_preferred_kex; i++) {
6474 const struct ssh_kexes *k = s->preferred_kex[i];
6475 if (!k) warn = TRUE;
6476 else for (j = 0; j < k->nkexes; j++) {
6477 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_KEX],
6479 alg->u.kex.kex = k->list[j];
6480 alg->u.kex.warn = warn;
6483 /* List server host key algorithms. */
6484 if (!s->got_session_id) {
6486 * In the first key exchange, we list all the algorithms
6487 * we're prepared to cope with, but prefer those algorithms
6488 * for which we have a host key for this host.
6490 * If the host key algorithm is below the warning
6491 * threshold, we warn even if we did already have a key
6492 * for it, on the basis that if the user has just
6493 * reconfigured that host key type to be warned about,
6494 * they surely _do_ want to be alerted that a server
6495 * they're actually connecting to is using it.
6498 for (i = 0; i < s->n_preferred_hk; i++) {
6499 if (s->preferred_hk[i] == HK_WARN)
6501 for (j = 0; j < lenof(hostkey_algs); j++) {
6502 if (hostkey_algs[j].id != s->preferred_hk[i])
6504 if (have_ssh_host_key(ssh->savedhost, ssh->savedport,
6505 hostkey_algs[j].alg->keytype)) {
6506 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6507 hostkey_algs[j].alg->name);
6508 alg->u.hk.hostkey = hostkey_algs[j].alg;
6509 alg->u.hk.warn = warn;
6514 for (i = 0; i < s->n_preferred_hk; i++) {
6515 if (s->preferred_hk[i] == HK_WARN)
6517 for (j = 0; j < lenof(hostkey_algs); j++) {
6518 if (hostkey_algs[j].id != s->preferred_hk[i])
6520 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6521 hostkey_algs[j].alg->name);
6522 alg->u.hk.hostkey = hostkey_algs[j].alg;
6523 alg->u.hk.warn = warn;
6528 * In subsequent key exchanges, we list only the kex
6529 * algorithm that was selected in the first key exchange,
6530 * so that we keep getting the same host key and hence
6531 * don't have to interrupt the user's session to ask for
6535 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6536 ssh->hostkey->name);
6537 alg->u.hk.hostkey = ssh->hostkey;
6538 alg->u.hk.warn = FALSE;
6540 /* List encryption algorithms (client->server then server->client). */
6541 for (k = KEXLIST_CSCIPHER; k <= KEXLIST_SCCIPHER; k++) {
6544 alg = ssh2_kexinit_addalg(s->kexlists[k], "none");
6545 alg->u.cipher.cipher = NULL;
6546 alg->u.cipher.warn = warn;
6547 #endif /* FUZZING */
6548 for (i = 0; i < s->n_preferred_ciphers; i++) {
6549 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6550 if (!c) warn = TRUE;
6551 else for (j = 0; j < c->nciphers; j++) {
6552 alg = ssh2_kexinit_addalg(s->kexlists[k],
6554 alg->u.cipher.cipher = c->list[j];
6555 alg->u.cipher.warn = warn;
6559 /* List MAC algorithms (client->server then server->client). */
6560 for (j = KEXLIST_CSMAC; j <= KEXLIST_SCMAC; j++) {
6562 alg = ssh2_kexinit_addalg(s->kexlists[j], "none");
6563 alg->u.mac.mac = NULL;
6564 alg->u.mac.etm = FALSE;
6565 #endif /* FUZZING */
6566 for (i = 0; i < s->nmacs; i++) {
6567 alg = ssh2_kexinit_addalg(s->kexlists[j], s->maclist[i]->name);
6568 alg->u.mac.mac = s->maclist[i];
6569 alg->u.mac.etm = FALSE;
6571 for (i = 0; i < s->nmacs; i++)
6572 /* For each MAC, there may also be an ETM version,
6573 * which we list second. */
6574 if (s->maclist[i]->etm_name) {
6575 alg = ssh2_kexinit_addalg(s->kexlists[j],
6576 s->maclist[i]->etm_name);
6577 alg->u.mac.mac = s->maclist[i];
6578 alg->u.mac.etm = TRUE;
6581 /* List client->server compression algorithms,
6582 * then server->client compression algorithms. (We use the
6583 * same set twice.) */
6584 for (j = KEXLIST_CSCOMP; j <= KEXLIST_SCCOMP; j++) {
6585 assert(lenof(compressions) > 1);
6586 /* Prefer non-delayed versions */
6587 alg = ssh2_kexinit_addalg(s->kexlists[j], s->preferred_comp->name);
6588 alg->u.comp = s->preferred_comp;
6589 /* We don't even list delayed versions of algorithms until
6590 * they're allowed to be used, to avoid a race. See the end of
6592 if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
6593 alg = ssh2_kexinit_addalg(s->kexlists[j],
6594 s->preferred_comp->delayed_name);
6595 alg->u.comp = s->preferred_comp;
6597 for (i = 0; i < lenof(compressions); i++) {
6598 const struct ssh_compress *c = compressions[i];
6599 alg = ssh2_kexinit_addalg(s->kexlists[j], c->name);
6601 if (s->userauth_succeeded && c->delayed_name) {
6602 alg = ssh2_kexinit_addalg(s->kexlists[j], c->delayed_name);
6608 * Construct and send our key exchange packet.
6610 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
6611 for (i = 0; i < 16; i++)
6612 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
6613 for (i = 0; i < NKEXLIST; i++) {
6614 ssh2_pkt_addstring_start(s->pktout);
6615 for (j = 0; j < MAXKEXLIST; j++) {
6616 if (s->kexlists[i][j].name == NULL) break;
6617 ssh2_pkt_addstring_commasep(s->pktout, s->kexlists[i][j].name);
6620 /* List client->server languages. Empty list. */
6621 ssh2_pkt_addstring_start(s->pktout);
6622 /* List server->client languages. Empty list. */
6623 ssh2_pkt_addstring_start(s->pktout);
6624 /* First KEX packet does _not_ follow, because we're not that brave. */
6625 ssh2_pkt_addbool(s->pktout, FALSE);
6627 ssh2_pkt_adduint32(s->pktout, 0);
6630 s->our_kexinitlen = s->pktout->length - 5;
6631 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
6632 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
6634 ssh2_pkt_send_noqueue(ssh, s->pktout);
6637 crWaitUntilV(pktin);
6640 * Now examine the other side's KEXINIT to see what we're up
6647 if (pktin->type != SSH2_MSG_KEXINIT) {
6648 bombout(("expected key exchange packet from server"));
6652 ssh->hostkey = NULL;
6653 s->cscipher_tobe = NULL;
6654 s->sccipher_tobe = NULL;
6655 s->csmac_tobe = NULL;
6656 s->scmac_tobe = NULL;
6657 s->cscomp_tobe = NULL;
6658 s->sccomp_tobe = NULL;
6659 s->warn_kex = s->warn_hk = FALSE;
6660 s->warn_cscipher = s->warn_sccipher = FALSE;
6662 pktin->savedpos += 16; /* skip garbage cookie */
6665 for (i = 0; i < NKEXLIST; i++) {
6666 ssh_pkt_getstring(pktin, &str, &len);
6668 bombout(("KEXINIT packet was incomplete"));
6672 /* If we've already selected a cipher which requires a
6673 * particular MAC, then just select that, and don't even
6674 * bother looking through the server's KEXINIT string for
6676 if (i == KEXLIST_CSMAC && s->cscipher_tobe &&
6677 s->cscipher_tobe->required_mac) {
6678 s->csmac_tobe = s->cscipher_tobe->required_mac;
6679 s->csmac_etm_tobe = !!(s->csmac_tobe->etm_name);
6682 if (i == KEXLIST_SCMAC && s->sccipher_tobe &&
6683 s->sccipher_tobe->required_mac) {
6684 s->scmac_tobe = s->sccipher_tobe->required_mac;
6685 s->scmac_etm_tobe = !!(s->scmac_tobe->etm_name);
6689 for (j = 0; j < MAXKEXLIST; j++) {
6690 struct kexinit_algorithm *alg = &s->kexlists[i][j];
6691 if (alg->name == NULL) break;
6692 if (in_commasep_string(alg->name, str, len)) {
6693 /* We've found a matching algorithm. */
6694 if (i == KEXLIST_KEX || i == KEXLIST_HOSTKEY) {
6695 /* Check if we might need to ignore first kex pkt */
6697 !first_in_commasep_string(alg->name, str, len))
6700 if (i == KEXLIST_KEX) {
6701 ssh->kex = alg->u.kex.kex;
6702 s->warn_kex = alg->u.kex.warn;
6703 } else if (i == KEXLIST_HOSTKEY) {
6704 ssh->hostkey = alg->u.hk.hostkey;
6705 s->warn_hk = alg->u.hk.warn;
6706 } else if (i == KEXLIST_CSCIPHER) {
6707 s->cscipher_tobe = alg->u.cipher.cipher;
6708 s->warn_cscipher = alg->u.cipher.warn;
6709 } else if (i == KEXLIST_SCCIPHER) {
6710 s->sccipher_tobe = alg->u.cipher.cipher;
6711 s->warn_sccipher = alg->u.cipher.warn;
6712 } else if (i == KEXLIST_CSMAC) {
6713 s->csmac_tobe = alg->u.mac.mac;
6714 s->csmac_etm_tobe = alg->u.mac.etm;
6715 } else if (i == KEXLIST_SCMAC) {
6716 s->scmac_tobe = alg->u.mac.mac;
6717 s->scmac_etm_tobe = alg->u.mac.etm;
6718 } else if (i == KEXLIST_CSCOMP) {
6719 s->cscomp_tobe = alg->u.comp;
6720 } else if (i == KEXLIST_SCCOMP) {
6721 s->sccomp_tobe = alg->u.comp;
6725 if ((i == KEXLIST_CSCOMP || i == KEXLIST_SCCOMP) &&
6726 in_commasep_string(alg->u.comp->delayed_name, str, len))
6727 s->pending_compression = TRUE; /* try this later */
6729 bombout(("Couldn't agree a %s (available: %.*s)",
6730 kexlist_descr[i], len, str));
6734 if (i == KEXLIST_HOSTKEY) {
6738 * In addition to deciding which host key we're
6739 * actually going to use, we should make a list of the
6740 * host keys offered by the server which we _don't_
6741 * have cached. These will be offered as cross-
6742 * certification options by ssh_get_specials.
6744 * We also count the key we're currently using for KEX
6745 * as one we've already got, because by the time this
6746 * menu becomes visible, it will be.
6748 ssh->n_uncert_hostkeys = 0;
6750 for (j = 0; j < lenof(hostkey_algs); j++) {
6751 if (hostkey_algs[j].alg != ssh->hostkey &&
6752 in_commasep_string(hostkey_algs[j].alg->name,
6754 !have_ssh_host_key(ssh->savedhost, ssh->savedport,
6755 hostkey_algs[j].alg->keytype)) {
6756 ssh->uncert_hostkeys[ssh->n_uncert_hostkeys++] = j;
6762 if (s->pending_compression) {
6763 logevent("Server supports delayed compression; "
6764 "will try this later");
6766 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
6767 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
6768 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
6770 ssh->exhash = ssh->kex->hash->init();
6771 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
6772 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
6773 hash_string(ssh->kex->hash, ssh->exhash,
6774 s->our_kexinit, s->our_kexinitlen);
6775 sfree(s->our_kexinit);
6776 /* Include the type byte in the hash of server's KEXINIT */
6777 hash_string(ssh->kex->hash, ssh->exhash,
6778 pktin->body - 1, pktin->length + 1);
6781 ssh_set_frozen(ssh, 1);
6782 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
6784 ssh_dialog_callback, ssh);
6785 if (s->dlgret < 0) {
6789 bombout(("Unexpected data from server while"
6790 " waiting for user response"));
6793 } while (pktin || inlen > 0);
6794 s->dlgret = ssh->user_response;
6796 ssh_set_frozen(ssh, 0);
6797 if (s->dlgret == 0) {
6798 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
6808 ssh_set_frozen(ssh, 1);
6811 * Change warning box wording depending on why we chose a
6812 * warning-level host key algorithm. If it's because
6813 * that's all we have *cached*, use the askhk mechanism,
6814 * and list the host keys we could usefully cross-certify.
6815 * Otherwise, use askalg for the standard wording.
6818 for (j = 0; j < ssh->n_uncert_hostkeys; j++) {
6819 const struct ssh_signkey_with_user_pref_id *hktype =
6820 &hostkey_algs[ssh->uncert_hostkeys[j]];
6822 for (k = 0; k < HK_MAX; k++) {
6823 int id = conf_get_int_int(ssh->conf, CONF_ssh_hklist, k);
6824 if (id == HK_WARN) {
6826 } else if (id == hktype->id) {
6833 char *old_ba = betteralgs;
6834 betteralgs = dupcat(betteralgs, ",",
6836 (const char *)NULL);
6839 betteralgs = dupstr(hktype->alg->name);
6844 s->dlgret = askhk(ssh->frontend, ssh->hostkey->name,
6845 betteralgs, ssh_dialog_callback, ssh);
6848 s->dlgret = askalg(ssh->frontend, "host key type",
6850 ssh_dialog_callback, ssh);
6852 if (s->dlgret < 0) {
6856 bombout(("Unexpected data from server while"
6857 " waiting for user response"));
6860 } while (pktin || inlen > 0);
6861 s->dlgret = ssh->user_response;
6863 ssh_set_frozen(ssh, 0);
6864 if (s->dlgret == 0) {
6865 ssh_disconnect(ssh, "User aborted at host key warning", NULL,
6871 if (s->warn_cscipher) {
6872 ssh_set_frozen(ssh, 1);
6873 s->dlgret = askalg(ssh->frontend,
6874 "client-to-server cipher",
6875 s->cscipher_tobe->name,
6876 ssh_dialog_callback, ssh);
6877 if (s->dlgret < 0) {
6881 bombout(("Unexpected data from server while"
6882 " waiting for user response"));
6885 } while (pktin || inlen > 0);
6886 s->dlgret = ssh->user_response;
6888 ssh_set_frozen(ssh, 0);
6889 if (s->dlgret == 0) {
6890 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6896 if (s->warn_sccipher) {
6897 ssh_set_frozen(ssh, 1);
6898 s->dlgret = askalg(ssh->frontend,
6899 "server-to-client cipher",
6900 s->sccipher_tobe->name,
6901 ssh_dialog_callback, ssh);
6902 if (s->dlgret < 0) {
6906 bombout(("Unexpected data from server while"
6907 " waiting for user response"));
6910 } while (pktin || inlen > 0);
6911 s->dlgret = ssh->user_response;
6913 ssh_set_frozen(ssh, 0);
6914 if (s->dlgret == 0) {
6915 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6921 if (s->ignorepkt) /* first_kex_packet_follows */
6922 crWaitUntilV(pktin); /* Ignore packet */
6925 if (ssh->kex->main_type == KEXTYPE_DH) {
6927 * Work out the number of bits of key we will need from the
6928 * key exchange. We start with the maximum key length of
6934 csbits = s->cscipher_tobe ? s->cscipher_tobe->real_keybits : 0;
6935 scbits = s->sccipher_tobe ? s->sccipher_tobe->real_keybits : 0;
6936 s->nbits = (csbits > scbits ? csbits : scbits);
6938 /* The keys only have hlen-bit entropy, since they're based on
6939 * a hash. So cap the key size at hlen bits. */
6940 if (s->nbits > ssh->kex->hash->hlen * 8)
6941 s->nbits = ssh->kex->hash->hlen * 8;
6944 * If we're doing Diffie-Hellman group exchange, start by
6945 * requesting a group.
6947 if (dh_is_gex(ssh->kex)) {
6948 logevent("Doing Diffie-Hellman group exchange");
6949 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
6951 * Work out how big a DH group we will need to allow that
6954 s->pbits = 512 << ((s->nbits - 1) / 64);
6955 if (s->pbits < DH_MIN_SIZE)
6956 s->pbits = DH_MIN_SIZE;
6957 if (s->pbits > DH_MAX_SIZE)
6958 s->pbits = DH_MAX_SIZE;
6959 if ((ssh->remote_bugs & BUG_SSH2_OLDGEX)) {
6960 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD);
6961 ssh2_pkt_adduint32(s->pktout, s->pbits);
6963 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
6964 ssh2_pkt_adduint32(s->pktout, DH_MIN_SIZE);
6965 ssh2_pkt_adduint32(s->pktout, s->pbits);
6966 ssh2_pkt_adduint32(s->pktout, DH_MAX_SIZE);
6968 ssh2_pkt_send_noqueue(ssh, s->pktout);
6970 crWaitUntilV(pktin);
6971 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
6972 bombout(("expected key exchange group packet from server"));
6975 s->p = ssh2_pkt_getmp(pktin);
6976 s->g = ssh2_pkt_getmp(pktin);
6977 if (!s->p || !s->g) {
6978 bombout(("unable to read mp-ints from incoming group packet"));
6981 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
6982 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
6983 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
6985 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
6986 ssh->kex_ctx = dh_setup_group(ssh->kex);
6987 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
6988 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
6989 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
6990 ssh->kex->groupname);
6993 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
6994 ssh->kex->hash->text_name);
6996 * Now generate and send e for Diffie-Hellman.
6998 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
6999 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
7000 s->pktout = ssh2_pkt_init(s->kex_init_value);
7001 ssh2_pkt_addmp(s->pktout, s->e);
7002 ssh2_pkt_send_noqueue(ssh, s->pktout);
7004 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
7005 crWaitUntilV(pktin);
7006 if (pktin->type != s->kex_reply_value) {
7007 bombout(("expected key exchange reply packet from server"));
7010 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
7011 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7012 if (!s->hostkeydata) {
7013 bombout(("unable to parse key exchange reply packet"));
7016 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7017 s->hostkeydata, s->hostkeylen);
7018 s->f = ssh2_pkt_getmp(pktin);
7020 bombout(("unable to parse key exchange reply packet"));
7023 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7025 bombout(("unable to parse key exchange reply packet"));
7030 const char *err = dh_validate_f(ssh->kex_ctx, s->f);
7032 bombout(("key exchange reply failed validation: %s", err));
7036 s->K = dh_find_K(ssh->kex_ctx, s->f);
7038 /* We assume everything from now on will be quick, and it might
7039 * involve user interaction. */
7040 set_busy_status(ssh->frontend, BUSY_NOT);
7042 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
7043 if (dh_is_gex(ssh->kex)) {
7044 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
7045 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MIN_SIZE);
7046 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
7047 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
7048 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MAX_SIZE);
7049 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
7050 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
7052 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
7053 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
7055 dh_cleanup(ssh->kex_ctx);
7057 if (dh_is_gex(ssh->kex)) {
7061 } else if (ssh->kex->main_type == KEXTYPE_ECDH) {
7063 logeventf(ssh, "Doing ECDH key exchange with curve %s and hash %s",
7064 ssh_ecdhkex_curve_textname(ssh->kex),
7065 ssh->kex->hash->text_name);
7066 ssh->pkt_kctx = SSH2_PKTCTX_ECDHKEX;
7068 s->eckey = ssh_ecdhkex_newkey(ssh->kex);
7070 bombout(("Unable to generate key for ECDH"));
7076 int publicPointLength;
7077 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
7079 ssh_ecdhkex_freekey(s->eckey);
7080 bombout(("Unable to encode public key for ECDH"));
7083 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_ECDH_INIT);
7084 ssh2_pkt_addstring_start(s->pktout);
7085 ssh2_pkt_addstring_data(s->pktout, publicPoint, publicPointLength);
7089 ssh2_pkt_send_noqueue(ssh, s->pktout);
7091 crWaitUntilV(pktin);
7092 if (pktin->type != SSH2_MSG_KEX_ECDH_REPLY) {
7093 ssh_ecdhkex_freekey(s->eckey);
7094 bombout(("expected ECDH reply packet from server"));
7098 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7099 if (!s->hostkeydata) {
7100 bombout(("unable to parse ECDH reply packet"));
7103 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
7104 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7105 s->hostkeydata, s->hostkeylen);
7109 int publicPointLength;
7110 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
7112 ssh_ecdhkex_freekey(s->eckey);
7113 bombout(("Unable to encode public key for ECDH hash"));
7116 hash_string(ssh->kex->hash, ssh->exhash,
7117 publicPoint, publicPointLength);
7124 ssh_pkt_getstring(pktin, &keydata, &keylen);
7126 bombout(("unable to parse ECDH reply packet"));
7129 hash_string(ssh->kex->hash, ssh->exhash, keydata, keylen);
7130 s->K = ssh_ecdhkex_getkey(s->eckey, keydata, keylen);
7132 ssh_ecdhkex_freekey(s->eckey);
7133 bombout(("point received in ECDH was not valid"));
7138 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7140 bombout(("unable to parse key exchange reply packet"));
7144 ssh_ecdhkex_freekey(s->eckey);
7146 logeventf(ssh, "Doing RSA key exchange with hash %s",
7147 ssh->kex->hash->text_name);
7148 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
7150 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
7153 crWaitUntilV(pktin);
7154 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
7155 bombout(("expected RSA public key packet from server"));
7159 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7160 if (!s->hostkeydata) {
7161 bombout(("unable to parse RSA public key packet"));
7164 hash_string(ssh->kex->hash, ssh->exhash,
7165 s->hostkeydata, s->hostkeylen);
7166 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7167 s->hostkeydata, s->hostkeylen);
7171 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
7173 bombout(("unable to parse RSA public key packet"));
7176 s->rsakeydata = snewn(s->rsakeylen, char);
7177 memcpy(s->rsakeydata, keydata, s->rsakeylen);
7180 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
7182 sfree(s->rsakeydata);
7183 bombout(("unable to parse RSA public key from server"));
7187 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
7190 * Next, set up a shared secret K, of precisely KLEN -
7191 * 2*HLEN - 49 bits, where KLEN is the bit length of the
7192 * RSA key modulus and HLEN is the bit length of the hash
7196 int klen = ssh_rsakex_klen(s->rsakey);
7197 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
7199 unsigned char *kstr1, *kstr2, *outstr;
7200 int kstr1len, kstr2len, outstrlen;
7202 s->K = bn_power_2(nbits - 1);
7204 for (i = 0; i < nbits; i++) {
7206 byte = random_byte();
7208 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
7212 * Encode this as an mpint.
7214 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
7215 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
7216 PUT_32BIT(kstr2, kstr1len);
7217 memcpy(kstr2 + 4, kstr1, kstr1len);
7220 * Encrypt it with the given RSA key.
7222 outstrlen = (klen + 7) / 8;
7223 outstr = snewn(outstrlen, unsigned char);
7224 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
7225 outstr, outstrlen, s->rsakey);
7228 * And send it off in a return packet.
7230 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
7231 ssh2_pkt_addstring_start(s->pktout);
7232 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
7233 ssh2_pkt_send_noqueue(ssh, s->pktout);
7235 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
7242 ssh_rsakex_freekey(s->rsakey);
7244 crWaitUntilV(pktin);
7245 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
7246 sfree(s->rsakeydata);
7247 bombout(("expected signature packet from server"));
7251 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7253 bombout(("unable to parse signature packet"));
7257 sfree(s->rsakeydata);
7260 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
7261 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
7262 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
7264 ssh->kex_ctx = NULL;
7267 debug(("Exchange hash is:\n"));
7268 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
7272 bombout(("Server's host key is invalid"));
7276 if (!ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
7277 (char *)s->exchange_hash,
7278 ssh->kex->hash->hlen)) {
7280 bombout(("Server's host key did not match the signature supplied"));
7285 s->keystr = ssh->hostkey->fmtkey(s->hkey);
7286 if (!s->got_session_id) {
7288 * Make a note of any other host key formats that are available.
7291 int i, j, nkeys = 0;
7293 for (i = 0; i < lenof(hostkey_algs); i++) {
7294 if (hostkey_algs[i].alg == ssh->hostkey)
7297 for (j = 0; j < ssh->n_uncert_hostkeys; j++)
7298 if (ssh->uncert_hostkeys[j] == i)
7301 if (j < ssh->n_uncert_hostkeys) {
7304 newlist = dupprintf("%s/%s", list,
7305 hostkey_algs[i].alg->name);
7307 newlist = dupprintf("%s", hostkey_algs[i].alg->name);
7315 "Server also has %s host key%s, but we "
7316 "don't know %s", list,
7317 nkeys > 1 ? "s" : "",
7318 nkeys > 1 ? "any of them" : "it");
7324 * Authenticate remote host: verify host key. (We've already
7325 * checked the signature of the exchange hash.)
7327 s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
7328 logevent("Host key fingerprint is:");
7329 logevent(s->fingerprint);
7330 /* First check against manually configured host keys. */
7331 s->dlgret = verify_ssh_manual_host_key(ssh, s->fingerprint,
7332 ssh->hostkey, s->hkey);
7333 if (s->dlgret == 0) { /* did not match */
7334 bombout(("Host key did not appear in manually configured list"));
7336 } else if (s->dlgret < 0) { /* none configured; use standard handling */
7337 ssh_set_frozen(ssh, 1);
7338 s->dlgret = verify_ssh_host_key(ssh->frontend,
7339 ssh->savedhost, ssh->savedport,
7340 ssh->hostkey->keytype, s->keystr,
7342 ssh_dialog_callback, ssh);
7346 if (s->dlgret < 0) {
7350 bombout(("Unexpected data from server while waiting"
7351 " for user host key response"));
7354 } while (pktin || inlen > 0);
7355 s->dlgret = ssh->user_response;
7357 ssh_set_frozen(ssh, 0);
7358 if (s->dlgret == 0) {
7359 ssh_disconnect(ssh, "Aborted at host key verification", NULL,
7364 sfree(s->fingerprint);
7366 * Save this host key, to check against the one presented in
7367 * subsequent rekeys.
7369 ssh->hostkey_str = s->keystr;
7370 } else if (ssh->cross_certifying) {
7371 s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
7372 logevent("Storing additional host key for this host:");
7373 logevent(s->fingerprint);
7374 store_host_key(ssh->savedhost, ssh->savedport,
7375 ssh->hostkey->keytype, s->keystr);
7376 ssh->cross_certifying = FALSE;
7378 * Don't forget to store the new key as the one we'll be
7379 * re-checking in future normal rekeys.
7381 ssh->hostkey_str = s->keystr;
7384 * In a rekey, we never present an interactive host key
7385 * verification request to the user. Instead, we simply
7386 * enforce that the key we're seeing this time is identical to
7387 * the one we saw before.
7389 if (strcmp(ssh->hostkey_str, s->keystr)) {
7391 bombout(("Host key was different in repeat key exchange"));
7397 ssh->hostkey->freekey(s->hkey);
7400 * The exchange hash from the very first key exchange is also
7401 * the session id, used in session key construction and
7404 if (!s->got_session_id) {
7405 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
7406 memcpy(ssh->v2_session_id, s->exchange_hash,
7407 sizeof(s->exchange_hash));
7408 ssh->v2_session_id_len = ssh->kex->hash->hlen;
7409 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
7410 s->got_session_id = TRUE;
7414 * Send SSH2_MSG_NEWKEYS.
7416 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
7417 ssh2_pkt_send_noqueue(ssh, s->pktout);
7418 ssh->outgoing_data_size = 0; /* start counting from here */
7421 * We've sent client NEWKEYS, so create and initialise
7422 * client-to-server session keys.
7424 if (ssh->cs_cipher_ctx)
7425 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
7426 ssh->cscipher = s->cscipher_tobe;
7427 if (ssh->cscipher) ssh->cs_cipher_ctx = ssh->cscipher->make_context();
7429 if (ssh->cs_mac_ctx)
7430 ssh->csmac->free_context(ssh->cs_mac_ctx);
7431 ssh->csmac = s->csmac_tobe;
7432 ssh->csmac_etm = s->csmac_etm_tobe;
7434 ssh->cs_mac_ctx = ssh->csmac->make_context(ssh->cs_cipher_ctx);
7436 if (ssh->cs_comp_ctx)
7437 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
7438 ssh->cscomp = s->cscomp_tobe;
7439 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
7442 * Set IVs on client-to-server keys. Here we use the exchange
7443 * hash from the _first_ key exchange.
7445 if (ssh->cscipher) {
7448 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'C',
7449 ssh->cscipher->padded_keybytes);
7450 ssh->cscipher->setkey(ssh->cs_cipher_ctx, key);
7451 smemclr(key, ssh->cscipher->padded_keybytes);
7454 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'A',
7455 ssh->cscipher->blksize);
7456 ssh->cscipher->setiv(ssh->cs_cipher_ctx, key);
7457 smemclr(key, ssh->cscipher->blksize);
7463 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'E',
7464 ssh->csmac->keylen);
7465 ssh->csmac->setkey(ssh->cs_mac_ctx, key);
7466 smemclr(key, ssh->csmac->keylen);
7471 logeventf(ssh, "Initialised %.200s client->server encryption",
7472 ssh->cscipher->text_name);
7474 logeventf(ssh, "Initialised %.200s client->server MAC algorithm%s%s",
7475 ssh->csmac->text_name,
7476 ssh->csmac_etm ? " (in ETM mode)" : "",
7477 ssh->cscipher->required_mac ? " (required by cipher)" : "");
7478 if (ssh->cscomp->text_name)
7479 logeventf(ssh, "Initialised %s compression",
7480 ssh->cscomp->text_name);
7483 * Now our end of the key exchange is complete, we can send all
7484 * our queued higher-layer packets.
7486 ssh->queueing = FALSE;
7487 ssh2_pkt_queuesend(ssh);
7490 * Expect SSH2_MSG_NEWKEYS from server.
7492 crWaitUntilV(pktin);
7493 if (pktin->type != SSH2_MSG_NEWKEYS) {
7494 bombout(("expected new-keys packet from server"));
7497 ssh->incoming_data_size = 0; /* start counting from here */
7500 * We've seen server NEWKEYS, so create and initialise
7501 * server-to-client session keys.
7503 if (ssh->sc_cipher_ctx)
7504 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
7505 if (s->sccipher_tobe) {
7506 ssh->sccipher = s->sccipher_tobe;
7507 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
7510 if (ssh->sc_mac_ctx)
7511 ssh->scmac->free_context(ssh->sc_mac_ctx);
7512 if (s->scmac_tobe) {
7513 ssh->scmac = s->scmac_tobe;
7514 ssh->scmac_etm = s->scmac_etm_tobe;
7515 ssh->sc_mac_ctx = ssh->scmac->make_context(ssh->sc_cipher_ctx);
7518 if (ssh->sc_comp_ctx)
7519 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
7520 ssh->sccomp = s->sccomp_tobe;
7521 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
7524 * Set IVs on server-to-client keys. Here we use the exchange
7525 * hash from the _first_ key exchange.
7527 if (ssh->sccipher) {
7530 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'D',
7531 ssh->sccipher->padded_keybytes);
7532 ssh->sccipher->setkey(ssh->sc_cipher_ctx, key);
7533 smemclr(key, ssh->sccipher->padded_keybytes);
7536 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'B',
7537 ssh->sccipher->blksize);
7538 ssh->sccipher->setiv(ssh->sc_cipher_ctx, key);
7539 smemclr(key, ssh->sccipher->blksize);
7545 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'F',
7546 ssh->scmac->keylen);
7547 ssh->scmac->setkey(ssh->sc_mac_ctx, key);
7548 smemclr(key, ssh->scmac->keylen);
7552 logeventf(ssh, "Initialised %.200s server->client encryption",
7553 ssh->sccipher->text_name);
7555 logeventf(ssh, "Initialised %.200s server->client MAC algorithm%s%s",
7556 ssh->scmac->text_name,
7557 ssh->scmac_etm ? " (in ETM mode)" : "",
7558 ssh->sccipher->required_mac ? " (required by cipher)" : "");
7559 if (ssh->sccomp->text_name)
7560 logeventf(ssh, "Initialised %s decompression",
7561 ssh->sccomp->text_name);
7564 * Free shared secret.
7569 * Update the specials menu to list the remaining uncertified host
7572 update_specials_menu(ssh->frontend);
7575 * Key exchange is over. Loop straight back round if we have a
7576 * deferred rekey reason.
7578 if (ssh->deferred_rekey_reason) {
7579 logevent(ssh->deferred_rekey_reason);
7581 ssh->deferred_rekey_reason = NULL;
7582 goto begin_key_exchange;
7586 * Otherwise, schedule a timer for our next rekey.
7588 ssh->kex_in_progress = FALSE;
7589 ssh->last_rekey = GETTICKCOUNT();
7590 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
7591 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7595 * Now we're encrypting. Begin returning 1 to the protocol main
7596 * function so that other things can run on top of the
7597 * transport. If we ever see a KEXINIT, we must go back to the
7600 * We _also_ go back to the start if we see pktin==NULL and
7601 * inlen negative, because this is a special signal meaning
7602 * `initiate client-driven rekey', and `in' contains a message
7603 * giving the reason for the rekey.
7605 * inlen==-1 means always initiate a rekey;
7606 * inlen==-2 means that userauth has completed successfully and
7607 * we should consider rekeying (for delayed compression).
7609 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
7610 (!pktin && inlen < 0))) {
7612 if (!ssh->protocol_initial_phase_done) {
7613 ssh->protocol_initial_phase_done = TRUE;
7615 * Allow authconn to initialise itself.
7617 do_ssh2_authconn(ssh, NULL, 0, NULL);
7622 logevent("Server initiated key re-exchange");
7626 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
7627 * delayed compression, if it's available.
7629 * draft-miller-secsh-compression-delayed-00 says that you
7630 * negotiate delayed compression in the first key exchange, and
7631 * both sides start compressing when the server has sent
7632 * USERAUTH_SUCCESS. This has a race condition -- the server
7633 * can't know when the client has seen it, and thus which incoming
7634 * packets it should treat as compressed.
7636 * Instead, we do the initial key exchange without offering the
7637 * delayed methods, but note if the server offers them; when we
7638 * get here, if a delayed method was available that was higher
7639 * on our list than what we got, we initiate a rekey in which we
7640 * _do_ list the delayed methods (and hopefully get it as a
7641 * result). Subsequent rekeys will do the same.
7643 assert(!s->userauth_succeeded); /* should only happen once */
7644 s->userauth_succeeded = TRUE;
7645 if (!s->pending_compression)
7646 /* Can't see any point rekeying. */
7647 goto wait_for_rekey; /* this is utterly horrid */
7648 /* else fall through to rekey... */
7649 s->pending_compression = FALSE;
7652 * Now we've decided to rekey.
7654 * Special case: if the server bug is set that doesn't
7655 * allow rekeying, we give a different log message and
7656 * continue waiting. (If such a server _initiates_ a rekey,
7657 * we process it anyway!)
7659 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
7660 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
7662 /* Reset the counters, so that at least this message doesn't
7663 * hit the event log _too_ often. */
7664 ssh->outgoing_data_size = 0;
7665 ssh->incoming_data_size = 0;
7666 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
7668 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7671 goto wait_for_rekey; /* this is still utterly horrid */
7673 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
7676 goto begin_key_exchange;
7682 * Send data on an SSH channel. In SSH-2, this involves buffering it
7685 static int ssh_send_channel_data(struct ssh_channel *c, const char *buf,
7688 if (c->ssh->version == 2) {
7689 bufchain_add(&c->v.v2.outbuffer, buf, len);
7690 return ssh2_try_send(c);
7692 send_packet(c->ssh, SSH1_MSG_CHANNEL_DATA,
7693 PKT_INT, c->remoteid,
7698 * In SSH-1 we can return 0 here - implying that channels are
7699 * never individually throttled - because the only
7700 * circumstance that can cause throttling will be the whole
7701 * SSH connection backing up, in which case _everything_ will
7702 * be throttled as a whole.
7709 * Attempt to send data on an SSH-2 channel.
7711 static int ssh2_try_send(struct ssh_channel *c)
7714 struct Packet *pktout;
7717 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
7720 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
7721 if ((unsigned)len > c->v.v2.remwindow)
7722 len = c->v.v2.remwindow;
7723 if ((unsigned)len > c->v.v2.remmaxpkt)
7724 len = c->v.v2.remmaxpkt;
7725 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
7726 ssh2_pkt_adduint32(pktout, c->remoteid);
7727 ssh2_pkt_addstring_start(pktout);
7728 ssh2_pkt_addstring_data(pktout, data, len);
7729 ssh2_pkt_send(ssh, pktout);
7730 bufchain_consume(&c->v.v2.outbuffer, len);
7731 c->v.v2.remwindow -= len;
7735 * After having sent as much data as we can, return the amount
7738 ret = bufchain_size(&c->v.v2.outbuffer);
7741 * And if there's no data pending but we need to send an EOF, send
7744 if (!ret && c->pending_eof)
7745 ssh_channel_try_eof(c);
7750 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
7753 if (c->closes & CLOSES_SENT_EOF)
7754 return; /* don't send on channels we've EOFed */
7755 bufsize = ssh2_try_send(c);
7758 case CHAN_MAINSESSION:
7759 /* stdin need not receive an unthrottle
7760 * notification since it will be polled */
7763 x11_unthrottle(c->u.x11.xconn);
7766 /* agent sockets are request/response and need no
7767 * buffer management */
7770 pfd_unthrottle(c->u.pfd.pf);
7776 static int ssh_is_simple(Ssh ssh)
7779 * We use the 'simple' variant of the SSH protocol if we're asked
7780 * to, except not if we're also doing connection-sharing (either
7781 * tunnelling our packets over an upstream or expecting to be
7782 * tunnelled over ourselves), since then the assumption that we
7783 * have only one channel to worry about is not true after all.
7785 return (conf_get_int(ssh->conf, CONF_ssh_simple) &&
7786 !ssh->bare_connection && !ssh->connshare);
7790 * Set up most of a new ssh_channel for SSH-2.
7792 static void ssh2_channel_init(struct ssh_channel *c)
7795 c->localid = alloc_channel_id(ssh);
7797 c->pending_eof = FALSE;
7798 c->throttling_conn = FALSE;
7799 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
7800 ssh_is_simple(ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
7801 c->v.v2.chanreq_head = NULL;
7802 c->v.v2.throttle_state = UNTHROTTLED;
7803 bufchain_init(&c->v.v2.outbuffer);
7807 * Construct the common parts of a CHANNEL_OPEN.
7809 static struct Packet *ssh2_chanopen_init(struct ssh_channel *c,
7812 struct Packet *pktout;
7814 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7815 ssh2_pkt_addstring(pktout, type);
7816 ssh2_pkt_adduint32(pktout, c->localid);
7817 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
7818 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7823 * CHANNEL_FAILURE doesn't come with any indication of what message
7824 * caused it, so we have to keep track of the outstanding
7825 * CHANNEL_REQUESTs ourselves.
7827 static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
7828 cchandler_fn_t handler, void *ctx)
7830 struct outstanding_channel_request *ocr =
7831 snew(struct outstanding_channel_request);
7833 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7834 ocr->handler = handler;
7837 if (!c->v.v2.chanreq_head)
7838 c->v.v2.chanreq_head = ocr;
7840 c->v.v2.chanreq_tail->next = ocr;
7841 c->v.v2.chanreq_tail = ocr;
7845 * Construct the common parts of a CHANNEL_REQUEST. If handler is not
7846 * NULL then a reply will be requested and the handler will be called
7847 * when it arrives. The returned packet is ready to have any
7848 * request-specific data added and be sent. Note that if a handler is
7849 * provided, it's essential that the request actually be sent.
7851 * The handler will usually be passed the response packet in pktin. If
7852 * pktin is NULL, this means that no reply will ever be forthcoming
7853 * (e.g. because the entire connection is being destroyed, or because
7854 * the server initiated channel closure before we saw the response)
7855 * and the handler should free any storage it's holding.
7857 static struct Packet *ssh2_chanreq_init(struct ssh_channel *c,
7859 cchandler_fn_t handler, void *ctx)
7861 struct Packet *pktout;
7863 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7864 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7865 ssh2_pkt_adduint32(pktout, c->remoteid);
7866 ssh2_pkt_addstring(pktout, type);
7867 ssh2_pkt_addbool(pktout, handler != NULL);
7868 if (handler != NULL)
7869 ssh2_queue_chanreq_handler(c, handler, ctx);
7874 * Potentially enlarge the window on an SSH-2 channel.
7876 static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
7878 static void ssh2_set_window(struct ssh_channel *c, int newwin)
7883 * Never send WINDOW_ADJUST for a channel that the remote side has
7884 * already sent EOF on; there's no point, since it won't be
7885 * sending any more data anyway. Ditto if _we've_ already sent
7888 if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
7892 * Also, never widen the window for an X11 channel when we're
7893 * still waiting to see its initial auth and may yet hand it off
7896 if (c->type == CHAN_X11 && c->u.x11.initial)
7900 * If the remote end has a habit of ignoring maxpkt, limit the
7901 * window so that it has no choice (assuming it doesn't ignore the
7904 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
7905 newwin = OUR_V2_MAXPKT;
7908 * Only send a WINDOW_ADJUST if there's significantly more window
7909 * available than the other end thinks there is. This saves us
7910 * sending a WINDOW_ADJUST for every character in a shell session.
7912 * "Significant" is arbitrarily defined as half the window size.
7914 if (newwin / 2 >= c->v.v2.locwindow) {
7915 struct Packet *pktout;
7919 * In order to keep track of how much window the client
7920 * actually has available, we'd like it to acknowledge each
7921 * WINDOW_ADJUST. We can't do that directly, so we accompany
7922 * it with a CHANNEL_REQUEST that has to be acknowledged.
7924 * This is only necessary if we're opening the window wide.
7925 * If we're not, then throughput is being constrained by
7926 * something other than the maximum window size anyway.
7928 if (newwin == c->v.v2.locmaxwin &&
7929 !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
7930 up = snew(unsigned);
7931 *up = newwin - c->v.v2.locwindow;
7932 pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org",
7933 ssh2_handle_winadj_response, up);
7934 ssh2_pkt_send(ssh, pktout);
7936 if (c->v.v2.throttle_state != UNTHROTTLED)
7937 c->v.v2.throttle_state = UNTHROTTLING;
7939 /* Pretend the WINDOW_ADJUST was acked immediately. */
7940 c->v.v2.remlocwin = newwin;
7941 c->v.v2.throttle_state = THROTTLED;
7943 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
7944 ssh2_pkt_adduint32(pktout, c->remoteid);
7945 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
7946 ssh2_pkt_send(ssh, pktout);
7947 c->v.v2.locwindow = newwin;
7952 * Find the channel associated with a message. If there's no channel,
7953 * or it's not properly open, make a noise about it and return NULL.
7955 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
7957 unsigned localid = ssh_pkt_getuint32(pktin);
7958 struct ssh_channel *c;
7960 c = find234(ssh->channels, &localid, ssh_channelfind);
7962 (c->type != CHAN_SHARING && c->halfopen &&
7963 pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
7964 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
7965 char *buf = dupprintf("Received %s for %s channel %u",
7966 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
7968 c ? "half-open" : "nonexistent", localid);
7969 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
7976 static void ssh2_handle_winadj_response(struct ssh_channel *c,
7977 struct Packet *pktin, void *ctx)
7979 unsigned *sizep = ctx;
7982 * Winadj responses should always be failures. However, at least
7983 * one server ("boks_sshd") is known to return SUCCESS for channel
7984 * requests it's never heard of, such as "winadj@putty". Raised
7985 * with foxt.com as bug 090916-090424, but for the sake of a quiet
7986 * life, we don't worry about what kind of response we got.
7989 c->v.v2.remlocwin += *sizep;
7992 * winadj messages are only sent when the window is fully open, so
7993 * if we get an ack of one, we know any pending unthrottle is
7996 if (c->v.v2.throttle_state == UNTHROTTLING)
7997 c->v.v2.throttle_state = UNTHROTTLED;
8000 static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
8002 struct ssh_channel *c = ssh2_channel_msg(ssh, pktin);
8003 struct outstanding_channel_request *ocr;
8006 if (c->type == CHAN_SHARING) {
8007 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8008 pktin->body, pktin->length);
8011 ocr = c->v.v2.chanreq_head;
8013 ssh2_msg_unexpected(ssh, pktin);
8016 ocr->handler(c, pktin, ocr->ctx);
8017 c->v.v2.chanreq_head = ocr->next;
8020 * We may now initiate channel-closing procedures, if that
8021 * CHANNEL_REQUEST was the last thing outstanding before we send
8024 ssh2_channel_check_close(c);
8027 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
8029 struct ssh_channel *c;
8030 c = ssh2_channel_msg(ssh, pktin);
8033 if (c->type == CHAN_SHARING) {
8034 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8035 pktin->body, pktin->length);
8038 if (!(c->closes & CLOSES_SENT_EOF)) {
8039 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
8040 ssh2_try_send_and_unthrottle(ssh, c);
8044 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
8048 struct ssh_channel *c;
8049 c = ssh2_channel_msg(ssh, pktin);
8052 if (c->type == CHAN_SHARING) {
8053 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8054 pktin->body, pktin->length);
8057 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
8058 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
8059 return; /* extended but not stderr */
8060 ssh_pkt_getstring(pktin, &data, &length);
8063 c->v.v2.locwindow -= length;
8064 c->v.v2.remlocwin -= length;
8066 case CHAN_MAINSESSION:
8068 from_backend(ssh->frontend, pktin->type ==
8069 SSH2_MSG_CHANNEL_EXTENDED_DATA,
8073 bufsize = x11_send(c->u.x11.xconn, data, length);
8076 bufsize = pfd_send(c->u.pfd.pf, data, length);
8079 bufsize = ssh_agent_channel_data(c, data, length);
8083 * If it looks like the remote end hit the end of its window,
8084 * and we didn't want it to do that, think about using a
8087 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
8088 c->v.v2.locmaxwin < 0x40000000)
8089 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
8091 * If we are not buffering too much data,
8092 * enlarge the window again at the remote side.
8093 * If we are buffering too much, we may still
8094 * need to adjust the window if the server's
8097 ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
8098 c->v.v2.locmaxwin - bufsize : 0);
8100 * If we're either buffering way too much data, or if we're
8101 * buffering anything at all and we're in "simple" mode,
8102 * throttle the whole channel.
8104 if ((bufsize > c->v.v2.locmaxwin || (ssh_is_simple(ssh) && bufsize>0))
8105 && !c->throttling_conn) {
8106 c->throttling_conn = 1;
8107 ssh_throttle_conn(ssh, +1);
8112 static void ssh_check_termination(Ssh ssh)
8114 if (ssh->version == 2 &&
8115 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
8116 (ssh->channels && count234(ssh->channels) == 0) &&
8117 !(ssh->connshare && share_ndownstreams(ssh->connshare) > 0)) {
8119 * We used to send SSH_MSG_DISCONNECT here, because I'd
8120 * believed that _every_ conforming SSH-2 connection had to
8121 * end with a disconnect being sent by at least one side;
8122 * apparently I was wrong and it's perfectly OK to
8123 * unceremoniously slam the connection shut when you're done,
8124 * and indeed OpenSSH feels this is more polite than sending a
8125 * DISCONNECT. So now we don't.
8127 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
8131 void ssh_sharing_downstream_connected(Ssh ssh, unsigned id,
8132 const char *peerinfo)
8135 logeventf(ssh, "Connection sharing downstream #%u connected from %s",
8138 logeventf(ssh, "Connection sharing downstream #%u connected", id);
8141 void ssh_sharing_downstream_disconnected(Ssh ssh, unsigned id)
8143 logeventf(ssh, "Connection sharing downstream #%u disconnected", id);
8144 ssh_check_termination(ssh);
8147 void ssh_sharing_logf(Ssh ssh, unsigned id, const char *logfmt, ...)
8152 va_start(ap, logfmt);
8153 buf = dupvprintf(logfmt, ap);
8156 logeventf(ssh, "Connection sharing downstream #%u: %s", id, buf);
8158 logeventf(ssh, "Connection sharing: %s", buf);
8162 static void ssh_channel_destroy(struct ssh_channel *c)
8167 case CHAN_MAINSESSION:
8168 ssh->mainchan = NULL;
8169 update_specials_menu(ssh->frontend);
8172 if (c->u.x11.xconn != NULL)
8173 x11_close(c->u.x11.xconn);
8174 logevent("Forwarded X11 connection terminated");
8177 sfree(c->u.a.message);
8180 if (c->u.pfd.pf != NULL)
8181 pfd_close(c->u.pfd.pf);
8182 logevent("Forwarded port closed");
8186 del234(ssh->channels, c);
8187 if (ssh->version == 2) {
8188 bufchain_clear(&c->v.v2.outbuffer);
8189 assert(c->v.v2.chanreq_head == NULL);
8194 * If that was the last channel left open, we might need to
8197 ssh_check_termination(ssh);
8200 static void ssh2_channel_check_close(struct ssh_channel *c)
8203 struct Packet *pktout;
8207 * If we've sent out our own CHANNEL_OPEN but not yet seen
8208 * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
8209 * it's too early to be sending close messages of any kind.
8214 if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
8215 c->type == CHAN_ZOMBIE) &&
8216 !c->v.v2.chanreq_head &&
8217 !(c->closes & CLOSES_SENT_CLOSE)) {
8219 * We have both sent and received EOF (or the channel is a
8220 * zombie), and we have no outstanding channel requests, which
8221 * means the channel is in final wind-up. But we haven't sent
8222 * CLOSE, so let's do so now.
8224 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
8225 ssh2_pkt_adduint32(pktout, c->remoteid);
8226 ssh2_pkt_send(ssh, pktout);
8227 c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
8230 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
8231 assert(c->v.v2.chanreq_head == NULL);
8233 * We have both sent and received CLOSE, which means we're
8234 * completely done with the channel.
8236 ssh_channel_destroy(c);
8240 static void ssh2_channel_got_eof(struct ssh_channel *c)
8242 if (c->closes & CLOSES_RCVD_EOF)
8243 return; /* already seen EOF */
8244 c->closes |= CLOSES_RCVD_EOF;
8246 if (c->type == CHAN_X11) {
8247 x11_send_eof(c->u.x11.xconn);
8248 } else if (c->type == CHAN_AGENT) {
8249 if (c->u.a.outstanding_requests == 0) {
8250 /* Manufacture an outgoing EOF in response to the incoming one. */
8251 sshfwd_write_eof(c);
8253 } else if (c->type == CHAN_SOCKDATA) {
8254 pfd_send_eof(c->u.pfd.pf);
8255 } else if (c->type == CHAN_MAINSESSION) {
8258 if (!ssh->sent_console_eof &&
8259 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
8261 * Either from_backend_eof told us that the front end
8262 * wants us to close the outgoing side of the connection
8263 * as soon as we see EOF from the far end, or else we've
8264 * unilaterally decided to do that because we've allocated
8265 * a remote pty and hence EOF isn't a particularly
8266 * meaningful concept.
8268 sshfwd_write_eof(c);
8270 ssh->sent_console_eof = TRUE;
8273 ssh2_channel_check_close(c);
8276 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
8278 struct ssh_channel *c;
8280 c = ssh2_channel_msg(ssh, pktin);
8283 if (c->type == CHAN_SHARING) {
8284 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8285 pktin->body, pktin->length);
8288 ssh2_channel_got_eof(c);
8291 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
8293 struct ssh_channel *c;
8295 c = ssh2_channel_msg(ssh, pktin);
8298 if (c->type == CHAN_SHARING) {
8299 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8300 pktin->body, pktin->length);
8305 * When we receive CLOSE on a channel, we assume it comes with an
8306 * implied EOF if we haven't seen EOF yet.
8308 ssh2_channel_got_eof(c);
8310 if (!(ssh->remote_bugs & BUG_SENDS_LATE_REQUEST_REPLY)) {
8312 * It also means we stop expecting to see replies to any
8313 * outstanding channel requests, so clean those up too.
8314 * (ssh_chanreq_init will enforce by assertion that we don't
8315 * subsequently put anything back on this list.)
8317 while (c->v.v2.chanreq_head) {
8318 struct outstanding_channel_request *ocr = c->v.v2.chanreq_head;
8319 ocr->handler(c, NULL, ocr->ctx);
8320 c->v.v2.chanreq_head = ocr->next;
8326 * And we also send an outgoing EOF, if we haven't already, on the
8327 * assumption that CLOSE is a pretty forceful announcement that
8328 * the remote side is doing away with the entire channel. (If it
8329 * had wanted to send us EOF and continue receiving data from us,
8330 * it would have just sent CHANNEL_EOF.)
8332 if (!(c->closes & CLOSES_SENT_EOF)) {
8334 * Make sure we don't read any more from whatever our local
8335 * data source is for this channel.
8338 case CHAN_MAINSESSION:
8339 ssh->send_ok = 0; /* stop trying to read from stdin */
8342 x11_override_throttle(c->u.x11.xconn, 1);
8345 pfd_override_throttle(c->u.pfd.pf, 1);
8350 * Abandon any buffered data we still wanted to send to this
8351 * channel. Receiving a CHANNEL_CLOSE is an indication that
8352 * the server really wants to get on and _destroy_ this
8353 * channel, and it isn't going to send us any further
8354 * WINDOW_ADJUSTs to permit us to send pending stuff.
8356 bufchain_clear(&c->v.v2.outbuffer);
8359 * Send outgoing EOF.
8361 sshfwd_write_eof(c);
8365 * Now process the actual close.
8367 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
8368 c->closes |= CLOSES_RCVD_CLOSE;
8369 ssh2_channel_check_close(c);
8373 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
8375 struct ssh_channel *c;
8377 c = ssh2_channel_msg(ssh, pktin);
8380 if (c->type == CHAN_SHARING) {
8381 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8382 pktin->body, pktin->length);
8385 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
8386 c->remoteid = ssh_pkt_getuint32(pktin);
8387 c->halfopen = FALSE;
8388 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8389 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8391 if (c->type == CHAN_SOCKDATA_DORMANT) {
8392 c->type = CHAN_SOCKDATA;
8394 pfd_confirm(c->u.pfd.pf);
8395 } else if (c->type == CHAN_ZOMBIE) {
8397 * This case can occur if a local socket error occurred
8398 * between us sending out CHANNEL_OPEN and receiving
8399 * OPEN_CONFIRMATION. In this case, all we can do is
8400 * immediately initiate close proceedings now that we know the
8401 * server's id to put in the close message.
8403 ssh2_channel_check_close(c);
8406 * We never expect to receive OPEN_CONFIRMATION for any
8407 * *other* channel type (since only local-to-remote port
8408 * forwardings cause us to send CHANNEL_OPEN after the main
8409 * channel is live - all other auxiliary channel types are
8410 * initiated from the server end). It's safe to enforce this
8411 * by assertion rather than by ssh_disconnect, because the
8412 * real point is that we never constructed a half-open channel
8413 * structure in the first place with any type other than the
8416 assert(!"Funny channel type in ssh2_msg_channel_open_confirmation");
8420 ssh_channel_try_eof(c); /* in case we had a pending EOF */
8423 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
8425 static const char *const reasons[] = {
8426 "<unknown reason code>",
8427 "Administratively prohibited",
8429 "Unknown channel type",
8430 "Resource shortage",
8432 unsigned reason_code;
8433 char *reason_string;
8435 struct ssh_channel *c;
8437 c = ssh2_channel_msg(ssh, pktin);
8440 if (c->type == CHAN_SHARING) {
8441 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8442 pktin->body, pktin->length);
8445 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
8447 if (c->type == CHAN_SOCKDATA_DORMANT) {
8448 reason_code = ssh_pkt_getuint32(pktin);
8449 if (reason_code >= lenof(reasons))
8450 reason_code = 0; /* ensure reasons[reason_code] in range */
8451 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
8452 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
8453 reasons[reason_code], reason_length,
8454 NULLTOEMPTY(reason_string));
8456 pfd_close(c->u.pfd.pf);
8457 } else if (c->type == CHAN_ZOMBIE) {
8459 * This case can occur if a local socket error occurred
8460 * between us sending out CHANNEL_OPEN and receiving
8461 * OPEN_FAILURE. In this case, we need do nothing except allow
8462 * the code below to throw the half-open channel away.
8466 * We never expect to receive OPEN_FAILURE for any *other*
8467 * channel type (since only local-to-remote port forwardings
8468 * cause us to send CHANNEL_OPEN after the main channel is
8469 * live - all other auxiliary channel types are initiated from
8470 * the server end). It's safe to enforce this by assertion
8471 * rather than by ssh_disconnect, because the real point is
8472 * that we never constructed a half-open channel structure in
8473 * the first place with any type other than the above.
8475 assert(!"Funny channel type in ssh2_msg_channel_open_failure");
8478 del234(ssh->channels, c);
8482 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
8485 int typelen, want_reply;
8486 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
8487 struct ssh_channel *c;
8488 struct Packet *pktout;
8490 c = ssh2_channel_msg(ssh, pktin);
8493 if (c->type == CHAN_SHARING) {
8494 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8495 pktin->body, pktin->length);
8498 ssh_pkt_getstring(pktin, &type, &typelen);
8499 want_reply = ssh2_pkt_getbool(pktin);
8501 if (c->closes & CLOSES_SENT_CLOSE) {
8503 * We don't reply to channel requests after we've sent
8504 * CHANNEL_CLOSE for the channel, because our reply might
8505 * cross in the network with the other side's CHANNEL_CLOSE
8506 * and arrive after they have wound the channel up completely.
8512 * Having got the channel number, we now look at
8513 * the request type string to see if it's something
8516 if (c == ssh->mainchan) {
8518 * We recognise "exit-status" and "exit-signal" on
8519 * the primary channel.
8521 if (typelen == 11 &&
8522 !memcmp(type, "exit-status", 11)) {
8524 ssh->exitcode = ssh_pkt_getuint32(pktin);
8525 logeventf(ssh, "Server sent command exit status %d",
8527 reply = SSH2_MSG_CHANNEL_SUCCESS;
8529 } else if (typelen == 11 &&
8530 !memcmp(type, "exit-signal", 11)) {
8532 int is_plausible = TRUE, is_int = FALSE;
8533 char *fmt_sig = NULL, *fmt_msg = NULL;
8535 int msglen = 0, core = FALSE;
8536 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
8537 * provide an `int' for the signal, despite its
8538 * having been a `string' in the drafts of RFC 4254 since at
8539 * least 2001. (Fixed in session.c 1.147.) Try to
8540 * infer which we can safely parse it as. */
8542 unsigned char *p = pktin->body +
8544 long len = pktin->length - pktin->savedpos;
8545 unsigned long num = GET_32BIT(p); /* what is it? */
8546 /* If it's 0, it hardly matters; assume string */
8550 int maybe_int = FALSE, maybe_str = FALSE;
8551 #define CHECK_HYPOTHESIS(offset, result) \
8554 int q = toint(offset); \
8555 if (q >= 0 && q+4 <= len) { \
8556 q = toint(q + 4 + GET_32BIT(p+q)); \
8557 if (q >= 0 && q+4 <= len && \
8558 ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
8563 CHECK_HYPOTHESIS(4+1, maybe_int);
8564 CHECK_HYPOTHESIS(4+num+1, maybe_str);
8565 #undef CHECK_HYPOTHESIS
8566 if (maybe_int && !maybe_str)
8568 else if (!maybe_int && maybe_str)
8571 /* Crikey. Either or neither. Panic. */
8572 is_plausible = FALSE;
8575 ssh->exitcode = 128; /* means `unknown signal' */
8578 /* Old non-standard OpenSSH. */
8579 int signum = ssh_pkt_getuint32(pktin);
8580 fmt_sig = dupprintf(" %d", signum);
8581 ssh->exitcode = 128 + signum;
8583 /* As per RFC 4254. */
8586 ssh_pkt_getstring(pktin, &sig, &siglen);
8587 /* Signal name isn't supposed to be blank, but
8588 * let's cope gracefully if it is. */
8590 fmt_sig = dupprintf(" \"%.*s\"",
8595 * Really hideous method of translating the
8596 * signal description back into a locally
8597 * meaningful number.
8602 #define TRANSLATE_SIGNAL(s) \
8603 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
8604 ssh->exitcode = 128 + SIG ## s
8606 TRANSLATE_SIGNAL(ABRT);
8609 TRANSLATE_SIGNAL(ALRM);
8612 TRANSLATE_SIGNAL(FPE);
8615 TRANSLATE_SIGNAL(HUP);
8618 TRANSLATE_SIGNAL(ILL);
8621 TRANSLATE_SIGNAL(INT);
8624 TRANSLATE_SIGNAL(KILL);
8627 TRANSLATE_SIGNAL(PIPE);
8630 TRANSLATE_SIGNAL(QUIT);
8633 TRANSLATE_SIGNAL(SEGV);
8636 TRANSLATE_SIGNAL(TERM);
8639 TRANSLATE_SIGNAL(USR1);
8642 TRANSLATE_SIGNAL(USR2);
8644 #undef TRANSLATE_SIGNAL
8646 ssh->exitcode = 128;
8648 core = ssh2_pkt_getbool(pktin);
8649 ssh_pkt_getstring(pktin, &msg, &msglen);
8651 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
8653 /* ignore lang tag */
8654 } /* else don't attempt to parse */
8655 logeventf(ssh, "Server exited on signal%s%s%s",
8656 fmt_sig ? fmt_sig : "",
8657 core ? " (core dumped)" : "",
8658 fmt_msg ? fmt_msg : "");
8661 reply = SSH2_MSG_CHANNEL_SUCCESS;
8666 * This is a channel request we don't know
8667 * about, so we now either ignore the request
8668 * or respond with CHANNEL_FAILURE, depending
8671 reply = SSH2_MSG_CHANNEL_FAILURE;
8674 pktout = ssh2_pkt_init(reply);
8675 ssh2_pkt_adduint32(pktout, c->remoteid);
8676 ssh2_pkt_send(ssh, pktout);
8680 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
8683 int typelen, want_reply;
8684 struct Packet *pktout;
8686 ssh_pkt_getstring(pktin, &type, &typelen);
8687 want_reply = ssh2_pkt_getbool(pktin);
8690 * We currently don't support any global requests
8691 * at all, so we either ignore the request or
8692 * respond with REQUEST_FAILURE, depending on
8696 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
8697 ssh2_pkt_send(ssh, pktout);
8701 struct X11FakeAuth *ssh_sharing_add_x11_display(Ssh ssh, int authtype,
8705 struct X11FakeAuth *auth;
8708 * Make up a new set of fake X11 auth data, and add it to the tree
8709 * of currently valid ones with an indication of the sharing
8710 * context that it's relevant to.
8712 auth = x11_invent_fake_auth(ssh->x11authtree, authtype);
8713 auth->share_cs = share_cs;
8714 auth->share_chan = share_chan;
8719 void ssh_sharing_remove_x11_display(Ssh ssh, struct X11FakeAuth *auth)
8721 del234(ssh->x11authtree, auth);
8722 x11_free_fake_auth(auth);
8725 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
8732 const char *error = NULL;
8733 struct ssh_channel *c;
8734 unsigned remid, winsize, pktsize;
8735 unsigned our_winsize_override = 0;
8736 struct Packet *pktout;
8738 ssh_pkt_getstring(pktin, &type, &typelen);
8739 c = snew(struct ssh_channel);
8742 remid = ssh_pkt_getuint32(pktin);
8743 winsize = ssh_pkt_getuint32(pktin);
8744 pktsize = ssh_pkt_getuint32(pktin);
8746 if (typelen == 3 && !memcmp(type, "x11", 3)) {
8749 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8750 addrstr = dupprintf("%.*s", peeraddrlen, NULLTOEMPTY(peeraddr));
8751 peerport = ssh_pkt_getuint32(pktin);
8753 logeventf(ssh, "Received X11 connect request from %s:%d",
8756 if (!ssh->X11_fwd_enabled && !ssh->connshare)
8757 error = "X11 forwarding is not enabled";
8759 c->u.x11.xconn = x11_init(ssh->x11authtree, c,
8762 c->u.x11.initial = TRUE;
8765 * If we are a connection-sharing upstream, then we should
8766 * initially present a very small window, adequate to take
8767 * the X11 initial authorisation packet but not much more.
8768 * Downstream will then present us a larger window (by
8769 * fiat of the connection-sharing protocol) and we can
8770 * guarantee to send a positive-valued WINDOW_ADJUST.
8773 our_winsize_override = 128;
8775 logevent("Opened X11 forward channel");
8779 } else if (typelen == 15 &&
8780 !memcmp(type, "forwarded-tcpip", 15)) {
8781 struct ssh_rportfwd pf, *realpf;
8784 ssh_pkt_getstring(pktin, &shost, &shostlen);/* skip address */
8785 pf.shost = dupprintf("%.*s", shostlen, NULLTOEMPTY(shost));
8786 pf.sport = ssh_pkt_getuint32(pktin);
8787 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8788 peerport = ssh_pkt_getuint32(pktin);
8789 realpf = find234(ssh->rportfwds, &pf, NULL);
8790 logeventf(ssh, "Received remote port %s:%d open request "
8791 "from %.*s:%d", pf.shost, pf.sport,
8792 peeraddrlen, NULLTOEMPTY(peeraddr), peerport);
8795 if (realpf == NULL) {
8796 error = "Remote port is not recognised";
8800 if (realpf->share_ctx) {
8802 * This port forwarding is on behalf of a
8803 * connection-sharing downstream, so abandon our own
8804 * channel-open procedure and just pass the message on
8807 share_got_pkt_from_server(realpf->share_ctx, pktin->type,
8808 pktin->body, pktin->length);
8813 err = pfd_connect(&c->u.pfd.pf, realpf->dhost, realpf->dport,
8814 c, ssh->conf, realpf->pfrec->addressfamily);
8815 logeventf(ssh, "Attempting to forward remote port to "
8816 "%s:%d", realpf->dhost, realpf->dport);
8818 logeventf(ssh, "Port open failed: %s", err);
8820 error = "Port open failed";
8822 logevent("Forwarded port opened successfully");
8823 c->type = CHAN_SOCKDATA;
8826 } else if (typelen == 22 &&
8827 !memcmp(type, "auth-agent@openssh.com", 22)) {
8828 if (!ssh->agentfwd_enabled)
8829 error = "Agent forwarding is not enabled";
8831 c->type = CHAN_AGENT; /* identify channel type */
8832 c->u.a.lensofar = 0;
8833 c->u.a.message = NULL;
8834 c->u.a.outstanding_requests = 0;
8837 error = "Unsupported channel type requested";
8840 c->remoteid = remid;
8841 c->halfopen = FALSE;
8843 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
8844 ssh2_pkt_adduint32(pktout, c->remoteid);
8845 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
8846 ssh2_pkt_addstring(pktout, error);
8847 ssh2_pkt_addstring(pktout, "en"); /* language tag */
8848 ssh2_pkt_send(ssh, pktout);
8849 logeventf(ssh, "Rejected channel open: %s", error);
8852 ssh2_channel_init(c);
8853 c->v.v2.remwindow = winsize;
8854 c->v.v2.remmaxpkt = pktsize;
8855 if (our_winsize_override) {
8856 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
8857 our_winsize_override;
8859 add234(ssh->channels, c);
8860 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
8861 ssh2_pkt_adduint32(pktout, c->remoteid);
8862 ssh2_pkt_adduint32(pktout, c->localid);
8863 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
8864 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
8865 ssh2_pkt_send(ssh, pktout);
8869 void sshfwd_x11_sharing_handover(struct ssh_channel *c,
8870 void *share_cs, void *share_chan,
8871 const char *peer_addr, int peer_port,
8872 int endian, int protomajor, int protominor,
8873 const void *initial_data, int initial_len)
8876 * This function is called when we've just discovered that an X
8877 * forwarding channel on which we'd been handling the initial auth
8878 * ourselves turns out to be destined for a connection-sharing
8879 * downstream. So we turn the channel into a CHAN_SHARING, meaning
8880 * that we completely stop tracking windows and buffering data and
8881 * just pass more or less unmodified SSH messages back and forth.
8883 c->type = CHAN_SHARING;
8884 c->u.sharing.ctx = share_cs;
8885 share_setup_x11_channel(share_cs, share_chan,
8886 c->localid, c->remoteid, c->v.v2.remwindow,
8887 c->v.v2.remmaxpkt, c->v.v2.locwindow,
8888 peer_addr, peer_port, endian,
8889 protomajor, protominor,
8890 initial_data, initial_len);
8893 void sshfwd_x11_is_local(struct ssh_channel *c)
8896 * This function is called when we've just discovered that an X
8897 * forwarding channel is _not_ destined for a connection-sharing
8898 * downstream but we're going to handle it ourselves. We stop
8899 * presenting a cautiously small window and go into ordinary data
8902 c->u.x11.initial = FALSE;
8903 ssh2_set_window(c, ssh_is_simple(c->ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE);
8907 * Buffer banner messages for later display at some convenient point,
8908 * if we're going to display them.
8910 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
8912 /* Arbitrary limit to prevent unbounded inflation of buffer */
8913 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
8914 bufchain_size(&ssh->banner) <= 131072) {
8915 char *banner = NULL;
8917 ssh_pkt_getstring(pktin, &banner, &size);
8919 bufchain_add(&ssh->banner, banner, size);
8923 /* Helper function to deal with sending tty modes for "pty-req" */
8924 static void ssh2_send_ttymode(void *data, char *mode, char *val)
8926 struct Packet *pktout = (struct Packet *)data;
8928 unsigned int arg = 0;
8929 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
8930 if (i == lenof(ssh_ttymodes)) return;
8931 switch (ssh_ttymodes[i].type) {
8933 arg = ssh_tty_parse_specchar(val);
8936 arg = ssh_tty_parse_boolean(val);
8939 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
8940 ssh2_pkt_adduint32(pktout, arg);
8943 static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
8946 struct ssh2_setup_x11_state {
8950 struct Packet *pktout;
8951 crStateP(ssh2_setup_x11_state, ctx);
8955 logevent("Requesting X11 forwarding");
8956 pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
8958 ssh2_pkt_addbool(pktout, 0); /* many connections */
8959 ssh2_pkt_addstring(pktout, ssh->x11auth->protoname);
8960 ssh2_pkt_addstring(pktout, ssh->x11auth->datastring);
8961 ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
8962 ssh2_pkt_send(ssh, pktout);
8964 /* Wait to be called back with either a response packet, or NULL
8965 * meaning clean up and free our data */
8969 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8970 logevent("X11 forwarding enabled");
8971 ssh->X11_fwd_enabled = TRUE;
8973 logevent("X11 forwarding refused");
8979 static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
8982 struct ssh2_setup_agent_state {
8986 struct Packet *pktout;
8987 crStateP(ssh2_setup_agent_state, ctx);
8991 logevent("Requesting OpenSSH-style agent forwarding");
8992 pktout = ssh2_chanreq_init(ssh->mainchan, "auth-agent-req@openssh.com",
8993 ssh2_setup_agent, s);
8994 ssh2_pkt_send(ssh, pktout);
8996 /* Wait to be called back with either a response packet, or NULL
8997 * meaning clean up and free our data */
9001 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
9002 logevent("Agent forwarding enabled");
9003 ssh->agentfwd_enabled = TRUE;
9005 logevent("Agent forwarding refused");
9011 static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
9014 struct ssh2_setup_pty_state {
9018 struct Packet *pktout;
9019 crStateP(ssh2_setup_pty_state, ctx);
9023 /* Unpick the terminal-speed string. */
9024 /* XXX perhaps we should allow no speeds to be sent. */
9025 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
9026 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
9027 /* Build the pty request. */
9028 pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
9030 ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
9031 ssh2_pkt_adduint32(pktout, ssh->term_width);
9032 ssh2_pkt_adduint32(pktout, ssh->term_height);
9033 ssh2_pkt_adduint32(pktout, 0); /* pixel width */
9034 ssh2_pkt_adduint32(pktout, 0); /* pixel height */
9035 ssh2_pkt_addstring_start(pktout);
9036 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
9037 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
9038 ssh2_pkt_adduint32(pktout, ssh->ispeed);
9039 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
9040 ssh2_pkt_adduint32(pktout, ssh->ospeed);
9041 ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
9042 ssh2_pkt_send(ssh, pktout);
9043 ssh->state = SSH_STATE_INTERMED;
9045 /* Wait to be called back with either a response packet, or NULL
9046 * meaning clean up and free our data */
9050 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
9051 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
9052 ssh->ospeed, ssh->ispeed);
9053 ssh->got_pty = TRUE;
9055 c_write_str(ssh, "Server refused to allocate pty\r\n");
9056 ssh->editing = ssh->echoing = 1;
9063 static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
9066 struct ssh2_setup_env_state {
9068 int num_env, env_left, env_ok;
9071 struct Packet *pktout;
9072 crStateP(ssh2_setup_env_state, ctx);
9077 * Send environment variables.
9079 * Simplest thing here is to send all the requests at once, and
9080 * then wait for a whole bunch of successes or failures.
9086 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
9088 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
9089 pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
9090 ssh2_pkt_addstring(pktout, key);
9091 ssh2_pkt_addstring(pktout, val);
9092 ssh2_pkt_send(ssh, pktout);
9097 logeventf(ssh, "Sent %d environment variables", s->num_env);
9102 s->env_left = s->num_env;
9104 while (s->env_left > 0) {
9105 /* Wait to be called back with either a response packet,
9106 * or NULL meaning clean up and free our data */
9108 if (!pktin) goto out;
9109 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
9114 if (s->env_ok == s->num_env) {
9115 logevent("All environment variables successfully set");
9116 } else if (s->env_ok == 0) {
9117 logevent("All environment variables refused");
9118 c_write_str(ssh, "Server refused to set environment variables\r\n");
9120 logeventf(ssh, "%d environment variables refused",
9121 s->num_env - s->env_ok);
9122 c_write_str(ssh, "Server refused to set all environment variables\r\n");
9130 * Handle the SSH-2 userauth and connection layers.
9132 static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
9134 do_ssh2_authconn(ssh, NULL, 0, pktin);
9137 static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
9141 do_ssh2_authconn(c->ssh, NULL, 0, pktin);
9144 static void do_ssh2_authconn(Ssh ssh, const unsigned char *in, int inlen,
9145 struct Packet *pktin)
9147 struct do_ssh2_authconn_state {
9151 AUTH_TYPE_PUBLICKEY,
9152 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
9153 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
9155 AUTH_TYPE_GSSAPI, /* always QUIET */
9156 AUTH_TYPE_KEYBOARD_INTERACTIVE,
9157 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
9159 int done_service_req;
9160 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
9161 int tried_pubkey_config, done_agent;
9166 int kbd_inter_refused;
9167 int we_are_in, userauth_success;
9168 prompts_t *cur_prompt;
9173 void *publickey_blob;
9174 int publickey_bloblen;
9175 int privatekey_available, privatekey_encrypted;
9176 char *publickey_algorithm;
9177 char *publickey_comment;
9178 unsigned char agent_request[5], *agent_response, *agentp;
9179 int agent_responselen;
9180 unsigned char *pkblob_in_agent;
9182 char *pkblob, *alg, *commentp;
9183 int pklen, alglen, commentlen;
9184 int siglen, retlen, len;
9185 char *q, *agentreq, *ret;
9186 struct Packet *pktout;
9189 struct ssh_gss_library *gsslib;
9190 Ssh_gss_ctx gss_ctx;
9191 Ssh_gss_buf gss_buf;
9192 Ssh_gss_buf gss_rcvtok, gss_sndtok;
9193 Ssh_gss_name gss_srv_name;
9194 Ssh_gss_stat gss_stat;
9197 crState(do_ssh2_authconn_state);
9201 /* Register as a handler for all the messages this coroutine handles. */
9202 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
9203 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
9204 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
9205 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
9206 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
9207 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
9208 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
9209 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
9210 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
9211 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
9212 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
9213 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
9214 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
9215 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
9216 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
9217 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
9218 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
9219 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
9220 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
9221 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
9223 s->done_service_req = FALSE;
9224 s->we_are_in = s->userauth_success = FALSE;
9225 s->agent_response = NULL;
9227 s->tried_gssapi = FALSE;
9230 if (!ssh->bare_connection) {
9231 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
9233 * Request userauth protocol, and await a response to it.
9235 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
9236 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
9237 ssh2_pkt_send(ssh, s->pktout);
9238 crWaitUntilV(pktin);
9239 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
9240 s->done_service_req = TRUE;
9242 if (!s->done_service_req) {
9244 * Request connection protocol directly, without authentication.
9246 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
9247 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9248 ssh2_pkt_send(ssh, s->pktout);
9249 crWaitUntilV(pktin);
9250 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
9251 s->we_are_in = TRUE; /* no auth required */
9253 bombout(("Server refused service request"));
9258 s->we_are_in = TRUE;
9261 /* Arrange to be able to deal with any BANNERs that come in.
9262 * (We do this now as packets may come in during the next bit.) */
9263 bufchain_init(&ssh->banner);
9264 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
9265 ssh2_msg_userauth_banner;
9268 * Misc one-time setup for authentication.
9270 s->publickey_blob = NULL;
9271 if (!s->we_are_in) {
9274 * Load the public half of any configured public key file
9277 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9278 if (!filename_is_null(s->keyfile)) {
9280 logeventf(ssh, "Reading key file \"%.150s\"",
9281 filename_to_str(s->keyfile));
9282 keytype = key_type(s->keyfile);
9283 if (keytype == SSH_KEYTYPE_SSH2 ||
9284 keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 ||
9285 keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
9288 ssh2_userkey_loadpub(s->keyfile,
9289 &s->publickey_algorithm,
9290 &s->publickey_bloblen,
9291 &s->publickey_comment, &error);
9292 if (s->publickey_blob) {
9293 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH2);
9294 if (!s->privatekey_available)
9295 logeventf(ssh, "Key file contains public key only");
9296 s->privatekey_encrypted =
9297 ssh2_userkey_encrypted(s->keyfile, NULL);
9300 logeventf(ssh, "Unable to load key (%s)",
9302 msgbuf = dupprintf("Unable to load key file "
9303 "\"%.150s\" (%s)\r\n",
9304 filename_to_str(s->keyfile),
9306 c_write_str(ssh, msgbuf);
9311 logeventf(ssh, "Unable to use this key file (%s)",
9312 key_type_to_str(keytype));
9313 msgbuf = dupprintf("Unable to use key file \"%.150s\""
9315 filename_to_str(s->keyfile),
9316 key_type_to_str(keytype));
9317 c_write_str(ssh, msgbuf);
9319 s->publickey_blob = NULL;
9324 * Find out about any keys Pageant has (but if there's a
9325 * public key configured, filter out all others).
9328 s->agent_response = NULL;
9329 s->pkblob_in_agent = NULL;
9330 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
9334 logevent("Pageant is running. Requesting keys.");
9336 /* Request the keys held by the agent. */
9337 PUT_32BIT(s->agent_request, 1);
9338 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
9339 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
9340 ssh_agent_callback, ssh)) {
9344 bombout(("Unexpected data from server while"
9345 " waiting for agent response"));
9348 } while (pktin || inlen > 0);
9349 r = ssh->agent_response;
9350 s->agent_responselen = ssh->agent_response_len;
9352 s->agent_response = (unsigned char *) r;
9353 if (s->agent_response && s->agent_responselen >= 5 &&
9354 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
9357 p = s->agent_response + 5;
9358 s->nkeys = toint(GET_32BIT(p));
9361 * Vet the Pageant response to ensure that the key
9362 * count and blob lengths make sense.
9365 logeventf(ssh, "Pageant response contained a negative"
9366 " key count %d", s->nkeys);
9368 goto done_agent_query;
9370 unsigned char *q = p + 4;
9371 int lenleft = s->agent_responselen - 5 - 4;
9373 for (keyi = 0; keyi < s->nkeys; keyi++) {
9374 int bloblen, commentlen;
9376 logeventf(ssh, "Pageant response was truncated");
9378 goto done_agent_query;
9380 bloblen = toint(GET_32BIT(q));
9381 if (bloblen < 0 || bloblen > lenleft) {
9382 logeventf(ssh, "Pageant response was truncated");
9384 goto done_agent_query;
9386 lenleft -= 4 + bloblen;
9388 commentlen = toint(GET_32BIT(q));
9389 if (commentlen < 0 || commentlen > lenleft) {
9390 logeventf(ssh, "Pageant response was truncated");
9392 goto done_agent_query;
9394 lenleft -= 4 + commentlen;
9395 q += 4 + commentlen;
9400 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
9401 if (s->publickey_blob) {
9402 /* See if configured key is in agent. */
9403 for (keyi = 0; keyi < s->nkeys; keyi++) {
9404 s->pklen = toint(GET_32BIT(p));
9405 if (s->pklen == s->publickey_bloblen &&
9406 !memcmp(p+4, s->publickey_blob,
9407 s->publickey_bloblen)) {
9408 logeventf(ssh, "Pageant key #%d matches "
9409 "configured key file", keyi);
9411 s->pkblob_in_agent = p;
9415 p += toint(GET_32BIT(p)) + 4; /* comment */
9417 if (!s->pkblob_in_agent) {
9418 logevent("Configured key file not in Pageant");
9423 logevent("Failed to get reply from Pageant");
9431 * We repeat this whole loop, including the username prompt,
9432 * until we manage a successful authentication. If the user
9433 * types the wrong _password_, they can be sent back to the
9434 * beginning to try another username, if this is configured on.
9435 * (If they specify a username in the config, they are never
9436 * asked, even if they do give a wrong password.)
9438 * I think this best serves the needs of
9440 * - the people who have no configuration, no keys, and just
9441 * want to try repeated (username,password) pairs until they
9442 * type both correctly
9444 * - people who have keys and configuration but occasionally
9445 * need to fall back to passwords
9447 * - people with a key held in Pageant, who might not have
9448 * logged in to a particular machine before; so they want to
9449 * type a username, and then _either_ their key will be
9450 * accepted, _or_ they will type a password. If they mistype
9451 * the username they will want to be able to get back and
9454 s->got_username = FALSE;
9455 while (!s->we_are_in) {
9459 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
9461 * We got a username last time round this loop, and
9462 * with change_username turned off we don't try to get
9465 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
9466 int ret; /* need not be kept over crReturn */
9467 s->cur_prompt = new_prompts(ssh->frontend);
9468 s->cur_prompt->to_server = TRUE;
9469 s->cur_prompt->name = dupstr("SSH login name");
9470 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
9471 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9474 crWaitUntilV(!pktin);
9475 ret = get_userpass_input(s->cur_prompt, in, inlen);
9480 * get_userpass_input() failed to get a username.
9483 free_prompts(s->cur_prompt);
9484 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
9487 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
9488 free_prompts(s->cur_prompt);
9491 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
9492 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
9493 c_write_str(ssh, stuff);
9497 s->got_username = TRUE;
9500 * Send an authentication request using method "none": (a)
9501 * just in case it succeeds, and (b) so that we know what
9502 * authentication methods we can usefully try next.
9504 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9506 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9507 ssh2_pkt_addstring(s->pktout, ssh->username);
9508 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
9509 ssh2_pkt_addstring(s->pktout, "none"); /* method */
9510 ssh2_pkt_send(ssh, s->pktout);
9511 s->type = AUTH_TYPE_NONE;
9513 s->we_are_in = FALSE;
9515 s->tried_pubkey_config = FALSE;
9516 s->kbd_inter_refused = FALSE;
9518 /* Reset agent request state. */
9519 s->done_agent = FALSE;
9520 if (s->agent_response) {
9521 if (s->pkblob_in_agent) {
9522 s->agentp = s->pkblob_in_agent;
9524 s->agentp = s->agent_response + 5 + 4;
9530 char *methods = NULL;
9534 * Wait for the result of the last authentication request.
9537 crWaitUntilV(pktin);
9539 * Now is a convenient point to spew any banner material
9540 * that we've accumulated. (This should ensure that when
9541 * we exit the auth loop, we haven't any left to deal
9545 int size = bufchain_size(&ssh->banner);
9547 * Don't show the banner if we're operating in
9548 * non-verbose non-interactive mode. (It's probably
9549 * a script, which means nobody will read the
9550 * banner _anyway_, and moreover the printing of
9551 * the banner will screw up processing on the
9552 * output of (say) plink.)
9554 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
9555 char *banner = snewn(size, char);
9556 bufchain_fetch(&ssh->banner, banner, size);
9557 c_write_untrusted(ssh, banner, size);
9560 bufchain_clear(&ssh->banner);
9562 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
9563 logevent("Access granted");
9564 s->we_are_in = s->userauth_success = TRUE;
9568 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
9569 bombout(("Strange packet received during authentication: "
9570 "type %d", pktin->type));
9577 * OK, we're now sitting on a USERAUTH_FAILURE message, so
9578 * we can look at the string in it and know what we can
9579 * helpfully try next.
9581 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
9582 ssh_pkt_getstring(pktin, &methods, &methlen);
9583 if (!ssh2_pkt_getbool(pktin)) {
9585 * We have received an unequivocal Access
9586 * Denied. This can translate to a variety of
9587 * messages, or no message at all.
9589 * For forms of authentication which are attempted
9590 * implicitly, by which I mean without printing
9591 * anything in the window indicating that we're
9592 * trying them, we should never print 'Access
9595 * If we do print a message saying that we're
9596 * attempting some kind of authentication, it's OK
9597 * to print a followup message saying it failed -
9598 * but the message may sometimes be more specific
9599 * than simply 'Access denied'.
9601 * Additionally, if we'd just tried password
9602 * authentication, we should break out of this
9603 * whole loop so as to go back to the username
9604 * prompt (iff we're configured to allow
9605 * username change attempts).
9607 if (s->type == AUTH_TYPE_NONE) {
9609 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
9610 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
9611 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
9612 c_write_str(ssh, "Server refused our key\r\n");
9613 logevent("Server refused our key");
9614 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
9615 /* This _shouldn't_ happen except by a
9616 * protocol bug causing client and server to
9617 * disagree on what is a correct signature. */
9618 c_write_str(ssh, "Server refused public-key signature"
9619 " despite accepting key!\r\n");
9620 logevent("Server refused public-key signature"
9621 " despite accepting key!");
9622 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
9623 /* quiet, so no c_write */
9624 logevent("Server refused keyboard-interactive authentication");
9625 } else if (s->type==AUTH_TYPE_GSSAPI) {
9626 /* always quiet, so no c_write */
9627 /* also, the code down in the GSSAPI block has
9628 * already logged this in the Event Log */
9629 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
9630 logevent("Keyboard-interactive authentication failed");
9631 c_write_str(ssh, "Access denied\r\n");
9633 assert(s->type == AUTH_TYPE_PASSWORD);
9634 logevent("Password authentication failed");
9635 c_write_str(ssh, "Access denied\r\n");
9637 if (conf_get_int(ssh->conf, CONF_change_username)) {
9638 /* XXX perhaps we should allow
9639 * keyboard-interactive to do this too? */
9640 s->we_are_in = FALSE;
9645 c_write_str(ssh, "Further authentication required\r\n");
9646 logevent("Further authentication required");
9650 in_commasep_string("publickey", methods, methlen);
9652 in_commasep_string("password", methods, methlen);
9653 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
9654 in_commasep_string("keyboard-interactive", methods, methlen);
9656 if (conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
9657 in_commasep_string("gssapi-with-mic", methods, methlen)) {
9658 /* Try loading the GSS libraries and see if we
9661 ssh->gsslibs = ssh_gss_setup(ssh->conf);
9662 s->can_gssapi = (ssh->gsslibs->nlibraries > 0);
9664 /* No point in even bothering to try to load the
9665 * GSS libraries, if the user configuration and
9666 * server aren't both prepared to attempt GSSAPI
9667 * auth in the first place. */
9668 s->can_gssapi = FALSE;
9673 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9675 if (s->can_pubkey && !s->done_agent && s->nkeys) {
9678 * Attempt public-key authentication using a key from Pageant.
9681 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9683 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
9685 /* Unpack key from agent response */
9686 s->pklen = toint(GET_32BIT(s->agentp));
9688 s->pkblob = (char *)s->agentp;
9689 s->agentp += s->pklen;
9690 s->alglen = toint(GET_32BIT(s->pkblob));
9691 s->alg = s->pkblob + 4;
9692 s->commentlen = toint(GET_32BIT(s->agentp));
9694 s->commentp = (char *)s->agentp;
9695 s->agentp += s->commentlen;
9696 /* s->agentp now points at next key, if any */
9698 /* See if server will accept it */
9699 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9700 ssh2_pkt_addstring(s->pktout, ssh->username);
9701 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9702 /* service requested */
9703 ssh2_pkt_addstring(s->pktout, "publickey");
9705 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
9706 ssh2_pkt_addstring_start(s->pktout);
9707 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9708 ssh2_pkt_addstring_start(s->pktout);
9709 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9710 ssh2_pkt_send(ssh, s->pktout);
9711 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
9713 crWaitUntilV(pktin);
9714 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9716 /* Offer of key refused. */
9723 if (flags & FLAG_VERBOSE) {
9724 c_write_str(ssh, "Authenticating with "
9726 c_write(ssh, s->commentp, s->commentlen);
9727 c_write_str(ssh, "\" from agent\r\n");
9731 * Server is willing to accept the key.
9732 * Construct a SIGN_REQUEST.
9734 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9735 ssh2_pkt_addstring(s->pktout, ssh->username);
9736 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9737 /* service requested */
9738 ssh2_pkt_addstring(s->pktout, "publickey");
9740 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
9741 ssh2_pkt_addstring_start(s->pktout);
9742 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9743 ssh2_pkt_addstring_start(s->pktout);
9744 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9746 /* Ask agent for signature. */
9747 s->siglen = s->pktout->length - 5 + 4 +
9748 ssh->v2_session_id_len;
9749 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9751 s->len = 1; /* message type */
9752 s->len += 4 + s->pklen; /* key blob */
9753 s->len += 4 + s->siglen; /* data to sign */
9754 s->len += 4; /* flags */
9755 s->agentreq = snewn(4 + s->len, char);
9756 PUT_32BIT(s->agentreq, s->len);
9757 s->q = s->agentreq + 4;
9758 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
9759 PUT_32BIT(s->q, s->pklen);
9761 memcpy(s->q, s->pkblob, s->pklen);
9763 PUT_32BIT(s->q, s->siglen);
9765 /* Now the data to be signed... */
9766 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9767 PUT_32BIT(s->q, ssh->v2_session_id_len);
9770 memcpy(s->q, ssh->v2_session_id,
9771 ssh->v2_session_id_len);
9772 s->q += ssh->v2_session_id_len;
9773 memcpy(s->q, s->pktout->data + 5,
9774 s->pktout->length - 5);
9775 s->q += s->pktout->length - 5;
9776 /* And finally the (zero) flags word. */
9778 if (!agent_query(s->agentreq, s->len + 4,
9780 ssh_agent_callback, ssh)) {
9784 bombout(("Unexpected data from server"
9785 " while waiting for agent"
9789 } while (pktin || inlen > 0);
9790 vret = ssh->agent_response;
9791 s->retlen = ssh->agent_response_len;
9796 if (s->retlen >= 9 &&
9797 s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
9798 GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
9799 logevent("Sending Pageant's response");
9800 ssh2_add_sigblob(ssh, s->pktout,
9801 s->pkblob, s->pklen,
9803 GET_32BIT(s->ret + 5));
9804 ssh2_pkt_send(ssh, s->pktout);
9805 s->type = AUTH_TYPE_PUBLICKEY;
9807 /* FIXME: less drastic response */
9808 bombout(("Pageant failed to answer challenge"));
9814 /* Do we have any keys left to try? */
9815 if (s->pkblob_in_agent) {
9816 s->done_agent = TRUE;
9817 s->tried_pubkey_config = TRUE;
9820 if (s->keyi >= s->nkeys)
9821 s->done_agent = TRUE;
9824 } else if (s->can_pubkey && s->publickey_blob &&
9825 s->privatekey_available && !s->tried_pubkey_config) {
9827 struct ssh2_userkey *key; /* not live over crReturn */
9828 char *passphrase; /* not live over crReturn */
9830 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9832 s->tried_pubkey_config = TRUE;
9835 * Try the public key supplied in the configuration.
9837 * First, offer the public blob to see if the server is
9838 * willing to accept it.
9840 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9841 ssh2_pkt_addstring(s->pktout, ssh->username);
9842 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9843 /* service requested */
9844 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
9845 ssh2_pkt_addbool(s->pktout, FALSE);
9846 /* no signature included */
9847 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
9848 ssh2_pkt_addstring_start(s->pktout);
9849 ssh2_pkt_addstring_data(s->pktout,
9850 (char *)s->publickey_blob,
9851 s->publickey_bloblen);
9852 ssh2_pkt_send(ssh, s->pktout);
9853 logevent("Offered public key");
9855 crWaitUntilV(pktin);
9856 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9857 /* Key refused. Give up. */
9858 s->gotit = TRUE; /* reconsider message next loop */
9859 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
9860 continue; /* process this new message */
9862 logevent("Offer of public key accepted");
9865 * Actually attempt a serious authentication using
9868 if (flags & FLAG_VERBOSE) {
9869 c_write_str(ssh, "Authenticating with public key \"");
9870 c_write_str(ssh, s->publickey_comment);
9871 c_write_str(ssh, "\"\r\n");
9875 const char *error; /* not live over crReturn */
9876 if (s->privatekey_encrypted) {
9878 * Get a passphrase from the user.
9880 int ret; /* need not be kept over crReturn */
9881 s->cur_prompt = new_prompts(ssh->frontend);
9882 s->cur_prompt->to_server = FALSE;
9883 s->cur_prompt->name = dupstr("SSH key passphrase");
9884 add_prompt(s->cur_prompt,
9885 dupprintf("Passphrase for key \"%.100s\": ",
9886 s->publickey_comment),
9888 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9891 crWaitUntilV(!pktin);
9892 ret = get_userpass_input(s->cur_prompt,
9897 /* Failed to get a passphrase. Terminate. */
9898 free_prompts(s->cur_prompt);
9899 ssh_disconnect(ssh, NULL,
9900 "Unable to authenticate",
9901 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9906 dupstr(s->cur_prompt->prompts[0]->result);
9907 free_prompts(s->cur_prompt);
9909 passphrase = NULL; /* no passphrase needed */
9913 * Try decrypting the key.
9915 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9916 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
9918 /* burn the evidence */
9919 smemclr(passphrase, strlen(passphrase));
9922 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
9924 (key == SSH2_WRONG_PASSPHRASE)) {
9925 c_write_str(ssh, "Wrong passphrase\r\n");
9927 /* and loop again */
9929 c_write_str(ssh, "Unable to load private key (");
9930 c_write_str(ssh, error);
9931 c_write_str(ssh, ")\r\n");
9933 break; /* try something else */
9939 unsigned char *pkblob, *sigblob, *sigdata;
9940 int pkblob_len, sigblob_len, sigdata_len;
9944 * We have loaded the private key and the server
9945 * has announced that it's willing to accept it.
9946 * Hallelujah. Generate a signature and send it.
9948 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9949 ssh2_pkt_addstring(s->pktout, ssh->username);
9950 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9951 /* service requested */
9952 ssh2_pkt_addstring(s->pktout, "publickey");
9954 ssh2_pkt_addbool(s->pktout, TRUE);
9955 /* signature follows */
9956 ssh2_pkt_addstring(s->pktout, key->alg->name);
9957 pkblob = key->alg->public_blob(key->data,
9959 ssh2_pkt_addstring_start(s->pktout);
9960 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
9964 * The data to be signed is:
9968 * followed by everything so far placed in the
9971 sigdata_len = s->pktout->length - 5 + 4 +
9972 ssh->v2_session_id_len;
9973 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9975 sigdata = snewn(sigdata_len, unsigned char);
9977 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9978 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
9981 memcpy(sigdata+p, ssh->v2_session_id,
9982 ssh->v2_session_id_len);
9983 p += ssh->v2_session_id_len;
9984 memcpy(sigdata+p, s->pktout->data + 5,
9985 s->pktout->length - 5);
9986 p += s->pktout->length - 5;
9987 assert(p == sigdata_len);
9988 sigblob = key->alg->sign(key->data, (char *)sigdata,
9989 sigdata_len, &sigblob_len);
9990 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
9991 sigblob, sigblob_len);
9996 ssh2_pkt_send(ssh, s->pktout);
9997 logevent("Sent public key signature");
9998 s->type = AUTH_TYPE_PUBLICKEY;
9999 key->alg->freekey(key->data);
10000 sfree(key->comment);
10005 } else if (s->can_gssapi && !s->tried_gssapi) {
10007 /* GSSAPI Authentication */
10009 int micoffset, len;
10012 s->type = AUTH_TYPE_GSSAPI;
10013 s->tried_gssapi = TRUE;
10015 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
10018 * Pick the highest GSS library on the preference
10024 for (i = 0; i < ngsslibs; i++) {
10025 int want_id = conf_get_int_int(ssh->conf,
10026 CONF_ssh_gsslist, i);
10027 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
10028 if (ssh->gsslibs->libraries[j].id == want_id) {
10029 s->gsslib = &ssh->gsslibs->libraries[j];
10030 goto got_gsslib; /* double break */
10035 * We always expect to have found something in
10036 * the above loop: we only came here if there
10037 * was at least one viable GSS library, and the
10038 * preference list should always mention
10039 * everything and only change the order.
10044 if (s->gsslib->gsslogmsg)
10045 logevent(s->gsslib->gsslogmsg);
10047 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
10048 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10049 ssh2_pkt_addstring(s->pktout, ssh->username);
10050 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10051 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
10052 logevent("Attempting GSSAPI authentication");
10054 /* add mechanism info */
10055 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
10057 /* number of GSSAPI mechanisms */
10058 ssh2_pkt_adduint32(s->pktout,1);
10060 /* length of OID + 2 */
10061 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
10062 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
10064 /* length of OID */
10065 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
10067 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
10068 s->gss_buf.length);
10069 ssh2_pkt_send(ssh, s->pktout);
10070 crWaitUntilV(pktin);
10071 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
10072 logevent("GSSAPI authentication request refused");
10076 /* check returned packet ... */
10078 ssh_pkt_getstring(pktin, &data, &len);
10079 s->gss_rcvtok.value = data;
10080 s->gss_rcvtok.length = len;
10081 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
10082 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
10083 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
10084 memcmp((char *)s->gss_rcvtok.value + 2,
10085 s->gss_buf.value,s->gss_buf.length) ) {
10086 logevent("GSSAPI authentication - wrong response from server");
10090 /* now start running */
10091 s->gss_stat = s->gsslib->import_name(s->gsslib,
10094 if (s->gss_stat != SSH_GSS_OK) {
10095 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
10096 logevent("GSSAPI import name failed - Bad service name");
10098 logevent("GSSAPI import name failed");
10102 /* fetch TGT into GSS engine */
10103 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
10105 if (s->gss_stat != SSH_GSS_OK) {
10106 logevent("GSSAPI authentication failed to get credentials");
10107 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10111 /* initial tokens are empty */
10112 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
10113 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
10115 /* now enter the loop */
10117 s->gss_stat = s->gsslib->init_sec_context
10121 conf_get_int(ssh->conf, CONF_gssapifwd),
10125 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
10126 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
10127 logevent("GSSAPI authentication initialisation failed");
10129 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
10130 &s->gss_buf) == SSH_GSS_OK) {
10131 logevent(s->gss_buf.value);
10132 sfree(s->gss_buf.value);
10137 logevent("GSSAPI authentication initialised");
10139 /* Client and server now exchange tokens until GSSAPI
10140 * no longer says CONTINUE_NEEDED */
10142 if (s->gss_sndtok.length != 0) {
10143 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
10144 ssh_pkt_addstring_start(s->pktout);
10145 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
10146 ssh2_pkt_send(ssh, s->pktout);
10147 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
10150 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
10151 crWaitUntilV(pktin);
10152 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
10153 logevent("GSSAPI authentication - bad server response");
10154 s->gss_stat = SSH_GSS_FAILURE;
10157 ssh_pkt_getstring(pktin, &data, &len);
10158 s->gss_rcvtok.value = data;
10159 s->gss_rcvtok.length = len;
10161 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
10163 if (s->gss_stat != SSH_GSS_OK) {
10164 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10165 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
10168 logevent("GSSAPI authentication loop finished OK");
10170 /* Now send the MIC */
10172 s->pktout = ssh2_pkt_init(0);
10173 micoffset = s->pktout->length;
10174 ssh_pkt_addstring_start(s->pktout);
10175 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
10176 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
10177 ssh_pkt_addstring(s->pktout, ssh->username);
10178 ssh_pkt_addstring(s->pktout, "ssh-connection");
10179 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
10181 s->gss_buf.value = (char *)s->pktout->data + micoffset;
10182 s->gss_buf.length = s->pktout->length - micoffset;
10184 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
10185 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
10186 ssh_pkt_addstring_start(s->pktout);
10187 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
10188 ssh2_pkt_send(ssh, s->pktout);
10189 s->gsslib->free_mic(s->gsslib, &mic);
10193 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10194 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
10197 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
10200 * Keyboard-interactive authentication.
10203 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
10205 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
10207 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10208 ssh2_pkt_addstring(s->pktout, ssh->username);
10209 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10210 /* service requested */
10211 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
10213 ssh2_pkt_addstring(s->pktout, ""); /* lang */
10214 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
10215 ssh2_pkt_send(ssh, s->pktout);
10217 logevent("Attempting keyboard-interactive authentication");
10219 crWaitUntilV(pktin);
10220 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
10221 /* Server is not willing to do keyboard-interactive
10222 * at all (or, bizarrely but legally, accepts the
10223 * user without actually issuing any prompts).
10224 * Give up on it entirely. */
10226 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
10227 s->kbd_inter_refused = TRUE; /* don't try it again */
10232 * Loop while the server continues to send INFO_REQUESTs.
10234 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
10236 char *name, *inst, *lang;
10237 int name_len, inst_len, lang_len;
10241 * We've got a fresh USERAUTH_INFO_REQUEST.
10242 * Get the preamble and start building a prompt.
10244 ssh_pkt_getstring(pktin, &name, &name_len);
10245 ssh_pkt_getstring(pktin, &inst, &inst_len);
10246 ssh_pkt_getstring(pktin, &lang, &lang_len);
10247 s->cur_prompt = new_prompts(ssh->frontend);
10248 s->cur_prompt->to_server = TRUE;
10251 * Get any prompt(s) from the packet.
10253 s->num_prompts = ssh_pkt_getuint32(pktin);
10254 for (i = 0; i < s->num_prompts; i++) {
10258 static char noprompt[] =
10259 "<server failed to send prompt>: ";
10261 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10262 echo = ssh2_pkt_getbool(pktin);
10265 prompt_len = lenof(noprompt)-1;
10267 add_prompt(s->cur_prompt,
10268 dupprintf("%.*s", prompt_len, prompt),
10273 /* FIXME: better prefix to distinguish from
10274 * local prompts? */
10275 s->cur_prompt->name =
10276 dupprintf("SSH server: %.*s", name_len, name);
10277 s->cur_prompt->name_reqd = TRUE;
10279 s->cur_prompt->name =
10280 dupstr("SSH server authentication");
10281 s->cur_prompt->name_reqd = FALSE;
10283 /* We add a prefix to try to make it clear that a prompt
10284 * has come from the server.
10285 * FIXME: ugly to print "Using..." in prompt _every_
10286 * time round. Can this be done more subtly? */
10287 /* Special case: for reasons best known to themselves,
10288 * some servers send k-i requests with no prompts and
10289 * nothing to display. Keep quiet in this case. */
10290 if (s->num_prompts || name_len || inst_len) {
10291 s->cur_prompt->instruction =
10292 dupprintf("Using keyboard-interactive authentication.%s%.*s",
10293 inst_len ? "\n" : "", inst_len, inst);
10294 s->cur_prompt->instr_reqd = TRUE;
10296 s->cur_prompt->instr_reqd = FALSE;
10300 * Display any instructions, and get the user's
10304 int ret; /* not live over crReturn */
10305 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10308 crWaitUntilV(!pktin);
10309 ret = get_userpass_input(s->cur_prompt, in, inlen);
10314 * Failed to get responses. Terminate.
10316 free_prompts(s->cur_prompt);
10317 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10318 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10325 * Send the response(s) to the server.
10327 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
10328 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
10329 for (i=0; i < s->num_prompts; i++) {
10330 ssh2_pkt_addstring(s->pktout,
10331 s->cur_prompt->prompts[i]->result);
10333 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10336 * Free the prompts structure from this iteration.
10337 * If there's another, a new one will be allocated
10338 * when we return to the top of this while loop.
10340 free_prompts(s->cur_prompt);
10343 * Get the next packet in case it's another
10346 crWaitUntilV(pktin);
10351 * We should have SUCCESS or FAILURE now.
10355 } else if (s->can_passwd) {
10358 * Plain old password authentication.
10360 int ret; /* not live over crReturn */
10361 int changereq_first_time; /* not live over crReturn */
10363 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
10365 s->cur_prompt = new_prompts(ssh->frontend);
10366 s->cur_prompt->to_server = TRUE;
10367 s->cur_prompt->name = dupstr("SSH password");
10368 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
10373 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10376 crWaitUntilV(!pktin);
10377 ret = get_userpass_input(s->cur_prompt, in, inlen);
10382 * Failed to get responses. Terminate.
10384 free_prompts(s->cur_prompt);
10385 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10386 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10391 * Squirrel away the password. (We may need it later if
10392 * asked to change it.)
10394 s->password = dupstr(s->cur_prompt->prompts[0]->result);
10395 free_prompts(s->cur_prompt);
10398 * Send the password packet.
10400 * We pad out the password packet to 256 bytes to make
10401 * it harder for an attacker to find the length of the
10404 * Anyone using a password longer than 256 bytes
10405 * probably doesn't have much to worry about from
10406 * people who find out how long their password is!
10408 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10409 ssh2_pkt_addstring(s->pktout, ssh->username);
10410 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10411 /* service requested */
10412 ssh2_pkt_addstring(s->pktout, "password");
10413 ssh2_pkt_addbool(s->pktout, FALSE);
10414 ssh2_pkt_addstring(s->pktout, s->password);
10415 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10416 logevent("Sent password");
10417 s->type = AUTH_TYPE_PASSWORD;
10420 * Wait for next packet, in case it's a password change
10423 crWaitUntilV(pktin);
10424 changereq_first_time = TRUE;
10426 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
10429 * We're being asked for a new password
10430 * (perhaps not for the first time).
10431 * Loop until the server accepts it.
10434 int got_new = FALSE; /* not live over crReturn */
10435 char *prompt; /* not live over crReturn */
10436 int prompt_len; /* not live over crReturn */
10440 if (changereq_first_time)
10441 msg = "Server requested password change";
10443 msg = "Server rejected new password";
10445 c_write_str(ssh, msg);
10446 c_write_str(ssh, "\r\n");
10449 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10451 s->cur_prompt = new_prompts(ssh->frontend);
10452 s->cur_prompt->to_server = TRUE;
10453 s->cur_prompt->name = dupstr("New SSH password");
10454 s->cur_prompt->instruction =
10455 dupprintf("%.*s", prompt_len, NULLTOEMPTY(prompt));
10456 s->cur_prompt->instr_reqd = TRUE;
10458 * There's no explicit requirement in the protocol
10459 * for the "old" passwords in the original and
10460 * password-change messages to be the same, and
10461 * apparently some Cisco kit supports password change
10462 * by the user entering a blank password originally
10463 * and the real password subsequently, so,
10464 * reluctantly, we prompt for the old password again.
10466 * (On the other hand, some servers don't even bother
10467 * to check this field.)
10469 add_prompt(s->cur_prompt,
10470 dupstr("Current password (blank for previously entered password): "),
10472 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
10474 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
10478 * Loop until the user manages to enter the same
10483 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10486 crWaitUntilV(!pktin);
10487 ret = get_userpass_input(s->cur_prompt, in, inlen);
10492 * Failed to get responses. Terminate.
10494 /* burn the evidence */
10495 free_prompts(s->cur_prompt);
10496 smemclr(s->password, strlen(s->password));
10497 sfree(s->password);
10498 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10499 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10505 * If the user specified a new original password
10506 * (IYSWIM), overwrite any previously specified
10508 * (A side effect is that the user doesn't have to
10509 * re-enter it if they louse up the new password.)
10511 if (s->cur_prompt->prompts[0]->result[0]) {
10512 smemclr(s->password, strlen(s->password));
10513 /* burn the evidence */
10514 sfree(s->password);
10516 dupstr(s->cur_prompt->prompts[0]->result);
10520 * Check the two new passwords match.
10522 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
10523 s->cur_prompt->prompts[2]->result)
10526 /* They don't. Silly user. */
10527 c_write_str(ssh, "Passwords do not match\r\n");
10532 * Send the new password (along with the old one).
10533 * (see above for padding rationale)
10535 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10536 ssh2_pkt_addstring(s->pktout, ssh->username);
10537 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10538 /* service requested */
10539 ssh2_pkt_addstring(s->pktout, "password");
10540 ssh2_pkt_addbool(s->pktout, TRUE);
10541 ssh2_pkt_addstring(s->pktout, s->password);
10542 ssh2_pkt_addstring(s->pktout,
10543 s->cur_prompt->prompts[1]->result);
10544 free_prompts(s->cur_prompt);
10545 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10546 logevent("Sent new password");
10549 * Now see what the server has to say about it.
10550 * (If it's CHANGEREQ again, it's not happy with the
10553 crWaitUntilV(pktin);
10554 changereq_first_time = FALSE;
10559 * We need to reexamine the current pktin at the top
10560 * of the loop. Either:
10561 * - we weren't asked to change password at all, in
10562 * which case it's a SUCCESS or FAILURE with the
10564 * - we sent a new password, and the server was
10565 * either OK with it (SUCCESS or FAILURE w/partial
10566 * success) or unhappy with the _old_ password
10567 * (FAILURE w/o partial success)
10568 * In any of these cases, we go back to the top of
10569 * the loop and start again.
10574 * We don't need the old password any more, in any
10575 * case. Burn the evidence.
10577 smemclr(s->password, strlen(s->password));
10578 sfree(s->password);
10581 char *str = dupprintf("No supported authentication methods available"
10582 " (server sent: %.*s)",
10585 ssh_disconnect(ssh, str,
10586 "No supported authentication methods available",
10587 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
10597 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
10599 /* Clear up various bits and pieces from authentication. */
10600 if (s->publickey_blob) {
10601 sfree(s->publickey_algorithm);
10602 sfree(s->publickey_blob);
10603 sfree(s->publickey_comment);
10605 if (s->agent_response)
10606 sfree(s->agent_response);
10608 if (s->userauth_success && !ssh->bare_connection) {
10610 * We've just received USERAUTH_SUCCESS, and we haven't sent any
10611 * packets since. Signal the transport layer to consider enacting
10612 * delayed compression.
10614 * (Relying on we_are_in is not sufficient, as
10615 * draft-miller-secsh-compression-delayed is quite clear that it
10616 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
10617 * become set for other reasons.)
10619 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
10622 ssh->channels = newtree234(ssh_channelcmp);
10625 * Set up handlers for some connection protocol messages, so we
10626 * don't have to handle them repeatedly in this coroutine.
10628 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
10629 ssh2_msg_channel_window_adjust;
10630 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
10631 ssh2_msg_global_request;
10634 * Create the main session channel.
10636 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
10637 ssh->mainchan = NULL;
10639 ssh->mainchan = snew(struct ssh_channel);
10640 ssh->mainchan->ssh = ssh;
10641 ssh2_channel_init(ssh->mainchan);
10643 if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
10645 * Just start a direct-tcpip channel and use it as the main
10648 ssh_send_port_open(ssh->mainchan,
10649 conf_get_str(ssh->conf, CONF_ssh_nc_host),
10650 conf_get_int(ssh->conf, CONF_ssh_nc_port),
10652 ssh->ncmode = TRUE;
10654 s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
10655 logevent("Opening session as main channel");
10656 ssh2_pkt_send(ssh, s->pktout);
10657 ssh->ncmode = FALSE;
10659 crWaitUntilV(pktin);
10660 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
10661 bombout(("Server refused to open channel"));
10663 /* FIXME: error data comes back in FAILURE packet */
10665 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
10666 bombout(("Server's channel confirmation cited wrong channel"));
10669 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
10670 ssh->mainchan->halfopen = FALSE;
10671 ssh->mainchan->type = CHAN_MAINSESSION;
10672 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
10673 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
10674 add234(ssh->channels, ssh->mainchan);
10675 update_specials_menu(ssh->frontend);
10676 logevent("Opened main channel");
10680 * Now we have a channel, make dispatch table entries for
10681 * general channel-based messages.
10683 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
10684 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
10685 ssh2_msg_channel_data;
10686 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
10687 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
10688 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
10689 ssh2_msg_channel_open_confirmation;
10690 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
10691 ssh2_msg_channel_open_failure;
10692 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
10693 ssh2_msg_channel_request;
10694 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
10695 ssh2_msg_channel_open;
10696 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
10697 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
10700 * Now the connection protocol is properly up and running, with
10701 * all those dispatch table entries, so it's safe to let
10702 * downstreams start trying to open extra channels through us.
10704 if (ssh->connshare)
10705 share_activate(ssh->connshare, ssh->v_s);
10707 if (ssh->mainchan && ssh_is_simple(ssh)) {
10709 * This message indicates to the server that we promise
10710 * not to try to run any other channel in parallel with
10711 * this one, so it's safe for it to advertise a very large
10712 * window and leave the flow control to TCP.
10714 s->pktout = ssh2_chanreq_init(ssh->mainchan,
10715 "simple@putty.projects.tartarus.org",
10717 ssh2_pkt_send(ssh, s->pktout);
10721 * Enable port forwardings.
10723 ssh_setup_portfwd(ssh, ssh->conf);
10725 if (ssh->mainchan && !ssh->ncmode) {
10727 * Send the CHANNEL_REQUESTS for the main session channel.
10728 * Each one is handled by its own little asynchronous
10732 /* Potentially enable X11 forwarding. */
10733 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
10735 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
10737 if (!ssh->x11disp) {
10738 /* FIXME: return an error message from x11_setup_display */
10739 logevent("X11 forwarding not enabled: unable to"
10740 " initialise X display");
10742 ssh->x11auth = x11_invent_fake_auth
10743 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
10744 ssh->x11auth->disp = ssh->x11disp;
10746 ssh2_setup_x11(ssh->mainchan, NULL, NULL);
10750 /* Potentially enable agent forwarding. */
10751 if (ssh_agent_forwarding_permitted(ssh))
10752 ssh2_setup_agent(ssh->mainchan, NULL, NULL);
10754 /* Now allocate a pty for the session. */
10755 if (!conf_get_int(ssh->conf, CONF_nopty))
10756 ssh2_setup_pty(ssh->mainchan, NULL, NULL);
10758 /* Send environment variables. */
10759 ssh2_setup_env(ssh->mainchan, NULL, NULL);
10762 * Start a shell or a remote command. We may have to attempt
10763 * this twice if the config data has provided a second choice
10770 if (ssh->fallback_cmd) {
10771 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
10772 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
10774 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
10775 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
10779 s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
10780 ssh2_response_authconn, NULL);
10781 ssh2_pkt_addstring(s->pktout, cmd);
10783 s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
10784 ssh2_response_authconn, NULL);
10785 ssh2_pkt_addstring(s->pktout, cmd);
10787 s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
10788 ssh2_response_authconn, NULL);
10790 ssh2_pkt_send(ssh, s->pktout);
10792 crWaitUntilV(pktin);
10794 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
10795 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
10796 bombout(("Unexpected response to shell/command request:"
10797 " packet type %d", pktin->type));
10801 * We failed to start the command. If this is the
10802 * fallback command, we really are finished; if it's
10803 * not, and if the fallback command exists, try falling
10804 * back to it before complaining.
10806 if (!ssh->fallback_cmd &&
10807 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
10808 logevent("Primary command failed; attempting fallback");
10809 ssh->fallback_cmd = TRUE;
10812 bombout(("Server refused to start a shell/command"));
10815 logevent("Started a shell/command");
10820 ssh->editing = ssh->echoing = TRUE;
10823 ssh->state = SSH_STATE_SESSION;
10824 if (ssh->size_needed)
10825 ssh_size(ssh, ssh->term_width, ssh->term_height);
10826 if (ssh->eof_needed)
10827 ssh_special(ssh, TS_EOF);
10833 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
10841 * _All_ the connection-layer packets we expect to
10842 * receive are now handled by the dispatch table.
10843 * Anything that reaches here must be bogus.
10846 bombout(("Strange packet received: type %d", pktin->type));
10848 } else if (ssh->mainchan) {
10850 * We have spare data. Add it to the channel buffer.
10852 ssh_send_channel_data(ssh->mainchan, (char *)in, inlen);
10860 * Handlers for SSH-2 messages that might arrive at any moment.
10862 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
10864 /* log reason code in disconnect message */
10866 int reason, msglen;
10868 reason = ssh_pkt_getuint32(pktin);
10869 ssh_pkt_getstring(pktin, &msg, &msglen);
10871 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
10872 buf = dupprintf("Received disconnect message (%s)",
10873 ssh2_disconnect_reasons[reason]);
10875 buf = dupprintf("Received disconnect message (unknown"
10876 " type %d)", reason);
10880 buf = dupprintf("Disconnection message text: %.*s",
10881 msglen, NULLTOEMPTY(msg));
10883 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
10885 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
10886 ssh2_disconnect_reasons[reason] : "unknown",
10887 msglen, NULLTOEMPTY(msg)));
10891 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
10893 /* log the debug message */
10897 /* XXX maybe we should actually take notice of the return value */
10898 ssh2_pkt_getbool(pktin);
10899 ssh_pkt_getstring(pktin, &msg, &msglen);
10901 logeventf(ssh, "Remote debug message: %.*s", msglen, NULLTOEMPTY(msg));
10904 static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
10906 do_ssh2_transport(ssh, NULL, 0, pktin);
10910 * Called if we receive a packet that isn't allowed by the protocol.
10911 * This only applies to packets whose meaning PuTTY understands.
10912 * Entirely unknown packets are handled below.
10914 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
10916 char *buf = dupprintf("Server protocol violation: unexpected %s packet",
10917 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
10919 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
10923 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
10925 struct Packet *pktout;
10926 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
10927 ssh2_pkt_adduint32(pktout, pktin->sequence);
10929 * UNIMPLEMENTED messages MUST appear in the same order as the
10930 * messages they respond to. Hence, never queue them.
10932 ssh2_pkt_send_noqueue(ssh, pktout);
10936 * Handle the top-level SSH-2 protocol.
10938 static void ssh2_protocol_setup(Ssh ssh)
10943 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10945 for (i = 0; i < 256; i++)
10946 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10949 * Initially, we only accept transport messages (and a few generic
10950 * ones). do_ssh2_authconn will add more when it starts.
10951 * Messages that are understood but not currently acceptable go to
10952 * ssh2_msg_unexpected.
10954 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10955 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
10956 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
10957 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
10958 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
10959 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
10960 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
10961 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
10962 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
10963 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
10964 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
10965 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
10966 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
10967 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
10968 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
10969 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
10970 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
10971 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
10972 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
10973 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10974 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10975 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10976 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10977 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10978 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10979 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10980 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10981 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10982 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10983 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10984 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10985 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10986 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10989 * These messages have a special handler from the start.
10991 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
10992 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
10993 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
10996 static void ssh2_bare_connection_protocol_setup(Ssh ssh)
11001 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
11003 for (i = 0; i < 256; i++)
11004 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
11007 * Initially, we set all ssh-connection messages to 'unexpected';
11008 * do_ssh2_authconn will fill things in properly. We also handle a
11009 * couple of messages from the transport protocol which aren't
11010 * related to key exchange (UNIMPLEMENTED, IGNORE, DEBUG,
11013 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
11014 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
11015 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
11016 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
11017 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
11018 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
11019 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
11020 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
11021 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
11022 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
11023 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
11024 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
11025 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
11026 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
11028 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
11031 * These messages have a special handler from the start.
11033 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
11034 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore;
11035 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
11038 static void ssh2_timer(void *ctx, unsigned long now)
11040 Ssh ssh = (Ssh)ctx;
11042 if (ssh->state == SSH_STATE_CLOSED)
11045 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11046 conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
11047 now == ssh->next_rekey) {
11048 do_ssh2_transport(ssh, "timeout", -1, NULL);
11052 static void ssh2_protocol(Ssh ssh, const void *vin, int inlen,
11053 struct Packet *pktin)
11055 const unsigned char *in = (const unsigned char *)vin;
11056 if (ssh->state == SSH_STATE_CLOSED)
11060 ssh->incoming_data_size += pktin->encrypted_len;
11061 if (!ssh->kex_in_progress &&
11062 ssh->max_data_size != 0 &&
11063 ssh->incoming_data_size > ssh->max_data_size)
11064 do_ssh2_transport(ssh, "too much data received", -1, NULL);
11068 ssh->packet_dispatch[pktin->type](ssh, pktin);
11069 else if (!ssh->protocol_initial_phase_done)
11070 do_ssh2_transport(ssh, in, inlen, pktin);
11072 do_ssh2_authconn(ssh, in, inlen, pktin);
11075 static void ssh2_bare_connection_protocol(Ssh ssh, const void *vin, int inlen,
11076 struct Packet *pktin)
11078 const unsigned char *in = (const unsigned char *)vin;
11079 if (ssh->state == SSH_STATE_CLOSED)
11083 ssh->packet_dispatch[pktin->type](ssh, pktin);
11085 do_ssh2_authconn(ssh, in, inlen, pktin);
11088 static void ssh_cache_conf_values(Ssh ssh)
11090 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
11094 * Called to set up the connection.
11096 * Returns an error message, or NULL on success.
11098 static const char *ssh_init(void *frontend_handle, void **backend_handle,
11100 const char *host, int port, char **realhost,
11101 int nodelay, int keepalive)
11106 ssh = snew(struct ssh_tag);
11107 ssh->conf = conf_copy(conf);
11108 ssh_cache_conf_values(ssh);
11109 ssh->version = 0; /* when not ready yet */
11111 ssh->cipher = NULL;
11112 ssh->v1_cipher_ctx = NULL;
11113 ssh->crcda_ctx = NULL;
11114 ssh->cscipher = NULL;
11115 ssh->cs_cipher_ctx = NULL;
11116 ssh->sccipher = NULL;
11117 ssh->sc_cipher_ctx = NULL;
11119 ssh->cs_mac_ctx = NULL;
11121 ssh->sc_mac_ctx = NULL;
11122 ssh->cscomp = NULL;
11123 ssh->cs_comp_ctx = NULL;
11124 ssh->sccomp = NULL;
11125 ssh->sc_comp_ctx = NULL;
11127 ssh->kex_ctx = NULL;
11128 ssh->hostkey = NULL;
11129 ssh->hostkey_str = NULL;
11130 ssh->exitcode = -1;
11131 ssh->close_expected = FALSE;
11132 ssh->clean_exit = FALSE;
11133 ssh->state = SSH_STATE_PREPACKET;
11134 ssh->size_needed = FALSE;
11135 ssh->eof_needed = FALSE;
11137 ssh->logctx = NULL;
11138 ssh->deferred_send_data = NULL;
11139 ssh->deferred_len = 0;
11140 ssh->deferred_size = 0;
11141 ssh->fallback_cmd = 0;
11142 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
11143 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
11144 ssh->x11disp = NULL;
11145 ssh->x11auth = NULL;
11146 ssh->x11authtree = newtree234(x11_authcmp);
11147 ssh->v1_compressing = FALSE;
11148 ssh->v2_outgoing_sequence = 0;
11149 ssh->ssh1_rdpkt_crstate = 0;
11150 ssh->ssh2_rdpkt_crstate = 0;
11151 ssh->ssh2_bare_rdpkt_crstate = 0;
11152 ssh->ssh_gotdata_crstate = 0;
11153 ssh->do_ssh1_connection_crstate = 0;
11154 ssh->do_ssh_init_state = NULL;
11155 ssh->do_ssh_connection_init_state = NULL;
11156 ssh->do_ssh1_login_state = NULL;
11157 ssh->do_ssh2_transport_state = NULL;
11158 ssh->do_ssh2_authconn_state = NULL;
11161 ssh->mainchan = NULL;
11162 ssh->throttled_all = 0;
11163 ssh->v1_stdout_throttling = 0;
11165 ssh->queuelen = ssh->queuesize = 0;
11166 ssh->queueing = FALSE;
11167 ssh->qhead = ssh->qtail = NULL;
11168 ssh->deferred_rekey_reason = NULL;
11169 bufchain_init(&ssh->queued_incoming_data);
11170 ssh->frozen = FALSE;
11171 ssh->username = NULL;
11172 ssh->sent_console_eof = FALSE;
11173 ssh->got_pty = FALSE;
11174 ssh->bare_connection = FALSE;
11175 ssh->X11_fwd_enabled = FALSE;
11176 ssh->connshare = NULL;
11177 ssh->attempting_connshare = FALSE;
11178 ssh->session_started = FALSE;
11179 ssh->specials = NULL;
11180 ssh->n_uncert_hostkeys = 0;
11181 ssh->cross_certifying = FALSE;
11183 *backend_handle = ssh;
11186 if (crypto_startup() == 0)
11187 return "Microsoft high encryption pack not installed!";
11190 ssh->frontend = frontend_handle;
11191 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
11192 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
11194 ssh->channels = NULL;
11195 ssh->rportfwds = NULL;
11196 ssh->portfwds = NULL;
11201 ssh->conn_throttle_count = 0;
11202 ssh->overall_bufsize = 0;
11203 ssh->fallback_cmd = 0;
11205 ssh->protocol = NULL;
11207 ssh->protocol_initial_phase_done = FALSE;
11209 ssh->pinger = NULL;
11211 ssh->incoming_data_size = ssh->outgoing_data_size =
11212 ssh->deferred_data_size = 0L;
11213 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11214 CONF_ssh_rekey_data));
11215 ssh->kex_in_progress = FALSE;
11218 ssh->gsslibs = NULL;
11221 random_ref(); /* do this now - may be needed by sharing setup code */
11223 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
11232 static void ssh_free(void *handle)
11234 Ssh ssh = (Ssh) handle;
11235 struct ssh_channel *c;
11236 struct ssh_rportfwd *pf;
11237 struct X11FakeAuth *auth;
11239 if (ssh->v1_cipher_ctx)
11240 ssh->cipher->free_context(ssh->v1_cipher_ctx);
11241 if (ssh->cs_cipher_ctx)
11242 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
11243 if (ssh->sc_cipher_ctx)
11244 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
11245 if (ssh->cs_mac_ctx)
11246 ssh->csmac->free_context(ssh->cs_mac_ctx);
11247 if (ssh->sc_mac_ctx)
11248 ssh->scmac->free_context(ssh->sc_mac_ctx);
11249 if (ssh->cs_comp_ctx) {
11251 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
11253 zlib_compress_cleanup(ssh->cs_comp_ctx);
11255 if (ssh->sc_comp_ctx) {
11257 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
11259 zlib_decompress_cleanup(ssh->sc_comp_ctx);
11262 dh_cleanup(ssh->kex_ctx);
11263 sfree(ssh->savedhost);
11265 while (ssh->queuelen-- > 0)
11266 ssh_free_packet(ssh->queue[ssh->queuelen]);
11269 while (ssh->qhead) {
11270 struct queued_handler *qh = ssh->qhead;
11271 ssh->qhead = qh->next;
11274 ssh->qhead = ssh->qtail = NULL;
11276 if (ssh->channels) {
11277 while ((c = delpos234(ssh->channels, 0)) != NULL) {
11280 if (c->u.x11.xconn != NULL)
11281 x11_close(c->u.x11.xconn);
11283 case CHAN_SOCKDATA:
11284 case CHAN_SOCKDATA_DORMANT:
11285 if (c->u.pfd.pf != NULL)
11286 pfd_close(c->u.pfd.pf);
11289 if (ssh->version == 2) {
11290 struct outstanding_channel_request *ocr, *nocr;
11291 ocr = c->v.v2.chanreq_head;
11293 ocr->handler(c, NULL, ocr->ctx);
11298 bufchain_clear(&c->v.v2.outbuffer);
11302 freetree234(ssh->channels);
11303 ssh->channels = NULL;
11306 if (ssh->connshare)
11307 sharestate_free(ssh->connshare);
11309 if (ssh->rportfwds) {
11310 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
11312 freetree234(ssh->rportfwds);
11313 ssh->rportfwds = NULL;
11315 sfree(ssh->deferred_send_data);
11317 x11_free_display(ssh->x11disp);
11318 while ((auth = delpos234(ssh->x11authtree, 0)) != NULL)
11319 x11_free_fake_auth(auth);
11320 freetree234(ssh->x11authtree);
11321 sfree(ssh->do_ssh_init_state);
11322 sfree(ssh->do_ssh1_login_state);
11323 sfree(ssh->do_ssh2_transport_state);
11324 sfree(ssh->do_ssh2_authconn_state);
11327 sfree(ssh->fullhostname);
11328 sfree(ssh->hostkey_str);
11329 sfree(ssh->specials);
11330 if (ssh->crcda_ctx) {
11331 crcda_free_context(ssh->crcda_ctx);
11332 ssh->crcda_ctx = NULL;
11335 ssh_do_close(ssh, TRUE);
11336 expire_timer_context(ssh);
11338 pinger_free(ssh->pinger);
11339 bufchain_clear(&ssh->queued_incoming_data);
11340 sfree(ssh->username);
11341 conf_free(ssh->conf);
11344 ssh_gss_cleanup(ssh->gsslibs);
11352 * Reconfigure the SSH backend.
11354 static void ssh_reconfig(void *handle, Conf *conf)
11356 Ssh ssh = (Ssh) handle;
11357 const char *rekeying = NULL;
11358 int rekey_mandatory = FALSE;
11359 unsigned long old_max_data_size;
11362 pinger_reconfig(ssh->pinger, ssh->conf, conf);
11364 ssh_setup_portfwd(ssh, conf);
11366 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
11367 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
11369 unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
11370 unsigned long now = GETTICKCOUNT();
11372 if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
11373 rekeying = "timeout shortened";
11375 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
11379 old_max_data_size = ssh->max_data_size;
11380 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11381 CONF_ssh_rekey_data));
11382 if (old_max_data_size != ssh->max_data_size &&
11383 ssh->max_data_size != 0) {
11384 if (ssh->outgoing_data_size > ssh->max_data_size ||
11385 ssh->incoming_data_size > ssh->max_data_size)
11386 rekeying = "data limit lowered";
11389 if (conf_get_int(ssh->conf, CONF_compression) !=
11390 conf_get_int(conf, CONF_compression)) {
11391 rekeying = "compression setting changed";
11392 rekey_mandatory = TRUE;
11395 for (i = 0; i < CIPHER_MAX; i++)
11396 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
11397 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
11398 rekeying = "cipher settings changed";
11399 rekey_mandatory = TRUE;
11401 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
11402 conf_get_int(conf, CONF_ssh2_des_cbc)) {
11403 rekeying = "cipher settings changed";
11404 rekey_mandatory = TRUE;
11407 conf_free(ssh->conf);
11408 ssh->conf = conf_copy(conf);
11409 ssh_cache_conf_values(ssh);
11411 if (!ssh->bare_connection && rekeying) {
11412 if (!ssh->kex_in_progress) {
11413 do_ssh2_transport(ssh, rekeying, -1, NULL);
11414 } else if (rekey_mandatory) {
11415 ssh->deferred_rekey_reason = rekeying;
11421 * Called to send data down the SSH connection.
11423 static int ssh_send(void *handle, const char *buf, int len)
11425 Ssh ssh = (Ssh) handle;
11427 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11430 ssh->protocol(ssh, (const unsigned char *)buf, len, 0);
11432 return ssh_sendbuffer(ssh);
11436 * Called to query the current amount of buffered stdin data.
11438 static int ssh_sendbuffer(void *handle)
11440 Ssh ssh = (Ssh) handle;
11441 int override_value;
11443 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11447 * If the SSH socket itself has backed up, add the total backup
11448 * size on that to any individual buffer on the stdin channel.
11450 override_value = 0;
11451 if (ssh->throttled_all)
11452 override_value = ssh->overall_bufsize;
11454 if (ssh->version == 1) {
11455 return override_value;
11456 } else if (ssh->version == 2) {
11457 if (!ssh->mainchan)
11458 return override_value;
11460 return (override_value +
11461 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
11468 * Called to set the size of the window from SSH's POV.
11470 static void ssh_size(void *handle, int width, int height)
11472 Ssh ssh = (Ssh) handle;
11473 struct Packet *pktout;
11475 ssh->term_width = width;
11476 ssh->term_height = height;
11478 switch (ssh->state) {
11479 case SSH_STATE_BEFORE_SIZE:
11480 case SSH_STATE_PREPACKET:
11481 case SSH_STATE_CLOSED:
11482 break; /* do nothing */
11483 case SSH_STATE_INTERMED:
11484 ssh->size_needed = TRUE; /* buffer for later */
11486 case SSH_STATE_SESSION:
11487 if (!conf_get_int(ssh->conf, CONF_nopty)) {
11488 if (ssh->version == 1) {
11489 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
11490 PKT_INT, ssh->term_height,
11491 PKT_INT, ssh->term_width,
11492 PKT_INT, 0, PKT_INT, 0, PKT_END);
11493 } else if (ssh->mainchan) {
11494 pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
11496 ssh2_pkt_adduint32(pktout, ssh->term_width);
11497 ssh2_pkt_adduint32(pktout, ssh->term_height);
11498 ssh2_pkt_adduint32(pktout, 0);
11499 ssh2_pkt_adduint32(pktout, 0);
11500 ssh2_pkt_send(ssh, pktout);
11508 * Return a list of the special codes that make sense in this
11511 static const struct telnet_special *ssh_get_specials(void *handle)
11513 static const struct telnet_special ssh1_ignore_special[] = {
11514 {"IGNORE message", TS_NOP}
11516 static const struct telnet_special ssh2_ignore_special[] = {
11517 {"IGNORE message", TS_NOP},
11519 static const struct telnet_special ssh2_rekey_special[] = {
11520 {"Repeat key exchange", TS_REKEY},
11522 static const struct telnet_special ssh2_session_specials[] = {
11525 /* These are the signal names defined by RFC 4254.
11526 * They include all the ISO C signals, but are a subset of the POSIX
11527 * required signals. */
11528 {"SIGINT (Interrupt)", TS_SIGINT},
11529 {"SIGTERM (Terminate)", TS_SIGTERM},
11530 {"SIGKILL (Kill)", TS_SIGKILL},
11531 {"SIGQUIT (Quit)", TS_SIGQUIT},
11532 {"SIGHUP (Hangup)", TS_SIGHUP},
11533 {"More signals", TS_SUBMENU},
11534 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
11535 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
11536 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
11537 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
11538 {NULL, TS_EXITMENU}
11540 static const struct telnet_special specials_end[] = {
11541 {NULL, TS_EXITMENU}
11544 struct telnet_special *specials = NULL;
11545 int nspecials = 0, specialsize = 0;
11547 Ssh ssh = (Ssh) handle;
11549 sfree(ssh->specials);
11551 #define ADD_SPECIALS(name) do \
11553 int len = lenof(name); \
11554 if (nspecials + len > specialsize) { \
11555 specialsize = (nspecials + len) * 5 / 4 + 32; \
11556 specials = sresize(specials, specialsize, struct telnet_special); \
11558 memcpy(specials+nspecials, name, len*sizeof(struct telnet_special)); \
11559 nspecials += len; \
11562 if (ssh->version == 1) {
11563 /* Don't bother offering IGNORE if we've decided the remote
11564 * won't cope with it, since we wouldn't bother sending it if
11566 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11567 ADD_SPECIALS(ssh1_ignore_special);
11568 } else if (ssh->version == 2) {
11569 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
11570 ADD_SPECIALS(ssh2_ignore_special);
11571 if (!(ssh->remote_bugs & BUG_SSH2_REKEY) && !ssh->bare_connection)
11572 ADD_SPECIALS(ssh2_rekey_special);
11574 ADD_SPECIALS(ssh2_session_specials);
11576 if (ssh->n_uncert_hostkeys) {
11577 static const struct telnet_special uncert_start[] = {
11579 {"Cache new host key type", TS_SUBMENU},
11581 static const struct telnet_special uncert_end[] = {
11582 {NULL, TS_EXITMENU},
11586 ADD_SPECIALS(uncert_start);
11587 for (i = 0; i < ssh->n_uncert_hostkeys; i++) {
11588 struct telnet_special uncert[1];
11589 const struct ssh_signkey *alg =
11590 hostkey_algs[ssh->uncert_hostkeys[i]].alg;
11591 uncert[0].name = alg->name;
11592 uncert[0].code = TS_LOCALSTART + ssh->uncert_hostkeys[i];
11593 ADD_SPECIALS(uncert);
11595 ADD_SPECIALS(uncert_end);
11597 } /* else we're not ready yet */
11600 ADD_SPECIALS(specials_end);
11602 ssh->specials = specials;
11609 #undef ADD_SPECIALS
11613 * Send special codes. TS_EOF is useful for `plink', so you
11614 * can send an EOF and collect resulting output (e.g. `plink
11617 static void ssh_special(void *handle, Telnet_Special code)
11619 Ssh ssh = (Ssh) handle;
11620 struct Packet *pktout;
11622 if (code == TS_EOF) {
11623 if (ssh->state != SSH_STATE_SESSION) {
11625 * Buffer the EOF in case we are pre-SESSION, so we can
11626 * send it as soon as we reach SESSION.
11628 if (code == TS_EOF)
11629 ssh->eof_needed = TRUE;
11632 if (ssh->version == 1) {
11633 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
11634 } else if (ssh->mainchan) {
11635 sshfwd_write_eof(ssh->mainchan);
11636 ssh->send_ok = 0; /* now stop trying to read from stdin */
11638 logevent("Sent EOF message");
11639 } else if (code == TS_PING || code == TS_NOP) {
11640 if (ssh->state == SSH_STATE_CLOSED
11641 || ssh->state == SSH_STATE_PREPACKET) return;
11642 if (ssh->version == 1) {
11643 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11644 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
11646 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
11647 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
11648 ssh2_pkt_addstring_start(pktout);
11649 ssh2_pkt_send_noqueue(ssh, pktout);
11652 } else if (code == TS_REKEY) {
11653 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11654 ssh->version == 2) {
11655 do_ssh2_transport(ssh, "at user request", -1, NULL);
11657 } else if (code >= TS_LOCALSTART) {
11658 ssh->hostkey = hostkey_algs[code - TS_LOCALSTART].alg;
11659 ssh->cross_certifying = TRUE;
11660 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11661 ssh->version == 2) {
11662 do_ssh2_transport(ssh, "cross-certifying new host key", -1, NULL);
11664 } else if (code == TS_BRK) {
11665 if (ssh->state == SSH_STATE_CLOSED
11666 || ssh->state == SSH_STATE_PREPACKET) return;
11667 if (ssh->version == 1) {
11668 logevent("Unable to send BREAK signal in SSH-1");
11669 } else if (ssh->mainchan) {
11670 pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
11671 ssh2_pkt_adduint32(pktout, 0); /* default break length */
11672 ssh2_pkt_send(ssh, pktout);
11675 /* Is is a POSIX signal? */
11676 const char *signame = NULL;
11677 if (code == TS_SIGABRT) signame = "ABRT";
11678 if (code == TS_SIGALRM) signame = "ALRM";
11679 if (code == TS_SIGFPE) signame = "FPE";
11680 if (code == TS_SIGHUP) signame = "HUP";
11681 if (code == TS_SIGILL) signame = "ILL";
11682 if (code == TS_SIGINT) signame = "INT";
11683 if (code == TS_SIGKILL) signame = "KILL";
11684 if (code == TS_SIGPIPE) signame = "PIPE";
11685 if (code == TS_SIGQUIT) signame = "QUIT";
11686 if (code == TS_SIGSEGV) signame = "SEGV";
11687 if (code == TS_SIGTERM) signame = "TERM";
11688 if (code == TS_SIGUSR1) signame = "USR1";
11689 if (code == TS_SIGUSR2) signame = "USR2";
11690 /* The SSH-2 protocol does in principle support arbitrary named
11691 * signals, including signame@domain, but we don't support those. */
11693 /* It's a signal. */
11694 if (ssh->version == 2 && ssh->mainchan) {
11695 pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
11696 ssh2_pkt_addstring(pktout, signame);
11697 ssh2_pkt_send(ssh, pktout);
11698 logeventf(ssh, "Sent signal SIG%s", signame);
11701 /* Never heard of it. Do nothing */
11706 void *new_sock_channel(void *handle, struct PortForwarding *pf)
11708 Ssh ssh = (Ssh) handle;
11709 struct ssh_channel *c;
11710 c = snew(struct ssh_channel);
11713 ssh2_channel_init(c);
11714 c->halfopen = TRUE;
11715 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
11717 add234(ssh->channels, c);
11721 unsigned ssh_alloc_sharing_channel(Ssh ssh, void *sharing_ctx)
11723 struct ssh_channel *c;
11724 c = snew(struct ssh_channel);
11727 ssh2_channel_init(c);
11728 c->type = CHAN_SHARING;
11729 c->u.sharing.ctx = sharing_ctx;
11730 add234(ssh->channels, c);
11734 void ssh_delete_sharing_channel(Ssh ssh, unsigned localid)
11736 struct ssh_channel *c;
11738 c = find234(ssh->channels, &localid, ssh_channelfind);
11740 ssh_channel_destroy(c);
11743 void ssh_send_packet_from_downstream(Ssh ssh, unsigned id, int type,
11744 const void *data, int datalen,
11745 const char *additional_log_text)
11747 struct Packet *pkt;
11749 pkt = ssh2_pkt_init(type);
11750 pkt->downstream_id = id;
11751 pkt->additional_log_text = additional_log_text;
11752 ssh2_pkt_adddata(pkt, data, datalen);
11753 ssh2_pkt_send(ssh, pkt);
11757 * This is called when stdout/stderr (the entity to which
11758 * from_backend sends data) manages to clear some backlog.
11760 static void ssh_unthrottle(void *handle, int bufsize)
11762 Ssh ssh = (Ssh) handle;
11765 if (ssh->version == 1) {
11766 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
11767 ssh->v1_stdout_throttling = 0;
11768 ssh_throttle_conn(ssh, -1);
11771 if (ssh->mainchan) {
11772 ssh2_set_window(ssh->mainchan,
11773 bufsize < ssh->mainchan->v.v2.locmaxwin ?
11774 ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
11775 if (ssh_is_simple(ssh))
11778 buflimit = ssh->mainchan->v.v2.locmaxwin;
11779 if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
11780 ssh->mainchan->throttling_conn = 0;
11781 ssh_throttle_conn(ssh, -1);
11787 * Now process any SSH connection data that was stashed in our
11788 * queue while we were frozen.
11790 ssh_process_queued_incoming_data(ssh);
11793 void ssh_send_port_open(void *channel, const char *hostname, int port,
11796 struct ssh_channel *c = (struct ssh_channel *)channel;
11798 struct Packet *pktout;
11800 logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
11802 if (ssh->version == 1) {
11803 send_packet(ssh, SSH1_MSG_PORT_OPEN,
11804 PKT_INT, c->localid,
11807 /* PKT_STR, <org:orgport>, */
11810 pktout = ssh2_chanopen_init(c, "direct-tcpip");
11812 char *trimmed_host = host_strduptrim(hostname);
11813 ssh2_pkt_addstring(pktout, trimmed_host);
11814 sfree(trimmed_host);
11816 ssh2_pkt_adduint32(pktout, port);
11818 * We make up values for the originator data; partly it's
11819 * too much hassle to keep track, and partly I'm not
11820 * convinced the server should be told details like that
11821 * about my local network configuration.
11822 * The "originator IP address" is syntactically a numeric
11823 * IP address, and some servers (e.g., Tectia) get upset
11824 * if it doesn't match this syntax.
11826 ssh2_pkt_addstring(pktout, "0.0.0.0");
11827 ssh2_pkt_adduint32(pktout, 0);
11828 ssh2_pkt_send(ssh, pktout);
11832 static int ssh_connected(void *handle)
11834 Ssh ssh = (Ssh) handle;
11835 return ssh->s != NULL;
11838 static int ssh_sendok(void *handle)
11840 Ssh ssh = (Ssh) handle;
11841 return ssh->send_ok;
11844 static int ssh_ldisc(void *handle, int option)
11846 Ssh ssh = (Ssh) handle;
11847 if (option == LD_ECHO)
11848 return ssh->echoing;
11849 if (option == LD_EDIT)
11850 return ssh->editing;
11854 static void ssh_provide_ldisc(void *handle, void *ldisc)
11856 Ssh ssh = (Ssh) handle;
11857 ssh->ldisc = ldisc;
11860 static void ssh_provide_logctx(void *handle, void *logctx)
11862 Ssh ssh = (Ssh) handle;
11863 ssh->logctx = logctx;
11866 static int ssh_return_exitcode(void *handle)
11868 Ssh ssh = (Ssh) handle;
11869 if (ssh->s != NULL)
11872 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
11876 * cfg_info for SSH is the protocol running in this session.
11877 * (1 or 2 for the full SSH-1 or SSH-2 protocol; -1 for the bare
11878 * SSH-2 connection protocol, i.e. a downstream; 0 for not-decided-yet.)
11880 static int ssh_cfg_info(void *handle)
11882 Ssh ssh = (Ssh) handle;
11883 if (ssh->version == 0)
11884 return 0; /* don't know yet */
11885 else if (ssh->bare_connection)
11888 return ssh->version;
11892 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
11893 * that fails. This variable is the means by which scp.c can reach
11894 * into the SSH code and find out which one it got.
11896 extern int ssh_fallback_cmd(void *handle)
11898 Ssh ssh = (Ssh) handle;
11899 return ssh->fallback_cmd;
11902 Backend ssh_backend = {
11912 ssh_return_exitcode,
11916 ssh_provide_logctx,
11919 ssh_test_for_upstream,