29 * Packet type contexts, so that ssh2_pkt_type can correctly decode
30 * the ambiguous type numbers back into the correct type strings.
41 SSH2_PKTCTX_PUBLICKEY,
47 static const char *const ssh2_disconnect_reasons[] = {
49 "host not allowed to connect",
51 "key exchange failed",
52 "host authentication failed",
55 "service not available",
56 "protocol version not supported",
57 "host key not verifiable",
60 "too many connections",
61 "auth cancelled by user",
62 "no more auth methods available",
67 * Various remote-bug flags.
69 #define BUG_CHOKES_ON_SSH1_IGNORE 1
70 #define BUG_SSH2_HMAC 2
71 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
72 #define BUG_CHOKES_ON_RSA 8
73 #define BUG_SSH2_RSA_PADDING 16
74 #define BUG_SSH2_DERIVEKEY 32
75 #define BUG_SSH2_REKEY 64
76 #define BUG_SSH2_PK_SESSIONID 128
77 #define BUG_SSH2_MAXPKT 256
78 #define BUG_CHOKES_ON_SSH2_IGNORE 512
79 #define BUG_CHOKES_ON_WINADJ 1024
80 #define BUG_SENDS_LATE_REQUEST_REPLY 2048
81 #define BUG_SSH2_OLDGEX 4096
83 #define DH_MIN_SIZE 1024
84 #define DH_MAX_SIZE 8192
87 * Codes for terminal modes.
88 * Most of these are the same in SSH-1 and SSH-2.
89 * This list is derived from RFC 4254 and
92 static const struct ssh_ttymode {
93 const char* const mode;
95 enum { TTY_OP_CHAR, TTY_OP_BOOL } type;
97 /* "V" prefix discarded for special characters relative to SSH specs */
98 { "INTR", 1, TTY_OP_CHAR },
99 { "QUIT", 2, TTY_OP_CHAR },
100 { "ERASE", 3, TTY_OP_CHAR },
101 { "KILL", 4, TTY_OP_CHAR },
102 { "EOF", 5, TTY_OP_CHAR },
103 { "EOL", 6, TTY_OP_CHAR },
104 { "EOL2", 7, TTY_OP_CHAR },
105 { "START", 8, TTY_OP_CHAR },
106 { "STOP", 9, TTY_OP_CHAR },
107 { "SUSP", 10, TTY_OP_CHAR },
108 { "DSUSP", 11, TTY_OP_CHAR },
109 { "REPRINT", 12, TTY_OP_CHAR },
110 { "WERASE", 13, TTY_OP_CHAR },
111 { "LNEXT", 14, TTY_OP_CHAR },
112 { "FLUSH", 15, TTY_OP_CHAR },
113 { "SWTCH", 16, TTY_OP_CHAR },
114 { "STATUS", 17, TTY_OP_CHAR },
115 { "DISCARD", 18, TTY_OP_CHAR },
116 { "IGNPAR", 30, TTY_OP_BOOL },
117 { "PARMRK", 31, TTY_OP_BOOL },
118 { "INPCK", 32, TTY_OP_BOOL },
119 { "ISTRIP", 33, TTY_OP_BOOL },
120 { "INLCR", 34, TTY_OP_BOOL },
121 { "IGNCR", 35, TTY_OP_BOOL },
122 { "ICRNL", 36, TTY_OP_BOOL },
123 { "IUCLC", 37, TTY_OP_BOOL },
124 { "IXON", 38, TTY_OP_BOOL },
125 { "IXANY", 39, TTY_OP_BOOL },
126 { "IXOFF", 40, TTY_OP_BOOL },
127 { "IMAXBEL", 41, TTY_OP_BOOL },
128 { "IUTF8", 42, TTY_OP_BOOL },
129 { "ISIG", 50, TTY_OP_BOOL },
130 { "ICANON", 51, TTY_OP_BOOL },
131 { "XCASE", 52, TTY_OP_BOOL },
132 { "ECHO", 53, TTY_OP_BOOL },
133 { "ECHOE", 54, TTY_OP_BOOL },
134 { "ECHOK", 55, TTY_OP_BOOL },
135 { "ECHONL", 56, TTY_OP_BOOL },
136 { "NOFLSH", 57, TTY_OP_BOOL },
137 { "TOSTOP", 58, TTY_OP_BOOL },
138 { "IEXTEN", 59, TTY_OP_BOOL },
139 { "ECHOCTL", 60, TTY_OP_BOOL },
140 { "ECHOKE", 61, TTY_OP_BOOL },
141 { "PENDIN", 62, TTY_OP_BOOL }, /* XXX is this a real mode? */
142 { "OPOST", 70, TTY_OP_BOOL },
143 { "OLCUC", 71, TTY_OP_BOOL },
144 { "ONLCR", 72, TTY_OP_BOOL },
145 { "OCRNL", 73, TTY_OP_BOOL },
146 { "ONOCR", 74, TTY_OP_BOOL },
147 { "ONLRET", 75, TTY_OP_BOOL },
148 { "CS7", 90, TTY_OP_BOOL },
149 { "CS8", 91, TTY_OP_BOOL },
150 { "PARENB", 92, TTY_OP_BOOL },
151 { "PARODD", 93, TTY_OP_BOOL }
154 /* Miscellaneous other tty-related constants. */
155 #define SSH_TTY_OP_END 0
156 /* The opcodes for ISPEED/OSPEED differ between SSH-1 and SSH-2. */
157 #define SSH1_TTY_OP_ISPEED 192
158 #define SSH1_TTY_OP_OSPEED 193
159 #define SSH2_TTY_OP_ISPEED 128
160 #define SSH2_TTY_OP_OSPEED 129
162 /* Helper functions for parsing tty-related config. */
163 static unsigned int ssh_tty_parse_specchar(char *s)
168 ret = ctrlparse(s, &next);
169 if (!next) ret = s[0];
171 ret = 255; /* special value meaning "don't set" */
175 static unsigned int ssh_tty_parse_boolean(char *s)
177 if (stricmp(s, "yes") == 0 ||
178 stricmp(s, "on") == 0 ||
179 stricmp(s, "true") == 0 ||
180 stricmp(s, "+") == 0)
182 else if (stricmp(s, "no") == 0 ||
183 stricmp(s, "off") == 0 ||
184 stricmp(s, "false") == 0 ||
185 stricmp(s, "-") == 0)
186 return 0; /* false */
188 return (atoi(s) != 0);
191 #define translate(x) if (type == x) return #x
192 #define translatek(x,ctx) if (type == x && (pkt_kctx == ctx)) return #x
193 #define translatea(x,ctx) if (type == x && (pkt_actx == ctx)) return #x
194 static const char *ssh1_pkt_type(int type)
196 translate(SSH1_MSG_DISCONNECT);
197 translate(SSH1_SMSG_PUBLIC_KEY);
198 translate(SSH1_CMSG_SESSION_KEY);
199 translate(SSH1_CMSG_USER);
200 translate(SSH1_CMSG_AUTH_RSA);
201 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
202 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
203 translate(SSH1_CMSG_AUTH_PASSWORD);
204 translate(SSH1_CMSG_REQUEST_PTY);
205 translate(SSH1_CMSG_WINDOW_SIZE);
206 translate(SSH1_CMSG_EXEC_SHELL);
207 translate(SSH1_CMSG_EXEC_CMD);
208 translate(SSH1_SMSG_SUCCESS);
209 translate(SSH1_SMSG_FAILURE);
210 translate(SSH1_CMSG_STDIN_DATA);
211 translate(SSH1_SMSG_STDOUT_DATA);
212 translate(SSH1_SMSG_STDERR_DATA);
213 translate(SSH1_CMSG_EOF);
214 translate(SSH1_SMSG_EXIT_STATUS);
215 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
216 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
217 translate(SSH1_MSG_CHANNEL_DATA);
218 translate(SSH1_MSG_CHANNEL_CLOSE);
219 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
220 translate(SSH1_SMSG_X11_OPEN);
221 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
222 translate(SSH1_MSG_PORT_OPEN);
223 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
224 translate(SSH1_SMSG_AGENT_OPEN);
225 translate(SSH1_MSG_IGNORE);
226 translate(SSH1_CMSG_EXIT_CONFIRMATION);
227 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
228 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
229 translate(SSH1_MSG_DEBUG);
230 translate(SSH1_CMSG_REQUEST_COMPRESSION);
231 translate(SSH1_CMSG_AUTH_TIS);
232 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
233 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
234 translate(SSH1_CMSG_AUTH_CCARD);
235 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
236 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
239 static const char *ssh2_pkt_type(Pkt_KCtx pkt_kctx, Pkt_ACtx pkt_actx,
242 translatea(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE,SSH2_PKTCTX_GSSAPI);
243 translatea(SSH2_MSG_USERAUTH_GSSAPI_TOKEN,SSH2_PKTCTX_GSSAPI);
244 translatea(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE,SSH2_PKTCTX_GSSAPI);
245 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERROR,SSH2_PKTCTX_GSSAPI);
246 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK,SSH2_PKTCTX_GSSAPI);
247 translatea(SSH2_MSG_USERAUTH_GSSAPI_MIC, SSH2_PKTCTX_GSSAPI);
248 translate(SSH2_MSG_DISCONNECT);
249 translate(SSH2_MSG_IGNORE);
250 translate(SSH2_MSG_UNIMPLEMENTED);
251 translate(SSH2_MSG_DEBUG);
252 translate(SSH2_MSG_SERVICE_REQUEST);
253 translate(SSH2_MSG_SERVICE_ACCEPT);
254 translate(SSH2_MSG_KEXINIT);
255 translate(SSH2_MSG_NEWKEYS);
256 translatek(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP);
257 translatek(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP);
258 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD, SSH2_PKTCTX_DHGEX);
259 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
260 translatek(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
261 translatek(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
262 translatek(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
263 translatek(SSH2_MSG_KEXRSA_PUBKEY, SSH2_PKTCTX_RSAKEX);
264 translatek(SSH2_MSG_KEXRSA_SECRET, SSH2_PKTCTX_RSAKEX);
265 translatek(SSH2_MSG_KEXRSA_DONE, SSH2_PKTCTX_RSAKEX);
266 translatek(SSH2_MSG_KEX_ECDH_INIT, SSH2_PKTCTX_ECDHKEX);
267 translatek(SSH2_MSG_KEX_ECDH_REPLY, SSH2_PKTCTX_ECDHKEX);
268 translate(SSH2_MSG_USERAUTH_REQUEST);
269 translate(SSH2_MSG_USERAUTH_FAILURE);
270 translate(SSH2_MSG_USERAUTH_SUCCESS);
271 translate(SSH2_MSG_USERAUTH_BANNER);
272 translatea(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
273 translatea(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
274 translatea(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
275 translatea(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
276 translate(SSH2_MSG_GLOBAL_REQUEST);
277 translate(SSH2_MSG_REQUEST_SUCCESS);
278 translate(SSH2_MSG_REQUEST_FAILURE);
279 translate(SSH2_MSG_CHANNEL_OPEN);
280 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
281 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
282 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
283 translate(SSH2_MSG_CHANNEL_DATA);
284 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
285 translate(SSH2_MSG_CHANNEL_EOF);
286 translate(SSH2_MSG_CHANNEL_CLOSE);
287 translate(SSH2_MSG_CHANNEL_REQUEST);
288 translate(SSH2_MSG_CHANNEL_SUCCESS);
289 translate(SSH2_MSG_CHANNEL_FAILURE);
295 /* Enumeration values for fields in SSH-1 packets */
297 PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
301 * Coroutine mechanics for the sillier bits of the code. If these
302 * macros look impenetrable to you, you might find it helpful to
305 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
307 * which explains the theory behind these macros.
309 * In particular, if you are getting `case expression not constant'
310 * errors when building with MS Visual Studio, this is because MS's
311 * Edit and Continue debugging feature causes their compiler to
312 * violate ANSI C. To disable Edit and Continue debugging:
314 * - right-click ssh.c in the FileView
316 * - select the C/C++ tab and the General category
317 * - under `Debug info:', select anything _other_ than `Program
318 * Database for Edit and Continue'.
320 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
321 #define crBeginState crBegin(s->crLine)
322 #define crStateP(t, v) \
324 if (!(v)) { s = (v) = snew(struct t); s->crLine = 0; } \
326 #define crState(t) crStateP(t, ssh->t)
327 #define crFinish(z) } *crLine = 0; return (z); }
328 #define crFinishV } *crLine = 0; return; }
329 #define crFinishFree(z) } sfree(s); return (z); }
330 #define crFinishFreeV } sfree(s); return; }
331 #define crReturn(z) \
333 *crLine =__LINE__; return (z); case __LINE__:;\
337 *crLine=__LINE__; return; case __LINE__:;\
339 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
340 #define crStopV do{ *crLine = 0; return; }while(0)
341 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
342 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
346 static struct Packet *ssh1_pkt_init(int pkt_type);
347 static struct Packet *ssh2_pkt_init(int pkt_type);
348 static void ssh_pkt_ensure(struct Packet *, int length);
349 static void ssh_pkt_adddata(struct Packet *, const void *data, int len);
350 static void ssh_pkt_addbyte(struct Packet *, unsigned char value);
351 static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
352 static void ssh_pkt_adduint32(struct Packet *, unsigned long value);
353 static void ssh_pkt_addstring_start(struct Packet *);
354 static void ssh_pkt_addstring_str(struct Packet *, const char *data);
355 static void ssh_pkt_addstring_data(struct Packet *, const char *data, int len);
356 static void ssh_pkt_addstring(struct Packet *, const char *data);
357 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
358 static void ssh1_pkt_addmp(struct Packet *, Bignum b);
359 static void ssh2_pkt_addmp(struct Packet *, Bignum b);
360 static int ssh2_pkt_construct(Ssh, struct Packet *);
361 static void ssh2_pkt_send(Ssh, struct Packet *);
362 static void ssh2_pkt_send_noqueue(Ssh, struct Packet *);
363 static int do_ssh1_login(Ssh ssh, const unsigned char *in, int inlen,
364 struct Packet *pktin);
365 static void do_ssh2_authconn(Ssh ssh, const unsigned char *in, int inlen,
366 struct Packet *pktin);
367 static void ssh2_channel_check_close(struct ssh_channel *c);
368 static void ssh_channel_destroy(struct ssh_channel *c);
369 static void ssh_channel_unthrottle(struct ssh_channel *c, int bufsize);
370 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin);
373 * Buffer management constants. There are several of these for
374 * various different purposes:
376 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
377 * on a local data stream before we throttle the whole SSH
378 * connection (in SSH-1 only). Throttling the whole connection is
379 * pretty drastic so we set this high in the hope it won't
382 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
383 * on the SSH connection itself before we defensively throttle
384 * _all_ local data streams. This is pretty drastic too (though
385 * thankfully unlikely in SSH-2 since the window mechanism should
386 * ensure that the server never has any need to throttle its end
387 * of the connection), so we set this high as well.
389 * - OUR_V2_WINSIZE is the default window size we present on SSH-2
392 * - OUR_V2_BIGWIN is the window size we advertise for the only
393 * channel in a simple connection. It must be <= INT_MAX.
395 * - OUR_V2_MAXPKT is the official "maximum packet size" we send
396 * to the remote side. This actually has nothing to do with the
397 * size of the _packet_, but is instead a limit on the amount
398 * of data we're willing to receive in a single SSH2 channel
401 * - OUR_V2_PACKETLIMIT is actually the maximum size of SSH
402 * _packet_ we're prepared to cope with. It must be a multiple
403 * of the cipher block size, and must be at least 35000.
406 #define SSH1_BUFFER_LIMIT 32768
407 #define SSH_MAX_BACKLOG 32768
408 #define OUR_V2_WINSIZE 16384
409 #define OUR_V2_BIGWIN 0x7fffffff
410 #define OUR_V2_MAXPKT 0x4000UL
411 #define OUR_V2_PACKETLIMIT 0x9000UL
413 struct ssh_signkey_with_user_pref_id {
414 const struct ssh_signkey *alg;
417 const static struct ssh_signkey_with_user_pref_id hostkey_algs[] = {
418 { &ssh_ecdsa_ed25519, HK_ED25519 },
419 { &ssh_ecdsa_nistp256, HK_ECDSA },
420 { &ssh_ecdsa_nistp384, HK_ECDSA },
421 { &ssh_ecdsa_nistp521, HK_ECDSA },
422 { &ssh_dss, HK_DSA },
423 { &ssh_rsa, HK_RSA },
426 const static struct ssh_mac *const macs[] = {
427 &ssh_hmac_sha256, &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
429 const static struct ssh_mac *const buggymacs[] = {
430 &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
433 static void *ssh_comp_none_init(void)
437 static void ssh_comp_none_cleanup(void *handle)
440 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
441 unsigned char **outblock, int *outlen)
445 static int ssh_comp_none_disable(void *handle)
449 const static struct ssh_compress ssh_comp_none = {
451 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
452 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
453 ssh_comp_none_disable, NULL
455 extern const struct ssh_compress ssh_zlib;
456 const static struct ssh_compress *const compressions[] = {
457 &ssh_zlib, &ssh_comp_none
460 enum { /* channel types */
465 CHAN_SOCKDATA_DORMANT, /* one the remote hasn't confirmed */
467 * CHAN_SHARING indicates a channel which is tracked here on
468 * behalf of a connection-sharing downstream. We do almost nothing
469 * with these channels ourselves: all messages relating to them
470 * get thrown straight to sshshare.c and passed on almost
471 * unmodified to downstream.
475 * CHAN_ZOMBIE is used to indicate a channel for which we've
476 * already destroyed the local data source: for instance, if a
477 * forwarded port experiences a socket error on the local side, we
478 * immediately destroy its local socket and turn the SSH channel
484 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
485 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
486 typedef void (*cchandler_fn_t)(struct ssh_channel *, struct Packet *, void *);
489 * Each channel has a queue of outstanding CHANNEL_REQUESTS and their
492 struct outstanding_channel_request {
493 cchandler_fn_t handler;
495 struct outstanding_channel_request *next;
499 * 2-3-4 tree storing channels.
502 Ssh ssh; /* pointer back to main context */
503 unsigned remoteid, localid;
505 /* True if we opened this channel but server hasn't confirmed. */
508 * In SSH-1, this value contains four bits:
510 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
511 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
512 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
513 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
515 * A channel is completely finished with when all four bits are set.
517 * In SSH-2, the four bits mean:
519 * 1 We have sent SSH2_MSG_CHANNEL_EOF.
520 * 2 We have sent SSH2_MSG_CHANNEL_CLOSE.
521 * 4 We have received SSH2_MSG_CHANNEL_EOF.
522 * 8 We have received SSH2_MSG_CHANNEL_CLOSE.
524 * A channel is completely finished with when we have both sent
525 * and received CLOSE.
527 * The symbolic constants below use the SSH-2 terminology, which
528 * is a bit confusing in SSH-1, but we have to use _something_.
530 #define CLOSES_SENT_EOF 1
531 #define CLOSES_SENT_CLOSE 2
532 #define CLOSES_RCVD_EOF 4
533 #define CLOSES_RCVD_CLOSE 8
537 * This flag indicates that an EOF is pending on the outgoing side
538 * of the channel: that is, wherever we're getting the data for
539 * this channel has sent us some data followed by EOF. We can't
540 * actually send the EOF until we've finished sending the data, so
541 * we set this flag instead to remind us to do so once our buffer
547 * True if this channel is causing the underlying connection to be
552 struct ssh2_data_channel {
554 unsigned remwindow, remmaxpkt;
555 /* locwindow is signed so we can cope with excess data. */
556 int locwindow, locmaxwin;
558 * remlocwin is the amount of local window that we think
559 * the remote end had available to it after it sent the
560 * last data packet or window adjust ack.
564 * These store the list of channel requests that haven't
567 struct outstanding_channel_request *chanreq_head, *chanreq_tail;
568 enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
572 struct ssh_agent_channel {
573 unsigned char *message;
574 unsigned char msglen[4];
575 unsigned lensofar, totallen;
576 int outstanding_requests;
578 struct ssh_x11_channel {
579 struct X11Connection *xconn;
582 struct ssh_pfd_channel {
583 struct PortForwarding *pf;
585 struct ssh_sharing_channel {
592 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
593 * use this structure in different ways, reflecting SSH-2's
594 * altogether saner approach to port forwarding.
596 * In SSH-1, you arrange a remote forwarding by sending the server
597 * the remote port number, and the local destination host:port.
598 * When a connection comes in, the server sends you back that
599 * host:port pair, and you connect to it. This is a ready-made
600 * security hole if you're not on the ball: a malicious server
601 * could send you back _any_ host:port pair, so if you trustingly
602 * connect to the address it gives you then you've just opened the
603 * entire inside of your corporate network just by connecting
604 * through it to a dodgy SSH server. Hence, we must store a list of
605 * host:port pairs we _are_ trying to forward to, and reject a
606 * connection request from the server if it's not in the list.
608 * In SSH-2, each side of the connection minds its own business and
609 * doesn't send unnecessary information to the other. You arrange a
610 * remote forwarding by sending the server just the remote port
611 * number. When a connection comes in, the server tells you which
612 * of its ports was connected to; and _you_ have to remember what
613 * local host:port pair went with that port number.
615 * Hence, in SSH-1 this structure is indexed by destination
616 * host:port pair, whereas in SSH-2 it is indexed by source port.
618 struct ssh_portfwd; /* forward declaration */
620 struct ssh_rportfwd {
621 unsigned sport, dport;
625 struct ssh_portfwd *pfrec;
628 static void free_rportfwd(struct ssh_rportfwd *pf)
631 sfree(pf->sportdesc);
639 * Separately to the rportfwd tree (which is for looking up port
640 * open requests from the server), a tree of _these_ structures is
641 * used to keep track of all the currently open port forwardings,
642 * so that we can reconfigure in mid-session if the user requests
646 enum { DESTROY, KEEP, CREATE } status;
648 unsigned sport, dport;
651 struct ssh_rportfwd *remote;
653 struct PortListener *local;
655 #define free_portfwd(pf) ( \
656 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
657 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
660 long length; /* length of packet: see below */
661 long forcepad; /* SSH-2: force padding to at least this length */
662 int type; /* only used for incoming packets */
663 unsigned long sequence; /* SSH-2 incoming sequence number */
664 unsigned char *data; /* allocated storage */
665 unsigned char *body; /* offset of payload within `data' */
666 long savedpos; /* dual-purpose saved packet position: see below */
667 long maxlen; /* amount of storage allocated for `data' */
668 long encrypted_len; /* for SSH-2 total-size counting */
671 * A note on the 'length' and 'savedpos' fields above.
673 * Incoming packets are set up so that pkt->length is measured
674 * relative to pkt->body, which itself points to a few bytes after
675 * pkt->data (skipping some uninteresting header fields including
676 * the packet type code). The ssh_pkt_get* functions all expect
677 * this setup, and they also use pkt->savedpos to indicate how far
678 * through the packet being decoded they've got - and that, too,
679 * is an offset from pkt->body rather than pkt->data.
681 * During construction of an outgoing packet, however, pkt->length
682 * is measured relative to the base pointer pkt->data, and
683 * pkt->body is not really used for anything until the packet is
684 * ready for sending. In this mode, pkt->savedpos is reused as a
685 * temporary variable by the addstring functions, which write out
686 * a string length field and then keep going back and updating it
687 * as more data is appended to the subsequent string data field;
688 * pkt->savedpos stores the offset (again relative to pkt->data)
689 * of the start of the string data field.
692 /* Extra metadata used in SSH packet logging mode, allowing us to
693 * log in the packet header line that the packet came from a
694 * connection-sharing downstream and what if anything unusual was
695 * done to it. The additional_log_text field is expected to be a
696 * static string - it will not be freed. */
697 unsigned downstream_id;
698 const char *additional_log_text;
701 static void ssh1_protocol(Ssh ssh, const void *vin, int inlen,
702 struct Packet *pktin);
703 static void ssh2_protocol(Ssh ssh, const void *vin, int inlen,
704 struct Packet *pktin);
705 static void ssh2_bare_connection_protocol(Ssh ssh, const void *vin, int inlen,
706 struct Packet *pktin);
707 static void ssh1_protocol_setup(Ssh ssh);
708 static void ssh2_protocol_setup(Ssh ssh);
709 static void ssh2_bare_connection_protocol_setup(Ssh ssh);
710 static void ssh_size(void *handle, int width, int height);
711 static void ssh_special(void *handle, Telnet_Special);
712 static int ssh2_try_send(struct ssh_channel *c);
713 static int ssh_send_channel_data(struct ssh_channel *c,
714 const char *buf, int len);
715 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
716 static void ssh2_set_window(struct ssh_channel *c, int newwin);
717 static int ssh_sendbuffer(void *handle);
718 static int ssh_do_close(Ssh ssh, int notify_exit);
719 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
720 static int ssh2_pkt_getbool(struct Packet *pkt);
721 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
722 static void ssh2_timer(void *ctx, unsigned long now);
723 static void do_ssh2_transport(Ssh ssh, const void *vin, int inlen,
724 struct Packet *pktin);
725 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin);
727 struct rdpkt1_state_tag {
728 long len, pad, biglen, to_read;
729 unsigned long realcrc, gotcrc;
733 struct Packet *pktin;
736 struct rdpkt2_state_tag {
737 long len, pad, payload, packetlen, maclen;
740 unsigned long incoming_sequence;
741 struct Packet *pktin;
744 struct rdpkt2_bare_state_tag {
748 unsigned long incoming_sequence;
749 struct Packet *pktin;
752 struct queued_handler;
753 struct queued_handler {
755 chandler_fn_t handler;
757 struct queued_handler *next;
761 const struct plug_function_table *fn;
762 /* the above field _must_ be first in the structure */
772 unsigned char session_key[32];
774 int v1_remote_protoflags;
775 int v1_local_protoflags;
776 int agentfwd_enabled;
779 const struct ssh_cipher *cipher;
782 const struct ssh2_cipher *cscipher, *sccipher;
783 void *cs_cipher_ctx, *sc_cipher_ctx;
784 const struct ssh_mac *csmac, *scmac;
785 int csmac_etm, scmac_etm;
786 void *cs_mac_ctx, *sc_mac_ctx;
787 const struct ssh_compress *cscomp, *sccomp;
788 void *cs_comp_ctx, *sc_comp_ctx;
789 const struct ssh_kex *kex;
790 const struct ssh_signkey *hostkey;
791 char *hostkey_str; /* string representation, for easy checking in rekeys */
792 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
793 int v2_session_id_len;
797 int attempting_connshare;
803 int echoing, editing;
808 int ospeed, ispeed; /* temporaries */
809 int term_width, term_height;
811 tree234 *channels; /* indexed by local id */
812 struct ssh_channel *mainchan; /* primary session channel */
813 int ncmode; /* is primary channel direct-tcpip? */
818 tree234 *rportfwds, *portfwds;
822 SSH_STATE_BEFORE_SIZE,
828 int size_needed, eof_needed;
829 int sent_console_eof;
830 int got_pty; /* affects EOF behaviour on main channel */
832 struct Packet **queue;
833 int queuelen, queuesize;
835 unsigned char *deferred_send_data;
836 int deferred_len, deferred_size;
839 * Gross hack: pscp will try to start SFTP but fall back to
840 * scp1 if that fails. This variable is the means by which
841 * scp.c can reach into the SSH code and find out which one it
846 bufchain banner; /* accumulates banners during do_ssh2_authconn */
851 struct X11Display *x11disp;
852 struct X11FakeAuth *x11auth;
853 tree234 *x11authtree;
856 int conn_throttle_count;
859 int v1_stdout_throttling;
860 unsigned long v2_outgoing_sequence;
862 int ssh1_rdpkt_crstate;
863 int ssh2_rdpkt_crstate;
864 int ssh2_bare_rdpkt_crstate;
865 int ssh_gotdata_crstate;
866 int do_ssh1_connection_crstate;
868 void *do_ssh_init_state;
869 void *do_ssh1_login_state;
870 void *do_ssh2_transport_state;
871 void *do_ssh2_authconn_state;
872 void *do_ssh_connection_init_state;
874 struct rdpkt1_state_tag rdpkt1_state;
875 struct rdpkt2_state_tag rdpkt2_state;
876 struct rdpkt2_bare_state_tag rdpkt2_bare_state;
878 /* SSH-1 and SSH-2 use this for different things, but both use it */
879 int protocol_initial_phase_done;
881 void (*protocol) (Ssh ssh, const void *vin, int inlen,
883 struct Packet *(*s_rdpkt) (Ssh ssh, const unsigned char **data,
885 int (*do_ssh_init)(Ssh ssh, unsigned char c);
888 * We maintain our own copy of a Conf structure here. That way,
889 * when we're passed a new one for reconfiguration, we can check
890 * the differences and potentially reconfigure port forwardings
891 * etc in mid-session.
896 * Values cached out of conf so as to avoid the tree234 lookup
897 * cost every time they're used.
902 * Dynamically allocated username string created during SSH
903 * login. Stored in here rather than in the coroutine state so
904 * that it'll be reliably freed if we shut down the SSH session
905 * at some unexpected moment.
910 * Used to transfer data back from async callbacks.
912 void *agent_response;
913 int agent_response_len;
917 * The SSH connection can be set as `frozen', meaning we are
918 * not currently accepting incoming data from the network. This
919 * is slightly more serious than setting the _socket_ as
920 * frozen, because we may already have had data passed to us
921 * from the network which we need to delay processing until
922 * after the freeze is lifted, so we also need a bufchain to
926 bufchain queued_incoming_data;
929 * Dispatch table for packet types that we may have to deal
932 handler_fn_t packet_dispatch[256];
935 * Queues of one-off handler functions for success/failure
936 * indications from a request.
938 struct queued_handler *qhead, *qtail;
939 handler_fn_t q_saved_handler1, q_saved_handler2;
942 * This module deals with sending keepalives.
947 * Track incoming and outgoing data sizes and time, for
950 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
951 unsigned long max_data_size;
953 unsigned long next_rekey, last_rekey;
954 const char *deferred_rekey_reason;
957 * Fully qualified host name, which we need if doing GSSAPI.
963 * GSSAPI libraries for this session.
965 struct ssh_gss_liblist *gsslibs;
969 * The last list returned from get_specials.
971 struct telnet_special *specials;
974 * List of host key algorithms for which we _don't_ have a stored
975 * host key. These are indices into the main hostkey_algs[] array
977 int uncert_hostkeys[lenof(hostkey_algs)];
978 int n_uncert_hostkeys;
981 * Flag indicating that the current rekey is intended to finish
982 * with a newly cross-certified host key.
984 int cross_certifying;
987 #define logevent(s) logevent(ssh->frontend, s)
989 /* logevent, only printf-formatted. */
990 static void logeventf(Ssh ssh, const char *fmt, ...)
996 buf = dupvprintf(fmt, ap);
1002 static void bomb_out(Ssh ssh, char *text)
1004 ssh_do_close(ssh, FALSE);
1006 connection_fatal(ssh->frontend, "%s", text);
1010 #define bombout(msg) bomb_out(ssh, dupprintf msg)
1012 /* Helper function for common bits of parsing ttymodes. */
1013 static void parse_ttymodes(Ssh ssh,
1014 void (*do_mode)(void *data,
1015 const struct ssh_ttymode *mode,
1020 const struct ssh_ttymode *mode;
1022 char default_val[2];
1024 strcpy(default_val, "A");
1026 for (i = 0; i < lenof(ssh_ttymodes); i++) {
1027 mode = ssh_ttymodes + i;
1028 val = conf_get_str_str_opt(ssh->conf, CONF_ttymodes, mode->mode);
1033 * val[0] is either 'V', indicating that an explicit value
1034 * follows it, or 'A' indicating that we should pass the
1035 * value through from the local environment via get_ttymode.
1037 if (val[0] == 'A') {
1038 val = get_ttymode(ssh->frontend, mode->mode);
1040 do_mode(data, mode, val);
1044 do_mode(data, mode, val + 1); /* skip the 'V' */
1048 static int ssh_channelcmp(void *av, void *bv)
1050 struct ssh_channel *a = (struct ssh_channel *) av;
1051 struct ssh_channel *b = (struct ssh_channel *) bv;
1052 if (a->localid < b->localid)
1054 if (a->localid > b->localid)
1058 static int ssh_channelfind(void *av, void *bv)
1060 unsigned *a = (unsigned *) av;
1061 struct ssh_channel *b = (struct ssh_channel *) bv;
1062 if (*a < b->localid)
1064 if (*a > b->localid)
1069 static int ssh_rportcmp_ssh1(void *av, void *bv)
1071 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1072 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1074 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
1075 return i < 0 ? -1 : +1;
1076 if (a->dport > b->dport)
1078 if (a->dport < b->dport)
1083 static int ssh_rportcmp_ssh2(void *av, void *bv)
1085 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1086 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1088 if ( (i = strcmp(a->shost, b->shost)) != 0)
1089 return i < 0 ? -1 : +1;
1090 if (a->sport > b->sport)
1092 if (a->sport < b->sport)
1098 * Special form of strcmp which can cope with NULL inputs. NULL is
1099 * defined to sort before even the empty string.
1101 static int nullstrcmp(const char *a, const char *b)
1103 if (a == NULL && b == NULL)
1109 return strcmp(a, b);
1112 static int ssh_portcmp(void *av, void *bv)
1114 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1115 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1117 if (a->type > b->type)
1119 if (a->type < b->type)
1121 if (a->addressfamily > b->addressfamily)
1123 if (a->addressfamily < b->addressfamily)
1125 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1126 return i < 0 ? -1 : +1;
1127 if (a->sport > b->sport)
1129 if (a->sport < b->sport)
1131 if (a->type != 'D') {
1132 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1133 return i < 0 ? -1 : +1;
1134 if (a->dport > b->dport)
1136 if (a->dport < b->dport)
1142 static int alloc_channel_id(Ssh ssh)
1144 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1145 unsigned low, high, mid;
1147 struct ssh_channel *c;
1150 * First-fit allocation of channel numbers: always pick the
1151 * lowest unused one. To do this, binary-search using the
1152 * counted B-tree to find the largest channel ID which is in a
1153 * contiguous sequence from the beginning. (Precisely
1154 * everything in that sequence must have ID equal to its tree
1155 * index plus CHANNEL_NUMBER_OFFSET.)
1157 tsize = count234(ssh->channels);
1161 while (high - low > 1) {
1162 mid = (high + low) / 2;
1163 c = index234(ssh->channels, mid);
1164 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1165 low = mid; /* this one is fine */
1167 high = mid; /* this one is past it */
1170 * Now low points to either -1, or the tree index of the
1171 * largest ID in the initial sequence.
1174 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1175 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1177 return low + 1 + CHANNEL_NUMBER_OFFSET;
1180 static void c_write_stderr(int trusted, const char *buf, int len)
1183 for (i = 0; i < len; i++)
1184 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1185 fputc(buf[i], stderr);
1188 static void c_write(Ssh ssh, const char *buf, int len)
1190 if (flags & FLAG_STDERR)
1191 c_write_stderr(1, buf, len);
1193 from_backend(ssh->frontend, 1, buf, len);
1196 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1198 if (flags & FLAG_STDERR)
1199 c_write_stderr(0, buf, len);
1201 from_backend_untrusted(ssh->frontend, buf, len);
1204 static void c_write_str(Ssh ssh, const char *buf)
1206 c_write(ssh, buf, strlen(buf));
1209 static void ssh_free_packet(struct Packet *pkt)
1214 static struct Packet *ssh_new_packet(void)
1216 struct Packet *pkt = snew(struct Packet);
1218 pkt->body = pkt->data = NULL;
1224 static void ssh1_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1227 struct logblank_t blanks[4];
1233 if (ssh->logomitdata &&
1234 (pkt->type == SSH1_SMSG_STDOUT_DATA ||
1235 pkt->type == SSH1_SMSG_STDERR_DATA ||
1236 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1237 /* "Session data" packets - omit the data string. */
1238 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1239 ssh_pkt_getuint32(pkt); /* skip channel id */
1240 blanks[nblanks].offset = pkt->savedpos + 4;
1241 blanks[nblanks].type = PKTLOG_OMIT;
1242 ssh_pkt_getstring(pkt, &str, &slen);
1244 blanks[nblanks].len = slen;
1248 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1249 ssh1_pkt_type(pkt->type),
1250 pkt->body, pkt->length, nblanks, blanks, NULL,
1254 static void ssh1_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1257 struct logblank_t blanks[4];
1262 * For outgoing packets, pkt->length represents the length of the
1263 * whole packet starting at pkt->data (including some header), and
1264 * pkt->body refers to the point within that where the log-worthy
1265 * payload begins. However, incoming packets expect pkt->length to
1266 * represent only the payload length (that is, it's measured from
1267 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1268 * packet to conform to the incoming-packet semantics, so that we
1269 * can analyse it with the ssh_pkt_get functions.
1271 pkt->length -= (pkt->body - pkt->data);
1274 if (ssh->logomitdata &&
1275 (pkt->type == SSH1_CMSG_STDIN_DATA ||
1276 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1277 /* "Session data" packets - omit the data string. */
1278 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1279 ssh_pkt_getuint32(pkt); /* skip channel id */
1280 blanks[nblanks].offset = pkt->savedpos + 4;
1281 blanks[nblanks].type = PKTLOG_OMIT;
1282 ssh_pkt_getstring(pkt, &str, &slen);
1284 blanks[nblanks].len = slen;
1289 if ((pkt->type == SSH1_CMSG_AUTH_PASSWORD ||
1290 pkt->type == SSH1_CMSG_AUTH_TIS_RESPONSE ||
1291 pkt->type == SSH1_CMSG_AUTH_CCARD_RESPONSE) &&
1292 conf_get_int(ssh->conf, CONF_logomitpass)) {
1293 /* If this is a password or similar packet, blank the password(s). */
1294 blanks[nblanks].offset = 0;
1295 blanks[nblanks].len = pkt->length;
1296 blanks[nblanks].type = PKTLOG_BLANK;
1298 } else if (pkt->type == SSH1_CMSG_X11_REQUEST_FORWARDING &&
1299 conf_get_int(ssh->conf, CONF_logomitpass)) {
1301 * If this is an X forwarding request packet, blank the fake
1304 * Note that while we blank the X authentication data here, we
1305 * don't take any special action to blank the start of an X11
1306 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1307 * an X connection without having session blanking enabled is
1308 * likely to leak your cookie into the log.
1311 ssh_pkt_getstring(pkt, &str, &slen);
1312 blanks[nblanks].offset = pkt->savedpos;
1313 blanks[nblanks].type = PKTLOG_BLANK;
1314 ssh_pkt_getstring(pkt, &str, &slen);
1316 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1321 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1322 ssh1_pkt_type(pkt->data[12]),
1323 pkt->body, pkt->length,
1324 nblanks, blanks, NULL, 0, NULL);
1327 * Undo the above adjustment of pkt->length, to put the packet
1328 * back in the state we found it.
1330 pkt->length += (pkt->body - pkt->data);
1334 * Collect incoming data in the incoming packet buffer.
1335 * Decipher and verify the packet when it is completely read.
1336 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1337 * Update the *data and *datalen variables.
1338 * Return a Packet structure when a packet is completed.
1340 static struct Packet *ssh1_rdpkt(Ssh ssh, const unsigned char **data,
1343 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1345 crBegin(ssh->ssh1_rdpkt_crstate);
1347 st->pktin = ssh_new_packet();
1349 st->pktin->type = 0;
1350 st->pktin->length = 0;
1352 for (st->i = st->len = 0; st->i < 4; st->i++) {
1353 while ((*datalen) == 0)
1355 st->len = (st->len << 8) + **data;
1356 (*data)++, (*datalen)--;
1359 st->pad = 8 - (st->len % 8);
1360 st->biglen = st->len + st->pad;
1361 st->pktin->length = st->len - 5;
1363 if (st->biglen < 0) {
1364 bombout(("Extremely large packet length from server suggests"
1365 " data stream corruption"));
1366 ssh_free_packet(st->pktin);
1370 st->pktin->maxlen = st->biglen;
1371 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1373 st->to_read = st->biglen;
1374 st->p = st->pktin->data;
1375 while (st->to_read > 0) {
1376 st->chunk = st->to_read;
1377 while ((*datalen) == 0)
1379 if (st->chunk > (*datalen))
1380 st->chunk = (*datalen);
1381 memcpy(st->p, *data, st->chunk);
1383 *datalen -= st->chunk;
1385 st->to_read -= st->chunk;
1388 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1389 st->biglen, NULL)) {
1390 bombout(("Network attack (CRC compensation) detected!"));
1391 ssh_free_packet(st->pktin);
1396 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1398 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1399 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1400 if (st->gotcrc != st->realcrc) {
1401 bombout(("Incorrect CRC received on packet"));
1402 ssh_free_packet(st->pktin);
1406 st->pktin->body = st->pktin->data + st->pad + 1;
1408 if (ssh->v1_compressing) {
1409 unsigned char *decompblk;
1411 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1412 st->pktin->body - 1, st->pktin->length + 1,
1413 &decompblk, &decomplen)) {
1414 bombout(("Zlib decompression encountered invalid data"));
1415 ssh_free_packet(st->pktin);
1419 if (st->pktin->maxlen < st->pad + decomplen) {
1420 st->pktin->maxlen = st->pad + decomplen;
1421 st->pktin->data = sresize(st->pktin->data,
1422 st->pktin->maxlen + APIEXTRA,
1424 st->pktin->body = st->pktin->data + st->pad + 1;
1427 memcpy(st->pktin->body - 1, decompblk, decomplen);
1429 st->pktin->length = decomplen - 1;
1432 st->pktin->type = st->pktin->body[-1];
1435 * Now pktin->body and pktin->length identify the semantic content
1436 * of the packet, excluding the initial type byte.
1440 ssh1_log_incoming_packet(ssh, st->pktin);
1442 st->pktin->savedpos = 0;
1444 crFinish(st->pktin);
1447 static void ssh2_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1450 struct logblank_t blanks[4];
1456 if (ssh->logomitdata &&
1457 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1458 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1459 /* "Session data" packets - omit the data string. */
1460 ssh_pkt_getuint32(pkt); /* skip channel id */
1461 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1462 ssh_pkt_getuint32(pkt); /* skip extended data type */
1463 blanks[nblanks].offset = pkt->savedpos + 4;
1464 blanks[nblanks].type = PKTLOG_OMIT;
1465 ssh_pkt_getstring(pkt, &str, &slen);
1467 blanks[nblanks].len = slen;
1472 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1473 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->type),
1474 pkt->body, pkt->length, nblanks, blanks, &pkt->sequence,
1478 static void ssh2_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1481 struct logblank_t blanks[4];
1486 * For outgoing packets, pkt->length represents the length of the
1487 * whole packet starting at pkt->data (including some header), and
1488 * pkt->body refers to the point within that where the log-worthy
1489 * payload begins. However, incoming packets expect pkt->length to
1490 * represent only the payload length (that is, it's measured from
1491 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1492 * packet to conform to the incoming-packet semantics, so that we
1493 * can analyse it with the ssh_pkt_get functions.
1495 pkt->length -= (pkt->body - pkt->data);
1498 if (ssh->logomitdata &&
1499 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1500 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1501 /* "Session data" packets - omit the data string. */
1502 ssh_pkt_getuint32(pkt); /* skip channel id */
1503 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1504 ssh_pkt_getuint32(pkt); /* skip extended data type */
1505 blanks[nblanks].offset = pkt->savedpos + 4;
1506 blanks[nblanks].type = PKTLOG_OMIT;
1507 ssh_pkt_getstring(pkt, &str, &slen);
1509 blanks[nblanks].len = slen;
1514 if (pkt->type == SSH2_MSG_USERAUTH_REQUEST &&
1515 conf_get_int(ssh->conf, CONF_logomitpass)) {
1516 /* If this is a password packet, blank the password(s). */
1518 ssh_pkt_getstring(pkt, &str, &slen);
1519 ssh_pkt_getstring(pkt, &str, &slen);
1520 ssh_pkt_getstring(pkt, &str, &slen);
1521 if (slen == 8 && !memcmp(str, "password", 8)) {
1522 ssh2_pkt_getbool(pkt);
1523 /* Blank the password field. */
1524 blanks[nblanks].offset = pkt->savedpos;
1525 blanks[nblanks].type = PKTLOG_BLANK;
1526 ssh_pkt_getstring(pkt, &str, &slen);
1528 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1530 /* If there's another password field beyond it (change of
1531 * password), blank that too. */
1532 ssh_pkt_getstring(pkt, &str, &slen);
1534 blanks[nblanks-1].len =
1535 pkt->savedpos - blanks[nblanks].offset;
1538 } else if (ssh->pkt_actx == SSH2_PKTCTX_KBDINTER &&
1539 pkt->type == SSH2_MSG_USERAUTH_INFO_RESPONSE &&
1540 conf_get_int(ssh->conf, CONF_logomitpass)) {
1541 /* If this is a keyboard-interactive response packet, blank
1544 ssh_pkt_getuint32(pkt);
1545 blanks[nblanks].offset = pkt->savedpos;
1546 blanks[nblanks].type = PKTLOG_BLANK;
1548 ssh_pkt_getstring(pkt, &str, &slen);
1552 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1554 } else if (pkt->type == SSH2_MSG_CHANNEL_REQUEST &&
1555 conf_get_int(ssh->conf, CONF_logomitpass)) {
1557 * If this is an X forwarding request packet, blank the fake
1560 * Note that while we blank the X authentication data here, we
1561 * don't take any special action to blank the start of an X11
1562 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1563 * an X connection without having session blanking enabled is
1564 * likely to leak your cookie into the log.
1567 ssh_pkt_getuint32(pkt);
1568 ssh_pkt_getstring(pkt, &str, &slen);
1569 if (slen == 7 && !memcmp(str, "x11-req", 0)) {
1570 ssh2_pkt_getbool(pkt);
1571 ssh2_pkt_getbool(pkt);
1572 ssh_pkt_getstring(pkt, &str, &slen);
1573 blanks[nblanks].offset = pkt->savedpos;
1574 blanks[nblanks].type = PKTLOG_BLANK;
1575 ssh_pkt_getstring(pkt, &str, &slen);
1577 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1583 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1584 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1585 pkt->body, pkt->length, nblanks, blanks,
1586 &ssh->v2_outgoing_sequence,
1587 pkt->downstream_id, pkt->additional_log_text);
1590 * Undo the above adjustment of pkt->length, to put the packet
1591 * back in the state we found it.
1593 pkt->length += (pkt->body - pkt->data);
1596 static struct Packet *ssh2_rdpkt(Ssh ssh, const unsigned char **data,
1599 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1601 crBegin(ssh->ssh2_rdpkt_crstate);
1603 st->pktin = ssh_new_packet();
1605 st->pktin->type = 0;
1606 st->pktin->length = 0;
1608 st->cipherblk = ssh->sccipher->blksize;
1611 if (st->cipherblk < 8)
1613 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1615 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1616 ssh->scmac && !ssh->scmac_etm) {
1618 * When dealing with a CBC-mode cipher, we want to avoid the
1619 * possibility of an attacker's tweaking the ciphertext stream
1620 * so as to cause us to feed the same block to the block
1621 * cipher more than once and thus leak information
1622 * (VU#958563). The way we do this is not to take any
1623 * decisions on the basis of anything we've decrypted until
1624 * we've verified it with a MAC. That includes the packet
1625 * length, so we just read data and check the MAC repeatedly,
1626 * and when the MAC passes, see if the length we've got is
1629 * This defence is unnecessary in OpenSSH ETM mode, because
1630 * the whole point of ETM mode is that the attacker can't
1631 * tweak the ciphertext stream at all without the MAC
1632 * detecting it before we decrypt anything.
1635 /* May as well allocate the whole lot now. */
1636 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1639 /* Read an amount corresponding to the MAC. */
1640 for (st->i = 0; st->i < st->maclen; st->i++) {
1641 while ((*datalen) == 0)
1643 st->pktin->data[st->i] = *(*data)++;
1649 unsigned char seq[4];
1650 ssh->scmac->start(ssh->sc_mac_ctx);
1651 PUT_32BIT(seq, st->incoming_sequence);
1652 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1655 for (;;) { /* Once around this loop per cipher block. */
1656 /* Read another cipher-block's worth, and tack it onto the end. */
1657 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1658 while ((*datalen) == 0)
1660 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1663 /* Decrypt one more block (a little further back in the stream). */
1664 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1665 st->pktin->data + st->packetlen,
1667 /* Feed that block to the MAC. */
1668 ssh->scmac->bytes(ssh->sc_mac_ctx,
1669 st->pktin->data + st->packetlen, st->cipherblk);
1670 st->packetlen += st->cipherblk;
1671 /* See if that gives us a valid packet. */
1672 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1673 st->pktin->data + st->packetlen) &&
1674 ((st->len = toint(GET_32BIT(st->pktin->data))) ==
1677 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1678 bombout(("No valid incoming packet found"));
1679 ssh_free_packet(st->pktin);
1683 st->pktin->maxlen = st->packetlen + st->maclen;
1684 st->pktin->data = sresize(st->pktin->data,
1685 st->pktin->maxlen + APIEXTRA,
1687 } else if (ssh->scmac && ssh->scmac_etm) {
1688 st->pktin->data = snewn(4 + APIEXTRA, unsigned char);
1691 * OpenSSH encrypt-then-MAC mode: the packet length is
1692 * unencrypted, unless the cipher supports length encryption.
1694 for (st->i = st->len = 0; st->i < 4; st->i++) {
1695 while ((*datalen) == 0)
1697 st->pktin->data[st->i] = *(*data)++;
1700 /* Cipher supports length decryption, so do it */
1701 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_SEPARATE_LENGTH)) {
1702 /* Keep the packet the same though, so the MAC passes */
1703 unsigned char len[4];
1704 memcpy(len, st->pktin->data, 4);
1705 ssh->sccipher->decrypt_length(ssh->sc_cipher_ctx, len, 4, st->incoming_sequence);
1706 st->len = toint(GET_32BIT(len));
1708 st->len = toint(GET_32BIT(st->pktin->data));
1712 * _Completely_ silly lengths should be stomped on before they
1713 * do us any more damage.
1715 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1716 st->len % st->cipherblk != 0) {
1717 bombout(("Incoming packet length field was garbled"));
1718 ssh_free_packet(st->pktin);
1723 * So now we can work out the total packet length.
1725 st->packetlen = st->len + 4;
1728 * Allocate memory for the rest of the packet.
1730 st->pktin->maxlen = st->packetlen + st->maclen;
1731 st->pktin->data = sresize(st->pktin->data,
1732 st->pktin->maxlen + APIEXTRA,
1736 * Read the remainder of the packet.
1738 for (st->i = 4; st->i < st->packetlen + st->maclen; st->i++) {
1739 while ((*datalen) == 0)
1741 st->pktin->data[st->i] = *(*data)++;
1749 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1750 st->len + 4, st->incoming_sequence)) {
1751 bombout(("Incorrect MAC received on packet"));
1752 ssh_free_packet(st->pktin);
1756 /* Decrypt everything between the length field and the MAC. */
1758 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1759 st->pktin->data + 4,
1762 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1765 * Acquire and decrypt the first block of the packet. This will
1766 * contain the length and padding details.
1768 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1769 while ((*datalen) == 0)
1771 st->pktin->data[st->i] = *(*data)++;
1776 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1777 st->pktin->data, st->cipherblk);
1780 * Now get the length figure.
1782 st->len = toint(GET_32BIT(st->pktin->data));
1785 * _Completely_ silly lengths should be stomped on before they
1786 * do us any more damage.
1788 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1789 (st->len + 4) % st->cipherblk != 0) {
1790 bombout(("Incoming packet was garbled on decryption"));
1791 ssh_free_packet(st->pktin);
1796 * So now we can work out the total packet length.
1798 st->packetlen = st->len + 4;
1801 * Allocate memory for the rest of the packet.
1803 st->pktin->maxlen = st->packetlen + st->maclen;
1804 st->pktin->data = sresize(st->pktin->data,
1805 st->pktin->maxlen + APIEXTRA,
1809 * Read and decrypt the remainder of the packet.
1811 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1813 while ((*datalen) == 0)
1815 st->pktin->data[st->i] = *(*data)++;
1818 /* Decrypt everything _except_ the MAC. */
1820 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1821 st->pktin->data + st->cipherblk,
1822 st->packetlen - st->cipherblk);
1828 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1829 st->len + 4, st->incoming_sequence)) {
1830 bombout(("Incorrect MAC received on packet"));
1831 ssh_free_packet(st->pktin);
1835 /* Get and sanity-check the amount of random padding. */
1836 st->pad = st->pktin->data[4];
1837 if (st->pad < 4 || st->len - st->pad < 1) {
1838 bombout(("Invalid padding length on received packet"));
1839 ssh_free_packet(st->pktin);
1843 * This enables us to deduce the payload length.
1845 st->payload = st->len - st->pad - 1;
1847 st->pktin->length = st->payload + 5;
1848 st->pktin->encrypted_len = st->packetlen;
1850 st->pktin->sequence = st->incoming_sequence++;
1852 st->pktin->length = st->packetlen - st->pad;
1853 assert(st->pktin->length >= 0);
1856 * Decompress packet payload.
1859 unsigned char *newpayload;
1862 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1863 st->pktin->data + 5, st->pktin->length - 5,
1864 &newpayload, &newlen)) {
1865 if (st->pktin->maxlen < newlen + 5) {
1866 st->pktin->maxlen = newlen + 5;
1867 st->pktin->data = sresize(st->pktin->data,
1868 st->pktin->maxlen + APIEXTRA,
1871 st->pktin->length = 5 + newlen;
1872 memcpy(st->pktin->data + 5, newpayload, newlen);
1878 * RFC 4253 doesn't explicitly say that completely empty packets
1879 * with no type byte are forbidden, so treat them as deserving
1880 * an SSH_MSG_UNIMPLEMENTED.
1882 if (st->pktin->length <= 5) { /* == 5 we hope, but robustness */
1883 ssh2_msg_something_unimplemented(ssh, st->pktin);
1887 * pktin->body and pktin->length should identify the semantic
1888 * content of the packet, excluding the initial type byte.
1890 st->pktin->type = st->pktin->data[5];
1891 st->pktin->body = st->pktin->data + 6;
1892 st->pktin->length -= 6;
1893 assert(st->pktin->length >= 0); /* one last double-check */
1896 ssh2_log_incoming_packet(ssh, st->pktin);
1898 st->pktin->savedpos = 0;
1900 crFinish(st->pktin);
1903 static struct Packet *ssh2_bare_connection_rdpkt(Ssh ssh,
1904 const unsigned char **data,
1907 struct rdpkt2_bare_state_tag *st = &ssh->rdpkt2_bare_state;
1909 crBegin(ssh->ssh2_bare_rdpkt_crstate);
1912 * Read the packet length field.
1914 for (st->i = 0; st->i < 4; st->i++) {
1915 while ((*datalen) == 0)
1917 st->length[st->i] = *(*data)++;
1921 st->packetlen = toint(GET_32BIT_MSB_FIRST(st->length));
1922 if (st->packetlen <= 0 || st->packetlen >= OUR_V2_PACKETLIMIT) {
1923 bombout(("Invalid packet length received"));
1927 st->pktin = ssh_new_packet();
1928 st->pktin->data = snewn(st->packetlen, unsigned char);
1930 st->pktin->encrypted_len = st->packetlen;
1932 st->pktin->sequence = st->incoming_sequence++;
1935 * Read the remainder of the packet.
1937 for (st->i = 0; st->i < st->packetlen; st->i++) {
1938 while ((*datalen) == 0)
1940 st->pktin->data[st->i] = *(*data)++;
1945 * pktin->body and pktin->length should identify the semantic
1946 * content of the packet, excluding the initial type byte.
1948 st->pktin->type = st->pktin->data[0];
1949 st->pktin->body = st->pktin->data + 1;
1950 st->pktin->length = st->packetlen - 1;
1953 * Log incoming packet, possibly omitting sensitive fields.
1956 ssh2_log_incoming_packet(ssh, st->pktin);
1958 st->pktin->savedpos = 0;
1960 crFinish(st->pktin);
1963 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1965 int pad, biglen, i, pktoffs;
1969 * XXX various versions of SC (including 8.8.4) screw up the
1970 * register allocation in this function and use the same register
1971 * (D6) for len and as a temporary, with predictable results. The
1972 * following sledgehammer prevents this.
1979 ssh1_log_outgoing_packet(ssh, pkt);
1981 if (ssh->v1_compressing) {
1982 unsigned char *compblk;
1984 zlib_compress_block(ssh->cs_comp_ctx,
1985 pkt->data + 12, pkt->length - 12,
1986 &compblk, &complen);
1987 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1988 memcpy(pkt->data + 12, compblk, complen);
1990 pkt->length = complen + 12;
1993 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1995 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1996 pad = 8 - (len % 8);
1998 biglen = len + pad; /* len(padding+type+data+CRC) */
2000 for (i = pktoffs; i < 4+8; i++)
2001 pkt->data[i] = random_byte();
2002 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
2003 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
2004 PUT_32BIT(pkt->data + pktoffs, len);
2007 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
2008 pkt->data + pktoffs + 4, biglen);
2010 if (offset_p) *offset_p = pktoffs;
2011 return biglen + 4; /* len(length+padding+type+data+CRC) */
2014 static int s_write(Ssh ssh, void *data, int len)
2017 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
2018 0, NULL, NULL, 0, NULL);
2021 return sk_write(ssh->s, (char *)data, len);
2024 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
2026 int len, backlog, offset;
2027 len = s_wrpkt_prepare(ssh, pkt, &offset);
2028 backlog = s_write(ssh, pkt->data + offset, len);
2029 if (backlog > SSH_MAX_BACKLOG)
2030 ssh_throttle_all(ssh, 1, backlog);
2031 ssh_free_packet(pkt);
2034 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
2037 len = s_wrpkt_prepare(ssh, pkt, &offset);
2038 if (ssh->deferred_len + len > ssh->deferred_size) {
2039 ssh->deferred_size = ssh->deferred_len + len + 128;
2040 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2044 memcpy(ssh->deferred_send_data + ssh->deferred_len,
2045 pkt->data + offset, len);
2046 ssh->deferred_len += len;
2047 ssh_free_packet(pkt);
2051 * Construct a SSH-1 packet with the specified contents.
2052 * (This all-at-once interface used to be the only one, but now SSH-1
2053 * packets can also be constructed incrementally.)
2055 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
2061 pkt = ssh1_pkt_init(pkttype);
2063 while ((argtype = va_arg(ap, int)) != PKT_END) {
2064 unsigned char *argp, argchar;
2066 unsigned long argint;
2069 /* Actual fields in the packet */
2071 argint = va_arg(ap, int);
2072 ssh_pkt_adduint32(pkt, argint);
2075 argchar = (unsigned char) va_arg(ap, int);
2076 ssh_pkt_addbyte(pkt, argchar);
2079 argp = va_arg(ap, unsigned char *);
2080 arglen = va_arg(ap, int);
2081 ssh_pkt_adddata(pkt, argp, arglen);
2084 sargp = va_arg(ap, char *);
2085 ssh_pkt_addstring(pkt, sargp);
2088 bn = va_arg(ap, Bignum);
2089 ssh1_pkt_addmp(pkt, bn);
2097 static void send_packet(Ssh ssh, int pkttype, ...)
2101 va_start(ap, pkttype);
2102 pkt = construct_packet(ssh, pkttype, ap);
2107 static void defer_packet(Ssh ssh, int pkttype, ...)
2111 va_start(ap, pkttype);
2112 pkt = construct_packet(ssh, pkttype, ap);
2114 s_wrpkt_defer(ssh, pkt);
2117 static int ssh_versioncmp(const char *a, const char *b)
2120 unsigned long av, bv;
2122 av = strtoul(a, &ae, 10);
2123 bv = strtoul(b, &be, 10);
2125 return (av < bv ? -1 : +1);
2130 av = strtoul(ae, &ae, 10);
2131 bv = strtoul(be, &be, 10);
2133 return (av < bv ? -1 : +1);
2138 * Utility routines for putting an SSH-protocol `string' and
2139 * `uint32' into a hash state.
2141 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
2143 unsigned char lenblk[4];
2144 PUT_32BIT(lenblk, len);
2145 h->bytes(s, lenblk, 4);
2146 h->bytes(s, str, len);
2149 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
2151 unsigned char intblk[4];
2152 PUT_32BIT(intblk, i);
2153 h->bytes(s, intblk, 4);
2157 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
2159 static void ssh_pkt_ensure(struct Packet *pkt, int length)
2161 if (pkt->maxlen < length) {
2162 unsigned char *body = pkt->body;
2163 int offset = body ? body - pkt->data : 0;
2164 pkt->maxlen = length + 256;
2165 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
2166 if (body) pkt->body = pkt->data + offset;
2169 static void ssh_pkt_adddata(struct Packet *pkt, const void *data, int len)
2172 ssh_pkt_ensure(pkt, pkt->length);
2173 memcpy(pkt->data + pkt->length - len, data, len);
2175 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
2177 ssh_pkt_adddata(pkt, &byte, 1);
2179 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
2181 ssh_pkt_adddata(pkt, &value, 1);
2183 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
2186 PUT_32BIT(x, value);
2187 ssh_pkt_adddata(pkt, x, 4);
2189 static void ssh_pkt_addstring_start(struct Packet *pkt)
2191 ssh_pkt_adduint32(pkt, 0);
2192 pkt->savedpos = pkt->length;
2194 static void ssh_pkt_addstring_data(struct Packet *pkt, const char *data,
2197 ssh_pkt_adddata(pkt, data, len);
2198 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
2200 static void ssh_pkt_addstring_str(struct Packet *pkt, const char *data)
2202 ssh_pkt_addstring_data(pkt, data, strlen(data));
2204 static void ssh_pkt_addstring(struct Packet *pkt, const char *data)
2206 ssh_pkt_addstring_start(pkt);
2207 ssh_pkt_addstring_str(pkt, data);
2209 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
2211 int len = ssh1_bignum_length(b);
2212 unsigned char *data = snewn(len, unsigned char);
2213 (void) ssh1_write_bignum(data, b);
2214 ssh_pkt_adddata(pkt, data, len);
2217 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
2220 int i, n = (bignum_bitcount(b) + 7) / 8;
2221 p = snewn(n + 1, unsigned char);
2223 for (i = 1; i <= n; i++)
2224 p[i] = bignum_byte(b, n - i);
2226 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
2228 memmove(p, p + i, n + 1 - i);
2232 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
2236 p = ssh2_mpint_fmt(b, &len);
2237 ssh_pkt_addstring_start(pkt);
2238 ssh_pkt_addstring_data(pkt, (char *)p, len);
2242 static struct Packet *ssh1_pkt_init(int pkt_type)
2244 struct Packet *pkt = ssh_new_packet();
2245 pkt->length = 4 + 8; /* space for length + max padding */
2246 ssh_pkt_addbyte(pkt, pkt_type);
2247 pkt->body = pkt->data + pkt->length;
2248 pkt->type = pkt_type;
2249 pkt->downstream_id = 0;
2250 pkt->additional_log_text = NULL;
2254 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
2255 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
2256 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
2257 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
2258 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
2259 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
2260 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
2261 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
2262 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
2264 static struct Packet *ssh2_pkt_init(int pkt_type)
2266 struct Packet *pkt = ssh_new_packet();
2267 pkt->length = 5; /* space for packet length + padding length */
2269 pkt->type = pkt_type;
2270 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
2271 pkt->body = pkt->data + pkt->length; /* after packet type */
2272 pkt->downstream_id = 0;
2273 pkt->additional_log_text = NULL;
2278 * Construct an SSH-2 final-form packet: compress it, encrypt it,
2279 * put the MAC on it. Final packet, ready to be sent, is stored in
2280 * pkt->data. Total length is returned.
2282 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
2284 int cipherblk, maclen, padding, unencrypted_prefix, i;
2287 ssh2_log_outgoing_packet(ssh, pkt);
2289 if (ssh->bare_connection) {
2291 * Trivial packet construction for the bare connection
2294 PUT_32BIT(pkt->data + 1, pkt->length - 5);
2295 pkt->body = pkt->data + 1;
2296 ssh->v2_outgoing_sequence++; /* only for diagnostics, really */
2297 return pkt->length - 1;
2301 * Compress packet payload.
2304 unsigned char *newpayload;
2307 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
2309 &newpayload, &newlen)) {
2311 ssh2_pkt_adddata(pkt, newpayload, newlen);
2317 * Add padding. At least four bytes, and must also bring total
2318 * length (minus MAC) up to a multiple of the block size.
2319 * If pkt->forcepad is set, make sure the packet is at least that size
2322 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
2323 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
2325 unencrypted_prefix = (ssh->csmac && ssh->csmac_etm) ? 4 : 0;
2326 if (pkt->length + padding < pkt->forcepad)
2327 padding = pkt->forcepad - pkt->length;
2329 (cipherblk - (pkt->length - unencrypted_prefix + padding) % cipherblk)
2331 assert(padding <= 255);
2332 maclen = ssh->csmac ? ssh->csmac->len : 0;
2333 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
2334 pkt->data[4] = padding;
2335 for (i = 0; i < padding; i++)
2336 pkt->data[pkt->length + i] = random_byte();
2337 PUT_32BIT(pkt->data, pkt->length + padding - 4);
2339 /* Encrypt length if the scheme requires it */
2340 if (ssh->cscipher && (ssh->cscipher->flags & SSH_CIPHER_SEPARATE_LENGTH)) {
2341 ssh->cscipher->encrypt_length(ssh->cs_cipher_ctx, pkt->data, 4,
2342 ssh->v2_outgoing_sequence);
2345 if (ssh->csmac && ssh->csmac_etm) {
2347 * OpenSSH-defined encrypt-then-MAC protocol.
2350 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2351 pkt->data + 4, pkt->length + padding - 4);
2352 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2353 pkt->length + padding,
2354 ssh->v2_outgoing_sequence);
2357 * SSH-2 standard protocol.
2360 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2361 pkt->length + padding,
2362 ssh->v2_outgoing_sequence);
2364 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2365 pkt->data, pkt->length + padding);
2368 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
2369 pkt->encrypted_len = pkt->length + padding;
2371 /* Ready-to-send packet starts at pkt->data. We return length. */
2372 pkt->body = pkt->data;
2373 return pkt->length + padding + maclen;
2377 * Routines called from the main SSH code to send packets. There
2378 * are quite a few of these, because we have two separate
2379 * mechanisms for delaying the sending of packets:
2381 * - In order to send an IGNORE message and a password message in
2382 * a single fixed-length blob, we require the ability to
2383 * concatenate the encrypted forms of those two packets _into_ a
2384 * single blob and then pass it to our <network.h> transport
2385 * layer in one go. Hence, there's a deferment mechanism which
2386 * works after packet encryption.
2388 * - In order to avoid sending any connection-layer messages
2389 * during repeat key exchange, we have to queue up any such
2390 * outgoing messages _before_ they are encrypted (and in
2391 * particular before they're allocated sequence numbers), and
2392 * then send them once we've finished.
2394 * I call these mechanisms `defer' and `queue' respectively, so as
2395 * to distinguish them reasonably easily.
2397 * The functions send_noqueue() and defer_noqueue() free the packet
2398 * structure they are passed. Every outgoing packet goes through
2399 * precisely one of these functions in its life; packets passed to
2400 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
2401 * these or get queued, and then when the queue is later emptied
2402 * the packets are all passed to defer_noqueue().
2404 * When using a CBC-mode cipher, it's necessary to ensure that an
2405 * attacker can't provide data to be encrypted using an IV that they
2406 * know. We ensure this by prefixing each packet that might contain
2407 * user data with an SSH_MSG_IGNORE. This is done using the deferral
2408 * mechanism, so in this case send_noqueue() ends up redirecting to
2409 * defer_noqueue(). If you don't like this inefficiency, don't use
2413 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
2414 static void ssh_pkt_defersend(Ssh);
2417 * Send an SSH-2 packet immediately, without queuing or deferring.
2419 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
2423 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
2424 /* We need to send two packets, so use the deferral mechanism. */
2425 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2426 ssh_pkt_defersend(ssh);
2429 len = ssh2_pkt_construct(ssh, pkt);
2430 backlog = s_write(ssh, pkt->body, len);
2431 if (backlog > SSH_MAX_BACKLOG)
2432 ssh_throttle_all(ssh, 1, backlog);
2434 ssh->outgoing_data_size += pkt->encrypted_len;
2435 if (!ssh->kex_in_progress &&
2436 !ssh->bare_connection &&
2437 ssh->max_data_size != 0 &&
2438 ssh->outgoing_data_size > ssh->max_data_size)
2439 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2441 ssh_free_packet(pkt);
2445 * Defer an SSH-2 packet.
2447 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2450 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2451 ssh->deferred_len == 0 && !noignore &&
2452 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2454 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2455 * get encrypted with a known IV.
2457 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2458 ssh2_pkt_addstring_start(ipkt);
2459 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2461 len = ssh2_pkt_construct(ssh, pkt);
2462 if (ssh->deferred_len + len > ssh->deferred_size) {
2463 ssh->deferred_size = ssh->deferred_len + len + 128;
2464 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2468 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->body, len);
2469 ssh->deferred_len += len;
2470 ssh->deferred_data_size += pkt->encrypted_len;
2471 ssh_free_packet(pkt);
2475 * Queue an SSH-2 packet.
2477 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2479 assert(ssh->queueing);
2481 if (ssh->queuelen >= ssh->queuesize) {
2482 ssh->queuesize = ssh->queuelen + 32;
2483 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2486 ssh->queue[ssh->queuelen++] = pkt;
2490 * Either queue or send a packet, depending on whether queueing is
2493 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2496 ssh2_pkt_queue(ssh, pkt);
2498 ssh2_pkt_send_noqueue(ssh, pkt);
2502 * Either queue or defer a packet, depending on whether queueing is
2505 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2508 ssh2_pkt_queue(ssh, pkt);
2510 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2514 * Send the whole deferred data block constructed by
2515 * ssh2_pkt_defer() or SSH-1's defer_packet().
2517 * The expected use of the defer mechanism is that you call
2518 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2519 * not currently queueing, this simply sets up deferred_send_data
2520 * and then sends it. If we _are_ currently queueing, the calls to
2521 * ssh2_pkt_defer() put the deferred packets on to the queue
2522 * instead, and therefore ssh_pkt_defersend() has no deferred data
2523 * to send. Hence, there's no need to make it conditional on
2526 static void ssh_pkt_defersend(Ssh ssh)
2529 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2530 ssh->deferred_len = ssh->deferred_size = 0;
2531 sfree(ssh->deferred_send_data);
2532 ssh->deferred_send_data = NULL;
2533 if (backlog > SSH_MAX_BACKLOG)
2534 ssh_throttle_all(ssh, 1, backlog);
2536 if (ssh->version == 2) {
2537 ssh->outgoing_data_size += ssh->deferred_data_size;
2538 ssh->deferred_data_size = 0;
2539 if (!ssh->kex_in_progress &&
2540 !ssh->bare_connection &&
2541 ssh->max_data_size != 0 &&
2542 ssh->outgoing_data_size > ssh->max_data_size)
2543 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2548 * Send a packet whose length needs to be disguised (typically
2549 * passwords or keyboard-interactive responses).
2551 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2557 * The simplest way to do this is to adjust the
2558 * variable-length padding field in the outgoing packet.
2560 * Currently compiled out, because some Cisco SSH servers
2561 * don't like excessively padded packets (bah, why's it
2564 pkt->forcepad = padsize;
2565 ssh2_pkt_send(ssh, pkt);
2570 * If we can't do that, however, an alternative approach is
2571 * to use the pkt_defer mechanism to bundle the packet
2572 * tightly together with an SSH_MSG_IGNORE such that their
2573 * combined length is a constant. So first we construct the
2574 * final form of this packet and defer its sending.
2576 ssh2_pkt_defer(ssh, pkt);
2579 * Now construct an SSH_MSG_IGNORE which includes a string
2580 * that's an exact multiple of the cipher block size. (If
2581 * the cipher is NULL so that the block size is
2582 * unavailable, we don't do this trick at all, because we
2583 * gain nothing by it.)
2585 if (ssh->cscipher &&
2586 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2589 stringlen = (256 - ssh->deferred_len);
2590 stringlen += ssh->cscipher->blksize - 1;
2591 stringlen -= (stringlen % ssh->cscipher->blksize);
2594 * Temporarily disable actual compression, so we
2595 * can guarantee to get this string exactly the
2596 * length we want it. The compression-disabling
2597 * routine should return an integer indicating how
2598 * many bytes we should adjust our string length
2602 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2604 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2605 ssh2_pkt_addstring_start(pkt);
2606 for (i = 0; i < stringlen; i++) {
2607 char c = (char) random_byte();
2608 ssh2_pkt_addstring_data(pkt, &c, 1);
2610 ssh2_pkt_defer(ssh, pkt);
2612 ssh_pkt_defersend(ssh);
2617 * Send all queued SSH-2 packets. We send them by means of
2618 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2619 * packets that needed to be lumped together.
2621 static void ssh2_pkt_queuesend(Ssh ssh)
2625 assert(!ssh->queueing);
2627 for (i = 0; i < ssh->queuelen; i++)
2628 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2631 ssh_pkt_defersend(ssh);
2635 void bndebug(char *string, Bignum b)
2639 p = ssh2_mpint_fmt(b, &len);
2640 debug(("%s", string));
2641 for (i = 0; i < len; i++)
2642 debug((" %02x", p[i]));
2648 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2652 p = ssh2_mpint_fmt(b, &len);
2653 hash_string(h, s, p, len);
2658 * Packet decode functions for both SSH-1 and SSH-2.
2660 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2662 unsigned long value;
2663 if (pkt->length - pkt->savedpos < 4)
2664 return 0; /* arrgh, no way to decline (FIXME?) */
2665 value = GET_32BIT(pkt->body + pkt->savedpos);
2669 static int ssh2_pkt_getbool(struct Packet *pkt)
2671 unsigned long value;
2672 if (pkt->length - pkt->savedpos < 1)
2673 return 0; /* arrgh, no way to decline (FIXME?) */
2674 value = pkt->body[pkt->savedpos] != 0;
2678 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2683 if (pkt->length - pkt->savedpos < 4)
2685 len = toint(GET_32BIT(pkt->body + pkt->savedpos));
2690 if (pkt->length - pkt->savedpos < *length)
2692 *p = (char *)(pkt->body + pkt->savedpos);
2693 pkt->savedpos += *length;
2695 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2697 if (pkt->length - pkt->savedpos < length)
2699 pkt->savedpos += length;
2700 return pkt->body + (pkt->savedpos - length);
2702 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2703 const unsigned char **keystr)
2707 j = makekey(pkt->body + pkt->savedpos,
2708 pkt->length - pkt->savedpos,
2715 assert(pkt->savedpos < pkt->length);
2719 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2724 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2725 pkt->length - pkt->savedpos, &b);
2733 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2739 ssh_pkt_getstring(pkt, &p, &length);
2744 b = bignum_from_bytes((unsigned char *)p, length);
2749 * Helper function to add an SSH-2 signature blob to a packet.
2750 * Expects to be shown the public key blob as well as the signature
2751 * blob. Normally works just like ssh2_pkt_addstring, but will
2752 * fiddle with the signature packet if necessary for
2753 * BUG_SSH2_RSA_PADDING.
2755 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2756 void *pkblob_v, int pkblob_len,
2757 void *sigblob_v, int sigblob_len)
2759 unsigned char *pkblob = (unsigned char *)pkblob_v;
2760 unsigned char *sigblob = (unsigned char *)sigblob_v;
2762 /* dmemdump(pkblob, pkblob_len); */
2763 /* dmemdump(sigblob, sigblob_len); */
2766 * See if this is in fact an ssh-rsa signature and a buggy
2767 * server; otherwise we can just do this the easy way.
2769 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) && pkblob_len > 4+7+4 &&
2770 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2771 int pos, len, siglen;
2774 * Find the byte length of the modulus.
2777 pos = 4+7; /* skip over "ssh-rsa" */
2778 len = toint(GET_32BIT(pkblob+pos)); /* get length of exponent */
2779 if (len < 0 || len > pkblob_len - pos - 4)
2781 pos += 4 + len; /* skip over exponent */
2782 if (pkblob_len - pos < 4)
2784 len = toint(GET_32BIT(pkblob+pos)); /* find length of modulus */
2785 if (len < 0 || len > pkblob_len - pos - 4)
2787 pos += 4; /* find modulus itself */
2788 while (len > 0 && pkblob[pos] == 0)
2790 /* debug(("modulus length is %d\n", len)); */
2793 * Now find the signature integer.
2795 pos = 4+7; /* skip over "ssh-rsa" */
2796 if (sigblob_len < pos+4)
2798 siglen = toint(GET_32BIT(sigblob+pos));
2799 if (siglen != sigblob_len - pos - 4)
2801 /* debug(("signature length is %d\n", siglen)); */
2803 if (len != siglen) {
2804 unsigned char newlen[4];
2805 ssh2_pkt_addstring_start(pkt);
2806 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2807 /* dmemdump(sigblob, pos); */
2808 pos += 4; /* point to start of actual sig */
2809 PUT_32BIT(newlen, len);
2810 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2811 /* dmemdump(newlen, 4); */
2813 while (len-- > siglen) {
2814 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2815 /* dmemdump(newlen, 1); */
2817 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2818 /* dmemdump(sigblob+pos, siglen); */
2822 /* Otherwise fall through and do it the easy way. We also come
2823 * here as a fallback if we discover above that the key blob
2824 * is misformatted in some way. */
2828 ssh2_pkt_addstring_start(pkt);
2829 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2833 * Examine the remote side's version string and compare it against
2834 * a list of known buggy implementations.
2836 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2838 char *imp; /* pointer to implementation part */
2840 imp += strcspn(imp, "-");
2842 imp += strcspn(imp, "-");
2845 ssh->remote_bugs = 0;
2848 * General notes on server version strings:
2849 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2850 * here -- in particular, we've heard of one that's perfectly happy
2851 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2852 * so we can't distinguish them.
2854 if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
2855 (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
2856 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2857 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2858 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2859 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2861 * These versions don't support SSH1_MSG_IGNORE, so we have
2862 * to use a different defence against password length
2865 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2866 logevent("We believe remote version has SSH-1 ignore bug");
2869 if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
2870 (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
2871 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2873 * These versions need a plain password sent; they can't
2874 * handle having a null and a random length of data after
2877 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2878 logevent("We believe remote version needs a plain SSH-1 password");
2881 if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
2882 (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
2883 (!strcmp(imp, "Cisco-1.25")))) {
2885 * These versions apparently have no clue whatever about
2886 * RSA authentication and will panic and die if they see
2887 * an AUTH_RSA message.
2889 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2890 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2893 if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
2894 (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
2895 !wc_match("* VShell", imp) &&
2896 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2897 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2898 wc_match("2.1 *", imp)))) {
2900 * These versions have the HMAC bug.
2902 ssh->remote_bugs |= BUG_SSH2_HMAC;
2903 logevent("We believe remote version has SSH-2 HMAC bug");
2906 if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
2907 (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
2908 !wc_match("* VShell", imp) &&
2909 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2911 * These versions have the key-derivation bug (failing to
2912 * include the literal shared secret in the hashes that
2913 * generate the keys).
2915 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2916 logevent("We believe remote version has SSH-2 key-derivation bug");
2919 if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
2920 (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
2921 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2922 wc_match("OpenSSH_3.[0-2]*", imp) ||
2923 wc_match("mod_sftp/0.[0-8]*", imp) ||
2924 wc_match("mod_sftp/0.9.[0-8]", imp)))) {
2926 * These versions have the SSH-2 RSA padding bug.
2928 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2929 logevent("We believe remote version has SSH-2 RSA padding bug");
2932 if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
2933 (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
2934 wc_match("OpenSSH_2.[0-2]*", imp))) {
2936 * These versions have the SSH-2 session-ID bug in
2937 * public-key authentication.
2939 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2940 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2943 if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
2944 (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
2945 (wc_match("DigiSSH_2.0", imp) ||
2946 wc_match("OpenSSH_2.[0-4]*", imp) ||
2947 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2948 wc_match("Sun_SSH_1.0", imp) ||
2949 wc_match("Sun_SSH_1.0.1", imp) ||
2950 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2951 wc_match("WeOnlyDo-*", imp)))) {
2953 * These versions have the SSH-2 rekey bug.
2955 ssh->remote_bugs |= BUG_SSH2_REKEY;
2956 logevent("We believe remote version has SSH-2 rekey bug");
2959 if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
2960 (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
2961 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2962 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2964 * This version ignores our makpkt and needs to be throttled.
2966 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2967 logevent("We believe remote version ignores SSH-2 maximum packet size");
2970 if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
2972 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2973 * none detected automatically.
2975 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2976 logevent("We believe remote version has SSH-2 ignore bug");
2979 if (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == FORCE_ON ||
2980 (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == AUTO &&
2981 (wc_match("OpenSSH_2.[235]*", imp)))) {
2983 * These versions only support the original (pre-RFC4419)
2984 * SSH-2 GEX request, and disconnect with a protocol error if
2985 * we use the newer version.
2987 ssh->remote_bugs |= BUG_SSH2_OLDGEX;
2988 logevent("We believe remote version has outdated SSH-2 GEX");
2991 if (conf_get_int(ssh->conf, CONF_sshbug_winadj) == FORCE_ON) {
2993 * Servers that don't support our winadj request for one
2994 * reason or another. Currently, none detected automatically.
2996 ssh->remote_bugs |= BUG_CHOKES_ON_WINADJ;
2997 logevent("We believe remote version has winadj bug");
3000 if (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == FORCE_ON ||
3001 (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == AUTO &&
3002 (wc_match("OpenSSH_[2-5].*", imp) ||
3003 wc_match("OpenSSH_6.[0-6]*", imp) ||
3004 wc_match("dropbear_0.[2-4][0-9]*", imp) ||
3005 wc_match("dropbear_0.5[01]*", imp)))) {
3007 * These versions have the SSH-2 channel request bug.
3008 * OpenSSH 6.7 and above do not:
3009 * https://bugzilla.mindrot.org/show_bug.cgi?id=1818
3010 * dropbear_0.52 and above do not:
3011 * https://secure.ucc.asn.au/hg/dropbear/rev/cd02449b709c
3013 ssh->remote_bugs |= BUG_SENDS_LATE_REQUEST_REPLY;
3014 logevent("We believe remote version has SSH-2 channel request bug");
3019 * The `software version' part of an SSH version string is required
3020 * to contain no spaces or minus signs.
3022 static void ssh_fix_verstring(char *str)
3024 /* Eat "<protoversion>-". */
3025 while (*str && *str != '-') str++;
3026 assert(*str == '-'); str++;
3028 /* Convert minus signs and spaces in the remaining string into
3031 if (*str == '-' || *str == ' ')
3038 * Send an appropriate SSH version string.
3040 static void ssh_send_verstring(Ssh ssh, const char *protoname, char *svers)
3044 if (ssh->version == 2) {
3046 * Construct a v2 version string.
3048 verstring = dupprintf("%s2.0-%s\015\012", protoname, sshver);
3051 * Construct a v1 version string.
3053 assert(!strcmp(protoname, "SSH-")); /* no v1 bare connection protocol */
3054 verstring = dupprintf("SSH-%s-%s\012",
3055 (ssh_versioncmp(svers, "1.5") <= 0 ?
3060 ssh_fix_verstring(verstring + strlen(protoname));
3062 /* FUZZING make PuTTY insecure, so make live use difficult. */
3066 if (ssh->version == 2) {
3069 * Record our version string.
3071 len = strcspn(verstring, "\015\012");
3072 ssh->v_c = snewn(len + 1, char);
3073 memcpy(ssh->v_c, verstring, len);
3077 logeventf(ssh, "We claim version: %.*s",
3078 strcspn(verstring, "\015\012"), verstring);
3079 s_write(ssh, verstring, strlen(verstring));
3083 static int do_ssh_init(Ssh ssh, unsigned char c)
3085 static const char protoname[] = "SSH-";
3087 struct do_ssh_init_state {
3096 crState(do_ssh_init_state);
3100 /* Search for a line beginning with the protocol name prefix in
3103 for (s->i = 0; protoname[s->i]; s->i++) {
3104 if ((char)c != protoname[s->i]) goto no;
3114 ssh->session_started = TRUE;
3116 s->vstrsize = sizeof(protoname) + 16;
3117 s->vstring = snewn(s->vstrsize, char);
3118 strcpy(s->vstring, protoname);
3119 s->vslen = strlen(protoname);
3122 if (s->vslen >= s->vstrsize - 1) {
3124 s->vstring = sresize(s->vstring, s->vstrsize, char);
3126 s->vstring[s->vslen++] = c;
3129 s->version[s->i] = '\0';
3131 } else if (s->i < sizeof(s->version) - 1)
3132 s->version[s->i++] = c;
3133 } else if (c == '\012')
3135 crReturn(1); /* get another char */
3138 ssh->agentfwd_enabled = FALSE;
3139 ssh->rdpkt2_state.incoming_sequence = 0;
3141 s->vstring[s->vslen] = 0;
3142 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3143 logeventf(ssh, "Server version: %s", s->vstring);
3144 ssh_detect_bugs(ssh, s->vstring);
3147 * Decide which SSH protocol version to support.
3150 /* Anything strictly below "2.0" means protocol 1 is supported. */
3151 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
3152 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
3153 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
3155 if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
3157 bombout(("SSH protocol version 1 required by our configuration "
3158 "but not provided by server"));
3161 } else if (conf_get_int(ssh->conf, CONF_sshprot) == 3) {
3163 bombout(("SSH protocol version 2 required by our configuration "
3164 "but server only provides (old, insecure) SSH-1"));
3168 /* No longer support values 1 or 2 for CONF_sshprot */
3169 assert(!"Unexpected value for CONF_sshprot");
3172 if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
3177 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
3179 /* Send the version string, if we haven't already */
3180 if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
3181 ssh_send_verstring(ssh, protoname, s->version);
3183 if (ssh->version == 2) {
3186 * Record their version string.
3188 len = strcspn(s->vstring, "\015\012");
3189 ssh->v_s = snewn(len + 1, char);
3190 memcpy(ssh->v_s, s->vstring, len);
3194 * Initialise SSH-2 protocol.
3196 ssh->protocol = ssh2_protocol;
3197 ssh2_protocol_setup(ssh);
3198 ssh->s_rdpkt = ssh2_rdpkt;
3201 * Initialise SSH-1 protocol.
3203 ssh->protocol = ssh1_protocol;
3204 ssh1_protocol_setup(ssh);
3205 ssh->s_rdpkt = ssh1_rdpkt;
3207 if (ssh->version == 2)
3208 do_ssh2_transport(ssh, NULL, -1, NULL);
3210 update_specials_menu(ssh->frontend);
3211 ssh->state = SSH_STATE_BEFORE_SIZE;
3212 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3219 static int do_ssh_connection_init(Ssh ssh, unsigned char c)
3222 * Ordinary SSH begins with the banner "SSH-x.y-...". This is just
3223 * the ssh-connection part, extracted and given a trivial binary
3224 * packet protocol, so we replace 'SSH-' at the start with a new
3225 * name. In proper SSH style (though of course this part of the
3226 * proper SSH protocol _isn't_ subject to this kind of
3227 * DNS-domain-based extension), we define the new name in our
3230 static const char protoname[] =
3231 "SSHCONNECTION@putty.projects.tartarus.org-";
3233 struct do_ssh_connection_init_state {
3241 crState(do_ssh_connection_init_state);
3245 /* Search for a line beginning with the protocol name prefix in
3248 for (s->i = 0; protoname[s->i]; s->i++) {
3249 if ((char)c != protoname[s->i]) goto no;
3259 s->vstrsize = sizeof(protoname) + 16;
3260 s->vstring = snewn(s->vstrsize, char);
3261 strcpy(s->vstring, protoname);
3262 s->vslen = strlen(protoname);
3265 if (s->vslen >= s->vstrsize - 1) {
3267 s->vstring = sresize(s->vstring, s->vstrsize, char);
3269 s->vstring[s->vslen++] = c;
3272 s->version[s->i] = '\0';
3274 } else if (s->i < sizeof(s->version) - 1)
3275 s->version[s->i++] = c;
3276 } else if (c == '\012')
3278 crReturn(1); /* get another char */
3281 ssh->agentfwd_enabled = FALSE;
3282 ssh->rdpkt2_bare_state.incoming_sequence = 0;
3284 s->vstring[s->vslen] = 0;
3285 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3286 logeventf(ssh, "Server version: %s", s->vstring);
3287 ssh_detect_bugs(ssh, s->vstring);
3290 * Decide which SSH protocol version to support. This is easy in
3291 * bare ssh-connection mode: only 2.0 is legal.
3293 if (ssh_versioncmp(s->version, "2.0") < 0) {
3294 bombout(("Server announces compatibility with SSH-1 in bare ssh-connection protocol"));
3297 if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
3298 bombout(("Bare ssh-connection protocol cannot be run in SSH-1-only mode"));
3304 logeventf(ssh, "Using bare ssh-connection protocol");
3306 /* Send the version string, if we haven't already */
3307 ssh_send_verstring(ssh, protoname, s->version);
3310 * Initialise bare connection protocol.
3312 ssh->protocol = ssh2_bare_connection_protocol;
3313 ssh2_bare_connection_protocol_setup(ssh);
3314 ssh->s_rdpkt = ssh2_bare_connection_rdpkt;
3316 update_specials_menu(ssh->frontend);
3317 ssh->state = SSH_STATE_BEFORE_SIZE;
3318 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3321 * Get authconn (really just conn) under way.
3323 do_ssh2_authconn(ssh, NULL, 0, NULL);
3330 static void ssh_process_incoming_data(Ssh ssh,
3331 const unsigned char **data, int *datalen)
3333 struct Packet *pktin;
3335 pktin = ssh->s_rdpkt(ssh, data, datalen);
3337 ssh->protocol(ssh, NULL, 0, pktin);
3338 ssh_free_packet(pktin);
3342 static void ssh_queue_incoming_data(Ssh ssh,
3343 const unsigned char **data, int *datalen)
3345 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
3350 static void ssh_process_queued_incoming_data(Ssh ssh)
3353 const unsigned char *data;
3356 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
3357 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
3361 while (!ssh->frozen && len > 0)
3362 ssh_process_incoming_data(ssh, &data, &len);
3365 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
3369 static void ssh_set_frozen(Ssh ssh, int frozen)
3372 sk_set_frozen(ssh->s, frozen);
3373 ssh->frozen = frozen;
3376 static void ssh_gotdata(Ssh ssh, const unsigned char *data, int datalen)
3378 /* Log raw data, if we're in that mode. */
3380 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
3381 0, NULL, NULL, 0, NULL);
3383 crBegin(ssh->ssh_gotdata_crstate);
3386 * To begin with, feed the characters one by one to the
3387 * protocol initialisation / selection function do_ssh_init().
3388 * When that returns 0, we're done with the initial greeting
3389 * exchange and can move on to packet discipline.
3392 int ret; /* need not be kept across crReturn */
3394 crReturnV; /* more data please */
3395 ret = ssh->do_ssh_init(ssh, *data);
3403 * We emerge from that loop when the initial negotiation is
3404 * over and we have selected an s_rdpkt function. Now pass
3405 * everything to s_rdpkt, and then pass the resulting packets
3406 * to the proper protocol handler.
3410 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
3412 ssh_queue_incoming_data(ssh, &data, &datalen);
3413 /* This uses up all data and cannot cause anything interesting
3414 * to happen; indeed, for anything to happen at all, we must
3415 * return, so break out. */
3417 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
3418 /* This uses up some or all data, and may freeze the
3420 ssh_process_queued_incoming_data(ssh);
3422 /* This uses up some or all data, and may freeze the
3424 ssh_process_incoming_data(ssh, &data, &datalen);
3426 /* FIXME this is probably EBW. */
3427 if (ssh->state == SSH_STATE_CLOSED)
3430 /* We're out of data. Go and get some more. */
3436 static int ssh_do_close(Ssh ssh, int notify_exit)
3439 struct ssh_channel *c;
3441 ssh->state = SSH_STATE_CLOSED;
3442 expire_timer_context(ssh);
3447 notify_remote_exit(ssh->frontend);
3452 * Now we must shut down any port- and X-forwarded channels going
3453 * through this connection.
3455 if (ssh->channels) {
3456 while (NULL != (c = index234(ssh->channels, 0))) {
3459 x11_close(c->u.x11.xconn);
3462 case CHAN_SOCKDATA_DORMANT:
3463 pfd_close(c->u.pfd.pf);
3466 del234(ssh->channels, c); /* moving next one to index 0 */
3467 if (ssh->version == 2)
3468 bufchain_clear(&c->v.v2.outbuffer);
3473 * Go through port-forwardings, and close any associated
3474 * listening sockets.
3476 if (ssh->portfwds) {
3477 struct ssh_portfwd *pf;
3478 while (NULL != (pf = index234(ssh->portfwds, 0))) {
3479 /* Dispose of any listening socket. */
3481 pfl_terminate(pf->local);
3482 del234(ssh->portfwds, pf); /* moving next one to index 0 */
3485 freetree234(ssh->portfwds);
3486 ssh->portfwds = NULL;
3490 * Also stop attempting to connection-share.
3492 if (ssh->connshare) {
3493 sharestate_free(ssh->connshare);
3494 ssh->connshare = NULL;
3500 static void ssh_socket_log(Plug plug, int type, SockAddr addr, int port,
3501 const char *error_msg, int error_code)
3503 Ssh ssh = (Ssh) plug;
3506 * While we're attempting connection sharing, don't loudly log
3507 * everything that happens. Real TCP connections need to be logged
3508 * when we _start_ trying to connect, because it might be ages
3509 * before they respond if something goes wrong; but connection
3510 * sharing is local and quick to respond, and it's sufficient to
3511 * simply wait and see whether it worked afterwards.
3514 if (!ssh->attempting_connshare)
3515 backend_socket_log(ssh->frontend, type, addr, port,
3516 error_msg, error_code, ssh->conf,
3517 ssh->session_started);
3520 void ssh_connshare_log(Ssh ssh, int event, const char *logtext,
3521 const char *ds_err, const char *us_err)
3523 if (event == SHARE_NONE) {
3524 /* In this case, 'logtext' is an error message indicating a
3525 * reason why connection sharing couldn't be set up _at all_.
3526 * Failing that, ds_err and us_err indicate why we couldn't be
3527 * a downstream and an upstream respectively. */
3529 logeventf(ssh, "Could not set up connection sharing: %s", logtext);
3532 logeventf(ssh, "Could not set up connection sharing"
3533 " as downstream: %s", ds_err);
3535 logeventf(ssh, "Could not set up connection sharing"
3536 " as upstream: %s", us_err);
3538 } else if (event == SHARE_DOWNSTREAM) {
3539 /* In this case, 'logtext' is a local endpoint address */
3540 logeventf(ssh, "Using existing shared connection at %s", logtext);
3541 /* Also we should mention this in the console window to avoid
3542 * confusing users as to why this window doesn't behave the
3544 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
3545 c_write_str(ssh,"Reusing a shared connection to this server.\r\n");
3547 } else if (event == SHARE_UPSTREAM) {
3548 /* In this case, 'logtext' is a local endpoint address too */
3549 logeventf(ssh, "Sharing this connection at %s", logtext);
3553 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
3556 Ssh ssh = (Ssh) plug;
3557 int need_notify = ssh_do_close(ssh, FALSE);
3560 if (!ssh->close_expected)
3561 error_msg = "Server unexpectedly closed network connection";
3563 error_msg = "Server closed network connection";
3566 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
3570 notify_remote_exit(ssh->frontend);
3573 logevent(error_msg);
3574 if (!ssh->close_expected || !ssh->clean_exit)
3575 connection_fatal(ssh->frontend, "%s", error_msg);
3579 static int ssh_receive(Plug plug, int urgent, char *data, int len)
3581 Ssh ssh = (Ssh) plug;
3582 ssh_gotdata(ssh, (unsigned char *)data, len);
3583 if (ssh->state == SSH_STATE_CLOSED) {
3584 ssh_do_close(ssh, TRUE);
3590 static void ssh_sent(Plug plug, int bufsize)
3592 Ssh ssh = (Ssh) plug;
3594 * If the send backlog on the SSH socket itself clears, we
3595 * should unthrottle the whole world if it was throttled.
3597 if (bufsize < SSH_MAX_BACKLOG)
3598 ssh_throttle_all(ssh, 0, bufsize);
3601 static void ssh_hostport_setup(const char *host, int port, Conf *conf,
3602 char **savedhost, int *savedport,
3605 char *loghost = conf_get_str(conf, CONF_loghost);
3607 *loghost_ret = loghost;
3613 tmphost = dupstr(loghost);
3614 *savedport = 22; /* default ssh port */
3617 * A colon suffix on the hostname string also lets us affect
3618 * savedport. (Unless there are multiple colons, in which case
3619 * we assume this is an unbracketed IPv6 literal.)
3621 colon = host_strrchr(tmphost, ':');
3622 if (colon && colon == host_strchr(tmphost, ':')) {
3625 *savedport = atoi(colon);
3628 *savedhost = host_strduptrim(tmphost);
3631 *savedhost = host_strduptrim(host);
3633 port = 22; /* default ssh port */
3638 static int ssh_test_for_upstream(const char *host, int port, Conf *conf)
3644 random_ref(); /* platform may need this to determine share socket name */
3645 ssh_hostport_setup(host, port, conf, &savedhost, &savedport, NULL);
3646 ret = ssh_share_test_for_upstream(savedhost, savedport, conf);
3654 * Connect to specified host and port.
3655 * Returns an error message, or NULL on success.
3656 * Also places the canonical host name into `realhost'. It must be
3657 * freed by the caller.
3659 static const char *connect_to_host(Ssh ssh, const char *host, int port,
3660 char **realhost, int nodelay, int keepalive)
3662 static const struct plug_function_table fn_table = {
3673 int addressfamily, sshprot;
3675 ssh_hostport_setup(host, port, ssh->conf,
3676 &ssh->savedhost, &ssh->savedport, &loghost);
3678 ssh->fn = &fn_table; /* make 'ssh' usable as a Plug */
3681 * Try connection-sharing, in case that means we don't open a
3682 * socket after all. ssh_connection_sharing_init will connect to a
3683 * previously established upstream if it can, and failing that,
3684 * establish a listening socket for _us_ to be the upstream. In
3685 * the latter case it will return NULL just as if it had done
3686 * nothing, because here we only need to care if we're a
3687 * downstream and need to do our connection setup differently.
3689 ssh->connshare = NULL;
3690 ssh->attempting_connshare = TRUE; /* affects socket logging behaviour */
3691 ssh->s = ssh_connection_sharing_init(ssh->savedhost, ssh->savedport,
3692 ssh->conf, ssh, &ssh->connshare);
3693 ssh->attempting_connshare = FALSE;
3694 if (ssh->s != NULL) {
3696 * We are a downstream.
3698 ssh->bare_connection = TRUE;
3699 ssh->do_ssh_init = do_ssh_connection_init;
3700 ssh->fullhostname = NULL;
3701 *realhost = dupstr(host); /* best we can do */
3704 * We're not a downstream, so open a normal socket.
3706 ssh->do_ssh_init = do_ssh_init;
3711 addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
3712 addr = name_lookup(host, port, realhost, ssh->conf, addressfamily,
3713 ssh->frontend, "SSH connection");
3714 if ((err = sk_addr_error(addr)) != NULL) {
3718 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
3720 ssh->s = new_connection(addr, *realhost, port,
3721 0, 1, nodelay, keepalive,
3722 (Plug) ssh, ssh->conf);
3723 if ((err = sk_socket_error(ssh->s)) != NULL) {
3725 notify_remote_exit(ssh->frontend);
3731 * The SSH version number is always fixed (since we no longer support
3732 * fallback between versions), so set it now, and if it's SSH-2,
3733 * send the version string now too.
3735 sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3736 assert(sshprot == 0 || sshprot == 3);
3740 if (sshprot == 3 && !ssh->bare_connection) {
3743 ssh_send_verstring(ssh, "SSH-", NULL);
3747 * loghost, if configured, overrides realhost.
3751 *realhost = dupstr(loghost);
3758 * Throttle or unthrottle the SSH connection.
3760 static void ssh_throttle_conn(Ssh ssh, int adjust)
3762 int old_count = ssh->conn_throttle_count;
3763 ssh->conn_throttle_count += adjust;
3764 assert(ssh->conn_throttle_count >= 0);
3765 if (ssh->conn_throttle_count && !old_count) {
3766 ssh_set_frozen(ssh, 1);
3767 } else if (!ssh->conn_throttle_count && old_count) {
3768 ssh_set_frozen(ssh, 0);
3773 * Throttle or unthrottle _all_ local data streams (for when sends
3774 * on the SSH connection itself back up).
3776 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3779 struct ssh_channel *c;
3781 if (enable == ssh->throttled_all)
3783 ssh->throttled_all = enable;
3784 ssh->overall_bufsize = bufsize;
3787 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3789 case CHAN_MAINSESSION:
3791 * This is treated separately, outside the switch.
3795 x11_override_throttle(c->u.x11.xconn, enable);
3798 /* Agent channels require no buffer management. */
3801 pfd_override_throttle(c->u.pfd.pf, enable);
3807 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3809 Ssh ssh = (Ssh) sshv;
3811 ssh->agent_response = reply;
3812 ssh->agent_response_len = replylen;
3814 if (ssh->version == 1)
3815 do_ssh1_login(ssh, NULL, -1, NULL);
3817 do_ssh2_authconn(ssh, NULL, -1, NULL);
3820 static void ssh_dialog_callback(void *sshv, int ret)
3822 Ssh ssh = (Ssh) sshv;
3824 ssh->user_response = ret;
3826 if (ssh->version == 1)
3827 do_ssh1_login(ssh, NULL, -1, NULL);
3829 do_ssh2_transport(ssh, NULL, -1, NULL);
3832 * This may have unfrozen the SSH connection, so do a
3835 ssh_process_queued_incoming_data(ssh);
3838 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3840 struct ssh_channel *c = (struct ssh_channel *)cv;
3841 const void *sentreply = reply;
3843 c->u.a.outstanding_requests--;
3845 /* Fake SSH_AGENT_FAILURE. */
3846 sentreply = "\0\0\0\1\5";
3849 ssh_send_channel_data(c, sentreply, replylen);
3853 * If we've already seen an incoming EOF but haven't sent an
3854 * outgoing one, this may be the moment to send it.
3856 if (c->u.a.outstanding_requests == 0 && (c->closes & CLOSES_RCVD_EOF))
3857 sshfwd_write_eof(c);
3861 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3862 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3863 * => log `wire_reason'.
3865 static void ssh_disconnect(Ssh ssh, const char *client_reason,
3866 const char *wire_reason,
3867 int code, int clean_exit)
3871 client_reason = wire_reason;
3873 error = dupprintf("Disconnected: %s", client_reason);
3875 error = dupstr("Disconnected");
3877 if (ssh->version == 1) {
3878 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3880 } else if (ssh->version == 2) {
3881 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3882 ssh2_pkt_adduint32(pktout, code);
3883 ssh2_pkt_addstring(pktout, wire_reason);
3884 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3885 ssh2_pkt_send_noqueue(ssh, pktout);
3888 ssh->close_expected = TRUE;
3889 ssh->clean_exit = clean_exit;
3890 ssh_closing((Plug)ssh, error, 0, 0);
3894 int verify_ssh_manual_host_key(Ssh ssh, const char *fingerprint,
3895 const struct ssh_signkey *ssh2keytype,
3898 if (!conf_get_str_nthstrkey(ssh->conf, CONF_ssh_manual_hostkeys, 0)) {
3899 return -1; /* no manual keys configured */
3904 * The fingerprint string we've been given will have things
3905 * like 'ssh-rsa 2048' at the front of it. Strip those off and
3906 * narrow down to just the colon-separated hex block at the
3907 * end of the string.
3909 const char *p = strrchr(fingerprint, ' ');
3910 fingerprint = p ? p+1 : fingerprint;
3911 /* Quick sanity checks, including making sure it's in lowercase */
3912 assert(strlen(fingerprint) == 16*3 - 1);
3913 assert(fingerprint[2] == ':');
3914 assert(fingerprint[strspn(fingerprint, "0123456789abcdef:")] == 0);
3916 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3918 return 1; /* success */
3923 * Construct the base64-encoded public key blob and see if
3926 unsigned char *binblob;
3928 int binlen, atoms, i;
3929 binblob = ssh2keytype->public_blob(ssh2keydata, &binlen);
3930 atoms = (binlen + 2) / 3;
3931 base64blob = snewn(atoms * 4 + 1, char);
3932 for (i = 0; i < atoms; i++)
3933 base64_encode_atom(binblob + 3*i, binlen - 3*i, base64blob + 4*i);
3934 base64blob[atoms * 4] = '\0';
3936 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3939 return 1; /* success */
3948 * Handle the key exchange and user authentication phases.
3950 static int do_ssh1_login(Ssh ssh, const unsigned char *in, int inlen,
3951 struct Packet *pktin)
3954 unsigned char cookie[8], *ptr;
3955 struct MD5Context md5c;
3956 struct do_ssh1_login_state {
3959 unsigned char *rsabuf;
3960 const unsigned char *keystr1, *keystr2;
3961 unsigned long supported_ciphers_mask, supported_auths_mask;
3962 int tried_publickey, tried_agent;
3963 int tis_auth_refused, ccard_auth_refused;
3964 unsigned char session_id[16];
3966 void *publickey_blob;
3967 int publickey_bloblen;
3968 char *publickey_comment;
3969 int privatekey_available, privatekey_encrypted;
3970 prompts_t *cur_prompt;
3973 unsigned char request[5], *response, *p;
3983 struct RSAKey servkey, hostkey;
3985 crState(do_ssh1_login_state);
3992 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3993 bombout(("Public key packet not received"));
3997 logevent("Received public keys");
3999 ptr = ssh_pkt_getdata(pktin, 8);
4001 bombout(("SSH-1 public key packet stopped before random cookie"));
4004 memcpy(cookie, ptr, 8);
4006 if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
4007 !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) {
4008 bombout(("Failed to read SSH-1 public keys from public key packet"));
4013 * Log the host key fingerprint.
4017 logevent("Host key fingerprint is:");
4018 strcpy(logmsg, " ");
4019 s->hostkey.comment = NULL;
4020 rsa_fingerprint(logmsg + strlen(logmsg),
4021 sizeof(logmsg) - strlen(logmsg), &s->hostkey);
4025 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
4026 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
4027 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
4028 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
4029 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
4031 ssh->v1_local_protoflags =
4032 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
4033 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
4036 MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
4037 MD5Update(&md5c, s->keystr1, s->servkey.bytes);
4038 MD5Update(&md5c, cookie, 8);
4039 MD5Final(s->session_id, &md5c);
4041 for (i = 0; i < 32; i++)
4042 ssh->session_key[i] = random_byte();
4045 * Verify that the `bits' and `bytes' parameters match.
4047 if (s->hostkey.bits > s->hostkey.bytes * 8 ||
4048 s->servkey.bits > s->servkey.bytes * 8) {
4049 bombout(("SSH-1 public keys were badly formatted"));
4053 s->len = (s->hostkey.bytes > s->servkey.bytes ?
4054 s->hostkey.bytes : s->servkey.bytes);
4056 s->rsabuf = snewn(s->len, unsigned char);
4059 * Verify the host key.
4063 * First format the key into a string.
4065 int len = rsastr_len(&s->hostkey);
4066 char fingerprint[100];
4067 char *keystr = snewn(len, char);
4068 rsastr_fmt(keystr, &s->hostkey);
4069 rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
4071 /* First check against manually configured host keys. */
4072 s->dlgret = verify_ssh_manual_host_key(ssh, fingerprint, NULL, NULL);
4073 if (s->dlgret == 0) { /* did not match */
4074 bombout(("Host key did not appear in manually configured list"));
4077 } else if (s->dlgret < 0) { /* none configured; use standard handling */
4078 ssh_set_frozen(ssh, 1);
4079 s->dlgret = verify_ssh_host_key(ssh->frontend,
4080 ssh->savedhost, ssh->savedport,
4081 "rsa", keystr, fingerprint,
4082 ssh_dialog_callback, ssh);
4087 if (s->dlgret < 0) {
4091 bombout(("Unexpected data from server while waiting"
4092 " for user host key response"));
4095 } while (pktin || inlen > 0);
4096 s->dlgret = ssh->user_response;
4098 ssh_set_frozen(ssh, 0);
4100 if (s->dlgret == 0) {
4101 ssh_disconnect(ssh, "User aborted at host key verification",
4110 for (i = 0; i < 32; i++) {
4111 s->rsabuf[i] = ssh->session_key[i];
4113 s->rsabuf[i] ^= s->session_id[i];
4116 if (s->hostkey.bytes > s->servkey.bytes) {
4117 ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
4119 ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
4121 ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
4123 ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
4126 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
4130 logevent("Encrypted session key");
4133 int cipher_chosen = 0, warn = 0;
4134 const char *cipher_string = NULL;
4136 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
4137 int next_cipher = conf_get_int_int(ssh->conf,
4138 CONF_ssh_cipherlist, i);
4139 if (next_cipher == CIPHER_WARN) {
4140 /* If/when we choose a cipher, warn about it */
4142 } else if (next_cipher == CIPHER_AES) {
4143 /* XXX Probably don't need to mention this. */
4144 logevent("AES not supported in SSH-1, skipping");
4146 switch (next_cipher) {
4147 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
4148 cipher_string = "3DES"; break;
4149 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
4150 cipher_string = "Blowfish"; break;
4151 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
4152 cipher_string = "single-DES"; break;
4154 if (s->supported_ciphers_mask & (1 << s->cipher_type))
4158 if (!cipher_chosen) {
4159 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
4160 bombout(("Server violates SSH-1 protocol by not "
4161 "supporting 3DES encryption"));
4163 /* shouldn't happen */
4164 bombout(("No supported ciphers found"));
4168 /* Warn about chosen cipher if necessary. */
4170 ssh_set_frozen(ssh, 1);
4171 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
4172 ssh_dialog_callback, ssh);
4173 if (s->dlgret < 0) {
4177 bombout(("Unexpected data from server while waiting"
4178 " for user response"));
4181 } while (pktin || inlen > 0);
4182 s->dlgret = ssh->user_response;
4184 ssh_set_frozen(ssh, 0);
4185 if (s->dlgret == 0) {
4186 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
4193 switch (s->cipher_type) {
4194 case SSH_CIPHER_3DES:
4195 logevent("Using 3DES encryption");
4197 case SSH_CIPHER_DES:
4198 logevent("Using single-DES encryption");
4200 case SSH_CIPHER_BLOWFISH:
4201 logevent("Using Blowfish encryption");
4205 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
4206 PKT_CHAR, s->cipher_type,
4207 PKT_DATA, cookie, 8,
4208 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
4209 PKT_DATA, s->rsabuf, s->len,
4210 PKT_INT, ssh->v1_local_protoflags, PKT_END);
4212 logevent("Trying to enable encryption...");
4216 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
4217 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
4219 ssh->v1_cipher_ctx = ssh->cipher->make_context();
4220 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
4221 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
4223 ssh->crcda_ctx = crcda_make_context();
4224 logevent("Installing CRC compensation attack detector");
4226 if (s->servkey.modulus) {
4227 sfree(s->servkey.modulus);
4228 s->servkey.modulus = NULL;
4230 if (s->servkey.exponent) {
4231 sfree(s->servkey.exponent);
4232 s->servkey.exponent = NULL;
4234 if (s->hostkey.modulus) {
4235 sfree(s->hostkey.modulus);
4236 s->hostkey.modulus = NULL;
4238 if (s->hostkey.exponent) {
4239 sfree(s->hostkey.exponent);
4240 s->hostkey.exponent = NULL;
4244 if (pktin->type != SSH1_SMSG_SUCCESS) {
4245 bombout(("Encryption not successfully enabled"));
4249 logevent("Successfully started encryption");
4251 fflush(stdout); /* FIXME eh? */
4253 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
4254 int ret; /* need not be kept over crReturn */
4255 s->cur_prompt = new_prompts(ssh->frontend);
4256 s->cur_prompt->to_server = TRUE;
4257 s->cur_prompt->name = dupstr("SSH login name");
4258 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
4259 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4262 crWaitUntil(!pktin);
4263 ret = get_userpass_input(s->cur_prompt, in, inlen);
4268 * Failed to get a username. Terminate.
4270 free_prompts(s->cur_prompt);
4271 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
4274 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
4275 free_prompts(s->cur_prompt);
4278 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
4280 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
4282 if (flags & FLAG_INTERACTIVE &&
4283 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
4284 c_write_str(ssh, userlog);
4285 c_write_str(ssh, "\r\n");
4293 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
4294 /* We must not attempt PK auth. Pretend we've already tried it. */
4295 s->tried_publickey = s->tried_agent = 1;
4297 s->tried_publickey = s->tried_agent = 0;
4299 s->tis_auth_refused = s->ccard_auth_refused = 0;
4301 * Load the public half of any configured keyfile for later use.
4303 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4304 if (!filename_is_null(s->keyfile)) {
4306 logeventf(ssh, "Reading key file \"%.150s\"",
4307 filename_to_str(s->keyfile));
4308 keytype = key_type(s->keyfile);
4309 if (keytype == SSH_KEYTYPE_SSH1 ||
4310 keytype == SSH_KEYTYPE_SSH1_PUBLIC) {
4312 if (rsakey_pubblob(s->keyfile,
4313 &s->publickey_blob, &s->publickey_bloblen,
4314 &s->publickey_comment, &error)) {
4315 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH1);
4316 if (!s->privatekey_available)
4317 logeventf(ssh, "Key file contains public key only");
4318 s->privatekey_encrypted = rsakey_encrypted(s->keyfile,
4322 logeventf(ssh, "Unable to load key (%s)", error);
4323 msgbuf = dupprintf("Unable to load key file "
4324 "\"%.150s\" (%s)\r\n",
4325 filename_to_str(s->keyfile),
4327 c_write_str(ssh, msgbuf);
4329 s->publickey_blob = NULL;
4333 logeventf(ssh, "Unable to use this key file (%s)",
4334 key_type_to_str(keytype));
4335 msgbuf = dupprintf("Unable to use key file \"%.150s\""
4337 filename_to_str(s->keyfile),
4338 key_type_to_str(keytype));
4339 c_write_str(ssh, msgbuf);
4341 s->publickey_blob = NULL;
4344 s->publickey_blob = NULL;
4346 while (pktin->type == SSH1_SMSG_FAILURE) {
4347 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
4349 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
4351 * Attempt RSA authentication using Pageant.
4357 logevent("Pageant is running. Requesting keys.");
4359 /* Request the keys held by the agent. */
4360 PUT_32BIT(s->request, 1);
4361 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
4362 if (!agent_query(s->request, 5, &r, &s->responselen,
4363 ssh_agent_callback, ssh)) {
4367 bombout(("Unexpected data from server while waiting"
4368 " for agent response"));
4371 } while (pktin || inlen > 0);
4372 r = ssh->agent_response;
4373 s->responselen = ssh->agent_response_len;
4375 s->response = (unsigned char *) r;
4376 if (s->response && s->responselen >= 5 &&
4377 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
4378 s->p = s->response + 5;
4379 s->nkeys = toint(GET_32BIT(s->p));
4381 logeventf(ssh, "Pageant reported negative key count %d",
4386 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
4387 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
4388 unsigned char *pkblob = s->p;
4392 do { /* do while (0) to make breaking easy */
4393 n = ssh1_read_bignum
4394 (s->p, toint(s->responselen-(s->p-s->response)),
4399 n = ssh1_read_bignum
4400 (s->p, toint(s->responselen-(s->p-s->response)),
4405 if (s->responselen - (s->p-s->response) < 4)
4407 s->commentlen = toint(GET_32BIT(s->p));
4409 if (s->commentlen < 0 ||
4410 toint(s->responselen - (s->p-s->response)) <
4413 s->commentp = (char *)s->p;
4414 s->p += s->commentlen;
4418 logevent("Pageant key list packet was truncated");
4422 if (s->publickey_blob) {
4423 if (!memcmp(pkblob, s->publickey_blob,
4424 s->publickey_bloblen)) {
4425 logeventf(ssh, "Pageant key #%d matches "
4426 "configured key file", s->keyi);
4427 s->tried_publickey = 1;
4429 /* Skip non-configured key */
4432 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
4433 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4434 PKT_BIGNUM, s->key.modulus, PKT_END);
4436 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4437 logevent("Key refused");
4440 logevent("Received RSA challenge");
4441 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4442 bombout(("Server's RSA challenge was badly formatted"));
4447 char *agentreq, *q, *ret;
4450 len = 1 + 4; /* message type, bit count */
4451 len += ssh1_bignum_length(s->key.exponent);
4452 len += ssh1_bignum_length(s->key.modulus);
4453 len += ssh1_bignum_length(s->challenge);
4454 len += 16; /* session id */
4455 len += 4; /* response format */
4456 agentreq = snewn(4 + len, char);
4457 PUT_32BIT(agentreq, len);
4459 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
4460 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
4462 q += ssh1_write_bignum(q, s->key.exponent);
4463 q += ssh1_write_bignum(q, s->key.modulus);
4464 q += ssh1_write_bignum(q, s->challenge);
4465 memcpy(q, s->session_id, 16);
4467 PUT_32BIT(q, 1); /* response format */
4468 if (!agent_query(agentreq, len + 4, &vret, &retlen,
4469 ssh_agent_callback, ssh)) {
4474 bombout(("Unexpected data from server"
4475 " while waiting for agent"
4479 } while (pktin || inlen > 0);
4480 vret = ssh->agent_response;
4481 retlen = ssh->agent_response_len;
4486 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
4487 logevent("Sending Pageant's response");
4488 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4489 PKT_DATA, ret + 5, 16,
4493 if (pktin->type == SSH1_SMSG_SUCCESS) {
4495 ("Pageant's response accepted");
4496 if (flags & FLAG_VERBOSE) {
4497 c_write_str(ssh, "Authenticated using"
4499 c_write(ssh, s->commentp,
4501 c_write_str(ssh, "\" from agent\r\n");
4506 ("Pageant's response not accepted");
4509 ("Pageant failed to answer challenge");
4513 logevent("No reply received from Pageant");
4516 freebn(s->key.exponent);
4517 freebn(s->key.modulus);
4518 freebn(s->challenge);
4523 if (s->publickey_blob && !s->tried_publickey)
4524 logevent("Configured key file not in Pageant");
4526 logevent("Failed to get reply from Pageant");
4531 if (s->publickey_blob && s->privatekey_available &&
4532 !s->tried_publickey) {
4534 * Try public key authentication with the specified
4537 int got_passphrase; /* need not be kept over crReturn */
4538 if (flags & FLAG_VERBOSE)
4539 c_write_str(ssh, "Trying public key authentication.\r\n");
4540 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4541 logeventf(ssh, "Trying public key \"%s\"",
4542 filename_to_str(s->keyfile));
4543 s->tried_publickey = 1;
4544 got_passphrase = FALSE;
4545 while (!got_passphrase) {
4547 * Get a passphrase, if necessary.
4549 char *passphrase = NULL; /* only written after crReturn */
4551 if (!s->privatekey_encrypted) {
4552 if (flags & FLAG_VERBOSE)
4553 c_write_str(ssh, "No passphrase required.\r\n");
4556 int ret; /* need not be kept over crReturn */
4557 s->cur_prompt = new_prompts(ssh->frontend);
4558 s->cur_prompt->to_server = FALSE;
4559 s->cur_prompt->name = dupstr("SSH key passphrase");
4560 add_prompt(s->cur_prompt,
4561 dupprintf("Passphrase for key \"%.100s\": ",
4562 s->publickey_comment), FALSE);
4563 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4566 crWaitUntil(!pktin);
4567 ret = get_userpass_input(s->cur_prompt, in, inlen);
4571 /* Failed to get a passphrase. Terminate. */
4572 free_prompts(s->cur_prompt);
4573 ssh_disconnect(ssh, NULL, "Unable to authenticate",
4577 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
4578 free_prompts(s->cur_prompt);
4581 * Try decrypting key with passphrase.
4583 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4584 ret = loadrsakey(s->keyfile, &s->key, passphrase,
4587 smemclr(passphrase, strlen(passphrase));
4591 /* Correct passphrase. */
4592 got_passphrase = TRUE;
4593 } else if (ret == 0) {
4594 c_write_str(ssh, "Couldn't load private key from ");
4595 c_write_str(ssh, filename_to_str(s->keyfile));
4596 c_write_str(ssh, " (");
4597 c_write_str(ssh, error);
4598 c_write_str(ssh, ").\r\n");
4599 got_passphrase = FALSE;
4600 break; /* go and try something else */
4601 } else if (ret == -1) {
4602 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
4603 got_passphrase = FALSE;
4606 assert(0 && "unexpected return from loadrsakey()");
4607 got_passphrase = FALSE; /* placate optimisers */
4611 if (got_passphrase) {
4614 * Send a public key attempt.
4616 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4617 PKT_BIGNUM, s->key.modulus, PKT_END);
4620 if (pktin->type == SSH1_SMSG_FAILURE) {
4621 c_write_str(ssh, "Server refused our public key.\r\n");
4622 continue; /* go and try something else */
4624 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4625 bombout(("Bizarre response to offer of public key"));
4631 unsigned char buffer[32];
4632 Bignum challenge, response;
4634 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4635 bombout(("Server's RSA challenge was badly formatted"));
4638 response = rsadecrypt(challenge, &s->key);
4639 freebn(s->key.private_exponent);/* burn the evidence */
4641 for (i = 0; i < 32; i++) {
4642 buffer[i] = bignum_byte(response, 31 - i);
4646 MD5Update(&md5c, buffer, 32);
4647 MD5Update(&md5c, s->session_id, 16);
4648 MD5Final(buffer, &md5c);
4650 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4651 PKT_DATA, buffer, 16, PKT_END);
4658 if (pktin->type == SSH1_SMSG_FAILURE) {
4659 if (flags & FLAG_VERBOSE)
4660 c_write_str(ssh, "Failed to authenticate with"
4661 " our public key.\r\n");
4662 continue; /* go and try something else */
4663 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4664 bombout(("Bizarre response to RSA authentication response"));
4668 break; /* we're through! */
4674 * Otherwise, try various forms of password-like authentication.
4676 s->cur_prompt = new_prompts(ssh->frontend);
4678 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4679 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
4680 !s->tis_auth_refused) {
4681 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
4682 logevent("Requested TIS authentication");
4683 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
4685 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
4686 logevent("TIS authentication declined");
4687 if (flags & FLAG_INTERACTIVE)
4688 c_write_str(ssh, "TIS authentication refused.\r\n");
4689 s->tis_auth_refused = 1;
4694 char *instr_suf, *prompt;
4696 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4698 bombout(("TIS challenge packet was badly formed"));
4701 logevent("Received TIS challenge");
4702 s->cur_prompt->to_server = TRUE;
4703 s->cur_prompt->name = dupstr("SSH TIS authentication");
4704 /* Prompt heuristic comes from OpenSSH */
4705 if (memchr(challenge, '\n', challengelen)) {
4706 instr_suf = dupstr("");
4707 prompt = dupprintf("%.*s", challengelen, challenge);
4709 instr_suf = dupprintf("%.*s", challengelen, challenge);
4710 prompt = dupstr("Response: ");
4712 s->cur_prompt->instruction =
4713 dupprintf("Using TIS authentication.%s%s",
4714 (*instr_suf) ? "\n" : "",
4716 s->cur_prompt->instr_reqd = TRUE;
4717 add_prompt(s->cur_prompt, prompt, FALSE);
4721 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4722 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
4723 !s->ccard_auth_refused) {
4724 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
4725 logevent("Requested CryptoCard authentication");
4726 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
4728 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
4729 logevent("CryptoCard authentication declined");
4730 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
4731 s->ccard_auth_refused = 1;
4736 char *instr_suf, *prompt;
4738 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4740 bombout(("CryptoCard challenge packet was badly formed"));
4743 logevent("Received CryptoCard challenge");
4744 s->cur_prompt->to_server = TRUE;
4745 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4746 s->cur_prompt->name_reqd = FALSE;
4747 /* Prompt heuristic comes from OpenSSH */
4748 if (memchr(challenge, '\n', challengelen)) {
4749 instr_suf = dupstr("");
4750 prompt = dupprintf("%.*s", challengelen, challenge);
4752 instr_suf = dupprintf("%.*s", challengelen, challenge);
4753 prompt = dupstr("Response: ");
4755 s->cur_prompt->instruction =
4756 dupprintf("Using CryptoCard authentication.%s%s",
4757 (*instr_suf) ? "\n" : "",
4759 s->cur_prompt->instr_reqd = TRUE;
4760 add_prompt(s->cur_prompt, prompt, FALSE);
4764 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4765 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4766 bombout(("No supported authentication methods available"));
4769 s->cur_prompt->to_server = TRUE;
4770 s->cur_prompt->name = dupstr("SSH password");
4771 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4772 ssh->username, ssh->savedhost),
4777 * Show password prompt, having first obtained it via a TIS
4778 * or CryptoCard exchange if we're doing TIS or CryptoCard
4782 int ret; /* need not be kept over crReturn */
4783 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4786 crWaitUntil(!pktin);
4787 ret = get_userpass_input(s->cur_prompt, in, inlen);
4792 * Failed to get a password (for example
4793 * because one was supplied on the command line
4794 * which has already failed to work). Terminate.
4796 free_prompts(s->cur_prompt);
4797 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4802 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4804 * Defence against traffic analysis: we send a
4805 * whole bunch of packets containing strings of
4806 * different lengths. One of these strings is the
4807 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4808 * The others are all random data in
4809 * SSH1_MSG_IGNORE packets. This way a passive
4810 * listener can't tell which is the password, and
4811 * hence can't deduce the password length.
4813 * Anybody with a password length greater than 16
4814 * bytes is going to have enough entropy in their
4815 * password that a listener won't find it _that_
4816 * much help to know how long it is. So what we'll
4819 * - if password length < 16, we send 15 packets
4820 * containing string lengths 1 through 15
4822 * - otherwise, we let N be the nearest multiple
4823 * of 8 below the password length, and send 8
4824 * packets containing string lengths N through
4825 * N+7. This won't obscure the order of
4826 * magnitude of the password length, but it will
4827 * introduce a bit of extra uncertainty.
4829 * A few servers can't deal with SSH1_MSG_IGNORE, at
4830 * least in this context. For these servers, we need
4831 * an alternative defence. We make use of the fact
4832 * that the password is interpreted as a C string:
4833 * so we can append a NUL, then some random data.
4835 * A few servers can deal with neither SSH1_MSG_IGNORE
4836 * here _nor_ a padded password string.
4837 * For these servers we are left with no defences
4838 * against password length sniffing.
4840 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4841 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4843 * The server can deal with SSH1_MSG_IGNORE, so
4844 * we can use the primary defence.
4846 int bottom, top, pwlen, i;
4849 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4851 bottom = 0; /* zero length passwords are OK! :-) */
4854 bottom = pwlen & ~7;
4858 assert(pwlen >= bottom && pwlen <= top);
4860 randomstr = snewn(top + 1, char);
4862 for (i = bottom; i <= top; i++) {
4864 defer_packet(ssh, s->pwpkt_type,
4865 PKT_STR,s->cur_prompt->prompts[0]->result,
4868 for (j = 0; j < i; j++) {
4870 randomstr[j] = random_byte();
4871 } while (randomstr[j] == '\0');
4873 randomstr[i] = '\0';
4874 defer_packet(ssh, SSH1_MSG_IGNORE,
4875 PKT_STR, randomstr, PKT_END);
4878 logevent("Sending password with camouflage packets");
4879 ssh_pkt_defersend(ssh);
4882 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4884 * The server can't deal with SSH1_MSG_IGNORE
4885 * but can deal with padded passwords, so we
4886 * can use the secondary defence.
4892 len = strlen(s->cur_prompt->prompts[0]->result);
4893 if (len < sizeof(string)) {
4895 strcpy(string, s->cur_prompt->prompts[0]->result);
4896 len++; /* cover the zero byte */
4897 while (len < sizeof(string)) {
4898 string[len++] = (char) random_byte();
4901 ss = s->cur_prompt->prompts[0]->result;
4903 logevent("Sending length-padded password");
4904 send_packet(ssh, s->pwpkt_type,
4905 PKT_INT, len, PKT_DATA, ss, len,
4909 * The server is believed unable to cope with
4910 * any of our password camouflage methods.
4913 len = strlen(s->cur_prompt->prompts[0]->result);
4914 logevent("Sending unpadded password");
4915 send_packet(ssh, s->pwpkt_type,
4917 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4921 send_packet(ssh, s->pwpkt_type,
4922 PKT_STR, s->cur_prompt->prompts[0]->result,
4925 logevent("Sent password");
4926 free_prompts(s->cur_prompt);
4928 if (pktin->type == SSH1_SMSG_FAILURE) {
4929 if (flags & FLAG_VERBOSE)
4930 c_write_str(ssh, "Access denied\r\n");
4931 logevent("Authentication refused");
4932 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4933 bombout(("Strange packet received, type %d", pktin->type));
4939 if (s->publickey_blob) {
4940 sfree(s->publickey_blob);
4941 sfree(s->publickey_comment);
4944 logevent("Authentication successful");
4949 static void ssh_channel_try_eof(struct ssh_channel *c)
4952 assert(c->pending_eof); /* precondition for calling us */
4954 return; /* can't close: not even opened yet */
4955 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4956 return; /* can't send EOF: pending outgoing data */
4958 c->pending_eof = FALSE; /* we're about to send it */
4959 if (ssh->version == 1) {
4960 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4962 c->closes |= CLOSES_SENT_EOF;
4964 struct Packet *pktout;
4965 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4966 ssh2_pkt_adduint32(pktout, c->remoteid);
4967 ssh2_pkt_send(ssh, pktout);
4968 c->closes |= CLOSES_SENT_EOF;
4969 ssh2_channel_check_close(c);
4973 Conf *sshfwd_get_conf(struct ssh_channel *c)
4979 void sshfwd_write_eof(struct ssh_channel *c)
4983 if (ssh->state == SSH_STATE_CLOSED)
4986 if (c->closes & CLOSES_SENT_EOF)
4989 c->pending_eof = TRUE;
4990 ssh_channel_try_eof(c);
4993 void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
4997 if (ssh->state == SSH_STATE_CLOSED)
5002 x11_close(c->u.x11.xconn);
5003 logeventf(ssh, "Forwarded X11 connection terminated due to local "
5007 case CHAN_SOCKDATA_DORMANT:
5008 pfd_close(c->u.pfd.pf);
5009 logeventf(ssh, "Forwarded port closed due to local error: %s", err);
5012 c->type = CHAN_ZOMBIE;
5013 c->pending_eof = FALSE; /* this will confuse a zombie channel */
5015 ssh2_channel_check_close(c);
5018 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
5022 if (ssh->state == SSH_STATE_CLOSED)
5025 return ssh_send_channel_data(c, buf, len);
5028 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
5032 if (ssh->state == SSH_STATE_CLOSED)
5035 ssh_channel_unthrottle(c, bufsize);
5038 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
5040 struct queued_handler *qh = ssh->qhead;
5044 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
5047 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
5048 ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
5051 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
5052 ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
5056 ssh->qhead = qh->next;
5058 if (ssh->qhead->msg1 > 0) {
5059 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5060 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
5062 if (ssh->qhead->msg2 > 0) {
5063 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5064 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
5067 ssh->qhead = ssh->qtail = NULL;
5070 qh->handler(ssh, pktin, qh->ctx);
5075 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
5076 chandler_fn_t handler, void *ctx)
5078 struct queued_handler *qh;
5080 qh = snew(struct queued_handler);
5083 qh->handler = handler;
5087 if (ssh->qtail == NULL) {
5091 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5092 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
5095 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5096 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
5099 ssh->qtail->next = qh;
5104 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
5106 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
5108 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
5109 SSH2_MSG_REQUEST_SUCCESS)) {
5110 logeventf(ssh, "Remote port forwarding from %s enabled",
5113 logeventf(ssh, "Remote port forwarding from %s refused",
5116 rpf = del234(ssh->rportfwds, pf);
5118 pf->pfrec->remote = NULL;
5123 int ssh_alloc_sharing_rportfwd(Ssh ssh, const char *shost, int sport,
5126 struct ssh_rportfwd *pf = snew(struct ssh_rportfwd);
5129 pf->share_ctx = share_ctx;
5130 pf->shost = dupstr(shost);
5132 pf->sportdesc = NULL;
5133 if (!ssh->rportfwds) {
5134 assert(ssh->version == 2);
5135 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5137 if (add234(ssh->rportfwds, pf) != pf) {
5145 static void ssh_sharing_global_request_response(Ssh ssh, struct Packet *pktin,
5148 share_got_pkt_from_server(ctx, pktin->type,
5149 pktin->body, pktin->length);
5152 void ssh_sharing_queue_global_request(Ssh ssh, void *share_ctx)
5154 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE,
5155 ssh_sharing_global_request_response, share_ctx);
5158 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
5160 struct ssh_portfwd *epf;
5164 if (!ssh->portfwds) {
5165 ssh->portfwds = newtree234(ssh_portcmp);
5168 * Go through the existing port forwardings and tag them
5169 * with status==DESTROY. Any that we want to keep will be
5170 * re-enabled (status==KEEP) as we go through the
5171 * configuration and find out which bits are the same as
5174 struct ssh_portfwd *epf;
5176 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5177 epf->status = DESTROY;
5180 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
5182 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
5183 char *kp, *kp2, *vp, *vp2;
5184 char address_family, type;
5185 int sport,dport,sserv,dserv;
5186 char *sports, *dports, *saddr, *host;
5190 address_family = 'A';
5192 if (*kp == 'A' || *kp == '4' || *kp == '6')
5193 address_family = *kp++;
5194 if (*kp == 'L' || *kp == 'R')
5197 if ((kp2 = host_strchr(kp, ':')) != NULL) {
5199 * There's a colon in the middle of the source port
5200 * string, which means that the part before it is
5201 * actually a source address.
5203 char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp);
5204 saddr = host_strduptrim(saddr_tmp);
5211 sport = atoi(sports);
5215 sport = net_service_lookup(sports);
5217 logeventf(ssh, "Service lookup failed for source"
5218 " port \"%s\"", sports);
5222 if (type == 'L' && !strcmp(val, "D")) {
5223 /* dynamic forwarding */
5230 /* ordinary forwarding */
5232 vp2 = vp + host_strcspn(vp, ":");
5233 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
5237 dport = atoi(dports);
5241 dport = net_service_lookup(dports);
5243 logeventf(ssh, "Service lookup failed for destination"
5244 " port \"%s\"", dports);
5249 if (sport && dport) {
5250 /* Set up a description of the source port. */
5251 struct ssh_portfwd *pfrec, *epfrec;
5253 pfrec = snew(struct ssh_portfwd);
5255 pfrec->saddr = saddr;
5256 pfrec->sserv = sserv ? dupstr(sports) : NULL;
5257 pfrec->sport = sport;
5258 pfrec->daddr = host;
5259 pfrec->dserv = dserv ? dupstr(dports) : NULL;
5260 pfrec->dport = dport;
5261 pfrec->local = NULL;
5262 pfrec->remote = NULL;
5263 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
5264 address_family == '6' ? ADDRTYPE_IPV6 :
5267 epfrec = add234(ssh->portfwds, pfrec);
5268 if (epfrec != pfrec) {
5269 if (epfrec->status == DESTROY) {
5271 * We already have a port forwarding up and running
5272 * with precisely these parameters. Hence, no need
5273 * to do anything; simply re-tag the existing one
5276 epfrec->status = KEEP;
5279 * Anything else indicates that there was a duplicate
5280 * in our input, which we'll silently ignore.
5282 free_portfwd(pfrec);
5284 pfrec->status = CREATE;
5293 * Now go through and destroy any port forwardings which were
5296 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5297 if (epf->status == DESTROY) {
5300 message = dupprintf("%s port forwarding from %s%s%d",
5301 epf->type == 'L' ? "local" :
5302 epf->type == 'R' ? "remote" : "dynamic",
5303 epf->saddr ? epf->saddr : "",
5304 epf->saddr ? ":" : "",
5307 if (epf->type != 'D') {
5308 char *msg2 = dupprintf("%s to %s:%d", message,
5309 epf->daddr, epf->dport);
5314 logeventf(ssh, "Cancelling %s", message);
5317 /* epf->remote or epf->local may be NULL if setting up a
5318 * forwarding failed. */
5320 struct ssh_rportfwd *rpf = epf->remote;
5321 struct Packet *pktout;
5324 * Cancel the port forwarding at the server
5327 if (ssh->version == 1) {
5329 * We cannot cancel listening ports on the
5330 * server side in SSH-1! There's no message
5331 * to support it. Instead, we simply remove
5332 * the rportfwd record from the local end
5333 * so that any connections the server tries
5334 * to make on it are rejected.
5337 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5338 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
5339 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
5341 ssh2_pkt_addstring(pktout, epf->saddr);
5342 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5343 /* XXX: rport_acceptall may not represent
5344 * what was used to open the original connection,
5345 * since it's reconfigurable. */
5346 ssh2_pkt_addstring(pktout, "");
5348 ssh2_pkt_addstring(pktout, "localhost");
5350 ssh2_pkt_adduint32(pktout, epf->sport);
5351 ssh2_pkt_send(ssh, pktout);
5354 del234(ssh->rportfwds, rpf);
5356 } else if (epf->local) {
5357 pfl_terminate(epf->local);
5360 delpos234(ssh->portfwds, i);
5362 i--; /* so we don't skip one in the list */
5366 * And finally, set up any new port forwardings (status==CREATE).
5368 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5369 if (epf->status == CREATE) {
5370 char *sportdesc, *dportdesc;
5371 sportdesc = dupprintf("%s%s%s%s%d%s",
5372 epf->saddr ? epf->saddr : "",
5373 epf->saddr ? ":" : "",
5374 epf->sserv ? epf->sserv : "",
5375 epf->sserv ? "(" : "",
5377 epf->sserv ? ")" : "");
5378 if (epf->type == 'D') {
5381 dportdesc = dupprintf("%s:%s%s%d%s",
5383 epf->dserv ? epf->dserv : "",
5384 epf->dserv ? "(" : "",
5386 epf->dserv ? ")" : "");
5389 if (epf->type == 'L') {
5390 char *err = pfl_listen(epf->daddr, epf->dport,
5391 epf->saddr, epf->sport,
5392 ssh, conf, &epf->local,
5393 epf->addressfamily);
5395 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
5396 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5397 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5398 sportdesc, dportdesc,
5399 err ? " failed: " : "", err ? err : "");
5402 } else if (epf->type == 'D') {
5403 char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport,
5404 ssh, conf, &epf->local,
5405 epf->addressfamily);
5407 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
5408 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5409 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5411 err ? " failed: " : "", err ? err : "");
5416 struct ssh_rportfwd *pf;
5419 * Ensure the remote port forwardings tree exists.
5421 if (!ssh->rportfwds) {
5422 if (ssh->version == 1)
5423 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
5425 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5428 pf = snew(struct ssh_rportfwd);
5429 pf->share_ctx = NULL;
5430 pf->dhost = dupstr(epf->daddr);
5431 pf->dport = epf->dport;
5433 pf->shost = dupstr(epf->saddr);
5434 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5435 pf->shost = dupstr("");
5437 pf->shost = dupstr("localhost");
5439 pf->sport = epf->sport;
5440 if (add234(ssh->rportfwds, pf) != pf) {
5441 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
5442 epf->daddr, epf->dport);
5445 logeventf(ssh, "Requesting remote port %s"
5446 " forward to %s", sportdesc, dportdesc);
5448 pf->sportdesc = sportdesc;
5453 if (ssh->version == 1) {
5454 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
5455 PKT_INT, epf->sport,
5456 PKT_STR, epf->daddr,
5457 PKT_INT, epf->dport,
5459 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
5461 ssh_rportfwd_succfail, pf);
5463 struct Packet *pktout;
5464 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5465 ssh2_pkt_addstring(pktout, "tcpip-forward");
5466 ssh2_pkt_addbool(pktout, 1);/* want reply */
5467 ssh2_pkt_addstring(pktout, pf->shost);
5468 ssh2_pkt_adduint32(pktout, pf->sport);
5469 ssh2_pkt_send(ssh, pktout);
5471 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
5472 SSH2_MSG_REQUEST_FAILURE,
5473 ssh_rportfwd_succfail, pf);
5482 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
5485 int stringlen, bufsize;
5487 ssh_pkt_getstring(pktin, &string, &stringlen);
5488 if (string == NULL) {
5489 bombout(("Incoming terminal data packet was badly formed"));
5493 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
5495 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
5496 ssh->v1_stdout_throttling = 1;
5497 ssh_throttle_conn(ssh, +1);
5501 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
5503 /* Remote side is trying to open a channel to talk to our
5504 * X-Server. Give them back a local channel number. */
5505 struct ssh_channel *c;
5506 int remoteid = ssh_pkt_getuint32(pktin);
5508 logevent("Received X11 connect request");
5509 /* Refuse if X11 forwarding is disabled. */
5510 if (!ssh->X11_fwd_enabled) {
5511 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5512 PKT_INT, remoteid, PKT_END);
5513 logevent("Rejected X11 connect request");
5515 c = snew(struct ssh_channel);
5518 c->u.x11.xconn = x11_init(ssh->x11authtree, c, NULL, -1);
5519 c->remoteid = remoteid;
5520 c->halfopen = FALSE;
5521 c->localid = alloc_channel_id(ssh);
5523 c->pending_eof = FALSE;
5524 c->throttling_conn = 0;
5525 c->type = CHAN_X11; /* identify channel type */
5526 add234(ssh->channels, c);
5527 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5528 PKT_INT, c->remoteid, PKT_INT,
5529 c->localid, PKT_END);
5530 logevent("Opened X11 forward channel");
5534 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
5536 /* Remote side is trying to open a channel to talk to our
5537 * agent. Give them back a local channel number. */
5538 struct ssh_channel *c;
5539 int remoteid = ssh_pkt_getuint32(pktin);
5541 /* Refuse if agent forwarding is disabled. */
5542 if (!ssh->agentfwd_enabled) {
5543 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5544 PKT_INT, remoteid, PKT_END);
5546 c = snew(struct ssh_channel);
5548 c->remoteid = remoteid;
5549 c->halfopen = FALSE;
5550 c->localid = alloc_channel_id(ssh);
5552 c->pending_eof = FALSE;
5553 c->throttling_conn = 0;
5554 c->type = CHAN_AGENT; /* identify channel type */
5555 c->u.a.lensofar = 0;
5556 c->u.a.message = NULL;
5557 c->u.a.outstanding_requests = 0;
5558 add234(ssh->channels, c);
5559 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5560 PKT_INT, c->remoteid, PKT_INT, c->localid,
5565 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
5567 /* Remote side is trying to open a channel to talk to a
5568 * forwarded port. Give them back a local channel number. */
5569 struct ssh_rportfwd pf, *pfp;
5575 remoteid = ssh_pkt_getuint32(pktin);
5576 ssh_pkt_getstring(pktin, &host, &hostsize);
5577 port = ssh_pkt_getuint32(pktin);
5579 pf.dhost = dupprintf("%.*s", hostsize, NULLTOEMPTY(host));
5581 pfp = find234(ssh->rportfwds, &pf, NULL);
5584 logeventf(ssh, "Rejected remote port open request for %s:%d",
5586 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5587 PKT_INT, remoteid, PKT_END);
5589 struct ssh_channel *c = snew(struct ssh_channel);
5592 logeventf(ssh, "Received remote port open request for %s:%d",
5594 err = pfd_connect(&c->u.pfd.pf, pf.dhost, port,
5595 c, ssh->conf, pfp->pfrec->addressfamily);
5597 logeventf(ssh, "Port open failed: %s", err);
5600 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5601 PKT_INT, remoteid, PKT_END);
5603 c->remoteid = remoteid;
5604 c->halfopen = FALSE;
5605 c->localid = alloc_channel_id(ssh);
5607 c->pending_eof = FALSE;
5608 c->throttling_conn = 0;
5609 c->type = CHAN_SOCKDATA; /* identify channel type */
5610 add234(ssh->channels, c);
5611 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5612 PKT_INT, c->remoteid, PKT_INT,
5613 c->localid, PKT_END);
5614 logevent("Forwarded port opened successfully");
5621 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
5623 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5624 unsigned int localid = ssh_pkt_getuint32(pktin);
5625 struct ssh_channel *c;
5627 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5628 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5629 c->remoteid = localid;
5630 c->halfopen = FALSE;
5631 c->type = CHAN_SOCKDATA;
5632 c->throttling_conn = 0;
5633 pfd_confirm(c->u.pfd.pf);
5636 if (c && c->pending_eof) {
5638 * We have a pending close on this channel,
5639 * which we decided on before the server acked
5640 * the channel open. So now we know the
5641 * remoteid, we can close it again.
5643 ssh_channel_try_eof(c);
5647 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
5649 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5650 struct ssh_channel *c;
5652 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5653 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5654 logevent("Forwarded connection refused by server");
5655 pfd_close(c->u.pfd.pf);
5656 del234(ssh->channels, c);
5661 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
5663 /* Remote side closes a channel. */
5664 unsigned i = ssh_pkt_getuint32(pktin);
5665 struct ssh_channel *c;
5666 c = find234(ssh->channels, &i, ssh_channelfind);
5667 if (c && !c->halfopen) {
5669 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
5670 !(c->closes & CLOSES_RCVD_EOF)) {
5672 * Received CHANNEL_CLOSE, which we translate into
5675 int send_close = FALSE;
5677 c->closes |= CLOSES_RCVD_EOF;
5682 x11_send_eof(c->u.x11.xconn);
5688 pfd_send_eof(c->u.pfd.pf);
5697 if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
5698 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
5700 c->closes |= CLOSES_SENT_EOF;
5704 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
5705 !(c->closes & CLOSES_RCVD_CLOSE)) {
5707 if (!(c->closes & CLOSES_SENT_EOF)) {
5708 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %d"
5709 " for which we never sent CHANNEL_CLOSE\n", i));
5712 c->closes |= CLOSES_RCVD_CLOSE;
5715 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
5716 !(c->closes & CLOSES_SENT_CLOSE)) {
5717 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
5718 PKT_INT, c->remoteid, PKT_END);
5719 c->closes |= CLOSES_SENT_CLOSE;
5722 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
5723 ssh_channel_destroy(c);
5725 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
5726 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
5727 "_CONFIRMATION", c ? "half-open" : "nonexistent",
5733 * Handle incoming data on an SSH-1 or SSH-2 agent-forwarding channel.
5735 static int ssh_agent_channel_data(struct ssh_channel *c, char *data,
5738 while (length > 0) {
5739 if (c->u.a.lensofar < 4) {
5740 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)length);
5741 memcpy(c->u.a.msglen + c->u.a.lensofar, data, l);
5744 c->u.a.lensofar += l;
5746 if (c->u.a.lensofar == 4) {
5747 c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
5748 c->u.a.message = snewn(c->u.a.totallen, unsigned char);
5749 memcpy(c->u.a.message, c->u.a.msglen, 4);
5751 if (c->u.a.lensofar >= 4 && length > 0) {
5752 unsigned int l = min(c->u.a.totallen - c->u.a.lensofar,
5754 memcpy(c->u.a.message + c->u.a.lensofar, data, l);
5757 c->u.a.lensofar += l;
5759 if (c->u.a.lensofar == c->u.a.totallen) {
5762 c->u.a.outstanding_requests++;
5763 if (agent_query(c->u.a.message, c->u.a.totallen, &reply, &replylen,
5764 ssh_agentf_callback, c))
5765 ssh_agentf_callback(c, reply, replylen);
5766 sfree(c->u.a.message);
5767 c->u.a.message = NULL;
5768 c->u.a.lensofar = 0;
5771 return 0; /* agent channels never back up */
5774 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
5776 /* Data sent down one of our channels. */
5777 int i = ssh_pkt_getuint32(pktin);
5780 struct ssh_channel *c;
5782 ssh_pkt_getstring(pktin, &p, &len);
5784 c = find234(ssh->channels, &i, ssh_channelfind);
5789 bufsize = x11_send(c->u.x11.xconn, p, len);
5792 bufsize = pfd_send(c->u.pfd.pf, p, len);
5795 bufsize = ssh_agent_channel_data(c, p, len);
5798 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5799 c->throttling_conn = 1;
5800 ssh_throttle_conn(ssh, +1);
5805 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5807 ssh->exitcode = ssh_pkt_getuint32(pktin);
5808 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5809 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5811 * In case `helpful' firewalls or proxies tack
5812 * extra human-readable text on the end of the
5813 * session which we might mistake for another
5814 * encrypted packet, we close the session once
5815 * we've sent EXIT_CONFIRMATION.
5817 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5820 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5821 static void ssh1_send_ttymode(void *data,
5822 const struct ssh_ttymode *mode, char *val)
5824 struct Packet *pktout = (struct Packet *)data;
5825 unsigned int arg = 0;
5827 switch (mode->type) {
5829 arg = ssh_tty_parse_specchar(val);
5832 arg = ssh_tty_parse_boolean(val);
5835 ssh2_pkt_addbyte(pktout, mode->opcode);
5836 ssh2_pkt_addbyte(pktout, arg);
5839 int ssh_agent_forwarding_permitted(Ssh ssh)
5841 return conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists();
5844 static void do_ssh1_connection(Ssh ssh, const unsigned char *in, int inlen,
5845 struct Packet *pktin)
5847 crBegin(ssh->do_ssh1_connection_crstate);
5849 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5850 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5851 ssh1_smsg_stdout_stderr_data;
5853 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5854 ssh1_msg_channel_open_confirmation;
5855 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5856 ssh1_msg_channel_open_failure;
5857 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5858 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5859 ssh1_msg_channel_close;
5860 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5861 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5863 if (ssh_agent_forwarding_permitted(ssh)) {
5864 logevent("Requesting agent forwarding");
5865 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5869 if (pktin->type != SSH1_SMSG_SUCCESS
5870 && pktin->type != SSH1_SMSG_FAILURE) {
5871 bombout(("Protocol confusion"));
5873 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5874 logevent("Agent forwarding refused");
5876 logevent("Agent forwarding enabled");
5877 ssh->agentfwd_enabled = TRUE;
5878 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5882 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
5884 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5886 if (!ssh->x11disp) {
5887 /* FIXME: return an error message from x11_setup_display */
5888 logevent("X11 forwarding not enabled: unable to"
5889 " initialise X display");
5891 ssh->x11auth = x11_invent_fake_auth
5892 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
5893 ssh->x11auth->disp = ssh->x11disp;
5895 logevent("Requesting X11 forwarding");
5896 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5897 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5898 PKT_STR, ssh->x11auth->protoname,
5899 PKT_STR, ssh->x11auth->datastring,
5900 PKT_INT, ssh->x11disp->screennum,
5903 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5904 PKT_STR, ssh->x11auth->protoname,
5905 PKT_STR, ssh->x11auth->datastring,
5911 if (pktin->type != SSH1_SMSG_SUCCESS
5912 && pktin->type != SSH1_SMSG_FAILURE) {
5913 bombout(("Protocol confusion"));
5915 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5916 logevent("X11 forwarding refused");
5918 logevent("X11 forwarding enabled");
5919 ssh->X11_fwd_enabled = TRUE;
5920 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5925 ssh_setup_portfwd(ssh, ssh->conf);
5926 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5928 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5930 /* Unpick the terminal-speed string. */
5931 /* XXX perhaps we should allow no speeds to be sent. */
5932 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5933 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5934 /* Send the pty request. */
5935 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5936 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5937 ssh_pkt_adduint32(pkt, ssh->term_height);
5938 ssh_pkt_adduint32(pkt, ssh->term_width);
5939 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5940 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5941 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5942 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5943 ssh_pkt_adduint32(pkt, ssh->ispeed);
5944 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5945 ssh_pkt_adduint32(pkt, ssh->ospeed);
5946 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5948 ssh->state = SSH_STATE_INTERMED;
5952 if (pktin->type != SSH1_SMSG_SUCCESS
5953 && pktin->type != SSH1_SMSG_FAILURE) {
5954 bombout(("Protocol confusion"));
5956 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5957 c_write_str(ssh, "Server refused to allocate pty\r\n");
5958 ssh->editing = ssh->echoing = 1;
5960 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5961 ssh->ospeed, ssh->ispeed);
5962 ssh->got_pty = TRUE;
5965 ssh->editing = ssh->echoing = 1;
5968 if (conf_get_int(ssh->conf, CONF_compression)) {
5969 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5973 if (pktin->type != SSH1_SMSG_SUCCESS
5974 && pktin->type != SSH1_SMSG_FAILURE) {
5975 bombout(("Protocol confusion"));
5977 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5978 c_write_str(ssh, "Server refused to compress\r\n");
5980 logevent("Started compression");
5981 ssh->v1_compressing = TRUE;
5982 ssh->cs_comp_ctx = zlib_compress_init();
5983 logevent("Initialised zlib (RFC1950) compression");
5984 ssh->sc_comp_ctx = zlib_decompress_init();
5985 logevent("Initialised zlib (RFC1950) decompression");
5989 * Start the shell or command.
5991 * Special case: if the first-choice command is an SSH-2
5992 * subsystem (hence not usable here) and the second choice
5993 * exists, we fall straight back to that.
5996 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
5998 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
5999 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
6000 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
6001 ssh->fallback_cmd = TRUE;
6004 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
6006 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
6007 logevent("Started session");
6010 ssh->state = SSH_STATE_SESSION;
6011 if (ssh->size_needed)
6012 ssh_size(ssh, ssh->term_width, ssh->term_height);
6013 if (ssh->eof_needed)
6014 ssh_special(ssh, TS_EOF);
6017 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
6019 ssh->channels = newtree234(ssh_channelcmp);
6023 * By this point, most incoming packets are already being
6024 * handled by the dispatch table, and we need only pay
6025 * attention to the unusual ones.
6030 if (pktin->type == SSH1_SMSG_SUCCESS) {
6031 /* may be from EXEC_SHELL on some servers */
6032 } else if (pktin->type == SSH1_SMSG_FAILURE) {
6033 /* may be from EXEC_SHELL on some servers
6034 * if no pty is available or in other odd cases. Ignore */
6036 bombout(("Strange packet received: type %d", pktin->type));
6041 int len = min(inlen, 512);
6042 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
6043 PKT_INT, len, PKT_DATA, in, len,
6055 * Handle the top-level SSH-2 protocol.
6057 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
6062 ssh_pkt_getstring(pktin, &msg, &msglen);
6063 logeventf(ssh, "Remote debug message: %.*s", msglen, NULLTOEMPTY(msg));
6066 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
6068 /* log reason code in disconnect message */
6072 ssh_pkt_getstring(pktin, &msg, &msglen);
6073 bombout(("Server sent disconnect message:\n\"%.*s\"",
6074 msglen, NULLTOEMPTY(msg)));
6077 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
6079 /* Do nothing, because we're ignoring it! Duhh. */
6082 static void ssh1_protocol_setup(Ssh ssh)
6087 * Most messages are handled by the coroutines.
6089 for (i = 0; i < 256; i++)
6090 ssh->packet_dispatch[i] = NULL;
6093 * These special message types we install handlers for.
6095 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
6096 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
6097 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
6100 static void ssh1_protocol(Ssh ssh, const void *vin, int inlen,
6101 struct Packet *pktin)
6103 const unsigned char *in = (const unsigned char *)vin;
6104 if (ssh->state == SSH_STATE_CLOSED)
6107 if (pktin && ssh->packet_dispatch[pktin->type]) {
6108 ssh->packet_dispatch[pktin->type](ssh, pktin);
6112 if (!ssh->protocol_initial_phase_done) {
6113 if (do_ssh1_login(ssh, in, inlen, pktin))
6114 ssh->protocol_initial_phase_done = TRUE;
6119 do_ssh1_connection(ssh, in, inlen, pktin);
6123 * Utility routines for decoding comma-separated strings in KEXINIT.
6125 static int first_in_commasep_string(char const *needle, char const *haystack,
6129 if (!needle || !haystack) /* protect against null pointers */
6131 needlen = strlen(needle);
6133 if (haylen >= needlen && /* haystack is long enough */
6134 !memcmp(needle, haystack, needlen) && /* initial match */
6135 (haylen == needlen || haystack[needlen] == ',')
6136 /* either , or EOS follows */
6142 static int in_commasep_string(char const *needle, char const *haystack,
6147 if (!needle || !haystack) /* protect against null pointers */
6150 * Is it at the start of the string?
6152 if (first_in_commasep_string(needle, haystack, haylen))
6155 * If not, search for the next comma and resume after that.
6156 * If no comma found, terminate.
6158 p = memchr(haystack, ',', haylen);
6160 /* + 1 to skip over comma */
6161 return in_commasep_string(needle, p + 1, haylen - (p + 1 - haystack));
6165 * Add a value to the comma-separated string at the end of the packet.
6167 static void ssh2_pkt_addstring_commasep(struct Packet *pkt, const char *data)
6169 if (pkt->length - pkt->savedpos > 0)
6170 ssh_pkt_addstring_str(pkt, ",");
6171 ssh_pkt_addstring_str(pkt, data);
6176 * SSH-2 key derivation (RFC 4253 section 7.2).
6178 static unsigned char *ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H,
6179 char chr, int keylen)
6181 const struct ssh_hash *h = ssh->kex->hash;
6189 /* Round up to the next multiple of hash length. */
6190 keylen_padded = ((keylen + h->hlen - 1) / h->hlen) * h->hlen;
6192 key = snewn(keylen_padded, unsigned char);
6194 /* First hlen bytes. */
6196 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6197 hash_mpint(h, s, K);
6198 h->bytes(s, H, h->hlen);
6199 h->bytes(s, &chr, 1);
6200 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
6203 /* Subsequent blocks of hlen bytes. */
6204 if (keylen_padded > h->hlen) {
6208 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6209 hash_mpint(h, s, K);
6210 h->bytes(s, H, h->hlen);
6212 for (offset = h->hlen; offset < keylen_padded; offset += h->hlen) {
6213 h->bytes(s, key + offset - h->hlen, h->hlen);
6215 h->final(s2, key + offset);
6221 /* Now clear any extra bytes of key material beyond the length
6222 * we're officially returning, because the caller won't know to
6224 if (keylen_padded > keylen)
6225 smemclr(key + keylen, keylen_padded - keylen);
6231 * Structure for constructing KEXINIT algorithm lists.
6233 #define MAXKEXLIST 16
6234 struct kexinit_algorithm {
6238 const struct ssh_kex *kex;
6242 const struct ssh_signkey *hostkey;
6246 const struct ssh2_cipher *cipher;
6250 const struct ssh_mac *mac;
6253 const struct ssh_compress *comp;
6258 * Find a slot in a KEXINIT algorithm list to use for a new algorithm.
6259 * If the algorithm is already in the list, return a pointer to its
6260 * entry, otherwise return an entry from the end of the list.
6261 * This assumes that every time a particular name is passed in, it
6262 * comes from the same string constant. If this isn't true, this
6263 * function may need to be rewritten to use strcmp() instead.
6265 static struct kexinit_algorithm *ssh2_kexinit_addalg(struct kexinit_algorithm
6266 *list, const char *name)
6270 for (i = 0; i < MAXKEXLIST; i++)
6271 if (list[i].name == NULL || list[i].name == name) {
6272 list[i].name = name;
6275 assert(!"No space in KEXINIT list");
6280 * Handle the SSH-2 transport layer.
6282 static void do_ssh2_transport(Ssh ssh, const void *vin, int inlen,
6283 struct Packet *pktin)
6285 const unsigned char *in = (const unsigned char *)vin;
6287 KEXLIST_KEX, KEXLIST_HOSTKEY, KEXLIST_CSCIPHER, KEXLIST_SCCIPHER,
6288 KEXLIST_CSMAC, KEXLIST_SCMAC, KEXLIST_CSCOMP, KEXLIST_SCCOMP,
6291 const char * kexlist_descr[NKEXLIST] = {
6292 "key exchange algorithm", "host key algorithm",
6293 "client-to-server cipher", "server-to-client cipher",
6294 "client-to-server MAC", "server-to-client MAC",
6295 "client-to-server compression method",
6296 "server-to-client compression method" };
6297 struct do_ssh2_transport_state {
6299 int nbits, pbits, warn_kex, warn_hk, warn_cscipher, warn_sccipher;
6300 Bignum p, g, e, f, K;
6303 int kex_init_value, kex_reply_value;
6304 const struct ssh_mac *const *maclist;
6306 const struct ssh2_cipher *cscipher_tobe;
6307 const struct ssh2_cipher *sccipher_tobe;
6308 const struct ssh_mac *csmac_tobe;
6309 const struct ssh_mac *scmac_tobe;
6310 int csmac_etm_tobe, scmac_etm_tobe;
6311 const struct ssh_compress *cscomp_tobe;
6312 const struct ssh_compress *sccomp_tobe;
6313 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
6314 int hostkeylen, siglen, rsakeylen;
6315 void *hkey; /* actual host key */
6316 void *rsakey; /* for RSA kex */
6317 void *eckey; /* for ECDH kex */
6318 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
6319 int n_preferred_kex;
6320 const struct ssh_kexes *preferred_kex[KEX_MAX];
6322 int preferred_hk[HK_MAX];
6323 int n_preferred_ciphers;
6324 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
6325 const struct ssh_compress *preferred_comp;
6326 int userauth_succeeded; /* for delayed compression */
6327 int pending_compression;
6328 int got_session_id, activated_authconn;
6329 struct Packet *pktout;
6333 struct kexinit_algorithm kexlists[NKEXLIST][MAXKEXLIST];
6335 crState(do_ssh2_transport_state);
6337 assert(!ssh->bare_connection);
6338 assert(ssh->version == 2);
6342 s->cscipher_tobe = s->sccipher_tobe = NULL;
6343 s->csmac_tobe = s->scmac_tobe = NULL;
6344 s->cscomp_tobe = s->sccomp_tobe = NULL;
6346 s->got_session_id = s->activated_authconn = FALSE;
6347 s->userauth_succeeded = FALSE;
6348 s->pending_compression = FALSE;
6351 * Be prepared to work around the buggy MAC problem.
6353 if (ssh->remote_bugs & BUG_SSH2_HMAC)
6354 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
6356 s->maclist = macs, s->nmacs = lenof(macs);
6359 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
6362 struct kexinit_algorithm *alg;
6365 * Set up the preferred key exchange. (NULL => warn below here)
6367 s->n_preferred_kex = 0;
6368 for (i = 0; i < KEX_MAX; i++) {
6369 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
6371 s->preferred_kex[s->n_preferred_kex++] =
6372 &ssh_diffiehellman_gex;
6375 s->preferred_kex[s->n_preferred_kex++] =
6376 &ssh_diffiehellman_group14;
6379 s->preferred_kex[s->n_preferred_kex++] =
6380 &ssh_diffiehellman_group1;
6383 s->preferred_kex[s->n_preferred_kex++] =
6387 s->preferred_kex[s->n_preferred_kex++] =
6391 /* Flag for later. Don't bother if it's the last in
6393 if (i < KEX_MAX - 1) {
6394 s->preferred_kex[s->n_preferred_kex++] = NULL;
6401 * Set up the preferred host key types. These are just the ids
6402 * in the enum in putty.h, so 'warn below here' is indicated
6405 s->n_preferred_hk = 0;
6406 for (i = 0; i < HK_MAX; i++) {
6407 int id = conf_get_int_int(ssh->conf, CONF_ssh_hklist, i);
6408 /* As above, don't bother with HK_WARN if it's last in the
6410 if (id != HK_WARN || i < HK_MAX - 1)
6411 s->preferred_hk[s->n_preferred_hk++] = id;
6415 * Set up the preferred ciphers. (NULL => warn below here)
6417 s->n_preferred_ciphers = 0;
6418 for (i = 0; i < CIPHER_MAX; i++) {
6419 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
6420 case CIPHER_BLOWFISH:
6421 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
6424 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
6425 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
6429 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
6432 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
6434 case CIPHER_ARCFOUR:
6435 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
6437 case CIPHER_CHACHA20:
6438 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_ccp;
6441 /* Flag for later. Don't bother if it's the last in
6443 if (i < CIPHER_MAX - 1) {
6444 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
6451 * Set up preferred compression.
6453 if (conf_get_int(ssh->conf, CONF_compression))
6454 s->preferred_comp = &ssh_zlib;
6456 s->preferred_comp = &ssh_comp_none;
6459 * Enable queueing of outgoing auth- or connection-layer
6460 * packets while we are in the middle of a key exchange.
6462 ssh->queueing = TRUE;
6465 * Flag that KEX is in progress.
6467 ssh->kex_in_progress = TRUE;
6469 for (i = 0; i < NKEXLIST; i++)
6470 for (j = 0; j < MAXKEXLIST; j++)
6471 s->kexlists[i][j].name = NULL;
6472 /* List key exchange algorithms. */
6474 for (i = 0; i < s->n_preferred_kex; i++) {
6475 const struct ssh_kexes *k = s->preferred_kex[i];
6476 if (!k) warn = TRUE;
6477 else for (j = 0; j < k->nkexes; j++) {
6478 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_KEX],
6480 alg->u.kex.kex = k->list[j];
6481 alg->u.kex.warn = warn;
6484 /* List server host key algorithms. */
6485 if (!s->got_session_id) {
6487 * In the first key exchange, we list all the algorithms
6488 * we're prepared to cope with, but prefer those algorithms
6489 * for which we have a host key for this host.
6491 * If the host key algorithm is below the warning
6492 * threshold, we warn even if we did already have a key
6493 * for it, on the basis that if the user has just
6494 * reconfigured that host key type to be warned about,
6495 * they surely _do_ want to be alerted that a server
6496 * they're actually connecting to is using it.
6499 for (i = 0; i < s->n_preferred_hk; i++) {
6500 if (s->preferred_hk[i] == HK_WARN)
6502 for (j = 0; j < lenof(hostkey_algs); j++) {
6503 if (hostkey_algs[j].id != s->preferred_hk[i])
6505 if (have_ssh_host_key(ssh->savedhost, ssh->savedport,
6506 hostkey_algs[j].alg->keytype)) {
6507 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6508 hostkey_algs[j].alg->name);
6509 alg->u.hk.hostkey = hostkey_algs[j].alg;
6510 alg->u.hk.warn = warn;
6515 for (i = 0; i < s->n_preferred_hk; i++) {
6516 if (s->preferred_hk[i] == HK_WARN)
6518 for (j = 0; j < lenof(hostkey_algs); j++) {
6519 if (hostkey_algs[j].id != s->preferred_hk[i])
6521 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6522 hostkey_algs[j].alg->name);
6523 alg->u.hk.hostkey = hostkey_algs[j].alg;
6524 alg->u.hk.warn = warn;
6529 * In subsequent key exchanges, we list only the kex
6530 * algorithm that was selected in the first key exchange,
6531 * so that we keep getting the same host key and hence
6532 * don't have to interrupt the user's session to ask for
6536 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6537 ssh->hostkey->name);
6538 alg->u.hk.hostkey = ssh->hostkey;
6539 alg->u.hk.warn = FALSE;
6541 /* List encryption algorithms (client->server then server->client). */
6542 for (k = KEXLIST_CSCIPHER; k <= KEXLIST_SCCIPHER; k++) {
6545 alg = ssh2_kexinit_addalg(s->kexlists[k], "none");
6546 alg->u.cipher.cipher = NULL;
6547 alg->u.cipher.warn = warn;
6548 #endif /* FUZZING */
6549 for (i = 0; i < s->n_preferred_ciphers; i++) {
6550 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6551 if (!c) warn = TRUE;
6552 else for (j = 0; j < c->nciphers; j++) {
6553 alg = ssh2_kexinit_addalg(s->kexlists[k],
6555 alg->u.cipher.cipher = c->list[j];
6556 alg->u.cipher.warn = warn;
6560 /* List MAC algorithms (client->server then server->client). */
6561 for (j = KEXLIST_CSMAC; j <= KEXLIST_SCMAC; j++) {
6563 alg = ssh2_kexinit_addalg(s->kexlists[j], "none");
6564 alg->u.mac.mac = NULL;
6565 alg->u.mac.etm = FALSE;
6566 #endif /* FUZZING */
6567 for (i = 0; i < s->nmacs; i++) {
6568 alg = ssh2_kexinit_addalg(s->kexlists[j], s->maclist[i]->name);
6569 alg->u.mac.mac = s->maclist[i];
6570 alg->u.mac.etm = FALSE;
6572 for (i = 0; i < s->nmacs; i++)
6573 /* For each MAC, there may also be an ETM version,
6574 * which we list second. */
6575 if (s->maclist[i]->etm_name) {
6576 alg = ssh2_kexinit_addalg(s->kexlists[j],
6577 s->maclist[i]->etm_name);
6578 alg->u.mac.mac = s->maclist[i];
6579 alg->u.mac.etm = TRUE;
6582 /* List client->server compression algorithms,
6583 * then server->client compression algorithms. (We use the
6584 * same set twice.) */
6585 for (j = KEXLIST_CSCOMP; j <= KEXLIST_SCCOMP; j++) {
6586 assert(lenof(compressions) > 1);
6587 /* Prefer non-delayed versions */
6588 alg = ssh2_kexinit_addalg(s->kexlists[j], s->preferred_comp->name);
6589 alg->u.comp = s->preferred_comp;
6590 /* We don't even list delayed versions of algorithms until
6591 * they're allowed to be used, to avoid a race. See the end of
6593 if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
6594 alg = ssh2_kexinit_addalg(s->kexlists[j],
6595 s->preferred_comp->delayed_name);
6596 alg->u.comp = s->preferred_comp;
6598 for (i = 0; i < lenof(compressions); i++) {
6599 const struct ssh_compress *c = compressions[i];
6600 alg = ssh2_kexinit_addalg(s->kexlists[j], c->name);
6602 if (s->userauth_succeeded && c->delayed_name) {
6603 alg = ssh2_kexinit_addalg(s->kexlists[j], c->delayed_name);
6609 * Construct and send our key exchange packet.
6611 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
6612 for (i = 0; i < 16; i++)
6613 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
6614 for (i = 0; i < NKEXLIST; i++) {
6615 ssh2_pkt_addstring_start(s->pktout);
6616 for (j = 0; j < MAXKEXLIST; j++) {
6617 if (s->kexlists[i][j].name == NULL) break;
6618 ssh2_pkt_addstring_commasep(s->pktout, s->kexlists[i][j].name);
6621 /* List client->server languages. Empty list. */
6622 ssh2_pkt_addstring_start(s->pktout);
6623 /* List server->client languages. Empty list. */
6624 ssh2_pkt_addstring_start(s->pktout);
6625 /* First KEX packet does _not_ follow, because we're not that brave. */
6626 ssh2_pkt_addbool(s->pktout, FALSE);
6628 ssh2_pkt_adduint32(s->pktout, 0);
6631 s->our_kexinitlen = s->pktout->length - 5;
6632 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
6633 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
6635 ssh2_pkt_send_noqueue(ssh, s->pktout);
6638 crWaitUntilV(pktin);
6641 * Now examine the other side's KEXINIT to see what we're up
6648 if (pktin->type != SSH2_MSG_KEXINIT) {
6649 bombout(("expected key exchange packet from server"));
6653 ssh->hostkey = NULL;
6654 s->cscipher_tobe = NULL;
6655 s->sccipher_tobe = NULL;
6656 s->csmac_tobe = NULL;
6657 s->scmac_tobe = NULL;
6658 s->cscomp_tobe = NULL;
6659 s->sccomp_tobe = NULL;
6660 s->warn_kex = s->warn_hk = FALSE;
6661 s->warn_cscipher = s->warn_sccipher = FALSE;
6663 pktin->savedpos += 16; /* skip garbage cookie */
6666 for (i = 0; i < NKEXLIST; i++) {
6667 ssh_pkt_getstring(pktin, &str, &len);
6669 bombout(("KEXINIT packet was incomplete"));
6673 /* If we've already selected a cipher which requires a
6674 * particular MAC, then just select that, and don't even
6675 * bother looking through the server's KEXINIT string for
6677 if (i == KEXLIST_CSMAC && s->cscipher_tobe &&
6678 s->cscipher_tobe->required_mac) {
6679 s->csmac_tobe = s->cscipher_tobe->required_mac;
6680 s->csmac_etm_tobe = !!(s->csmac_tobe->etm_name);
6683 if (i == KEXLIST_SCMAC && s->sccipher_tobe &&
6684 s->sccipher_tobe->required_mac) {
6685 s->scmac_tobe = s->sccipher_tobe->required_mac;
6686 s->scmac_etm_tobe = !!(s->scmac_tobe->etm_name);
6690 for (j = 0; j < MAXKEXLIST; j++) {
6691 struct kexinit_algorithm *alg = &s->kexlists[i][j];
6692 if (alg->name == NULL) break;
6693 if (in_commasep_string(alg->name, str, len)) {
6694 /* We've found a matching algorithm. */
6695 if (i == KEXLIST_KEX || i == KEXLIST_HOSTKEY) {
6696 /* Check if we might need to ignore first kex pkt */
6698 !first_in_commasep_string(alg->name, str, len))
6701 if (i == KEXLIST_KEX) {
6702 ssh->kex = alg->u.kex.kex;
6703 s->warn_kex = alg->u.kex.warn;
6704 } else if (i == KEXLIST_HOSTKEY) {
6705 ssh->hostkey = alg->u.hk.hostkey;
6706 s->warn_hk = alg->u.hk.warn;
6707 } else if (i == KEXLIST_CSCIPHER) {
6708 s->cscipher_tobe = alg->u.cipher.cipher;
6709 s->warn_cscipher = alg->u.cipher.warn;
6710 } else if (i == KEXLIST_SCCIPHER) {
6711 s->sccipher_tobe = alg->u.cipher.cipher;
6712 s->warn_sccipher = alg->u.cipher.warn;
6713 } else if (i == KEXLIST_CSMAC) {
6714 s->csmac_tobe = alg->u.mac.mac;
6715 s->csmac_etm_tobe = alg->u.mac.etm;
6716 } else if (i == KEXLIST_SCMAC) {
6717 s->scmac_tobe = alg->u.mac.mac;
6718 s->scmac_etm_tobe = alg->u.mac.etm;
6719 } else if (i == KEXLIST_CSCOMP) {
6720 s->cscomp_tobe = alg->u.comp;
6721 } else if (i == KEXLIST_SCCOMP) {
6722 s->sccomp_tobe = alg->u.comp;
6726 if ((i == KEXLIST_CSCOMP || i == KEXLIST_SCCOMP) &&
6727 in_commasep_string(alg->u.comp->delayed_name, str, len))
6728 s->pending_compression = TRUE; /* try this later */
6730 bombout(("Couldn't agree a %s (available: %.*s)",
6731 kexlist_descr[i], len, str));
6735 if (i == KEXLIST_HOSTKEY) {
6739 * In addition to deciding which host key we're
6740 * actually going to use, we should make a list of the
6741 * host keys offered by the server which we _don't_
6742 * have cached. These will be offered as cross-
6743 * certification options by ssh_get_specials.
6745 * We also count the key we're currently using for KEX
6746 * as one we've already got, because by the time this
6747 * menu becomes visible, it will be.
6749 ssh->n_uncert_hostkeys = 0;
6751 for (j = 0; j < lenof(hostkey_algs); j++) {
6752 if (hostkey_algs[j].alg != ssh->hostkey &&
6753 in_commasep_string(hostkey_algs[j].alg->name,
6755 !have_ssh_host_key(ssh->savedhost, ssh->savedport,
6756 hostkey_algs[j].alg->keytype)) {
6757 ssh->uncert_hostkeys[ssh->n_uncert_hostkeys++] = j;
6763 if (s->pending_compression) {
6764 logevent("Server supports delayed compression; "
6765 "will try this later");
6767 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
6768 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
6769 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
6771 ssh->exhash = ssh->kex->hash->init();
6772 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
6773 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
6774 hash_string(ssh->kex->hash, ssh->exhash,
6775 s->our_kexinit, s->our_kexinitlen);
6776 sfree(s->our_kexinit);
6777 /* Include the type byte in the hash of server's KEXINIT */
6778 hash_string(ssh->kex->hash, ssh->exhash,
6779 pktin->body - 1, pktin->length + 1);
6782 ssh_set_frozen(ssh, 1);
6783 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
6785 ssh_dialog_callback, ssh);
6786 if (s->dlgret < 0) {
6790 bombout(("Unexpected data from server while"
6791 " waiting for user response"));
6794 } while (pktin || inlen > 0);
6795 s->dlgret = ssh->user_response;
6797 ssh_set_frozen(ssh, 0);
6798 if (s->dlgret == 0) {
6799 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
6809 ssh_set_frozen(ssh, 1);
6812 * Change warning box wording depending on why we chose a
6813 * warning-level host key algorithm. If it's because
6814 * that's all we have *cached*, use the askhk mechanism,
6815 * and list the host keys we could usefully cross-certify.
6816 * Otherwise, use askalg for the standard wording.
6819 for (j = 0; j < ssh->n_uncert_hostkeys; j++) {
6820 const struct ssh_signkey_with_user_pref_id *hktype =
6821 &hostkey_algs[ssh->uncert_hostkeys[j]];
6823 for (k = 0; k < HK_MAX; k++) {
6824 int id = conf_get_int_int(ssh->conf, CONF_ssh_hklist, k);
6825 if (id == HK_WARN) {
6827 } else if (id == hktype->id) {
6834 char *old_ba = betteralgs;
6835 betteralgs = dupcat(betteralgs, ",",
6837 (const char *)NULL);
6840 betteralgs = dupstr(hktype->alg->name);
6845 s->dlgret = askhk(ssh->frontend, ssh->hostkey->name,
6846 betteralgs, ssh_dialog_callback, ssh);
6849 s->dlgret = askalg(ssh->frontend, "host key type",
6851 ssh_dialog_callback, ssh);
6853 if (s->dlgret < 0) {
6857 bombout(("Unexpected data from server while"
6858 " waiting for user response"));
6861 } while (pktin || inlen > 0);
6862 s->dlgret = ssh->user_response;
6864 ssh_set_frozen(ssh, 0);
6865 if (s->dlgret == 0) {
6866 ssh_disconnect(ssh, "User aborted at host key warning", NULL,
6872 if (s->warn_cscipher) {
6873 ssh_set_frozen(ssh, 1);
6874 s->dlgret = askalg(ssh->frontend,
6875 "client-to-server cipher",
6876 s->cscipher_tobe->name,
6877 ssh_dialog_callback, ssh);
6878 if (s->dlgret < 0) {
6882 bombout(("Unexpected data from server while"
6883 " waiting for user response"));
6886 } while (pktin || inlen > 0);
6887 s->dlgret = ssh->user_response;
6889 ssh_set_frozen(ssh, 0);
6890 if (s->dlgret == 0) {
6891 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6897 if (s->warn_sccipher) {
6898 ssh_set_frozen(ssh, 1);
6899 s->dlgret = askalg(ssh->frontend,
6900 "server-to-client cipher",
6901 s->sccipher_tobe->name,
6902 ssh_dialog_callback, ssh);
6903 if (s->dlgret < 0) {
6907 bombout(("Unexpected data from server while"
6908 " waiting for user response"));
6911 } while (pktin || inlen > 0);
6912 s->dlgret = ssh->user_response;
6914 ssh_set_frozen(ssh, 0);
6915 if (s->dlgret == 0) {
6916 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6922 if (s->ignorepkt) /* first_kex_packet_follows */
6923 crWaitUntilV(pktin); /* Ignore packet */
6926 if (ssh->kex->main_type == KEXTYPE_DH) {
6928 * Work out the number of bits of key we will need from the
6929 * key exchange. We start with the maximum key length of
6935 csbits = s->cscipher_tobe ? s->cscipher_tobe->real_keybits : 0;
6936 scbits = s->sccipher_tobe ? s->sccipher_tobe->real_keybits : 0;
6937 s->nbits = (csbits > scbits ? csbits : scbits);
6939 /* The keys only have hlen-bit entropy, since they're based on
6940 * a hash. So cap the key size at hlen bits. */
6941 if (s->nbits > ssh->kex->hash->hlen * 8)
6942 s->nbits = ssh->kex->hash->hlen * 8;
6945 * If we're doing Diffie-Hellman group exchange, start by
6946 * requesting a group.
6948 if (dh_is_gex(ssh->kex)) {
6949 logevent("Doing Diffie-Hellman group exchange");
6950 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
6952 * Work out how big a DH group we will need to allow that
6955 s->pbits = 512 << ((s->nbits - 1) / 64);
6956 if (s->pbits < DH_MIN_SIZE)
6957 s->pbits = DH_MIN_SIZE;
6958 if (s->pbits > DH_MAX_SIZE)
6959 s->pbits = DH_MAX_SIZE;
6960 if ((ssh->remote_bugs & BUG_SSH2_OLDGEX)) {
6961 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD);
6962 ssh2_pkt_adduint32(s->pktout, s->pbits);
6964 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
6965 ssh2_pkt_adduint32(s->pktout, DH_MIN_SIZE);
6966 ssh2_pkt_adduint32(s->pktout, s->pbits);
6967 ssh2_pkt_adduint32(s->pktout, DH_MAX_SIZE);
6969 ssh2_pkt_send_noqueue(ssh, s->pktout);
6971 crWaitUntilV(pktin);
6972 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
6973 bombout(("expected key exchange group packet from server"));
6976 s->p = ssh2_pkt_getmp(pktin);
6977 s->g = ssh2_pkt_getmp(pktin);
6978 if (!s->p || !s->g) {
6979 bombout(("unable to read mp-ints from incoming group packet"));
6982 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
6983 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
6984 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
6986 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
6987 ssh->kex_ctx = dh_setup_group(ssh->kex);
6988 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
6989 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
6990 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
6991 ssh->kex->groupname);
6994 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
6995 ssh->kex->hash->text_name);
6997 * Now generate and send e for Diffie-Hellman.
6999 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
7000 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
7001 s->pktout = ssh2_pkt_init(s->kex_init_value);
7002 ssh2_pkt_addmp(s->pktout, s->e);
7003 ssh2_pkt_send_noqueue(ssh, s->pktout);
7005 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
7006 crWaitUntilV(pktin);
7007 if (pktin->type != s->kex_reply_value) {
7008 bombout(("expected key exchange reply packet from server"));
7011 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
7012 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7013 if (!s->hostkeydata) {
7014 bombout(("unable to parse key exchange reply packet"));
7017 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7018 s->hostkeydata, s->hostkeylen);
7019 s->f = ssh2_pkt_getmp(pktin);
7021 bombout(("unable to parse key exchange reply packet"));
7024 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7026 bombout(("unable to parse key exchange reply packet"));
7031 const char *err = dh_validate_f(ssh->kex_ctx, s->f);
7033 bombout(("key exchange reply failed validation: %s", err));
7037 s->K = dh_find_K(ssh->kex_ctx, s->f);
7039 /* We assume everything from now on will be quick, and it might
7040 * involve user interaction. */
7041 set_busy_status(ssh->frontend, BUSY_NOT);
7043 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
7044 if (dh_is_gex(ssh->kex)) {
7045 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
7046 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MIN_SIZE);
7047 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
7048 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
7049 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MAX_SIZE);
7050 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
7051 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
7053 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
7054 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
7056 dh_cleanup(ssh->kex_ctx);
7058 if (dh_is_gex(ssh->kex)) {
7062 } else if (ssh->kex->main_type == KEXTYPE_ECDH) {
7064 logeventf(ssh, "Doing ECDH key exchange with curve %s and hash %s",
7065 ssh_ecdhkex_curve_textname(ssh->kex),
7066 ssh->kex->hash->text_name);
7067 ssh->pkt_kctx = SSH2_PKTCTX_ECDHKEX;
7069 s->eckey = ssh_ecdhkex_newkey(ssh->kex);
7071 bombout(("Unable to generate key for ECDH"));
7077 int publicPointLength;
7078 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
7080 ssh_ecdhkex_freekey(s->eckey);
7081 bombout(("Unable to encode public key for ECDH"));
7084 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_ECDH_INIT);
7085 ssh2_pkt_addstring_start(s->pktout);
7086 ssh2_pkt_addstring_data(s->pktout, publicPoint, publicPointLength);
7090 ssh2_pkt_send_noqueue(ssh, s->pktout);
7092 crWaitUntilV(pktin);
7093 if (pktin->type != SSH2_MSG_KEX_ECDH_REPLY) {
7094 ssh_ecdhkex_freekey(s->eckey);
7095 bombout(("expected ECDH reply packet from server"));
7099 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7100 if (!s->hostkeydata) {
7101 bombout(("unable to parse ECDH reply packet"));
7104 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
7105 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7106 s->hostkeydata, s->hostkeylen);
7110 int publicPointLength;
7111 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
7113 ssh_ecdhkex_freekey(s->eckey);
7114 bombout(("Unable to encode public key for ECDH hash"));
7117 hash_string(ssh->kex->hash, ssh->exhash,
7118 publicPoint, publicPointLength);
7125 ssh_pkt_getstring(pktin, &keydata, &keylen);
7127 bombout(("unable to parse ECDH reply packet"));
7130 hash_string(ssh->kex->hash, ssh->exhash, keydata, keylen);
7131 s->K = ssh_ecdhkex_getkey(s->eckey, keydata, keylen);
7133 ssh_ecdhkex_freekey(s->eckey);
7134 bombout(("point received in ECDH was not valid"));
7139 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7141 bombout(("unable to parse key exchange reply packet"));
7145 ssh_ecdhkex_freekey(s->eckey);
7147 logeventf(ssh, "Doing RSA key exchange with hash %s",
7148 ssh->kex->hash->text_name);
7149 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
7151 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
7154 crWaitUntilV(pktin);
7155 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
7156 bombout(("expected RSA public key packet from server"));
7160 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7161 if (!s->hostkeydata) {
7162 bombout(("unable to parse RSA public key packet"));
7165 hash_string(ssh->kex->hash, ssh->exhash,
7166 s->hostkeydata, s->hostkeylen);
7167 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7168 s->hostkeydata, s->hostkeylen);
7172 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
7174 bombout(("unable to parse RSA public key packet"));
7177 s->rsakeydata = snewn(s->rsakeylen, char);
7178 memcpy(s->rsakeydata, keydata, s->rsakeylen);
7181 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
7183 sfree(s->rsakeydata);
7184 bombout(("unable to parse RSA public key from server"));
7188 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
7191 * Next, set up a shared secret K, of precisely KLEN -
7192 * 2*HLEN - 49 bits, where KLEN is the bit length of the
7193 * RSA key modulus and HLEN is the bit length of the hash
7197 int klen = ssh_rsakex_klen(s->rsakey);
7198 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
7200 unsigned char *kstr1, *kstr2, *outstr;
7201 int kstr1len, kstr2len, outstrlen;
7203 s->K = bn_power_2(nbits - 1);
7205 for (i = 0; i < nbits; i++) {
7207 byte = random_byte();
7209 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
7213 * Encode this as an mpint.
7215 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
7216 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
7217 PUT_32BIT(kstr2, kstr1len);
7218 memcpy(kstr2 + 4, kstr1, kstr1len);
7221 * Encrypt it with the given RSA key.
7223 outstrlen = (klen + 7) / 8;
7224 outstr = snewn(outstrlen, unsigned char);
7225 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
7226 outstr, outstrlen, s->rsakey);
7229 * And send it off in a return packet.
7231 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
7232 ssh2_pkt_addstring_start(s->pktout);
7233 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
7234 ssh2_pkt_send_noqueue(ssh, s->pktout);
7236 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
7243 ssh_rsakex_freekey(s->rsakey);
7245 crWaitUntilV(pktin);
7246 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
7247 sfree(s->rsakeydata);
7248 bombout(("expected signature packet from server"));
7252 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7254 bombout(("unable to parse signature packet"));
7258 sfree(s->rsakeydata);
7261 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
7262 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
7263 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
7265 ssh->kex_ctx = NULL;
7268 debug(("Exchange hash is:\n"));
7269 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
7273 bombout(("Server's host key is invalid"));
7277 if (!ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
7278 (char *)s->exchange_hash,
7279 ssh->kex->hash->hlen)) {
7281 bombout(("Server's host key did not match the signature supplied"));
7286 s->keystr = ssh->hostkey->fmtkey(s->hkey);
7287 if (!s->got_session_id) {
7289 * Make a note of any other host key formats that are available.
7292 int i, j, nkeys = 0;
7294 for (i = 0; i < lenof(hostkey_algs); i++) {
7295 if (hostkey_algs[i].alg == ssh->hostkey)
7298 for (j = 0; j < ssh->n_uncert_hostkeys; j++)
7299 if (ssh->uncert_hostkeys[j] == i)
7302 if (j < ssh->n_uncert_hostkeys) {
7305 newlist = dupprintf("%s/%s", list,
7306 hostkey_algs[i].alg->name);
7308 newlist = dupprintf("%s", hostkey_algs[i].alg->name);
7316 "Server also has %s host key%s, but we "
7317 "don't know %s", list,
7318 nkeys > 1 ? "s" : "",
7319 nkeys > 1 ? "any of them" : "it");
7325 * Authenticate remote host: verify host key. (We've already
7326 * checked the signature of the exchange hash.)
7328 s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
7329 logevent("Host key fingerprint is:");
7330 logevent(s->fingerprint);
7331 /* First check against manually configured host keys. */
7332 s->dlgret = verify_ssh_manual_host_key(ssh, s->fingerprint,
7333 ssh->hostkey, s->hkey);
7334 if (s->dlgret == 0) { /* did not match */
7335 bombout(("Host key did not appear in manually configured list"));
7337 } else if (s->dlgret < 0) { /* none configured; use standard handling */
7338 ssh_set_frozen(ssh, 1);
7339 s->dlgret = verify_ssh_host_key(ssh->frontend,
7340 ssh->savedhost, ssh->savedport,
7341 ssh->hostkey->keytype, s->keystr,
7343 ssh_dialog_callback, ssh);
7347 if (s->dlgret < 0) {
7351 bombout(("Unexpected data from server while waiting"
7352 " for user host key response"));
7355 } while (pktin || inlen > 0);
7356 s->dlgret = ssh->user_response;
7358 ssh_set_frozen(ssh, 0);
7359 if (s->dlgret == 0) {
7360 ssh_disconnect(ssh, "Aborted at host key verification", NULL,
7365 sfree(s->fingerprint);
7367 * Save this host key, to check against the one presented in
7368 * subsequent rekeys.
7370 ssh->hostkey_str = s->keystr;
7371 } else if (ssh->cross_certifying) {
7372 s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
7373 logevent("Storing additional host key for this host:");
7374 logevent(s->fingerprint);
7375 store_host_key(ssh->savedhost, ssh->savedport,
7376 ssh->hostkey->keytype, s->keystr);
7377 ssh->cross_certifying = FALSE;
7379 * Don't forget to store the new key as the one we'll be
7380 * re-checking in future normal rekeys.
7382 ssh->hostkey_str = s->keystr;
7385 * In a rekey, we never present an interactive host key
7386 * verification request to the user. Instead, we simply
7387 * enforce that the key we're seeing this time is identical to
7388 * the one we saw before.
7390 if (strcmp(ssh->hostkey_str, s->keystr)) {
7392 bombout(("Host key was different in repeat key exchange"));
7398 ssh->hostkey->freekey(s->hkey);
7401 * The exchange hash from the very first key exchange is also
7402 * the session id, used in session key construction and
7405 if (!s->got_session_id) {
7406 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
7407 memcpy(ssh->v2_session_id, s->exchange_hash,
7408 sizeof(s->exchange_hash));
7409 ssh->v2_session_id_len = ssh->kex->hash->hlen;
7410 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
7411 s->got_session_id = TRUE;
7415 * Send SSH2_MSG_NEWKEYS.
7417 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
7418 ssh2_pkt_send_noqueue(ssh, s->pktout);
7419 ssh->outgoing_data_size = 0; /* start counting from here */
7422 * We've sent client NEWKEYS, so create and initialise
7423 * client-to-server session keys.
7425 if (ssh->cs_cipher_ctx)
7426 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
7427 ssh->cscipher = s->cscipher_tobe;
7428 if (ssh->cscipher) ssh->cs_cipher_ctx = ssh->cscipher->make_context();
7430 if (ssh->cs_mac_ctx)
7431 ssh->csmac->free_context(ssh->cs_mac_ctx);
7432 ssh->csmac = s->csmac_tobe;
7433 ssh->csmac_etm = s->csmac_etm_tobe;
7435 ssh->cs_mac_ctx = ssh->csmac->make_context(ssh->cs_cipher_ctx);
7437 if (ssh->cs_comp_ctx)
7438 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
7439 ssh->cscomp = s->cscomp_tobe;
7440 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
7443 * Set IVs on client-to-server keys. Here we use the exchange
7444 * hash from the _first_ key exchange.
7446 if (ssh->cscipher) {
7449 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'C',
7450 ssh->cscipher->padded_keybytes);
7451 ssh->cscipher->setkey(ssh->cs_cipher_ctx, key);
7452 smemclr(key, ssh->cscipher->padded_keybytes);
7455 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'A',
7456 ssh->cscipher->blksize);
7457 ssh->cscipher->setiv(ssh->cs_cipher_ctx, key);
7458 smemclr(key, ssh->cscipher->blksize);
7464 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'E',
7465 ssh->csmac->keylen);
7466 ssh->csmac->setkey(ssh->cs_mac_ctx, key);
7467 smemclr(key, ssh->csmac->keylen);
7472 logeventf(ssh, "Initialised %.200s client->server encryption",
7473 ssh->cscipher->text_name);
7475 logeventf(ssh, "Initialised %.200s client->server MAC algorithm%s%s",
7476 ssh->csmac->text_name,
7477 ssh->csmac_etm ? " (in ETM mode)" : "",
7478 ssh->cscipher->required_mac ? " (required by cipher)" : "");
7479 if (ssh->cscomp->text_name)
7480 logeventf(ssh, "Initialised %s compression",
7481 ssh->cscomp->text_name);
7484 * Now our end of the key exchange is complete, we can send all
7485 * our queued higher-layer packets.
7487 ssh->queueing = FALSE;
7488 ssh2_pkt_queuesend(ssh);
7491 * Expect SSH2_MSG_NEWKEYS from server.
7493 crWaitUntilV(pktin);
7494 if (pktin->type != SSH2_MSG_NEWKEYS) {
7495 bombout(("expected new-keys packet from server"));
7498 ssh->incoming_data_size = 0; /* start counting from here */
7501 * We've seen server NEWKEYS, so create and initialise
7502 * server-to-client session keys.
7504 if (ssh->sc_cipher_ctx)
7505 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
7506 if (s->sccipher_tobe) {
7507 ssh->sccipher = s->sccipher_tobe;
7508 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
7511 if (ssh->sc_mac_ctx)
7512 ssh->scmac->free_context(ssh->sc_mac_ctx);
7513 if (s->scmac_tobe) {
7514 ssh->scmac = s->scmac_tobe;
7515 ssh->scmac_etm = s->scmac_etm_tobe;
7516 ssh->sc_mac_ctx = ssh->scmac->make_context(ssh->sc_cipher_ctx);
7519 if (ssh->sc_comp_ctx)
7520 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
7521 ssh->sccomp = s->sccomp_tobe;
7522 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
7525 * Set IVs on server-to-client keys. Here we use the exchange
7526 * hash from the _first_ key exchange.
7528 if (ssh->sccipher) {
7531 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'D',
7532 ssh->sccipher->padded_keybytes);
7533 ssh->sccipher->setkey(ssh->sc_cipher_ctx, key);
7534 smemclr(key, ssh->sccipher->padded_keybytes);
7537 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'B',
7538 ssh->sccipher->blksize);
7539 ssh->sccipher->setiv(ssh->sc_cipher_ctx, key);
7540 smemclr(key, ssh->sccipher->blksize);
7546 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'F',
7547 ssh->scmac->keylen);
7548 ssh->scmac->setkey(ssh->sc_mac_ctx, key);
7549 smemclr(key, ssh->scmac->keylen);
7553 logeventf(ssh, "Initialised %.200s server->client encryption",
7554 ssh->sccipher->text_name);
7556 logeventf(ssh, "Initialised %.200s server->client MAC algorithm%s%s",
7557 ssh->scmac->text_name,
7558 ssh->scmac_etm ? " (in ETM mode)" : "",
7559 ssh->sccipher->required_mac ? " (required by cipher)" : "");
7560 if (ssh->sccomp->text_name)
7561 logeventf(ssh, "Initialised %s decompression",
7562 ssh->sccomp->text_name);
7565 * Free shared secret.
7570 * Update the specials menu to list the remaining uncertified host
7573 update_specials_menu(ssh->frontend);
7576 * Key exchange is over. Loop straight back round if we have a
7577 * deferred rekey reason.
7579 if (ssh->deferred_rekey_reason) {
7580 logevent(ssh->deferred_rekey_reason);
7582 ssh->deferred_rekey_reason = NULL;
7583 goto begin_key_exchange;
7587 * Otherwise, schedule a timer for our next rekey.
7589 ssh->kex_in_progress = FALSE;
7590 ssh->last_rekey = GETTICKCOUNT();
7591 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
7592 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7596 * Now we're encrypting. Begin returning 1 to the protocol main
7597 * function so that other things can run on top of the
7598 * transport. If we ever see a KEXINIT, we must go back to the
7601 * We _also_ go back to the start if we see pktin==NULL and
7602 * inlen negative, because this is a special signal meaning
7603 * `initiate client-driven rekey', and `in' contains a message
7604 * giving the reason for the rekey.
7606 * inlen==-1 means always initiate a rekey;
7607 * inlen==-2 means that userauth has completed successfully and
7608 * we should consider rekeying (for delayed compression).
7610 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
7611 (!pktin && inlen < 0))) {
7613 if (!ssh->protocol_initial_phase_done) {
7614 ssh->protocol_initial_phase_done = TRUE;
7616 * Allow authconn to initialise itself.
7618 do_ssh2_authconn(ssh, NULL, 0, NULL);
7623 logevent("Server initiated key re-exchange");
7627 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
7628 * delayed compression, if it's available.
7630 * draft-miller-secsh-compression-delayed-00 says that you
7631 * negotiate delayed compression in the first key exchange, and
7632 * both sides start compressing when the server has sent
7633 * USERAUTH_SUCCESS. This has a race condition -- the server
7634 * can't know when the client has seen it, and thus which incoming
7635 * packets it should treat as compressed.
7637 * Instead, we do the initial key exchange without offering the
7638 * delayed methods, but note if the server offers them; when we
7639 * get here, if a delayed method was available that was higher
7640 * on our list than what we got, we initiate a rekey in which we
7641 * _do_ list the delayed methods (and hopefully get it as a
7642 * result). Subsequent rekeys will do the same.
7644 assert(!s->userauth_succeeded); /* should only happen once */
7645 s->userauth_succeeded = TRUE;
7646 if (!s->pending_compression)
7647 /* Can't see any point rekeying. */
7648 goto wait_for_rekey; /* this is utterly horrid */
7649 /* else fall through to rekey... */
7650 s->pending_compression = FALSE;
7653 * Now we've decided to rekey.
7655 * Special case: if the server bug is set that doesn't
7656 * allow rekeying, we give a different log message and
7657 * continue waiting. (If such a server _initiates_ a rekey,
7658 * we process it anyway!)
7660 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
7661 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
7663 /* Reset the counters, so that at least this message doesn't
7664 * hit the event log _too_ often. */
7665 ssh->outgoing_data_size = 0;
7666 ssh->incoming_data_size = 0;
7667 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
7669 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7672 goto wait_for_rekey; /* this is still utterly horrid */
7674 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
7677 goto begin_key_exchange;
7683 * Send data on an SSH channel. In SSH-2, this involves buffering it
7686 static int ssh_send_channel_data(struct ssh_channel *c, const char *buf,
7689 if (c->ssh->version == 2) {
7690 bufchain_add(&c->v.v2.outbuffer, buf, len);
7691 return ssh2_try_send(c);
7693 send_packet(c->ssh, SSH1_MSG_CHANNEL_DATA,
7694 PKT_INT, c->remoteid,
7699 * In SSH-1 we can return 0 here - implying that channels are
7700 * never individually throttled - because the only
7701 * circumstance that can cause throttling will be the whole
7702 * SSH connection backing up, in which case _everything_ will
7703 * be throttled as a whole.
7710 * Attempt to send data on an SSH-2 channel.
7712 static int ssh2_try_send(struct ssh_channel *c)
7715 struct Packet *pktout;
7718 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
7721 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
7722 if ((unsigned)len > c->v.v2.remwindow)
7723 len = c->v.v2.remwindow;
7724 if ((unsigned)len > c->v.v2.remmaxpkt)
7725 len = c->v.v2.remmaxpkt;
7726 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
7727 ssh2_pkt_adduint32(pktout, c->remoteid);
7728 ssh2_pkt_addstring_start(pktout);
7729 ssh2_pkt_addstring_data(pktout, data, len);
7730 ssh2_pkt_send(ssh, pktout);
7731 bufchain_consume(&c->v.v2.outbuffer, len);
7732 c->v.v2.remwindow -= len;
7736 * After having sent as much data as we can, return the amount
7739 ret = bufchain_size(&c->v.v2.outbuffer);
7742 * And if there's no data pending but we need to send an EOF, send
7745 if (!ret && c->pending_eof)
7746 ssh_channel_try_eof(c);
7751 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
7754 if (c->closes & CLOSES_SENT_EOF)
7755 return; /* don't send on channels we've EOFed */
7756 bufsize = ssh2_try_send(c);
7759 case CHAN_MAINSESSION:
7760 /* stdin need not receive an unthrottle
7761 * notification since it will be polled */
7764 x11_unthrottle(c->u.x11.xconn);
7767 /* agent sockets are request/response and need no
7768 * buffer management */
7771 pfd_unthrottle(c->u.pfd.pf);
7777 static int ssh_is_simple(Ssh ssh)
7780 * We use the 'simple' variant of the SSH protocol if we're asked
7781 * to, except not if we're also doing connection-sharing (either
7782 * tunnelling our packets over an upstream or expecting to be
7783 * tunnelled over ourselves), since then the assumption that we
7784 * have only one channel to worry about is not true after all.
7786 return (conf_get_int(ssh->conf, CONF_ssh_simple) &&
7787 !ssh->bare_connection && !ssh->connshare);
7791 * Set up most of a new ssh_channel for SSH-2.
7793 static void ssh2_channel_init(struct ssh_channel *c)
7796 c->localid = alloc_channel_id(ssh);
7798 c->pending_eof = FALSE;
7799 c->throttling_conn = FALSE;
7800 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
7801 ssh_is_simple(ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
7802 c->v.v2.chanreq_head = NULL;
7803 c->v.v2.throttle_state = UNTHROTTLED;
7804 bufchain_init(&c->v.v2.outbuffer);
7808 * Construct the common parts of a CHANNEL_OPEN.
7810 static struct Packet *ssh2_chanopen_init(struct ssh_channel *c,
7813 struct Packet *pktout;
7815 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7816 ssh2_pkt_addstring(pktout, type);
7817 ssh2_pkt_adduint32(pktout, c->localid);
7818 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
7819 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7824 * CHANNEL_FAILURE doesn't come with any indication of what message
7825 * caused it, so we have to keep track of the outstanding
7826 * CHANNEL_REQUESTs ourselves.
7828 static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
7829 cchandler_fn_t handler, void *ctx)
7831 struct outstanding_channel_request *ocr =
7832 snew(struct outstanding_channel_request);
7834 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7835 ocr->handler = handler;
7838 if (!c->v.v2.chanreq_head)
7839 c->v.v2.chanreq_head = ocr;
7841 c->v.v2.chanreq_tail->next = ocr;
7842 c->v.v2.chanreq_tail = ocr;
7846 * Construct the common parts of a CHANNEL_REQUEST. If handler is not
7847 * NULL then a reply will be requested and the handler will be called
7848 * when it arrives. The returned packet is ready to have any
7849 * request-specific data added and be sent. Note that if a handler is
7850 * provided, it's essential that the request actually be sent.
7852 * The handler will usually be passed the response packet in pktin. If
7853 * pktin is NULL, this means that no reply will ever be forthcoming
7854 * (e.g. because the entire connection is being destroyed, or because
7855 * the server initiated channel closure before we saw the response)
7856 * and the handler should free any storage it's holding.
7858 static struct Packet *ssh2_chanreq_init(struct ssh_channel *c,
7860 cchandler_fn_t handler, void *ctx)
7862 struct Packet *pktout;
7864 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7865 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7866 ssh2_pkt_adduint32(pktout, c->remoteid);
7867 ssh2_pkt_addstring(pktout, type);
7868 ssh2_pkt_addbool(pktout, handler != NULL);
7869 if (handler != NULL)
7870 ssh2_queue_chanreq_handler(c, handler, ctx);
7874 static void ssh_channel_unthrottle(struct ssh_channel *c, int bufsize)
7879 if (ssh->version == 1) {
7880 buflimit = SSH1_BUFFER_LIMIT;
7882 if (ssh_is_simple(ssh))
7885 buflimit = c->v.v2.locmaxwin;
7886 if (bufsize < buflimit)
7887 ssh2_set_window(c, buflimit - bufsize);
7889 if (c->throttling_conn && bufsize <= buflimit) {
7890 c->throttling_conn = 0;
7891 ssh_throttle_conn(ssh, -1);
7896 * Potentially enlarge the window on an SSH-2 channel.
7898 static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
7900 static void ssh2_set_window(struct ssh_channel *c, int newwin)
7905 * Never send WINDOW_ADJUST for a channel that the remote side has
7906 * already sent EOF on; there's no point, since it won't be
7907 * sending any more data anyway. Ditto if _we've_ already sent
7910 if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
7914 * Also, never widen the window for an X11 channel when we're
7915 * still waiting to see its initial auth and may yet hand it off
7918 if (c->type == CHAN_X11 && c->u.x11.initial)
7922 * If the remote end has a habit of ignoring maxpkt, limit the
7923 * window so that it has no choice (assuming it doesn't ignore the
7926 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
7927 newwin = OUR_V2_MAXPKT;
7930 * Only send a WINDOW_ADJUST if there's significantly more window
7931 * available than the other end thinks there is. This saves us
7932 * sending a WINDOW_ADJUST for every character in a shell session.
7934 * "Significant" is arbitrarily defined as half the window size.
7936 if (newwin / 2 >= c->v.v2.locwindow) {
7937 struct Packet *pktout;
7941 * In order to keep track of how much window the client
7942 * actually has available, we'd like it to acknowledge each
7943 * WINDOW_ADJUST. We can't do that directly, so we accompany
7944 * it with a CHANNEL_REQUEST that has to be acknowledged.
7946 * This is only necessary if we're opening the window wide.
7947 * If we're not, then throughput is being constrained by
7948 * something other than the maximum window size anyway.
7950 if (newwin == c->v.v2.locmaxwin &&
7951 !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
7952 up = snew(unsigned);
7953 *up = newwin - c->v.v2.locwindow;
7954 pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org",
7955 ssh2_handle_winadj_response, up);
7956 ssh2_pkt_send(ssh, pktout);
7958 if (c->v.v2.throttle_state != UNTHROTTLED)
7959 c->v.v2.throttle_state = UNTHROTTLING;
7961 /* Pretend the WINDOW_ADJUST was acked immediately. */
7962 c->v.v2.remlocwin = newwin;
7963 c->v.v2.throttle_state = THROTTLED;
7965 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
7966 ssh2_pkt_adduint32(pktout, c->remoteid);
7967 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
7968 ssh2_pkt_send(ssh, pktout);
7969 c->v.v2.locwindow = newwin;
7974 * Find the channel associated with a message. If there's no channel,
7975 * or it's not properly open, make a noise about it and return NULL.
7977 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
7979 unsigned localid = ssh_pkt_getuint32(pktin);
7980 struct ssh_channel *c;
7982 c = find234(ssh->channels, &localid, ssh_channelfind);
7984 (c->type != CHAN_SHARING && c->halfopen &&
7985 pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
7986 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
7987 char *buf = dupprintf("Received %s for %s channel %u",
7988 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
7990 c ? "half-open" : "nonexistent", localid);
7991 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
7998 static void ssh2_handle_winadj_response(struct ssh_channel *c,
7999 struct Packet *pktin, void *ctx)
8001 unsigned *sizep = ctx;
8004 * Winadj responses should always be failures. However, at least
8005 * one server ("boks_sshd") is known to return SUCCESS for channel
8006 * requests it's never heard of, such as "winadj@putty". Raised
8007 * with foxt.com as bug 090916-090424, but for the sake of a quiet
8008 * life, we don't worry about what kind of response we got.
8011 c->v.v2.remlocwin += *sizep;
8014 * winadj messages are only sent when the window is fully open, so
8015 * if we get an ack of one, we know any pending unthrottle is
8018 if (c->v.v2.throttle_state == UNTHROTTLING)
8019 c->v.v2.throttle_state = UNTHROTTLED;
8022 static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
8024 struct ssh_channel *c = ssh2_channel_msg(ssh, pktin);
8025 struct outstanding_channel_request *ocr;
8028 if (c->type == CHAN_SHARING) {
8029 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8030 pktin->body, pktin->length);
8033 ocr = c->v.v2.chanreq_head;
8035 ssh2_msg_unexpected(ssh, pktin);
8038 ocr->handler(c, pktin, ocr->ctx);
8039 c->v.v2.chanreq_head = ocr->next;
8042 * We may now initiate channel-closing procedures, if that
8043 * CHANNEL_REQUEST was the last thing outstanding before we send
8046 ssh2_channel_check_close(c);
8049 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
8051 struct ssh_channel *c;
8052 c = ssh2_channel_msg(ssh, pktin);
8055 if (c->type == CHAN_SHARING) {
8056 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8057 pktin->body, pktin->length);
8060 if (!(c->closes & CLOSES_SENT_EOF)) {
8061 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
8062 ssh2_try_send_and_unthrottle(ssh, c);
8066 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
8070 struct ssh_channel *c;
8071 c = ssh2_channel_msg(ssh, pktin);
8074 if (c->type == CHAN_SHARING) {
8075 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8076 pktin->body, pktin->length);
8079 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
8080 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
8081 return; /* extended but not stderr */
8082 ssh_pkt_getstring(pktin, &data, &length);
8085 c->v.v2.locwindow -= length;
8086 c->v.v2.remlocwin -= length;
8088 case CHAN_MAINSESSION:
8090 from_backend(ssh->frontend, pktin->type ==
8091 SSH2_MSG_CHANNEL_EXTENDED_DATA,
8095 bufsize = x11_send(c->u.x11.xconn, data, length);
8098 bufsize = pfd_send(c->u.pfd.pf, data, length);
8101 bufsize = ssh_agent_channel_data(c, data, length);
8105 * If it looks like the remote end hit the end of its window,
8106 * and we didn't want it to do that, think about using a
8109 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
8110 c->v.v2.locmaxwin < 0x40000000)
8111 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
8113 * If we are not buffering too much data,
8114 * enlarge the window again at the remote side.
8115 * If we are buffering too much, we may still
8116 * need to adjust the window if the server's
8119 if (bufsize < c->v.v2.locmaxwin)
8120 ssh2_set_window(c, c->v.v2.locmaxwin - bufsize);
8122 * If we're either buffering way too much data, or if we're
8123 * buffering anything at all and we're in "simple" mode,
8124 * throttle the whole channel.
8126 if ((bufsize > c->v.v2.locmaxwin || (ssh_is_simple(ssh) && bufsize>0))
8127 && !c->throttling_conn) {
8128 c->throttling_conn = 1;
8129 ssh_throttle_conn(ssh, +1);
8134 static void ssh_check_termination(Ssh ssh)
8136 if (ssh->version == 2 &&
8137 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
8138 (ssh->channels && count234(ssh->channels) == 0) &&
8139 !(ssh->connshare && share_ndownstreams(ssh->connshare) > 0)) {
8141 * We used to send SSH_MSG_DISCONNECT here, because I'd
8142 * believed that _every_ conforming SSH-2 connection had to
8143 * end with a disconnect being sent by at least one side;
8144 * apparently I was wrong and it's perfectly OK to
8145 * unceremoniously slam the connection shut when you're done,
8146 * and indeed OpenSSH feels this is more polite than sending a
8147 * DISCONNECT. So now we don't.
8149 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
8153 void ssh_sharing_downstream_connected(Ssh ssh, unsigned id,
8154 const char *peerinfo)
8157 logeventf(ssh, "Connection sharing downstream #%u connected from %s",
8160 logeventf(ssh, "Connection sharing downstream #%u connected", id);
8163 void ssh_sharing_downstream_disconnected(Ssh ssh, unsigned id)
8165 logeventf(ssh, "Connection sharing downstream #%u disconnected", id);
8166 ssh_check_termination(ssh);
8169 void ssh_sharing_logf(Ssh ssh, unsigned id, const char *logfmt, ...)
8174 va_start(ap, logfmt);
8175 buf = dupvprintf(logfmt, ap);
8178 logeventf(ssh, "Connection sharing downstream #%u: %s", id, buf);
8180 logeventf(ssh, "Connection sharing: %s", buf);
8184 static void ssh_channel_destroy(struct ssh_channel *c)
8189 case CHAN_MAINSESSION:
8190 ssh->mainchan = NULL;
8191 update_specials_menu(ssh->frontend);
8194 if (c->u.x11.xconn != NULL)
8195 x11_close(c->u.x11.xconn);
8196 logevent("Forwarded X11 connection terminated");
8199 sfree(c->u.a.message);
8202 if (c->u.pfd.pf != NULL)
8203 pfd_close(c->u.pfd.pf);
8204 logevent("Forwarded port closed");
8208 del234(ssh->channels, c);
8209 if (ssh->version == 2) {
8210 bufchain_clear(&c->v.v2.outbuffer);
8211 assert(c->v.v2.chanreq_head == NULL);
8216 * If that was the last channel left open, we might need to
8219 ssh_check_termination(ssh);
8222 static void ssh2_channel_check_close(struct ssh_channel *c)
8225 struct Packet *pktout;
8229 * If we've sent out our own CHANNEL_OPEN but not yet seen
8230 * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
8231 * it's too early to be sending close messages of any kind.
8236 if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
8237 c->type == CHAN_ZOMBIE) &&
8238 !c->v.v2.chanreq_head &&
8239 !(c->closes & CLOSES_SENT_CLOSE)) {
8241 * We have both sent and received EOF (or the channel is a
8242 * zombie), and we have no outstanding channel requests, which
8243 * means the channel is in final wind-up. But we haven't sent
8244 * CLOSE, so let's do so now.
8246 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
8247 ssh2_pkt_adduint32(pktout, c->remoteid);
8248 ssh2_pkt_send(ssh, pktout);
8249 c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
8252 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
8253 assert(c->v.v2.chanreq_head == NULL);
8255 * We have both sent and received CLOSE, which means we're
8256 * completely done with the channel.
8258 ssh_channel_destroy(c);
8262 static void ssh2_channel_got_eof(struct ssh_channel *c)
8264 if (c->closes & CLOSES_RCVD_EOF)
8265 return; /* already seen EOF */
8266 c->closes |= CLOSES_RCVD_EOF;
8268 if (c->type == CHAN_X11) {
8269 x11_send_eof(c->u.x11.xconn);
8270 } else if (c->type == CHAN_AGENT) {
8271 if (c->u.a.outstanding_requests == 0) {
8272 /* Manufacture an outgoing EOF in response to the incoming one. */
8273 sshfwd_write_eof(c);
8275 } else if (c->type == CHAN_SOCKDATA) {
8276 pfd_send_eof(c->u.pfd.pf);
8277 } else if (c->type == CHAN_MAINSESSION) {
8280 if (!ssh->sent_console_eof &&
8281 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
8283 * Either from_backend_eof told us that the front end
8284 * wants us to close the outgoing side of the connection
8285 * as soon as we see EOF from the far end, or else we've
8286 * unilaterally decided to do that because we've allocated
8287 * a remote pty and hence EOF isn't a particularly
8288 * meaningful concept.
8290 sshfwd_write_eof(c);
8292 ssh->sent_console_eof = TRUE;
8295 ssh2_channel_check_close(c);
8298 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
8300 struct ssh_channel *c;
8302 c = ssh2_channel_msg(ssh, pktin);
8305 if (c->type == CHAN_SHARING) {
8306 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8307 pktin->body, pktin->length);
8310 ssh2_channel_got_eof(c);
8313 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
8315 struct ssh_channel *c;
8317 c = ssh2_channel_msg(ssh, pktin);
8320 if (c->type == CHAN_SHARING) {
8321 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8322 pktin->body, pktin->length);
8327 * When we receive CLOSE on a channel, we assume it comes with an
8328 * implied EOF if we haven't seen EOF yet.
8330 ssh2_channel_got_eof(c);
8332 if (!(ssh->remote_bugs & BUG_SENDS_LATE_REQUEST_REPLY)) {
8334 * It also means we stop expecting to see replies to any
8335 * outstanding channel requests, so clean those up too.
8336 * (ssh_chanreq_init will enforce by assertion that we don't
8337 * subsequently put anything back on this list.)
8339 while (c->v.v2.chanreq_head) {
8340 struct outstanding_channel_request *ocr = c->v.v2.chanreq_head;
8341 ocr->handler(c, NULL, ocr->ctx);
8342 c->v.v2.chanreq_head = ocr->next;
8348 * And we also send an outgoing EOF, if we haven't already, on the
8349 * assumption that CLOSE is a pretty forceful announcement that
8350 * the remote side is doing away with the entire channel. (If it
8351 * had wanted to send us EOF and continue receiving data from us,
8352 * it would have just sent CHANNEL_EOF.)
8354 if (!(c->closes & CLOSES_SENT_EOF)) {
8356 * Make sure we don't read any more from whatever our local
8357 * data source is for this channel.
8360 case CHAN_MAINSESSION:
8361 ssh->send_ok = 0; /* stop trying to read from stdin */
8364 x11_override_throttle(c->u.x11.xconn, 1);
8367 pfd_override_throttle(c->u.pfd.pf, 1);
8372 * Abandon any buffered data we still wanted to send to this
8373 * channel. Receiving a CHANNEL_CLOSE is an indication that
8374 * the server really wants to get on and _destroy_ this
8375 * channel, and it isn't going to send us any further
8376 * WINDOW_ADJUSTs to permit us to send pending stuff.
8378 bufchain_clear(&c->v.v2.outbuffer);
8381 * Send outgoing EOF.
8383 sshfwd_write_eof(c);
8387 * Now process the actual close.
8389 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
8390 c->closes |= CLOSES_RCVD_CLOSE;
8391 ssh2_channel_check_close(c);
8395 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
8397 struct ssh_channel *c;
8399 c = ssh2_channel_msg(ssh, pktin);
8402 if (c->type == CHAN_SHARING) {
8403 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8404 pktin->body, pktin->length);
8407 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
8408 c->remoteid = ssh_pkt_getuint32(pktin);
8409 c->halfopen = FALSE;
8410 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8411 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8413 if (c->type == CHAN_SOCKDATA_DORMANT) {
8414 c->type = CHAN_SOCKDATA;
8416 pfd_confirm(c->u.pfd.pf);
8417 } else if (c->type == CHAN_ZOMBIE) {
8419 * This case can occur if a local socket error occurred
8420 * between us sending out CHANNEL_OPEN and receiving
8421 * OPEN_CONFIRMATION. In this case, all we can do is
8422 * immediately initiate close proceedings now that we know the
8423 * server's id to put in the close message.
8425 ssh2_channel_check_close(c);
8428 * We never expect to receive OPEN_CONFIRMATION for any
8429 * *other* channel type (since only local-to-remote port
8430 * forwardings cause us to send CHANNEL_OPEN after the main
8431 * channel is live - all other auxiliary channel types are
8432 * initiated from the server end). It's safe to enforce this
8433 * by assertion rather than by ssh_disconnect, because the
8434 * real point is that we never constructed a half-open channel
8435 * structure in the first place with any type other than the
8438 assert(!"Funny channel type in ssh2_msg_channel_open_confirmation");
8442 ssh_channel_try_eof(c); /* in case we had a pending EOF */
8445 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
8447 static const char *const reasons[] = {
8448 "<unknown reason code>",
8449 "Administratively prohibited",
8451 "Unknown channel type",
8452 "Resource shortage",
8454 unsigned reason_code;
8455 char *reason_string;
8457 struct ssh_channel *c;
8459 c = ssh2_channel_msg(ssh, pktin);
8462 if (c->type == CHAN_SHARING) {
8463 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8464 pktin->body, pktin->length);
8467 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
8469 if (c->type == CHAN_SOCKDATA_DORMANT) {
8470 reason_code = ssh_pkt_getuint32(pktin);
8471 if (reason_code >= lenof(reasons))
8472 reason_code = 0; /* ensure reasons[reason_code] in range */
8473 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
8474 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
8475 reasons[reason_code], reason_length,
8476 NULLTOEMPTY(reason_string));
8478 pfd_close(c->u.pfd.pf);
8479 } else if (c->type == CHAN_ZOMBIE) {
8481 * This case can occur if a local socket error occurred
8482 * between us sending out CHANNEL_OPEN and receiving
8483 * OPEN_FAILURE. In this case, we need do nothing except allow
8484 * the code below to throw the half-open channel away.
8488 * We never expect to receive OPEN_FAILURE for any *other*
8489 * channel type (since only local-to-remote port forwardings
8490 * cause us to send CHANNEL_OPEN after the main channel is
8491 * live - all other auxiliary channel types are initiated from
8492 * the server end). It's safe to enforce this by assertion
8493 * rather than by ssh_disconnect, because the real point is
8494 * that we never constructed a half-open channel structure in
8495 * the first place with any type other than the above.
8497 assert(!"Funny channel type in ssh2_msg_channel_open_failure");
8500 del234(ssh->channels, c);
8504 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
8507 int typelen, want_reply;
8508 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
8509 struct ssh_channel *c;
8510 struct Packet *pktout;
8512 c = ssh2_channel_msg(ssh, pktin);
8515 if (c->type == CHAN_SHARING) {
8516 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8517 pktin->body, pktin->length);
8520 ssh_pkt_getstring(pktin, &type, &typelen);
8521 want_reply = ssh2_pkt_getbool(pktin);
8523 if (c->closes & CLOSES_SENT_CLOSE) {
8525 * We don't reply to channel requests after we've sent
8526 * CHANNEL_CLOSE for the channel, because our reply might
8527 * cross in the network with the other side's CHANNEL_CLOSE
8528 * and arrive after they have wound the channel up completely.
8534 * Having got the channel number, we now look at
8535 * the request type string to see if it's something
8538 if (c == ssh->mainchan) {
8540 * We recognise "exit-status" and "exit-signal" on
8541 * the primary channel.
8543 if (typelen == 11 &&
8544 !memcmp(type, "exit-status", 11)) {
8546 ssh->exitcode = ssh_pkt_getuint32(pktin);
8547 logeventf(ssh, "Server sent command exit status %d",
8549 reply = SSH2_MSG_CHANNEL_SUCCESS;
8551 } else if (typelen == 11 &&
8552 !memcmp(type, "exit-signal", 11)) {
8554 int is_plausible = TRUE, is_int = FALSE;
8555 char *fmt_sig = NULL, *fmt_msg = NULL;
8557 int msglen = 0, core = FALSE;
8558 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
8559 * provide an `int' for the signal, despite its
8560 * having been a `string' in the drafts of RFC 4254 since at
8561 * least 2001. (Fixed in session.c 1.147.) Try to
8562 * infer which we can safely parse it as. */
8564 unsigned char *p = pktin->body +
8566 long len = pktin->length - pktin->savedpos;
8567 unsigned long num = GET_32BIT(p); /* what is it? */
8568 /* If it's 0, it hardly matters; assume string */
8572 int maybe_int = FALSE, maybe_str = FALSE;
8573 #define CHECK_HYPOTHESIS(offset, result) \
8576 int q = toint(offset); \
8577 if (q >= 0 && q+4 <= len) { \
8578 q = toint(q + 4 + GET_32BIT(p+q)); \
8579 if (q >= 0 && q+4 <= len && \
8580 ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
8585 CHECK_HYPOTHESIS(4+1, maybe_int);
8586 CHECK_HYPOTHESIS(4+num+1, maybe_str);
8587 #undef CHECK_HYPOTHESIS
8588 if (maybe_int && !maybe_str)
8590 else if (!maybe_int && maybe_str)
8593 /* Crikey. Either or neither. Panic. */
8594 is_plausible = FALSE;
8597 ssh->exitcode = 128; /* means `unknown signal' */
8600 /* Old non-standard OpenSSH. */
8601 int signum = ssh_pkt_getuint32(pktin);
8602 fmt_sig = dupprintf(" %d", signum);
8603 ssh->exitcode = 128 + signum;
8605 /* As per RFC 4254. */
8608 ssh_pkt_getstring(pktin, &sig, &siglen);
8609 /* Signal name isn't supposed to be blank, but
8610 * let's cope gracefully if it is. */
8612 fmt_sig = dupprintf(" \"%.*s\"",
8617 * Really hideous method of translating the
8618 * signal description back into a locally
8619 * meaningful number.
8624 #define TRANSLATE_SIGNAL(s) \
8625 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
8626 ssh->exitcode = 128 + SIG ## s
8628 TRANSLATE_SIGNAL(ABRT);
8631 TRANSLATE_SIGNAL(ALRM);
8634 TRANSLATE_SIGNAL(FPE);
8637 TRANSLATE_SIGNAL(HUP);
8640 TRANSLATE_SIGNAL(ILL);
8643 TRANSLATE_SIGNAL(INT);
8646 TRANSLATE_SIGNAL(KILL);
8649 TRANSLATE_SIGNAL(PIPE);
8652 TRANSLATE_SIGNAL(QUIT);
8655 TRANSLATE_SIGNAL(SEGV);
8658 TRANSLATE_SIGNAL(TERM);
8661 TRANSLATE_SIGNAL(USR1);
8664 TRANSLATE_SIGNAL(USR2);
8666 #undef TRANSLATE_SIGNAL
8668 ssh->exitcode = 128;
8670 core = ssh2_pkt_getbool(pktin);
8671 ssh_pkt_getstring(pktin, &msg, &msglen);
8673 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
8675 /* ignore lang tag */
8676 } /* else don't attempt to parse */
8677 logeventf(ssh, "Server exited on signal%s%s%s",
8678 fmt_sig ? fmt_sig : "",
8679 core ? " (core dumped)" : "",
8680 fmt_msg ? fmt_msg : "");
8683 reply = SSH2_MSG_CHANNEL_SUCCESS;
8688 * This is a channel request we don't know
8689 * about, so we now either ignore the request
8690 * or respond with CHANNEL_FAILURE, depending
8693 reply = SSH2_MSG_CHANNEL_FAILURE;
8696 pktout = ssh2_pkt_init(reply);
8697 ssh2_pkt_adduint32(pktout, c->remoteid);
8698 ssh2_pkt_send(ssh, pktout);
8702 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
8705 int typelen, want_reply;
8706 struct Packet *pktout;
8708 ssh_pkt_getstring(pktin, &type, &typelen);
8709 want_reply = ssh2_pkt_getbool(pktin);
8712 * We currently don't support any global requests
8713 * at all, so we either ignore the request or
8714 * respond with REQUEST_FAILURE, depending on
8718 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
8719 ssh2_pkt_send(ssh, pktout);
8723 struct X11FakeAuth *ssh_sharing_add_x11_display(Ssh ssh, int authtype,
8727 struct X11FakeAuth *auth;
8730 * Make up a new set of fake X11 auth data, and add it to the tree
8731 * of currently valid ones with an indication of the sharing
8732 * context that it's relevant to.
8734 auth = x11_invent_fake_auth(ssh->x11authtree, authtype);
8735 auth->share_cs = share_cs;
8736 auth->share_chan = share_chan;
8741 void ssh_sharing_remove_x11_display(Ssh ssh, struct X11FakeAuth *auth)
8743 del234(ssh->x11authtree, auth);
8744 x11_free_fake_auth(auth);
8747 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
8754 const char *error = NULL;
8755 struct ssh_channel *c;
8756 unsigned remid, winsize, pktsize;
8757 unsigned our_winsize_override = 0;
8758 struct Packet *pktout;
8760 ssh_pkt_getstring(pktin, &type, &typelen);
8761 c = snew(struct ssh_channel);
8764 remid = ssh_pkt_getuint32(pktin);
8765 winsize = ssh_pkt_getuint32(pktin);
8766 pktsize = ssh_pkt_getuint32(pktin);
8768 if (typelen == 3 && !memcmp(type, "x11", 3)) {
8771 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8772 addrstr = dupprintf("%.*s", peeraddrlen, NULLTOEMPTY(peeraddr));
8773 peerport = ssh_pkt_getuint32(pktin);
8775 logeventf(ssh, "Received X11 connect request from %s:%d",
8778 if (!ssh->X11_fwd_enabled && !ssh->connshare)
8779 error = "X11 forwarding is not enabled";
8781 c->u.x11.xconn = x11_init(ssh->x11authtree, c,
8784 c->u.x11.initial = TRUE;
8787 * If we are a connection-sharing upstream, then we should
8788 * initially present a very small window, adequate to take
8789 * the X11 initial authorisation packet but not much more.
8790 * Downstream will then present us a larger window (by
8791 * fiat of the connection-sharing protocol) and we can
8792 * guarantee to send a positive-valued WINDOW_ADJUST.
8795 our_winsize_override = 128;
8797 logevent("Opened X11 forward channel");
8801 } else if (typelen == 15 &&
8802 !memcmp(type, "forwarded-tcpip", 15)) {
8803 struct ssh_rportfwd pf, *realpf;
8806 ssh_pkt_getstring(pktin, &shost, &shostlen);/* skip address */
8807 pf.shost = dupprintf("%.*s", shostlen, NULLTOEMPTY(shost));
8808 pf.sport = ssh_pkt_getuint32(pktin);
8809 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8810 peerport = ssh_pkt_getuint32(pktin);
8811 realpf = find234(ssh->rportfwds, &pf, NULL);
8812 logeventf(ssh, "Received remote port %s:%d open request "
8813 "from %.*s:%d", pf.shost, pf.sport,
8814 peeraddrlen, NULLTOEMPTY(peeraddr), peerport);
8817 if (realpf == NULL) {
8818 error = "Remote port is not recognised";
8822 if (realpf->share_ctx) {
8824 * This port forwarding is on behalf of a
8825 * connection-sharing downstream, so abandon our own
8826 * channel-open procedure and just pass the message on
8829 share_got_pkt_from_server(realpf->share_ctx, pktin->type,
8830 pktin->body, pktin->length);
8835 err = pfd_connect(&c->u.pfd.pf, realpf->dhost, realpf->dport,
8836 c, ssh->conf, realpf->pfrec->addressfamily);
8837 logeventf(ssh, "Attempting to forward remote port to "
8838 "%s:%d", realpf->dhost, realpf->dport);
8840 logeventf(ssh, "Port open failed: %s", err);
8842 error = "Port open failed";
8844 logevent("Forwarded port opened successfully");
8845 c->type = CHAN_SOCKDATA;
8848 } else if (typelen == 22 &&
8849 !memcmp(type, "auth-agent@openssh.com", 22)) {
8850 if (!ssh->agentfwd_enabled)
8851 error = "Agent forwarding is not enabled";
8853 c->type = CHAN_AGENT; /* identify channel type */
8854 c->u.a.lensofar = 0;
8855 c->u.a.message = NULL;
8856 c->u.a.outstanding_requests = 0;
8859 error = "Unsupported channel type requested";
8862 c->remoteid = remid;
8863 c->halfopen = FALSE;
8865 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
8866 ssh2_pkt_adduint32(pktout, c->remoteid);
8867 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
8868 ssh2_pkt_addstring(pktout, error);
8869 ssh2_pkt_addstring(pktout, "en"); /* language tag */
8870 ssh2_pkt_send(ssh, pktout);
8871 logeventf(ssh, "Rejected channel open: %s", error);
8874 ssh2_channel_init(c);
8875 c->v.v2.remwindow = winsize;
8876 c->v.v2.remmaxpkt = pktsize;
8877 if (our_winsize_override) {
8878 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
8879 our_winsize_override;
8881 add234(ssh->channels, c);
8882 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
8883 ssh2_pkt_adduint32(pktout, c->remoteid);
8884 ssh2_pkt_adduint32(pktout, c->localid);
8885 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
8886 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
8887 ssh2_pkt_send(ssh, pktout);
8891 void sshfwd_x11_sharing_handover(struct ssh_channel *c,
8892 void *share_cs, void *share_chan,
8893 const char *peer_addr, int peer_port,
8894 int endian, int protomajor, int protominor,
8895 const void *initial_data, int initial_len)
8898 * This function is called when we've just discovered that an X
8899 * forwarding channel on which we'd been handling the initial auth
8900 * ourselves turns out to be destined for a connection-sharing
8901 * downstream. So we turn the channel into a CHAN_SHARING, meaning
8902 * that we completely stop tracking windows and buffering data and
8903 * just pass more or less unmodified SSH messages back and forth.
8905 c->type = CHAN_SHARING;
8906 c->u.sharing.ctx = share_cs;
8907 share_setup_x11_channel(share_cs, share_chan,
8908 c->localid, c->remoteid, c->v.v2.remwindow,
8909 c->v.v2.remmaxpkt, c->v.v2.locwindow,
8910 peer_addr, peer_port, endian,
8911 protomajor, protominor,
8912 initial_data, initial_len);
8915 void sshfwd_x11_is_local(struct ssh_channel *c)
8918 * This function is called when we've just discovered that an X
8919 * forwarding channel is _not_ destined for a connection-sharing
8920 * downstream but we're going to handle it ourselves. We stop
8921 * presenting a cautiously small window and go into ordinary data
8924 c->u.x11.initial = FALSE;
8925 ssh2_set_window(c, ssh_is_simple(c->ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE);
8929 * Buffer banner messages for later display at some convenient point,
8930 * if we're going to display them.
8932 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
8934 /* Arbitrary limit to prevent unbounded inflation of buffer */
8935 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
8936 bufchain_size(&ssh->banner) <= 131072) {
8937 char *banner = NULL;
8939 ssh_pkt_getstring(pktin, &banner, &size);
8941 bufchain_add(&ssh->banner, banner, size);
8945 /* Helper function to deal with sending tty modes for "pty-req" */
8946 static void ssh2_send_ttymode(void *data,
8947 const struct ssh_ttymode *mode, char *val)
8949 struct Packet *pktout = (struct Packet *)data;
8950 unsigned int arg = 0;
8952 switch (mode->type) {
8954 arg = ssh_tty_parse_specchar(val);
8957 arg = ssh_tty_parse_boolean(val);
8960 ssh2_pkt_addbyte(pktout, mode->opcode);
8961 ssh2_pkt_adduint32(pktout, arg);
8964 static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
8967 struct ssh2_setup_x11_state {
8971 struct Packet *pktout;
8972 crStateP(ssh2_setup_x11_state, ctx);
8976 logevent("Requesting X11 forwarding");
8977 pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
8979 ssh2_pkt_addbool(pktout, 0); /* many connections */
8980 ssh2_pkt_addstring(pktout, ssh->x11auth->protoname);
8981 ssh2_pkt_addstring(pktout, ssh->x11auth->datastring);
8982 ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
8983 ssh2_pkt_send(ssh, pktout);
8985 /* Wait to be called back with either a response packet, or NULL
8986 * meaning clean up and free our data */
8990 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8991 logevent("X11 forwarding enabled");
8992 ssh->X11_fwd_enabled = TRUE;
8994 logevent("X11 forwarding refused");
9000 static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
9003 struct ssh2_setup_agent_state {
9007 struct Packet *pktout;
9008 crStateP(ssh2_setup_agent_state, ctx);
9012 logevent("Requesting OpenSSH-style agent forwarding");
9013 pktout = ssh2_chanreq_init(ssh->mainchan, "auth-agent-req@openssh.com",
9014 ssh2_setup_agent, s);
9015 ssh2_pkt_send(ssh, pktout);
9017 /* Wait to be called back with either a response packet, or NULL
9018 * meaning clean up and free our data */
9022 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
9023 logevent("Agent forwarding enabled");
9024 ssh->agentfwd_enabled = TRUE;
9026 logevent("Agent forwarding refused");
9032 static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
9035 struct ssh2_setup_pty_state {
9039 struct Packet *pktout;
9040 crStateP(ssh2_setup_pty_state, ctx);
9044 /* Unpick the terminal-speed string. */
9045 /* XXX perhaps we should allow no speeds to be sent. */
9046 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
9047 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
9048 /* Build the pty request. */
9049 pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
9051 ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
9052 ssh2_pkt_adduint32(pktout, ssh->term_width);
9053 ssh2_pkt_adduint32(pktout, ssh->term_height);
9054 ssh2_pkt_adduint32(pktout, 0); /* pixel width */
9055 ssh2_pkt_adduint32(pktout, 0); /* pixel height */
9056 ssh2_pkt_addstring_start(pktout);
9057 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
9058 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
9059 ssh2_pkt_adduint32(pktout, ssh->ispeed);
9060 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
9061 ssh2_pkt_adduint32(pktout, ssh->ospeed);
9062 ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
9063 ssh2_pkt_send(ssh, pktout);
9064 ssh->state = SSH_STATE_INTERMED;
9066 /* Wait to be called back with either a response packet, or NULL
9067 * meaning clean up and free our data */
9071 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
9072 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
9073 ssh->ospeed, ssh->ispeed);
9074 ssh->got_pty = TRUE;
9076 c_write_str(ssh, "Server refused to allocate pty\r\n");
9077 ssh->editing = ssh->echoing = 1;
9084 static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
9087 struct ssh2_setup_env_state {
9089 int num_env, env_left, env_ok;
9092 struct Packet *pktout;
9093 crStateP(ssh2_setup_env_state, ctx);
9098 * Send environment variables.
9100 * Simplest thing here is to send all the requests at once, and
9101 * then wait for a whole bunch of successes or failures.
9107 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
9109 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
9110 pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
9111 ssh2_pkt_addstring(pktout, key);
9112 ssh2_pkt_addstring(pktout, val);
9113 ssh2_pkt_send(ssh, pktout);
9118 logeventf(ssh, "Sent %d environment variables", s->num_env);
9123 s->env_left = s->num_env;
9125 while (s->env_left > 0) {
9126 /* Wait to be called back with either a response packet,
9127 * or NULL meaning clean up and free our data */
9129 if (!pktin) goto out;
9130 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
9135 if (s->env_ok == s->num_env) {
9136 logevent("All environment variables successfully set");
9137 } else if (s->env_ok == 0) {
9138 logevent("All environment variables refused");
9139 c_write_str(ssh, "Server refused to set environment variables\r\n");
9141 logeventf(ssh, "%d environment variables refused",
9142 s->num_env - s->env_ok);
9143 c_write_str(ssh, "Server refused to set all environment variables\r\n");
9151 * Handle the SSH-2 userauth and connection layers.
9153 static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
9155 do_ssh2_authconn(ssh, NULL, 0, pktin);
9158 static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
9162 do_ssh2_authconn(c->ssh, NULL, 0, pktin);
9165 static void do_ssh2_authconn(Ssh ssh, const unsigned char *in, int inlen,
9166 struct Packet *pktin)
9168 struct do_ssh2_authconn_state {
9172 AUTH_TYPE_PUBLICKEY,
9173 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
9174 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
9176 AUTH_TYPE_GSSAPI, /* always QUIET */
9177 AUTH_TYPE_KEYBOARD_INTERACTIVE,
9178 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
9180 int done_service_req;
9181 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
9182 int tried_pubkey_config, done_agent;
9187 int kbd_inter_refused;
9188 int we_are_in, userauth_success;
9189 prompts_t *cur_prompt;
9194 void *publickey_blob;
9195 int publickey_bloblen;
9196 int privatekey_available, privatekey_encrypted;
9197 char *publickey_algorithm;
9198 char *publickey_comment;
9199 unsigned char agent_request[5], *agent_response, *agentp;
9200 int agent_responselen;
9201 unsigned char *pkblob_in_agent;
9203 char *pkblob, *alg, *commentp;
9204 int pklen, alglen, commentlen;
9205 int siglen, retlen, len;
9206 char *q, *agentreq, *ret;
9207 struct Packet *pktout;
9210 struct ssh_gss_library *gsslib;
9211 Ssh_gss_ctx gss_ctx;
9212 Ssh_gss_buf gss_buf;
9213 Ssh_gss_buf gss_rcvtok, gss_sndtok;
9214 Ssh_gss_name gss_srv_name;
9215 Ssh_gss_stat gss_stat;
9218 crState(do_ssh2_authconn_state);
9222 /* Register as a handler for all the messages this coroutine handles. */
9223 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
9224 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
9225 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
9226 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
9227 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
9228 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
9229 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
9230 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
9231 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
9232 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
9233 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
9234 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
9235 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
9236 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
9237 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
9238 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
9239 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
9240 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
9241 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
9242 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
9244 s->done_service_req = FALSE;
9245 s->we_are_in = s->userauth_success = FALSE;
9246 s->agent_response = NULL;
9248 s->tried_gssapi = FALSE;
9251 if (!ssh->bare_connection) {
9252 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
9254 * Request userauth protocol, and await a response to it.
9256 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
9257 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
9258 ssh2_pkt_send(ssh, s->pktout);
9259 crWaitUntilV(pktin);
9260 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
9261 s->done_service_req = TRUE;
9263 if (!s->done_service_req) {
9265 * Request connection protocol directly, without authentication.
9267 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
9268 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9269 ssh2_pkt_send(ssh, s->pktout);
9270 crWaitUntilV(pktin);
9271 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
9272 s->we_are_in = TRUE; /* no auth required */
9274 bombout(("Server refused service request"));
9279 s->we_are_in = TRUE;
9282 /* Arrange to be able to deal with any BANNERs that come in.
9283 * (We do this now as packets may come in during the next bit.) */
9284 bufchain_init(&ssh->banner);
9285 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
9286 ssh2_msg_userauth_banner;
9289 * Misc one-time setup for authentication.
9291 s->publickey_blob = NULL;
9292 if (!s->we_are_in) {
9295 * Load the public half of any configured public key file
9298 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9299 if (!filename_is_null(s->keyfile)) {
9301 logeventf(ssh, "Reading key file \"%.150s\"",
9302 filename_to_str(s->keyfile));
9303 keytype = key_type(s->keyfile);
9304 if (keytype == SSH_KEYTYPE_SSH2 ||
9305 keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 ||
9306 keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
9309 ssh2_userkey_loadpub(s->keyfile,
9310 &s->publickey_algorithm,
9311 &s->publickey_bloblen,
9312 &s->publickey_comment, &error);
9313 if (s->publickey_blob) {
9314 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH2);
9315 if (!s->privatekey_available)
9316 logeventf(ssh, "Key file contains public key only");
9317 s->privatekey_encrypted =
9318 ssh2_userkey_encrypted(s->keyfile, NULL);
9321 logeventf(ssh, "Unable to load key (%s)",
9323 msgbuf = dupprintf("Unable to load key file "
9324 "\"%.150s\" (%s)\r\n",
9325 filename_to_str(s->keyfile),
9327 c_write_str(ssh, msgbuf);
9332 logeventf(ssh, "Unable to use this key file (%s)",
9333 key_type_to_str(keytype));
9334 msgbuf = dupprintf("Unable to use key file \"%.150s\""
9336 filename_to_str(s->keyfile),
9337 key_type_to_str(keytype));
9338 c_write_str(ssh, msgbuf);
9340 s->publickey_blob = NULL;
9345 * Find out about any keys Pageant has (but if there's a
9346 * public key configured, filter out all others).
9349 s->agent_response = NULL;
9350 s->pkblob_in_agent = NULL;
9351 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
9355 logevent("Pageant is running. Requesting keys.");
9357 /* Request the keys held by the agent. */
9358 PUT_32BIT(s->agent_request, 1);
9359 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
9360 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
9361 ssh_agent_callback, ssh)) {
9365 bombout(("Unexpected data from server while"
9366 " waiting for agent response"));
9369 } while (pktin || inlen > 0);
9370 r = ssh->agent_response;
9371 s->agent_responselen = ssh->agent_response_len;
9373 s->agent_response = (unsigned char *) r;
9374 if (s->agent_response && s->agent_responselen >= 5 &&
9375 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
9378 p = s->agent_response + 5;
9379 s->nkeys = toint(GET_32BIT(p));
9382 * Vet the Pageant response to ensure that the key
9383 * count and blob lengths make sense.
9386 logeventf(ssh, "Pageant response contained a negative"
9387 " key count %d", s->nkeys);
9389 goto done_agent_query;
9391 unsigned char *q = p + 4;
9392 int lenleft = s->agent_responselen - 5 - 4;
9394 for (keyi = 0; keyi < s->nkeys; keyi++) {
9395 int bloblen, commentlen;
9397 logeventf(ssh, "Pageant response was truncated");
9399 goto done_agent_query;
9401 bloblen = toint(GET_32BIT(q));
9402 if (bloblen < 0 || bloblen > lenleft) {
9403 logeventf(ssh, "Pageant response was truncated");
9405 goto done_agent_query;
9407 lenleft -= 4 + bloblen;
9409 commentlen = toint(GET_32BIT(q));
9410 if (commentlen < 0 || commentlen > lenleft) {
9411 logeventf(ssh, "Pageant response was truncated");
9413 goto done_agent_query;
9415 lenleft -= 4 + commentlen;
9416 q += 4 + commentlen;
9421 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
9422 if (s->publickey_blob) {
9423 /* See if configured key is in agent. */
9424 for (keyi = 0; keyi < s->nkeys; keyi++) {
9425 s->pklen = toint(GET_32BIT(p));
9426 if (s->pklen == s->publickey_bloblen &&
9427 !memcmp(p+4, s->publickey_blob,
9428 s->publickey_bloblen)) {
9429 logeventf(ssh, "Pageant key #%d matches "
9430 "configured key file", keyi);
9432 s->pkblob_in_agent = p;
9436 p += toint(GET_32BIT(p)) + 4; /* comment */
9438 if (!s->pkblob_in_agent) {
9439 logevent("Configured key file not in Pageant");
9444 logevent("Failed to get reply from Pageant");
9452 * We repeat this whole loop, including the username prompt,
9453 * until we manage a successful authentication. If the user
9454 * types the wrong _password_, they can be sent back to the
9455 * beginning to try another username, if this is configured on.
9456 * (If they specify a username in the config, they are never
9457 * asked, even if they do give a wrong password.)
9459 * I think this best serves the needs of
9461 * - the people who have no configuration, no keys, and just
9462 * want to try repeated (username,password) pairs until they
9463 * type both correctly
9465 * - people who have keys and configuration but occasionally
9466 * need to fall back to passwords
9468 * - people with a key held in Pageant, who might not have
9469 * logged in to a particular machine before; so they want to
9470 * type a username, and then _either_ their key will be
9471 * accepted, _or_ they will type a password. If they mistype
9472 * the username they will want to be able to get back and
9475 s->got_username = FALSE;
9476 while (!s->we_are_in) {
9480 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
9482 * We got a username last time round this loop, and
9483 * with change_username turned off we don't try to get
9486 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
9487 int ret; /* need not be kept over crReturn */
9488 s->cur_prompt = new_prompts(ssh->frontend);
9489 s->cur_prompt->to_server = TRUE;
9490 s->cur_prompt->name = dupstr("SSH login name");
9491 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
9492 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9495 crWaitUntilV(!pktin);
9496 ret = get_userpass_input(s->cur_prompt, in, inlen);
9501 * get_userpass_input() failed to get a username.
9504 free_prompts(s->cur_prompt);
9505 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
9508 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
9509 free_prompts(s->cur_prompt);
9512 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
9513 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
9514 c_write_str(ssh, stuff);
9518 s->got_username = TRUE;
9521 * Send an authentication request using method "none": (a)
9522 * just in case it succeeds, and (b) so that we know what
9523 * authentication methods we can usefully try next.
9525 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9527 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9528 ssh2_pkt_addstring(s->pktout, ssh->username);
9529 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
9530 ssh2_pkt_addstring(s->pktout, "none"); /* method */
9531 ssh2_pkt_send(ssh, s->pktout);
9532 s->type = AUTH_TYPE_NONE;
9534 s->we_are_in = FALSE;
9536 s->tried_pubkey_config = FALSE;
9537 s->kbd_inter_refused = FALSE;
9539 /* Reset agent request state. */
9540 s->done_agent = FALSE;
9541 if (s->agent_response) {
9542 if (s->pkblob_in_agent) {
9543 s->agentp = s->pkblob_in_agent;
9545 s->agentp = s->agent_response + 5 + 4;
9551 char *methods = NULL;
9555 * Wait for the result of the last authentication request.
9558 crWaitUntilV(pktin);
9560 * Now is a convenient point to spew any banner material
9561 * that we've accumulated. (This should ensure that when
9562 * we exit the auth loop, we haven't any left to deal
9566 int size = bufchain_size(&ssh->banner);
9568 * Don't show the banner if we're operating in
9569 * non-verbose non-interactive mode. (It's probably
9570 * a script, which means nobody will read the
9571 * banner _anyway_, and moreover the printing of
9572 * the banner will screw up processing on the
9573 * output of (say) plink.)
9575 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
9576 char *banner = snewn(size, char);
9577 bufchain_fetch(&ssh->banner, banner, size);
9578 c_write_untrusted(ssh, banner, size);
9581 bufchain_clear(&ssh->banner);
9583 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
9584 logevent("Access granted");
9585 s->we_are_in = s->userauth_success = TRUE;
9589 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
9590 bombout(("Strange packet received during authentication: "
9591 "type %d", pktin->type));
9598 * OK, we're now sitting on a USERAUTH_FAILURE message, so
9599 * we can look at the string in it and know what we can
9600 * helpfully try next.
9602 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
9603 ssh_pkt_getstring(pktin, &methods, &methlen);
9604 if (!ssh2_pkt_getbool(pktin)) {
9606 * We have received an unequivocal Access
9607 * Denied. This can translate to a variety of
9608 * messages, or no message at all.
9610 * For forms of authentication which are attempted
9611 * implicitly, by which I mean without printing
9612 * anything in the window indicating that we're
9613 * trying them, we should never print 'Access
9616 * If we do print a message saying that we're
9617 * attempting some kind of authentication, it's OK
9618 * to print a followup message saying it failed -
9619 * but the message may sometimes be more specific
9620 * than simply 'Access denied'.
9622 * Additionally, if we'd just tried password
9623 * authentication, we should break out of this
9624 * whole loop so as to go back to the username
9625 * prompt (iff we're configured to allow
9626 * username change attempts).
9628 if (s->type == AUTH_TYPE_NONE) {
9630 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
9631 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
9632 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
9633 c_write_str(ssh, "Server refused our key\r\n");
9634 logevent("Server refused our key");
9635 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
9636 /* This _shouldn't_ happen except by a
9637 * protocol bug causing client and server to
9638 * disagree on what is a correct signature. */
9639 c_write_str(ssh, "Server refused public-key signature"
9640 " despite accepting key!\r\n");
9641 logevent("Server refused public-key signature"
9642 " despite accepting key!");
9643 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
9644 /* quiet, so no c_write */
9645 logevent("Server refused keyboard-interactive authentication");
9646 } else if (s->type==AUTH_TYPE_GSSAPI) {
9647 /* always quiet, so no c_write */
9648 /* also, the code down in the GSSAPI block has
9649 * already logged this in the Event Log */
9650 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
9651 logevent("Keyboard-interactive authentication failed");
9652 c_write_str(ssh, "Access denied\r\n");
9654 assert(s->type == AUTH_TYPE_PASSWORD);
9655 logevent("Password authentication failed");
9656 c_write_str(ssh, "Access denied\r\n");
9658 if (conf_get_int(ssh->conf, CONF_change_username)) {
9659 /* XXX perhaps we should allow
9660 * keyboard-interactive to do this too? */
9661 s->we_are_in = FALSE;
9666 c_write_str(ssh, "Further authentication required\r\n");
9667 logevent("Further authentication required");
9671 in_commasep_string("publickey", methods, methlen);
9673 in_commasep_string("password", methods, methlen);
9674 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
9675 in_commasep_string("keyboard-interactive", methods, methlen);
9677 if (conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
9678 in_commasep_string("gssapi-with-mic", methods, methlen)) {
9679 /* Try loading the GSS libraries and see if we
9682 ssh->gsslibs = ssh_gss_setup(ssh->conf);
9683 s->can_gssapi = (ssh->gsslibs->nlibraries > 0);
9685 /* No point in even bothering to try to load the
9686 * GSS libraries, if the user configuration and
9687 * server aren't both prepared to attempt GSSAPI
9688 * auth in the first place. */
9689 s->can_gssapi = FALSE;
9694 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9696 if (s->can_pubkey && !s->done_agent && s->nkeys) {
9699 * Attempt public-key authentication using a key from Pageant.
9702 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9704 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
9706 /* Unpack key from agent response */
9707 s->pklen = toint(GET_32BIT(s->agentp));
9709 s->pkblob = (char *)s->agentp;
9710 s->agentp += s->pklen;
9711 s->alglen = toint(GET_32BIT(s->pkblob));
9712 s->alg = s->pkblob + 4;
9713 s->commentlen = toint(GET_32BIT(s->agentp));
9715 s->commentp = (char *)s->agentp;
9716 s->agentp += s->commentlen;
9717 /* s->agentp now points at next key, if any */
9719 /* See if server will accept it */
9720 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9721 ssh2_pkt_addstring(s->pktout, ssh->username);
9722 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9723 /* service requested */
9724 ssh2_pkt_addstring(s->pktout, "publickey");
9726 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
9727 ssh2_pkt_addstring_start(s->pktout);
9728 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9729 ssh2_pkt_addstring_start(s->pktout);
9730 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9731 ssh2_pkt_send(ssh, s->pktout);
9732 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
9734 crWaitUntilV(pktin);
9735 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9737 /* Offer of key refused. */
9744 if (flags & FLAG_VERBOSE) {
9745 c_write_str(ssh, "Authenticating with "
9747 c_write(ssh, s->commentp, s->commentlen);
9748 c_write_str(ssh, "\" from agent\r\n");
9752 * Server is willing to accept the key.
9753 * Construct a SIGN_REQUEST.
9755 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9756 ssh2_pkt_addstring(s->pktout, ssh->username);
9757 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9758 /* service requested */
9759 ssh2_pkt_addstring(s->pktout, "publickey");
9761 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
9762 ssh2_pkt_addstring_start(s->pktout);
9763 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9764 ssh2_pkt_addstring_start(s->pktout);
9765 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9767 /* Ask agent for signature. */
9768 s->siglen = s->pktout->length - 5 + 4 +
9769 ssh->v2_session_id_len;
9770 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9772 s->len = 1; /* message type */
9773 s->len += 4 + s->pklen; /* key blob */
9774 s->len += 4 + s->siglen; /* data to sign */
9775 s->len += 4; /* flags */
9776 s->agentreq = snewn(4 + s->len, char);
9777 PUT_32BIT(s->agentreq, s->len);
9778 s->q = s->agentreq + 4;
9779 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
9780 PUT_32BIT(s->q, s->pklen);
9782 memcpy(s->q, s->pkblob, s->pklen);
9784 PUT_32BIT(s->q, s->siglen);
9786 /* Now the data to be signed... */
9787 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9788 PUT_32BIT(s->q, ssh->v2_session_id_len);
9791 memcpy(s->q, ssh->v2_session_id,
9792 ssh->v2_session_id_len);
9793 s->q += ssh->v2_session_id_len;
9794 memcpy(s->q, s->pktout->data + 5,
9795 s->pktout->length - 5);
9796 s->q += s->pktout->length - 5;
9797 /* And finally the (zero) flags word. */
9799 if (!agent_query(s->agentreq, s->len + 4,
9801 ssh_agent_callback, ssh)) {
9805 bombout(("Unexpected data from server"
9806 " while waiting for agent"
9810 } while (pktin || inlen > 0);
9811 vret = ssh->agent_response;
9812 s->retlen = ssh->agent_response_len;
9817 if (s->retlen >= 9 &&
9818 s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
9819 GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
9820 logevent("Sending Pageant's response");
9821 ssh2_add_sigblob(ssh, s->pktout,
9822 s->pkblob, s->pklen,
9824 GET_32BIT(s->ret + 5));
9825 ssh2_pkt_send(ssh, s->pktout);
9826 s->type = AUTH_TYPE_PUBLICKEY;
9828 /* FIXME: less drastic response */
9829 bombout(("Pageant failed to answer challenge"));
9835 /* Do we have any keys left to try? */
9836 if (s->pkblob_in_agent) {
9837 s->done_agent = TRUE;
9838 s->tried_pubkey_config = TRUE;
9841 if (s->keyi >= s->nkeys)
9842 s->done_agent = TRUE;
9845 } else if (s->can_pubkey && s->publickey_blob &&
9846 s->privatekey_available && !s->tried_pubkey_config) {
9848 struct ssh2_userkey *key; /* not live over crReturn */
9849 char *passphrase; /* not live over crReturn */
9851 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9853 s->tried_pubkey_config = TRUE;
9856 * Try the public key supplied in the configuration.
9858 * First, offer the public blob to see if the server is
9859 * willing to accept it.
9861 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9862 ssh2_pkt_addstring(s->pktout, ssh->username);
9863 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9864 /* service requested */
9865 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
9866 ssh2_pkt_addbool(s->pktout, FALSE);
9867 /* no signature included */
9868 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
9869 ssh2_pkt_addstring_start(s->pktout);
9870 ssh2_pkt_addstring_data(s->pktout,
9871 (char *)s->publickey_blob,
9872 s->publickey_bloblen);
9873 ssh2_pkt_send(ssh, s->pktout);
9874 logevent("Offered public key");
9876 crWaitUntilV(pktin);
9877 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9878 /* Key refused. Give up. */
9879 s->gotit = TRUE; /* reconsider message next loop */
9880 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
9881 continue; /* process this new message */
9883 logevent("Offer of public key accepted");
9886 * Actually attempt a serious authentication using
9889 if (flags & FLAG_VERBOSE) {
9890 c_write_str(ssh, "Authenticating with public key \"");
9891 c_write_str(ssh, s->publickey_comment);
9892 c_write_str(ssh, "\"\r\n");
9896 const char *error; /* not live over crReturn */
9897 if (s->privatekey_encrypted) {
9899 * Get a passphrase from the user.
9901 int ret; /* need not be kept over crReturn */
9902 s->cur_prompt = new_prompts(ssh->frontend);
9903 s->cur_prompt->to_server = FALSE;
9904 s->cur_prompt->name = dupstr("SSH key passphrase");
9905 add_prompt(s->cur_prompt,
9906 dupprintf("Passphrase for key \"%.100s\": ",
9907 s->publickey_comment),
9909 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9912 crWaitUntilV(!pktin);
9913 ret = get_userpass_input(s->cur_prompt,
9918 /* Failed to get a passphrase. Terminate. */
9919 free_prompts(s->cur_prompt);
9920 ssh_disconnect(ssh, NULL,
9921 "Unable to authenticate",
9922 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9927 dupstr(s->cur_prompt->prompts[0]->result);
9928 free_prompts(s->cur_prompt);
9930 passphrase = NULL; /* no passphrase needed */
9934 * Try decrypting the key.
9936 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9937 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
9939 /* burn the evidence */
9940 smemclr(passphrase, strlen(passphrase));
9943 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
9945 (key == SSH2_WRONG_PASSPHRASE)) {
9946 c_write_str(ssh, "Wrong passphrase\r\n");
9948 /* and loop again */
9950 c_write_str(ssh, "Unable to load private key (");
9951 c_write_str(ssh, error);
9952 c_write_str(ssh, ")\r\n");
9954 break; /* try something else */
9960 unsigned char *pkblob, *sigblob, *sigdata;
9961 int pkblob_len, sigblob_len, sigdata_len;
9965 * We have loaded the private key and the server
9966 * has announced that it's willing to accept it.
9967 * Hallelujah. Generate a signature and send it.
9969 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9970 ssh2_pkt_addstring(s->pktout, ssh->username);
9971 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9972 /* service requested */
9973 ssh2_pkt_addstring(s->pktout, "publickey");
9975 ssh2_pkt_addbool(s->pktout, TRUE);
9976 /* signature follows */
9977 ssh2_pkt_addstring(s->pktout, key->alg->name);
9978 pkblob = key->alg->public_blob(key->data,
9980 ssh2_pkt_addstring_start(s->pktout);
9981 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
9985 * The data to be signed is:
9989 * followed by everything so far placed in the
9992 sigdata_len = s->pktout->length - 5 + 4 +
9993 ssh->v2_session_id_len;
9994 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9996 sigdata = snewn(sigdata_len, unsigned char);
9998 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9999 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
10002 memcpy(sigdata+p, ssh->v2_session_id,
10003 ssh->v2_session_id_len);
10004 p += ssh->v2_session_id_len;
10005 memcpy(sigdata+p, s->pktout->data + 5,
10006 s->pktout->length - 5);
10007 p += s->pktout->length - 5;
10008 assert(p == sigdata_len);
10009 sigblob = key->alg->sign(key->data, (char *)sigdata,
10010 sigdata_len, &sigblob_len);
10011 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
10012 sigblob, sigblob_len);
10017 ssh2_pkt_send(ssh, s->pktout);
10018 logevent("Sent public key signature");
10019 s->type = AUTH_TYPE_PUBLICKEY;
10020 key->alg->freekey(key->data);
10021 sfree(key->comment);
10026 } else if (s->can_gssapi && !s->tried_gssapi) {
10028 /* GSSAPI Authentication */
10030 int micoffset, len;
10033 s->type = AUTH_TYPE_GSSAPI;
10034 s->tried_gssapi = TRUE;
10036 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
10039 * Pick the highest GSS library on the preference
10045 for (i = 0; i < ngsslibs; i++) {
10046 int want_id = conf_get_int_int(ssh->conf,
10047 CONF_ssh_gsslist, i);
10048 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
10049 if (ssh->gsslibs->libraries[j].id == want_id) {
10050 s->gsslib = &ssh->gsslibs->libraries[j];
10051 goto got_gsslib; /* double break */
10056 * We always expect to have found something in
10057 * the above loop: we only came here if there
10058 * was at least one viable GSS library, and the
10059 * preference list should always mention
10060 * everything and only change the order.
10065 if (s->gsslib->gsslogmsg)
10066 logevent(s->gsslib->gsslogmsg);
10068 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
10069 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10070 ssh2_pkt_addstring(s->pktout, ssh->username);
10071 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10072 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
10073 logevent("Attempting GSSAPI authentication");
10075 /* add mechanism info */
10076 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
10078 /* number of GSSAPI mechanisms */
10079 ssh2_pkt_adduint32(s->pktout,1);
10081 /* length of OID + 2 */
10082 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
10083 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
10085 /* length of OID */
10086 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
10088 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
10089 s->gss_buf.length);
10090 ssh2_pkt_send(ssh, s->pktout);
10091 crWaitUntilV(pktin);
10092 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
10093 logevent("GSSAPI authentication request refused");
10097 /* check returned packet ... */
10099 ssh_pkt_getstring(pktin, &data, &len);
10100 s->gss_rcvtok.value = data;
10101 s->gss_rcvtok.length = len;
10102 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
10103 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
10104 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
10105 memcmp((char *)s->gss_rcvtok.value + 2,
10106 s->gss_buf.value,s->gss_buf.length) ) {
10107 logevent("GSSAPI authentication - wrong response from server");
10111 /* now start running */
10112 s->gss_stat = s->gsslib->import_name(s->gsslib,
10115 if (s->gss_stat != SSH_GSS_OK) {
10116 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
10117 logevent("GSSAPI import name failed - Bad service name");
10119 logevent("GSSAPI import name failed");
10123 /* fetch TGT into GSS engine */
10124 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
10126 if (s->gss_stat != SSH_GSS_OK) {
10127 logevent("GSSAPI authentication failed to get credentials");
10128 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10132 /* initial tokens are empty */
10133 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
10134 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
10136 /* now enter the loop */
10138 s->gss_stat = s->gsslib->init_sec_context
10142 conf_get_int(ssh->conf, CONF_gssapifwd),
10146 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
10147 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
10148 logevent("GSSAPI authentication initialisation failed");
10150 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
10151 &s->gss_buf) == SSH_GSS_OK) {
10152 logevent(s->gss_buf.value);
10153 sfree(s->gss_buf.value);
10158 logevent("GSSAPI authentication initialised");
10160 /* Client and server now exchange tokens until GSSAPI
10161 * no longer says CONTINUE_NEEDED */
10163 if (s->gss_sndtok.length != 0) {
10164 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
10165 ssh_pkt_addstring_start(s->pktout);
10166 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
10167 ssh2_pkt_send(ssh, s->pktout);
10168 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
10171 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
10172 crWaitUntilV(pktin);
10173 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
10174 logevent("GSSAPI authentication - bad server response");
10175 s->gss_stat = SSH_GSS_FAILURE;
10178 ssh_pkt_getstring(pktin, &data, &len);
10179 s->gss_rcvtok.value = data;
10180 s->gss_rcvtok.length = len;
10182 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
10184 if (s->gss_stat != SSH_GSS_OK) {
10185 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10186 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
10189 logevent("GSSAPI authentication loop finished OK");
10191 /* Now send the MIC */
10193 s->pktout = ssh2_pkt_init(0);
10194 micoffset = s->pktout->length;
10195 ssh_pkt_addstring_start(s->pktout);
10196 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
10197 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
10198 ssh_pkt_addstring(s->pktout, ssh->username);
10199 ssh_pkt_addstring(s->pktout, "ssh-connection");
10200 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
10202 s->gss_buf.value = (char *)s->pktout->data + micoffset;
10203 s->gss_buf.length = s->pktout->length - micoffset;
10205 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
10206 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
10207 ssh_pkt_addstring_start(s->pktout);
10208 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
10209 ssh2_pkt_send(ssh, s->pktout);
10210 s->gsslib->free_mic(s->gsslib, &mic);
10214 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10215 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
10218 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
10221 * Keyboard-interactive authentication.
10224 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
10226 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
10228 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10229 ssh2_pkt_addstring(s->pktout, ssh->username);
10230 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10231 /* service requested */
10232 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
10234 ssh2_pkt_addstring(s->pktout, ""); /* lang */
10235 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
10236 ssh2_pkt_send(ssh, s->pktout);
10238 logevent("Attempting keyboard-interactive authentication");
10240 crWaitUntilV(pktin);
10241 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
10242 /* Server is not willing to do keyboard-interactive
10243 * at all (or, bizarrely but legally, accepts the
10244 * user without actually issuing any prompts).
10245 * Give up on it entirely. */
10247 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
10248 s->kbd_inter_refused = TRUE; /* don't try it again */
10253 * Loop while the server continues to send INFO_REQUESTs.
10255 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
10257 char *name, *inst, *lang;
10258 int name_len, inst_len, lang_len;
10262 * We've got a fresh USERAUTH_INFO_REQUEST.
10263 * Get the preamble and start building a prompt.
10265 ssh_pkt_getstring(pktin, &name, &name_len);
10266 ssh_pkt_getstring(pktin, &inst, &inst_len);
10267 ssh_pkt_getstring(pktin, &lang, &lang_len);
10268 s->cur_prompt = new_prompts(ssh->frontend);
10269 s->cur_prompt->to_server = TRUE;
10272 * Get any prompt(s) from the packet.
10274 s->num_prompts = ssh_pkt_getuint32(pktin);
10275 for (i = 0; i < s->num_prompts; i++) {
10279 static char noprompt[] =
10280 "<server failed to send prompt>: ";
10282 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10283 echo = ssh2_pkt_getbool(pktin);
10286 prompt_len = lenof(noprompt)-1;
10288 add_prompt(s->cur_prompt,
10289 dupprintf("%.*s", prompt_len, prompt),
10294 /* FIXME: better prefix to distinguish from
10295 * local prompts? */
10296 s->cur_prompt->name =
10297 dupprintf("SSH server: %.*s", name_len, name);
10298 s->cur_prompt->name_reqd = TRUE;
10300 s->cur_prompt->name =
10301 dupstr("SSH server authentication");
10302 s->cur_prompt->name_reqd = FALSE;
10304 /* We add a prefix to try to make it clear that a prompt
10305 * has come from the server.
10306 * FIXME: ugly to print "Using..." in prompt _every_
10307 * time round. Can this be done more subtly? */
10308 /* Special case: for reasons best known to themselves,
10309 * some servers send k-i requests with no prompts and
10310 * nothing to display. Keep quiet in this case. */
10311 if (s->num_prompts || name_len || inst_len) {
10312 s->cur_prompt->instruction =
10313 dupprintf("Using keyboard-interactive authentication.%s%.*s",
10314 inst_len ? "\n" : "", inst_len, inst);
10315 s->cur_prompt->instr_reqd = TRUE;
10317 s->cur_prompt->instr_reqd = FALSE;
10321 * Display any instructions, and get the user's
10325 int ret; /* not live over crReturn */
10326 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10329 crWaitUntilV(!pktin);
10330 ret = get_userpass_input(s->cur_prompt, in, inlen);
10335 * Failed to get responses. Terminate.
10337 free_prompts(s->cur_prompt);
10338 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10339 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10346 * Send the response(s) to the server.
10348 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
10349 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
10350 for (i=0; i < s->num_prompts; i++) {
10351 ssh2_pkt_addstring(s->pktout,
10352 s->cur_prompt->prompts[i]->result);
10354 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10357 * Free the prompts structure from this iteration.
10358 * If there's another, a new one will be allocated
10359 * when we return to the top of this while loop.
10361 free_prompts(s->cur_prompt);
10364 * Get the next packet in case it's another
10367 crWaitUntilV(pktin);
10372 * We should have SUCCESS or FAILURE now.
10376 } else if (s->can_passwd) {
10379 * Plain old password authentication.
10381 int ret; /* not live over crReturn */
10382 int changereq_first_time; /* not live over crReturn */
10384 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
10386 s->cur_prompt = new_prompts(ssh->frontend);
10387 s->cur_prompt->to_server = TRUE;
10388 s->cur_prompt->name = dupstr("SSH password");
10389 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
10394 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10397 crWaitUntilV(!pktin);
10398 ret = get_userpass_input(s->cur_prompt, in, inlen);
10403 * Failed to get responses. Terminate.
10405 free_prompts(s->cur_prompt);
10406 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10407 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10412 * Squirrel away the password. (We may need it later if
10413 * asked to change it.)
10415 s->password = dupstr(s->cur_prompt->prompts[0]->result);
10416 free_prompts(s->cur_prompt);
10419 * Send the password packet.
10421 * We pad out the password packet to 256 bytes to make
10422 * it harder for an attacker to find the length of the
10425 * Anyone using a password longer than 256 bytes
10426 * probably doesn't have much to worry about from
10427 * people who find out how long their password is!
10429 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10430 ssh2_pkt_addstring(s->pktout, ssh->username);
10431 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10432 /* service requested */
10433 ssh2_pkt_addstring(s->pktout, "password");
10434 ssh2_pkt_addbool(s->pktout, FALSE);
10435 ssh2_pkt_addstring(s->pktout, s->password);
10436 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10437 logevent("Sent password");
10438 s->type = AUTH_TYPE_PASSWORD;
10441 * Wait for next packet, in case it's a password change
10444 crWaitUntilV(pktin);
10445 changereq_first_time = TRUE;
10447 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
10450 * We're being asked for a new password
10451 * (perhaps not for the first time).
10452 * Loop until the server accepts it.
10455 int got_new = FALSE; /* not live over crReturn */
10456 char *prompt; /* not live over crReturn */
10457 int prompt_len; /* not live over crReturn */
10461 if (changereq_first_time)
10462 msg = "Server requested password change";
10464 msg = "Server rejected new password";
10466 c_write_str(ssh, msg);
10467 c_write_str(ssh, "\r\n");
10470 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10472 s->cur_prompt = new_prompts(ssh->frontend);
10473 s->cur_prompt->to_server = TRUE;
10474 s->cur_prompt->name = dupstr("New SSH password");
10475 s->cur_prompt->instruction =
10476 dupprintf("%.*s", prompt_len, NULLTOEMPTY(prompt));
10477 s->cur_prompt->instr_reqd = TRUE;
10479 * There's no explicit requirement in the protocol
10480 * for the "old" passwords in the original and
10481 * password-change messages to be the same, and
10482 * apparently some Cisco kit supports password change
10483 * by the user entering a blank password originally
10484 * and the real password subsequently, so,
10485 * reluctantly, we prompt for the old password again.
10487 * (On the other hand, some servers don't even bother
10488 * to check this field.)
10490 add_prompt(s->cur_prompt,
10491 dupstr("Current password (blank for previously entered password): "),
10493 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
10495 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
10499 * Loop until the user manages to enter the same
10504 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10507 crWaitUntilV(!pktin);
10508 ret = get_userpass_input(s->cur_prompt, in, inlen);
10513 * Failed to get responses. Terminate.
10515 /* burn the evidence */
10516 free_prompts(s->cur_prompt);
10517 smemclr(s->password, strlen(s->password));
10518 sfree(s->password);
10519 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10520 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10526 * If the user specified a new original password
10527 * (IYSWIM), overwrite any previously specified
10529 * (A side effect is that the user doesn't have to
10530 * re-enter it if they louse up the new password.)
10532 if (s->cur_prompt->prompts[0]->result[0]) {
10533 smemclr(s->password, strlen(s->password));
10534 /* burn the evidence */
10535 sfree(s->password);
10537 dupstr(s->cur_prompt->prompts[0]->result);
10541 * Check the two new passwords match.
10543 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
10544 s->cur_prompt->prompts[2]->result)
10547 /* They don't. Silly user. */
10548 c_write_str(ssh, "Passwords do not match\r\n");
10553 * Send the new password (along with the old one).
10554 * (see above for padding rationale)
10556 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10557 ssh2_pkt_addstring(s->pktout, ssh->username);
10558 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10559 /* service requested */
10560 ssh2_pkt_addstring(s->pktout, "password");
10561 ssh2_pkt_addbool(s->pktout, TRUE);
10562 ssh2_pkt_addstring(s->pktout, s->password);
10563 ssh2_pkt_addstring(s->pktout,
10564 s->cur_prompt->prompts[1]->result);
10565 free_prompts(s->cur_prompt);
10566 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10567 logevent("Sent new password");
10570 * Now see what the server has to say about it.
10571 * (If it's CHANGEREQ again, it's not happy with the
10574 crWaitUntilV(pktin);
10575 changereq_first_time = FALSE;
10580 * We need to reexamine the current pktin at the top
10581 * of the loop. Either:
10582 * - we weren't asked to change password at all, in
10583 * which case it's a SUCCESS or FAILURE with the
10585 * - we sent a new password, and the server was
10586 * either OK with it (SUCCESS or FAILURE w/partial
10587 * success) or unhappy with the _old_ password
10588 * (FAILURE w/o partial success)
10589 * In any of these cases, we go back to the top of
10590 * the loop and start again.
10595 * We don't need the old password any more, in any
10596 * case. Burn the evidence.
10598 smemclr(s->password, strlen(s->password));
10599 sfree(s->password);
10602 char *str = dupprintf("No supported authentication methods available"
10603 " (server sent: %.*s)",
10606 ssh_disconnect(ssh, str,
10607 "No supported authentication methods available",
10608 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
10618 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
10620 /* Clear up various bits and pieces from authentication. */
10621 if (s->publickey_blob) {
10622 sfree(s->publickey_algorithm);
10623 sfree(s->publickey_blob);
10624 sfree(s->publickey_comment);
10626 if (s->agent_response)
10627 sfree(s->agent_response);
10629 if (s->userauth_success && !ssh->bare_connection) {
10631 * We've just received USERAUTH_SUCCESS, and we haven't sent any
10632 * packets since. Signal the transport layer to consider enacting
10633 * delayed compression.
10635 * (Relying on we_are_in is not sufficient, as
10636 * draft-miller-secsh-compression-delayed is quite clear that it
10637 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
10638 * become set for other reasons.)
10640 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
10643 ssh->channels = newtree234(ssh_channelcmp);
10646 * Set up handlers for some connection protocol messages, so we
10647 * don't have to handle them repeatedly in this coroutine.
10649 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
10650 ssh2_msg_channel_window_adjust;
10651 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
10652 ssh2_msg_global_request;
10655 * Create the main session channel.
10657 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
10658 ssh->mainchan = NULL;
10660 ssh->mainchan = snew(struct ssh_channel);
10661 ssh->mainchan->ssh = ssh;
10662 ssh2_channel_init(ssh->mainchan);
10664 if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
10666 * Just start a direct-tcpip channel and use it as the main
10669 ssh_send_port_open(ssh->mainchan,
10670 conf_get_str(ssh->conf, CONF_ssh_nc_host),
10671 conf_get_int(ssh->conf, CONF_ssh_nc_port),
10673 ssh->ncmode = TRUE;
10675 s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
10676 logevent("Opening session as main channel");
10677 ssh2_pkt_send(ssh, s->pktout);
10678 ssh->ncmode = FALSE;
10680 crWaitUntilV(pktin);
10681 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
10682 bombout(("Server refused to open channel"));
10684 /* FIXME: error data comes back in FAILURE packet */
10686 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
10687 bombout(("Server's channel confirmation cited wrong channel"));
10690 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
10691 ssh->mainchan->halfopen = FALSE;
10692 ssh->mainchan->type = CHAN_MAINSESSION;
10693 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
10694 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
10695 add234(ssh->channels, ssh->mainchan);
10696 update_specials_menu(ssh->frontend);
10697 logevent("Opened main channel");
10701 * Now we have a channel, make dispatch table entries for
10702 * general channel-based messages.
10704 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
10705 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
10706 ssh2_msg_channel_data;
10707 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
10708 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
10709 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
10710 ssh2_msg_channel_open_confirmation;
10711 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
10712 ssh2_msg_channel_open_failure;
10713 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
10714 ssh2_msg_channel_request;
10715 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
10716 ssh2_msg_channel_open;
10717 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
10718 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
10721 * Now the connection protocol is properly up and running, with
10722 * all those dispatch table entries, so it's safe to let
10723 * downstreams start trying to open extra channels through us.
10725 if (ssh->connshare)
10726 share_activate(ssh->connshare, ssh->v_s);
10728 if (ssh->mainchan && ssh_is_simple(ssh)) {
10730 * This message indicates to the server that we promise
10731 * not to try to run any other channel in parallel with
10732 * this one, so it's safe for it to advertise a very large
10733 * window and leave the flow control to TCP.
10735 s->pktout = ssh2_chanreq_init(ssh->mainchan,
10736 "simple@putty.projects.tartarus.org",
10738 ssh2_pkt_send(ssh, s->pktout);
10742 * Enable port forwardings.
10744 ssh_setup_portfwd(ssh, ssh->conf);
10746 if (ssh->mainchan && !ssh->ncmode) {
10748 * Send the CHANNEL_REQUESTS for the main session channel.
10749 * Each one is handled by its own little asynchronous
10753 /* Potentially enable X11 forwarding. */
10754 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
10756 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
10758 if (!ssh->x11disp) {
10759 /* FIXME: return an error message from x11_setup_display */
10760 logevent("X11 forwarding not enabled: unable to"
10761 " initialise X display");
10763 ssh->x11auth = x11_invent_fake_auth
10764 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
10765 ssh->x11auth->disp = ssh->x11disp;
10767 ssh2_setup_x11(ssh->mainchan, NULL, NULL);
10771 /* Potentially enable agent forwarding. */
10772 if (ssh_agent_forwarding_permitted(ssh))
10773 ssh2_setup_agent(ssh->mainchan, NULL, NULL);
10775 /* Now allocate a pty for the session. */
10776 if (!conf_get_int(ssh->conf, CONF_nopty))
10777 ssh2_setup_pty(ssh->mainchan, NULL, NULL);
10779 /* Send environment variables. */
10780 ssh2_setup_env(ssh->mainchan, NULL, NULL);
10783 * Start a shell or a remote command. We may have to attempt
10784 * this twice if the config data has provided a second choice
10791 if (ssh->fallback_cmd) {
10792 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
10793 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
10795 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
10796 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
10800 s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
10801 ssh2_response_authconn, NULL);
10802 ssh2_pkt_addstring(s->pktout, cmd);
10804 s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
10805 ssh2_response_authconn, NULL);
10806 ssh2_pkt_addstring(s->pktout, cmd);
10808 s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
10809 ssh2_response_authconn, NULL);
10811 ssh2_pkt_send(ssh, s->pktout);
10813 crWaitUntilV(pktin);
10815 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
10816 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
10817 bombout(("Unexpected response to shell/command request:"
10818 " packet type %d", pktin->type));
10822 * We failed to start the command. If this is the
10823 * fallback command, we really are finished; if it's
10824 * not, and if the fallback command exists, try falling
10825 * back to it before complaining.
10827 if (!ssh->fallback_cmd &&
10828 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
10829 logevent("Primary command failed; attempting fallback");
10830 ssh->fallback_cmd = TRUE;
10833 bombout(("Server refused to start a shell/command"));
10836 logevent("Started a shell/command");
10841 ssh->editing = ssh->echoing = TRUE;
10844 ssh->state = SSH_STATE_SESSION;
10845 if (ssh->size_needed)
10846 ssh_size(ssh, ssh->term_width, ssh->term_height);
10847 if (ssh->eof_needed)
10848 ssh_special(ssh, TS_EOF);
10854 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
10862 * _All_ the connection-layer packets we expect to
10863 * receive are now handled by the dispatch table.
10864 * Anything that reaches here must be bogus.
10867 bombout(("Strange packet received: type %d", pktin->type));
10869 } else if (ssh->mainchan) {
10871 * We have spare data. Add it to the channel buffer.
10873 ssh_send_channel_data(ssh->mainchan, (char *)in, inlen);
10881 * Handlers for SSH-2 messages that might arrive at any moment.
10883 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
10885 /* log reason code in disconnect message */
10887 int reason, msglen;
10889 reason = ssh_pkt_getuint32(pktin);
10890 ssh_pkt_getstring(pktin, &msg, &msglen);
10892 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
10893 buf = dupprintf("Received disconnect message (%s)",
10894 ssh2_disconnect_reasons[reason]);
10896 buf = dupprintf("Received disconnect message (unknown"
10897 " type %d)", reason);
10901 buf = dupprintf("Disconnection message text: %.*s",
10902 msglen, NULLTOEMPTY(msg));
10904 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
10906 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
10907 ssh2_disconnect_reasons[reason] : "unknown",
10908 msglen, NULLTOEMPTY(msg)));
10912 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
10914 /* log the debug message */
10918 /* XXX maybe we should actually take notice of the return value */
10919 ssh2_pkt_getbool(pktin);
10920 ssh_pkt_getstring(pktin, &msg, &msglen);
10922 logeventf(ssh, "Remote debug message: %.*s", msglen, NULLTOEMPTY(msg));
10925 static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
10927 do_ssh2_transport(ssh, NULL, 0, pktin);
10931 * Called if we receive a packet that isn't allowed by the protocol.
10932 * This only applies to packets whose meaning PuTTY understands.
10933 * Entirely unknown packets are handled below.
10935 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
10937 char *buf = dupprintf("Server protocol violation: unexpected %s packet",
10938 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
10940 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
10944 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
10946 struct Packet *pktout;
10947 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
10948 ssh2_pkt_adduint32(pktout, pktin->sequence);
10950 * UNIMPLEMENTED messages MUST appear in the same order as the
10951 * messages they respond to. Hence, never queue them.
10953 ssh2_pkt_send_noqueue(ssh, pktout);
10957 * Handle the top-level SSH-2 protocol.
10959 static void ssh2_protocol_setup(Ssh ssh)
10964 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10966 for (i = 0; i < 256; i++)
10967 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10970 * Initially, we only accept transport messages (and a few generic
10971 * ones). do_ssh2_authconn will add more when it starts.
10972 * Messages that are understood but not currently acceptable go to
10973 * ssh2_msg_unexpected.
10975 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10976 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
10977 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
10978 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
10979 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
10980 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
10981 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
10982 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
10983 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
10984 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
10985 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
10986 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
10987 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
10988 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
10989 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
10990 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
10991 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
10992 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
10993 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
10994 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10995 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10996 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10997 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10998 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10999 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
11000 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
11001 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
11002 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
11003 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
11004 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
11005 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
11006 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
11007 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
11010 * These messages have a special handler from the start.
11012 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
11013 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
11014 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
11017 static void ssh2_bare_connection_protocol_setup(Ssh ssh)
11022 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
11024 for (i = 0; i < 256; i++)
11025 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
11028 * Initially, we set all ssh-connection messages to 'unexpected';
11029 * do_ssh2_authconn will fill things in properly. We also handle a
11030 * couple of messages from the transport protocol which aren't
11031 * related to key exchange (UNIMPLEMENTED, IGNORE, DEBUG,
11034 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
11035 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
11036 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
11037 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
11038 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
11039 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
11040 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
11041 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
11042 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
11043 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
11044 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
11045 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
11046 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
11047 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
11049 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
11052 * These messages have a special handler from the start.
11054 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
11055 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore;
11056 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
11059 static void ssh2_timer(void *ctx, unsigned long now)
11061 Ssh ssh = (Ssh)ctx;
11063 if (ssh->state == SSH_STATE_CLOSED)
11066 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11067 conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
11068 now == ssh->next_rekey) {
11069 do_ssh2_transport(ssh, "timeout", -1, NULL);
11073 static void ssh2_protocol(Ssh ssh, const void *vin, int inlen,
11074 struct Packet *pktin)
11076 const unsigned char *in = (const unsigned char *)vin;
11077 if (ssh->state == SSH_STATE_CLOSED)
11081 ssh->incoming_data_size += pktin->encrypted_len;
11082 if (!ssh->kex_in_progress &&
11083 ssh->max_data_size != 0 &&
11084 ssh->incoming_data_size > ssh->max_data_size)
11085 do_ssh2_transport(ssh, "too much data received", -1, NULL);
11089 ssh->packet_dispatch[pktin->type](ssh, pktin);
11090 else if (!ssh->protocol_initial_phase_done)
11091 do_ssh2_transport(ssh, in, inlen, pktin);
11093 do_ssh2_authconn(ssh, in, inlen, pktin);
11096 static void ssh2_bare_connection_protocol(Ssh ssh, const void *vin, int inlen,
11097 struct Packet *pktin)
11099 const unsigned char *in = (const unsigned char *)vin;
11100 if (ssh->state == SSH_STATE_CLOSED)
11104 ssh->packet_dispatch[pktin->type](ssh, pktin);
11106 do_ssh2_authconn(ssh, in, inlen, pktin);
11109 static void ssh_cache_conf_values(Ssh ssh)
11111 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
11115 * Called to set up the connection.
11117 * Returns an error message, or NULL on success.
11119 static const char *ssh_init(void *frontend_handle, void **backend_handle,
11121 const char *host, int port, char **realhost,
11122 int nodelay, int keepalive)
11127 ssh = snew(struct ssh_tag);
11128 ssh->conf = conf_copy(conf);
11129 ssh_cache_conf_values(ssh);
11130 ssh->version = 0; /* when not ready yet */
11132 ssh->cipher = NULL;
11133 ssh->v1_cipher_ctx = NULL;
11134 ssh->crcda_ctx = NULL;
11135 ssh->cscipher = NULL;
11136 ssh->cs_cipher_ctx = NULL;
11137 ssh->sccipher = NULL;
11138 ssh->sc_cipher_ctx = NULL;
11140 ssh->cs_mac_ctx = NULL;
11142 ssh->sc_mac_ctx = NULL;
11143 ssh->cscomp = NULL;
11144 ssh->cs_comp_ctx = NULL;
11145 ssh->sccomp = NULL;
11146 ssh->sc_comp_ctx = NULL;
11148 ssh->kex_ctx = NULL;
11149 ssh->hostkey = NULL;
11150 ssh->hostkey_str = NULL;
11151 ssh->exitcode = -1;
11152 ssh->close_expected = FALSE;
11153 ssh->clean_exit = FALSE;
11154 ssh->state = SSH_STATE_PREPACKET;
11155 ssh->size_needed = FALSE;
11156 ssh->eof_needed = FALSE;
11158 ssh->logctx = NULL;
11159 ssh->deferred_send_data = NULL;
11160 ssh->deferred_len = 0;
11161 ssh->deferred_size = 0;
11162 ssh->fallback_cmd = 0;
11163 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
11164 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
11165 ssh->x11disp = NULL;
11166 ssh->x11auth = NULL;
11167 ssh->x11authtree = newtree234(x11_authcmp);
11168 ssh->v1_compressing = FALSE;
11169 ssh->v2_outgoing_sequence = 0;
11170 ssh->ssh1_rdpkt_crstate = 0;
11171 ssh->ssh2_rdpkt_crstate = 0;
11172 ssh->ssh2_bare_rdpkt_crstate = 0;
11173 ssh->ssh_gotdata_crstate = 0;
11174 ssh->do_ssh1_connection_crstate = 0;
11175 ssh->do_ssh_init_state = NULL;
11176 ssh->do_ssh_connection_init_state = NULL;
11177 ssh->do_ssh1_login_state = NULL;
11178 ssh->do_ssh2_transport_state = NULL;
11179 ssh->do_ssh2_authconn_state = NULL;
11182 ssh->mainchan = NULL;
11183 ssh->throttled_all = 0;
11184 ssh->v1_stdout_throttling = 0;
11186 ssh->queuelen = ssh->queuesize = 0;
11187 ssh->queueing = FALSE;
11188 ssh->qhead = ssh->qtail = NULL;
11189 ssh->deferred_rekey_reason = NULL;
11190 bufchain_init(&ssh->queued_incoming_data);
11191 ssh->frozen = FALSE;
11192 ssh->username = NULL;
11193 ssh->sent_console_eof = FALSE;
11194 ssh->got_pty = FALSE;
11195 ssh->bare_connection = FALSE;
11196 ssh->X11_fwd_enabled = FALSE;
11197 ssh->connshare = NULL;
11198 ssh->attempting_connshare = FALSE;
11199 ssh->session_started = FALSE;
11200 ssh->specials = NULL;
11201 ssh->n_uncert_hostkeys = 0;
11202 ssh->cross_certifying = FALSE;
11204 *backend_handle = ssh;
11207 if (crypto_startup() == 0)
11208 return "Microsoft high encryption pack not installed!";
11211 ssh->frontend = frontend_handle;
11212 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
11213 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
11215 ssh->channels = NULL;
11216 ssh->rportfwds = NULL;
11217 ssh->portfwds = NULL;
11222 ssh->conn_throttle_count = 0;
11223 ssh->overall_bufsize = 0;
11224 ssh->fallback_cmd = 0;
11226 ssh->protocol = NULL;
11228 ssh->protocol_initial_phase_done = FALSE;
11230 ssh->pinger = NULL;
11232 ssh->incoming_data_size = ssh->outgoing_data_size =
11233 ssh->deferred_data_size = 0L;
11234 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11235 CONF_ssh_rekey_data));
11236 ssh->kex_in_progress = FALSE;
11239 ssh->gsslibs = NULL;
11242 random_ref(); /* do this now - may be needed by sharing setup code */
11244 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
11253 static void ssh_free(void *handle)
11255 Ssh ssh = (Ssh) handle;
11256 struct ssh_channel *c;
11257 struct ssh_rportfwd *pf;
11258 struct X11FakeAuth *auth;
11260 if (ssh->v1_cipher_ctx)
11261 ssh->cipher->free_context(ssh->v1_cipher_ctx);
11262 if (ssh->cs_cipher_ctx)
11263 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
11264 if (ssh->sc_cipher_ctx)
11265 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
11266 if (ssh->cs_mac_ctx)
11267 ssh->csmac->free_context(ssh->cs_mac_ctx);
11268 if (ssh->sc_mac_ctx)
11269 ssh->scmac->free_context(ssh->sc_mac_ctx);
11270 if (ssh->cs_comp_ctx) {
11272 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
11274 zlib_compress_cleanup(ssh->cs_comp_ctx);
11276 if (ssh->sc_comp_ctx) {
11278 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
11280 zlib_decompress_cleanup(ssh->sc_comp_ctx);
11283 dh_cleanup(ssh->kex_ctx);
11284 sfree(ssh->savedhost);
11286 while (ssh->queuelen-- > 0)
11287 ssh_free_packet(ssh->queue[ssh->queuelen]);
11290 while (ssh->qhead) {
11291 struct queued_handler *qh = ssh->qhead;
11292 ssh->qhead = qh->next;
11295 ssh->qhead = ssh->qtail = NULL;
11297 if (ssh->channels) {
11298 while ((c = delpos234(ssh->channels, 0)) != NULL) {
11301 if (c->u.x11.xconn != NULL)
11302 x11_close(c->u.x11.xconn);
11304 case CHAN_SOCKDATA:
11305 case CHAN_SOCKDATA_DORMANT:
11306 if (c->u.pfd.pf != NULL)
11307 pfd_close(c->u.pfd.pf);
11310 if (ssh->version == 2) {
11311 struct outstanding_channel_request *ocr, *nocr;
11312 ocr = c->v.v2.chanreq_head;
11314 ocr->handler(c, NULL, ocr->ctx);
11319 bufchain_clear(&c->v.v2.outbuffer);
11323 freetree234(ssh->channels);
11324 ssh->channels = NULL;
11327 if (ssh->connshare)
11328 sharestate_free(ssh->connshare);
11330 if (ssh->rportfwds) {
11331 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
11333 freetree234(ssh->rportfwds);
11334 ssh->rportfwds = NULL;
11336 sfree(ssh->deferred_send_data);
11338 x11_free_display(ssh->x11disp);
11339 while ((auth = delpos234(ssh->x11authtree, 0)) != NULL)
11340 x11_free_fake_auth(auth);
11341 freetree234(ssh->x11authtree);
11342 sfree(ssh->do_ssh_init_state);
11343 sfree(ssh->do_ssh1_login_state);
11344 sfree(ssh->do_ssh2_transport_state);
11345 sfree(ssh->do_ssh2_authconn_state);
11348 sfree(ssh->fullhostname);
11349 sfree(ssh->hostkey_str);
11350 sfree(ssh->specials);
11351 if (ssh->crcda_ctx) {
11352 crcda_free_context(ssh->crcda_ctx);
11353 ssh->crcda_ctx = NULL;
11356 ssh_do_close(ssh, TRUE);
11357 expire_timer_context(ssh);
11359 pinger_free(ssh->pinger);
11360 bufchain_clear(&ssh->queued_incoming_data);
11361 sfree(ssh->username);
11362 conf_free(ssh->conf);
11365 ssh_gss_cleanup(ssh->gsslibs);
11373 * Reconfigure the SSH backend.
11375 static void ssh_reconfig(void *handle, Conf *conf)
11377 Ssh ssh = (Ssh) handle;
11378 const char *rekeying = NULL;
11379 int rekey_mandatory = FALSE;
11380 unsigned long old_max_data_size;
11383 pinger_reconfig(ssh->pinger, ssh->conf, conf);
11385 ssh_setup_portfwd(ssh, conf);
11387 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
11388 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
11390 unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
11391 unsigned long now = GETTICKCOUNT();
11393 if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
11394 rekeying = "timeout shortened";
11396 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
11400 old_max_data_size = ssh->max_data_size;
11401 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11402 CONF_ssh_rekey_data));
11403 if (old_max_data_size != ssh->max_data_size &&
11404 ssh->max_data_size != 0) {
11405 if (ssh->outgoing_data_size > ssh->max_data_size ||
11406 ssh->incoming_data_size > ssh->max_data_size)
11407 rekeying = "data limit lowered";
11410 if (conf_get_int(ssh->conf, CONF_compression) !=
11411 conf_get_int(conf, CONF_compression)) {
11412 rekeying = "compression setting changed";
11413 rekey_mandatory = TRUE;
11416 for (i = 0; i < CIPHER_MAX; i++)
11417 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
11418 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
11419 rekeying = "cipher settings changed";
11420 rekey_mandatory = TRUE;
11422 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
11423 conf_get_int(conf, CONF_ssh2_des_cbc)) {
11424 rekeying = "cipher settings changed";
11425 rekey_mandatory = TRUE;
11428 conf_free(ssh->conf);
11429 ssh->conf = conf_copy(conf);
11430 ssh_cache_conf_values(ssh);
11432 if (!ssh->bare_connection && rekeying) {
11433 if (!ssh->kex_in_progress) {
11434 do_ssh2_transport(ssh, rekeying, -1, NULL);
11435 } else if (rekey_mandatory) {
11436 ssh->deferred_rekey_reason = rekeying;
11442 * Called to send data down the SSH connection.
11444 static int ssh_send(void *handle, const char *buf, int len)
11446 Ssh ssh = (Ssh) handle;
11448 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11451 ssh->protocol(ssh, (const unsigned char *)buf, len, 0);
11453 return ssh_sendbuffer(ssh);
11457 * Called to query the current amount of buffered stdin data.
11459 static int ssh_sendbuffer(void *handle)
11461 Ssh ssh = (Ssh) handle;
11462 int override_value;
11464 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11468 * If the SSH socket itself has backed up, add the total backup
11469 * size on that to any individual buffer on the stdin channel.
11471 override_value = 0;
11472 if (ssh->throttled_all)
11473 override_value = ssh->overall_bufsize;
11475 if (ssh->version == 1) {
11476 return override_value;
11477 } else if (ssh->version == 2) {
11478 if (!ssh->mainchan)
11479 return override_value;
11481 return (override_value +
11482 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
11489 * Called to set the size of the window from SSH's POV.
11491 static void ssh_size(void *handle, int width, int height)
11493 Ssh ssh = (Ssh) handle;
11494 struct Packet *pktout;
11496 ssh->term_width = width;
11497 ssh->term_height = height;
11499 switch (ssh->state) {
11500 case SSH_STATE_BEFORE_SIZE:
11501 case SSH_STATE_PREPACKET:
11502 case SSH_STATE_CLOSED:
11503 break; /* do nothing */
11504 case SSH_STATE_INTERMED:
11505 ssh->size_needed = TRUE; /* buffer for later */
11507 case SSH_STATE_SESSION:
11508 if (!conf_get_int(ssh->conf, CONF_nopty)) {
11509 if (ssh->version == 1) {
11510 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
11511 PKT_INT, ssh->term_height,
11512 PKT_INT, ssh->term_width,
11513 PKT_INT, 0, PKT_INT, 0, PKT_END);
11514 } else if (ssh->mainchan) {
11515 pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
11517 ssh2_pkt_adduint32(pktout, ssh->term_width);
11518 ssh2_pkt_adduint32(pktout, ssh->term_height);
11519 ssh2_pkt_adduint32(pktout, 0);
11520 ssh2_pkt_adduint32(pktout, 0);
11521 ssh2_pkt_send(ssh, pktout);
11529 * Return a list of the special codes that make sense in this
11532 static const struct telnet_special *ssh_get_specials(void *handle)
11534 static const struct telnet_special ssh1_ignore_special[] = {
11535 {"IGNORE message", TS_NOP}
11537 static const struct telnet_special ssh2_ignore_special[] = {
11538 {"IGNORE message", TS_NOP},
11540 static const struct telnet_special ssh2_rekey_special[] = {
11541 {"Repeat key exchange", TS_REKEY},
11543 static const struct telnet_special ssh2_session_specials[] = {
11546 /* These are the signal names defined by RFC 4254.
11547 * They include all the ISO C signals, but are a subset of the POSIX
11548 * required signals. */
11549 {"SIGINT (Interrupt)", TS_SIGINT},
11550 {"SIGTERM (Terminate)", TS_SIGTERM},
11551 {"SIGKILL (Kill)", TS_SIGKILL},
11552 {"SIGQUIT (Quit)", TS_SIGQUIT},
11553 {"SIGHUP (Hangup)", TS_SIGHUP},
11554 {"More signals", TS_SUBMENU},
11555 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
11556 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
11557 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
11558 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
11559 {NULL, TS_EXITMENU}
11561 static const struct telnet_special specials_end[] = {
11562 {NULL, TS_EXITMENU}
11565 struct telnet_special *specials = NULL;
11566 int nspecials = 0, specialsize = 0;
11568 Ssh ssh = (Ssh) handle;
11570 sfree(ssh->specials);
11572 #define ADD_SPECIALS(name) do \
11574 int len = lenof(name); \
11575 if (nspecials + len > specialsize) { \
11576 specialsize = (nspecials + len) * 5 / 4 + 32; \
11577 specials = sresize(specials, specialsize, struct telnet_special); \
11579 memcpy(specials+nspecials, name, len*sizeof(struct telnet_special)); \
11580 nspecials += len; \
11583 if (ssh->version == 1) {
11584 /* Don't bother offering IGNORE if we've decided the remote
11585 * won't cope with it, since we wouldn't bother sending it if
11587 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11588 ADD_SPECIALS(ssh1_ignore_special);
11589 } else if (ssh->version == 2) {
11590 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
11591 ADD_SPECIALS(ssh2_ignore_special);
11592 if (!(ssh->remote_bugs & BUG_SSH2_REKEY) && !ssh->bare_connection)
11593 ADD_SPECIALS(ssh2_rekey_special);
11595 ADD_SPECIALS(ssh2_session_specials);
11597 if (ssh->n_uncert_hostkeys) {
11598 static const struct telnet_special uncert_start[] = {
11600 {"Cache new host key type", TS_SUBMENU},
11602 static const struct telnet_special uncert_end[] = {
11603 {NULL, TS_EXITMENU},
11607 ADD_SPECIALS(uncert_start);
11608 for (i = 0; i < ssh->n_uncert_hostkeys; i++) {
11609 struct telnet_special uncert[1];
11610 const struct ssh_signkey *alg =
11611 hostkey_algs[ssh->uncert_hostkeys[i]].alg;
11612 uncert[0].name = alg->name;
11613 uncert[0].code = TS_LOCALSTART + ssh->uncert_hostkeys[i];
11614 ADD_SPECIALS(uncert);
11616 ADD_SPECIALS(uncert_end);
11618 } /* else we're not ready yet */
11621 ADD_SPECIALS(specials_end);
11623 ssh->specials = specials;
11630 #undef ADD_SPECIALS
11634 * Send special codes. TS_EOF is useful for `plink', so you
11635 * can send an EOF and collect resulting output (e.g. `plink
11638 static void ssh_special(void *handle, Telnet_Special code)
11640 Ssh ssh = (Ssh) handle;
11641 struct Packet *pktout;
11643 if (code == TS_EOF) {
11644 if (ssh->state != SSH_STATE_SESSION) {
11646 * Buffer the EOF in case we are pre-SESSION, so we can
11647 * send it as soon as we reach SESSION.
11649 if (code == TS_EOF)
11650 ssh->eof_needed = TRUE;
11653 if (ssh->version == 1) {
11654 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
11655 } else if (ssh->mainchan) {
11656 sshfwd_write_eof(ssh->mainchan);
11657 ssh->send_ok = 0; /* now stop trying to read from stdin */
11659 logevent("Sent EOF message");
11660 } else if (code == TS_PING || code == TS_NOP) {
11661 if (ssh->state == SSH_STATE_CLOSED
11662 || ssh->state == SSH_STATE_PREPACKET) return;
11663 if (ssh->version == 1) {
11664 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11665 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
11667 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
11668 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
11669 ssh2_pkt_addstring_start(pktout);
11670 ssh2_pkt_send_noqueue(ssh, pktout);
11673 } else if (code == TS_REKEY) {
11674 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11675 ssh->version == 2) {
11676 do_ssh2_transport(ssh, "at user request", -1, NULL);
11678 } else if (code >= TS_LOCALSTART) {
11679 ssh->hostkey = hostkey_algs[code - TS_LOCALSTART].alg;
11680 ssh->cross_certifying = TRUE;
11681 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11682 ssh->version == 2) {
11683 do_ssh2_transport(ssh, "cross-certifying new host key", -1, NULL);
11685 } else if (code == TS_BRK) {
11686 if (ssh->state == SSH_STATE_CLOSED
11687 || ssh->state == SSH_STATE_PREPACKET) return;
11688 if (ssh->version == 1) {
11689 logevent("Unable to send BREAK signal in SSH-1");
11690 } else if (ssh->mainchan) {
11691 pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
11692 ssh2_pkt_adduint32(pktout, 0); /* default break length */
11693 ssh2_pkt_send(ssh, pktout);
11696 /* Is is a POSIX signal? */
11697 const char *signame = NULL;
11698 if (code == TS_SIGABRT) signame = "ABRT";
11699 if (code == TS_SIGALRM) signame = "ALRM";
11700 if (code == TS_SIGFPE) signame = "FPE";
11701 if (code == TS_SIGHUP) signame = "HUP";
11702 if (code == TS_SIGILL) signame = "ILL";
11703 if (code == TS_SIGINT) signame = "INT";
11704 if (code == TS_SIGKILL) signame = "KILL";
11705 if (code == TS_SIGPIPE) signame = "PIPE";
11706 if (code == TS_SIGQUIT) signame = "QUIT";
11707 if (code == TS_SIGSEGV) signame = "SEGV";
11708 if (code == TS_SIGTERM) signame = "TERM";
11709 if (code == TS_SIGUSR1) signame = "USR1";
11710 if (code == TS_SIGUSR2) signame = "USR2";
11711 /* The SSH-2 protocol does in principle support arbitrary named
11712 * signals, including signame@domain, but we don't support those. */
11714 /* It's a signal. */
11715 if (ssh->version == 2 && ssh->mainchan) {
11716 pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
11717 ssh2_pkt_addstring(pktout, signame);
11718 ssh2_pkt_send(ssh, pktout);
11719 logeventf(ssh, "Sent signal SIG%s", signame);
11722 /* Never heard of it. Do nothing */
11727 void *new_sock_channel(void *handle, struct PortForwarding *pf)
11729 Ssh ssh = (Ssh) handle;
11730 struct ssh_channel *c;
11731 c = snew(struct ssh_channel);
11734 ssh2_channel_init(c);
11735 c->halfopen = TRUE;
11736 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
11738 add234(ssh->channels, c);
11742 unsigned ssh_alloc_sharing_channel(Ssh ssh, void *sharing_ctx)
11744 struct ssh_channel *c;
11745 c = snew(struct ssh_channel);
11748 ssh2_channel_init(c);
11749 c->type = CHAN_SHARING;
11750 c->u.sharing.ctx = sharing_ctx;
11751 add234(ssh->channels, c);
11755 void ssh_delete_sharing_channel(Ssh ssh, unsigned localid)
11757 struct ssh_channel *c;
11759 c = find234(ssh->channels, &localid, ssh_channelfind);
11761 ssh_channel_destroy(c);
11764 void ssh_send_packet_from_downstream(Ssh ssh, unsigned id, int type,
11765 const void *data, int datalen,
11766 const char *additional_log_text)
11768 struct Packet *pkt;
11770 pkt = ssh2_pkt_init(type);
11771 pkt->downstream_id = id;
11772 pkt->additional_log_text = additional_log_text;
11773 ssh2_pkt_adddata(pkt, data, datalen);
11774 ssh2_pkt_send(ssh, pkt);
11778 * This is called when stdout/stderr (the entity to which
11779 * from_backend sends data) manages to clear some backlog.
11781 static void ssh_unthrottle(void *handle, int bufsize)
11783 Ssh ssh = (Ssh) handle;
11785 if (ssh->version == 1) {
11786 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
11787 ssh->v1_stdout_throttling = 0;
11788 ssh_throttle_conn(ssh, -1);
11792 ssh_channel_unthrottle(ssh->mainchan, bufsize);
11796 * Now process any SSH connection data that was stashed in our
11797 * queue while we were frozen.
11799 ssh_process_queued_incoming_data(ssh);
11802 void ssh_send_port_open(void *channel, const char *hostname, int port,
11805 struct ssh_channel *c = (struct ssh_channel *)channel;
11807 struct Packet *pktout;
11809 logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
11811 if (ssh->version == 1) {
11812 send_packet(ssh, SSH1_MSG_PORT_OPEN,
11813 PKT_INT, c->localid,
11816 /* PKT_STR, <org:orgport>, */
11819 pktout = ssh2_chanopen_init(c, "direct-tcpip");
11821 char *trimmed_host = host_strduptrim(hostname);
11822 ssh2_pkt_addstring(pktout, trimmed_host);
11823 sfree(trimmed_host);
11825 ssh2_pkt_adduint32(pktout, port);
11827 * We make up values for the originator data; partly it's
11828 * too much hassle to keep track, and partly I'm not
11829 * convinced the server should be told details like that
11830 * about my local network configuration.
11831 * The "originator IP address" is syntactically a numeric
11832 * IP address, and some servers (e.g., Tectia) get upset
11833 * if it doesn't match this syntax.
11835 ssh2_pkt_addstring(pktout, "0.0.0.0");
11836 ssh2_pkt_adduint32(pktout, 0);
11837 ssh2_pkt_send(ssh, pktout);
11841 static int ssh_connected(void *handle)
11843 Ssh ssh = (Ssh) handle;
11844 return ssh->s != NULL;
11847 static int ssh_sendok(void *handle)
11849 Ssh ssh = (Ssh) handle;
11850 return ssh->send_ok;
11853 static int ssh_ldisc(void *handle, int option)
11855 Ssh ssh = (Ssh) handle;
11856 if (option == LD_ECHO)
11857 return ssh->echoing;
11858 if (option == LD_EDIT)
11859 return ssh->editing;
11863 static void ssh_provide_ldisc(void *handle, void *ldisc)
11865 Ssh ssh = (Ssh) handle;
11866 ssh->ldisc = ldisc;
11869 static void ssh_provide_logctx(void *handle, void *logctx)
11871 Ssh ssh = (Ssh) handle;
11872 ssh->logctx = logctx;
11875 static int ssh_return_exitcode(void *handle)
11877 Ssh ssh = (Ssh) handle;
11878 if (ssh->s != NULL)
11881 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
11885 * cfg_info for SSH is the protocol running in this session.
11886 * (1 or 2 for the full SSH-1 or SSH-2 protocol; -1 for the bare
11887 * SSH-2 connection protocol, i.e. a downstream; 0 for not-decided-yet.)
11889 static int ssh_cfg_info(void *handle)
11891 Ssh ssh = (Ssh) handle;
11892 if (ssh->version == 0)
11893 return 0; /* don't know yet */
11894 else if (ssh->bare_connection)
11897 return ssh->version;
11901 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
11902 * that fails. This variable is the means by which scp.c can reach
11903 * into the SSH code and find out which one it got.
11905 extern int ssh_fallback_cmd(void *handle)
11907 Ssh ssh = (Ssh) handle;
11908 return ssh->fallback_cmd;
11911 Backend ssh_backend = {
11921 ssh_return_exitcode,
11925 ssh_provide_logctx,
11928 ssh_test_for_upstream,