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 int ssh_channel_data(struct ssh_channel *c, int is_stderr,
5775 char *data, int length)
5778 case CHAN_MAINSESSION:
5779 return from_backend(c->ssh->frontend, is_stderr, data, length);
5781 return x11_send(c->u.x11.xconn, data, length);
5783 return pfd_send(c->u.pfd.pf, data, length);
5785 return ssh_agent_channel_data(c, data, length);
5790 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
5792 /* Data sent down one of our channels. */
5793 int i = ssh_pkt_getuint32(pktin);
5796 struct ssh_channel *c;
5798 ssh_pkt_getstring(pktin, &p, &len);
5800 c = find234(ssh->channels, &i, ssh_channelfind);
5802 int bufsize = ssh_channel_data(c, FALSE, p, len);
5803 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5804 c->throttling_conn = 1;
5805 ssh_throttle_conn(ssh, +1);
5810 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5812 ssh->exitcode = ssh_pkt_getuint32(pktin);
5813 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5814 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5816 * In case `helpful' firewalls or proxies tack
5817 * extra human-readable text on the end of the
5818 * session which we might mistake for another
5819 * encrypted packet, we close the session once
5820 * we've sent EXIT_CONFIRMATION.
5822 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5825 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5826 static void ssh1_send_ttymode(void *data,
5827 const struct ssh_ttymode *mode, char *val)
5829 struct Packet *pktout = (struct Packet *)data;
5830 unsigned int arg = 0;
5832 switch (mode->type) {
5834 arg = ssh_tty_parse_specchar(val);
5837 arg = ssh_tty_parse_boolean(val);
5840 ssh2_pkt_addbyte(pktout, mode->opcode);
5841 ssh2_pkt_addbyte(pktout, arg);
5844 int ssh_agent_forwarding_permitted(Ssh ssh)
5846 return conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists();
5849 static void do_ssh1_connection(Ssh ssh, const unsigned char *in, int inlen,
5850 struct Packet *pktin)
5852 crBegin(ssh->do_ssh1_connection_crstate);
5854 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5855 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5856 ssh1_smsg_stdout_stderr_data;
5858 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5859 ssh1_msg_channel_open_confirmation;
5860 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5861 ssh1_msg_channel_open_failure;
5862 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5863 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5864 ssh1_msg_channel_close;
5865 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5866 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5868 if (ssh_agent_forwarding_permitted(ssh)) {
5869 logevent("Requesting agent forwarding");
5870 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5874 if (pktin->type != SSH1_SMSG_SUCCESS
5875 && pktin->type != SSH1_SMSG_FAILURE) {
5876 bombout(("Protocol confusion"));
5878 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5879 logevent("Agent forwarding refused");
5881 logevent("Agent forwarding enabled");
5882 ssh->agentfwd_enabled = TRUE;
5883 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5887 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
5889 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5891 if (!ssh->x11disp) {
5892 /* FIXME: return an error message from x11_setup_display */
5893 logevent("X11 forwarding not enabled: unable to"
5894 " initialise X display");
5896 ssh->x11auth = x11_invent_fake_auth
5897 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
5898 ssh->x11auth->disp = ssh->x11disp;
5900 logevent("Requesting X11 forwarding");
5901 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5902 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5903 PKT_STR, ssh->x11auth->protoname,
5904 PKT_STR, ssh->x11auth->datastring,
5905 PKT_INT, ssh->x11disp->screennum,
5908 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5909 PKT_STR, ssh->x11auth->protoname,
5910 PKT_STR, ssh->x11auth->datastring,
5916 if (pktin->type != SSH1_SMSG_SUCCESS
5917 && pktin->type != SSH1_SMSG_FAILURE) {
5918 bombout(("Protocol confusion"));
5920 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5921 logevent("X11 forwarding refused");
5923 logevent("X11 forwarding enabled");
5924 ssh->X11_fwd_enabled = TRUE;
5925 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5930 ssh_setup_portfwd(ssh, ssh->conf);
5931 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5933 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5935 /* Unpick the terminal-speed string. */
5936 /* XXX perhaps we should allow no speeds to be sent. */
5937 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5938 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5939 /* Send the pty request. */
5940 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5941 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5942 ssh_pkt_adduint32(pkt, ssh->term_height);
5943 ssh_pkt_adduint32(pkt, ssh->term_width);
5944 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5945 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5946 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5947 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5948 ssh_pkt_adduint32(pkt, ssh->ispeed);
5949 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5950 ssh_pkt_adduint32(pkt, ssh->ospeed);
5951 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5953 ssh->state = SSH_STATE_INTERMED;
5957 if (pktin->type != SSH1_SMSG_SUCCESS
5958 && pktin->type != SSH1_SMSG_FAILURE) {
5959 bombout(("Protocol confusion"));
5961 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5962 c_write_str(ssh, "Server refused to allocate pty\r\n");
5963 ssh->editing = ssh->echoing = 1;
5965 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5966 ssh->ospeed, ssh->ispeed);
5967 ssh->got_pty = TRUE;
5970 ssh->editing = ssh->echoing = 1;
5973 if (conf_get_int(ssh->conf, CONF_compression)) {
5974 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5978 if (pktin->type != SSH1_SMSG_SUCCESS
5979 && pktin->type != SSH1_SMSG_FAILURE) {
5980 bombout(("Protocol confusion"));
5982 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5983 c_write_str(ssh, "Server refused to compress\r\n");
5985 logevent("Started compression");
5986 ssh->v1_compressing = TRUE;
5987 ssh->cs_comp_ctx = zlib_compress_init();
5988 logevent("Initialised zlib (RFC1950) compression");
5989 ssh->sc_comp_ctx = zlib_decompress_init();
5990 logevent("Initialised zlib (RFC1950) decompression");
5994 * Start the shell or command.
5996 * Special case: if the first-choice command is an SSH-2
5997 * subsystem (hence not usable here) and the second choice
5998 * exists, we fall straight back to that.
6001 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
6003 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
6004 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
6005 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
6006 ssh->fallback_cmd = TRUE;
6009 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
6011 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
6012 logevent("Started session");
6015 ssh->state = SSH_STATE_SESSION;
6016 if (ssh->size_needed)
6017 ssh_size(ssh, ssh->term_width, ssh->term_height);
6018 if (ssh->eof_needed)
6019 ssh_special(ssh, TS_EOF);
6022 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
6024 ssh->channels = newtree234(ssh_channelcmp);
6028 * By this point, most incoming packets are already being
6029 * handled by the dispatch table, and we need only pay
6030 * attention to the unusual ones.
6035 if (pktin->type == SSH1_SMSG_SUCCESS) {
6036 /* may be from EXEC_SHELL on some servers */
6037 } else if (pktin->type == SSH1_SMSG_FAILURE) {
6038 /* may be from EXEC_SHELL on some servers
6039 * if no pty is available or in other odd cases. Ignore */
6041 bombout(("Strange packet received: type %d", pktin->type));
6046 int len = min(inlen, 512);
6047 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
6048 PKT_INT, len, PKT_DATA, in, len,
6060 * Handle the top-level SSH-2 protocol.
6062 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
6067 ssh_pkt_getstring(pktin, &msg, &msglen);
6068 logeventf(ssh, "Remote debug message: %.*s", msglen, NULLTOEMPTY(msg));
6071 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
6073 /* log reason code in disconnect message */
6077 ssh_pkt_getstring(pktin, &msg, &msglen);
6078 bombout(("Server sent disconnect message:\n\"%.*s\"",
6079 msglen, NULLTOEMPTY(msg)));
6082 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
6084 /* Do nothing, because we're ignoring it! Duhh. */
6087 static void ssh1_protocol_setup(Ssh ssh)
6092 * Most messages are handled by the coroutines.
6094 for (i = 0; i < 256; i++)
6095 ssh->packet_dispatch[i] = NULL;
6098 * These special message types we install handlers for.
6100 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
6101 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
6102 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
6105 static void ssh1_protocol(Ssh ssh, const void *vin, int inlen,
6106 struct Packet *pktin)
6108 const unsigned char *in = (const unsigned char *)vin;
6109 if (ssh->state == SSH_STATE_CLOSED)
6112 if (pktin && ssh->packet_dispatch[pktin->type]) {
6113 ssh->packet_dispatch[pktin->type](ssh, pktin);
6117 if (!ssh->protocol_initial_phase_done) {
6118 if (do_ssh1_login(ssh, in, inlen, pktin))
6119 ssh->protocol_initial_phase_done = TRUE;
6124 do_ssh1_connection(ssh, in, inlen, pktin);
6128 * Utility routines for decoding comma-separated strings in KEXINIT.
6130 static int first_in_commasep_string(char const *needle, char const *haystack,
6134 if (!needle || !haystack) /* protect against null pointers */
6136 needlen = strlen(needle);
6138 if (haylen >= needlen && /* haystack is long enough */
6139 !memcmp(needle, haystack, needlen) && /* initial match */
6140 (haylen == needlen || haystack[needlen] == ',')
6141 /* either , or EOS follows */
6147 static int in_commasep_string(char const *needle, char const *haystack,
6152 if (!needle || !haystack) /* protect against null pointers */
6155 * Is it at the start of the string?
6157 if (first_in_commasep_string(needle, haystack, haylen))
6160 * If not, search for the next comma and resume after that.
6161 * If no comma found, terminate.
6163 p = memchr(haystack, ',', haylen);
6165 /* + 1 to skip over comma */
6166 return in_commasep_string(needle, p + 1, haylen - (p + 1 - haystack));
6170 * Add a value to the comma-separated string at the end of the packet.
6172 static void ssh2_pkt_addstring_commasep(struct Packet *pkt, const char *data)
6174 if (pkt->length - pkt->savedpos > 0)
6175 ssh_pkt_addstring_str(pkt, ",");
6176 ssh_pkt_addstring_str(pkt, data);
6181 * SSH-2 key derivation (RFC 4253 section 7.2).
6183 static unsigned char *ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H,
6184 char chr, int keylen)
6186 const struct ssh_hash *h = ssh->kex->hash;
6194 /* Round up to the next multiple of hash length. */
6195 keylen_padded = ((keylen + h->hlen - 1) / h->hlen) * h->hlen;
6197 key = snewn(keylen_padded, unsigned char);
6199 /* First hlen bytes. */
6201 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6202 hash_mpint(h, s, K);
6203 h->bytes(s, H, h->hlen);
6204 h->bytes(s, &chr, 1);
6205 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
6208 /* Subsequent blocks of hlen bytes. */
6209 if (keylen_padded > h->hlen) {
6213 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6214 hash_mpint(h, s, K);
6215 h->bytes(s, H, h->hlen);
6217 for (offset = h->hlen; offset < keylen_padded; offset += h->hlen) {
6218 h->bytes(s, key + offset - h->hlen, h->hlen);
6220 h->final(s2, key + offset);
6226 /* Now clear any extra bytes of key material beyond the length
6227 * we're officially returning, because the caller won't know to
6229 if (keylen_padded > keylen)
6230 smemclr(key + keylen, keylen_padded - keylen);
6236 * Structure for constructing KEXINIT algorithm lists.
6238 #define MAXKEXLIST 16
6239 struct kexinit_algorithm {
6243 const struct ssh_kex *kex;
6247 const struct ssh_signkey *hostkey;
6251 const struct ssh2_cipher *cipher;
6255 const struct ssh_mac *mac;
6258 const struct ssh_compress *comp;
6263 * Find a slot in a KEXINIT algorithm list to use for a new algorithm.
6264 * If the algorithm is already in the list, return a pointer to its
6265 * entry, otherwise return an entry from the end of the list.
6266 * This assumes that every time a particular name is passed in, it
6267 * comes from the same string constant. If this isn't true, this
6268 * function may need to be rewritten to use strcmp() instead.
6270 static struct kexinit_algorithm *ssh2_kexinit_addalg(struct kexinit_algorithm
6271 *list, const char *name)
6275 for (i = 0; i < MAXKEXLIST; i++)
6276 if (list[i].name == NULL || list[i].name == name) {
6277 list[i].name = name;
6280 assert(!"No space in KEXINIT list");
6285 * Handle the SSH-2 transport layer.
6287 static void do_ssh2_transport(Ssh ssh, const void *vin, int inlen,
6288 struct Packet *pktin)
6290 const unsigned char *in = (const unsigned char *)vin;
6292 KEXLIST_KEX, KEXLIST_HOSTKEY, KEXLIST_CSCIPHER, KEXLIST_SCCIPHER,
6293 KEXLIST_CSMAC, KEXLIST_SCMAC, KEXLIST_CSCOMP, KEXLIST_SCCOMP,
6296 const char * kexlist_descr[NKEXLIST] = {
6297 "key exchange algorithm", "host key algorithm",
6298 "client-to-server cipher", "server-to-client cipher",
6299 "client-to-server MAC", "server-to-client MAC",
6300 "client-to-server compression method",
6301 "server-to-client compression method" };
6302 struct do_ssh2_transport_state {
6304 int nbits, pbits, warn_kex, warn_hk, warn_cscipher, warn_sccipher;
6305 Bignum p, g, e, f, K;
6308 int kex_init_value, kex_reply_value;
6309 const struct ssh_mac *const *maclist;
6311 const struct ssh2_cipher *cscipher_tobe;
6312 const struct ssh2_cipher *sccipher_tobe;
6313 const struct ssh_mac *csmac_tobe;
6314 const struct ssh_mac *scmac_tobe;
6315 int csmac_etm_tobe, scmac_etm_tobe;
6316 const struct ssh_compress *cscomp_tobe;
6317 const struct ssh_compress *sccomp_tobe;
6318 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
6319 int hostkeylen, siglen, rsakeylen;
6320 void *hkey; /* actual host key */
6321 void *rsakey; /* for RSA kex */
6322 void *eckey; /* for ECDH kex */
6323 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
6324 int n_preferred_kex;
6325 const struct ssh_kexes *preferred_kex[KEX_MAX];
6327 int preferred_hk[HK_MAX];
6328 int n_preferred_ciphers;
6329 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
6330 const struct ssh_compress *preferred_comp;
6331 int userauth_succeeded; /* for delayed compression */
6332 int pending_compression;
6333 int got_session_id, activated_authconn;
6334 struct Packet *pktout;
6338 struct kexinit_algorithm kexlists[NKEXLIST][MAXKEXLIST];
6340 crState(do_ssh2_transport_state);
6342 assert(!ssh->bare_connection);
6343 assert(ssh->version == 2);
6347 s->cscipher_tobe = s->sccipher_tobe = NULL;
6348 s->csmac_tobe = s->scmac_tobe = NULL;
6349 s->cscomp_tobe = s->sccomp_tobe = NULL;
6351 s->got_session_id = s->activated_authconn = FALSE;
6352 s->userauth_succeeded = FALSE;
6353 s->pending_compression = FALSE;
6356 * Be prepared to work around the buggy MAC problem.
6358 if (ssh->remote_bugs & BUG_SSH2_HMAC)
6359 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
6361 s->maclist = macs, s->nmacs = lenof(macs);
6364 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
6367 struct kexinit_algorithm *alg;
6370 * Set up the preferred key exchange. (NULL => warn below here)
6372 s->n_preferred_kex = 0;
6373 for (i = 0; i < KEX_MAX; i++) {
6374 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
6376 s->preferred_kex[s->n_preferred_kex++] =
6377 &ssh_diffiehellman_gex;
6380 s->preferred_kex[s->n_preferred_kex++] =
6381 &ssh_diffiehellman_group14;
6384 s->preferred_kex[s->n_preferred_kex++] =
6385 &ssh_diffiehellman_group1;
6388 s->preferred_kex[s->n_preferred_kex++] =
6392 s->preferred_kex[s->n_preferred_kex++] =
6396 /* Flag for later. Don't bother if it's the last in
6398 if (i < KEX_MAX - 1) {
6399 s->preferred_kex[s->n_preferred_kex++] = NULL;
6406 * Set up the preferred host key types. These are just the ids
6407 * in the enum in putty.h, so 'warn below here' is indicated
6410 s->n_preferred_hk = 0;
6411 for (i = 0; i < HK_MAX; i++) {
6412 int id = conf_get_int_int(ssh->conf, CONF_ssh_hklist, i);
6413 /* As above, don't bother with HK_WARN if it's last in the
6415 if (id != HK_WARN || i < HK_MAX - 1)
6416 s->preferred_hk[s->n_preferred_hk++] = id;
6420 * Set up the preferred ciphers. (NULL => warn below here)
6422 s->n_preferred_ciphers = 0;
6423 for (i = 0; i < CIPHER_MAX; i++) {
6424 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
6425 case CIPHER_BLOWFISH:
6426 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
6429 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
6430 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
6434 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
6437 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
6439 case CIPHER_ARCFOUR:
6440 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
6442 case CIPHER_CHACHA20:
6443 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_ccp;
6446 /* Flag for later. Don't bother if it's the last in
6448 if (i < CIPHER_MAX - 1) {
6449 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
6456 * Set up preferred compression.
6458 if (conf_get_int(ssh->conf, CONF_compression))
6459 s->preferred_comp = &ssh_zlib;
6461 s->preferred_comp = &ssh_comp_none;
6464 * Enable queueing of outgoing auth- or connection-layer
6465 * packets while we are in the middle of a key exchange.
6467 ssh->queueing = TRUE;
6470 * Flag that KEX is in progress.
6472 ssh->kex_in_progress = TRUE;
6474 for (i = 0; i < NKEXLIST; i++)
6475 for (j = 0; j < MAXKEXLIST; j++)
6476 s->kexlists[i][j].name = NULL;
6477 /* List key exchange algorithms. */
6479 for (i = 0; i < s->n_preferred_kex; i++) {
6480 const struct ssh_kexes *k = s->preferred_kex[i];
6481 if (!k) warn = TRUE;
6482 else for (j = 0; j < k->nkexes; j++) {
6483 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_KEX],
6485 alg->u.kex.kex = k->list[j];
6486 alg->u.kex.warn = warn;
6489 /* List server host key algorithms. */
6490 if (!s->got_session_id) {
6492 * In the first key exchange, we list all the algorithms
6493 * we're prepared to cope with, but prefer those algorithms
6494 * for which we have a host key for this host.
6496 * If the host key algorithm is below the warning
6497 * threshold, we warn even if we did already have a key
6498 * for it, on the basis that if the user has just
6499 * reconfigured that host key type to be warned about,
6500 * they surely _do_ want to be alerted that a server
6501 * they're actually connecting to is using it.
6504 for (i = 0; i < s->n_preferred_hk; i++) {
6505 if (s->preferred_hk[i] == HK_WARN)
6507 for (j = 0; j < lenof(hostkey_algs); j++) {
6508 if (hostkey_algs[j].id != s->preferred_hk[i])
6510 if (have_ssh_host_key(ssh->savedhost, ssh->savedport,
6511 hostkey_algs[j].alg->keytype)) {
6512 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6513 hostkey_algs[j].alg->name);
6514 alg->u.hk.hostkey = hostkey_algs[j].alg;
6515 alg->u.hk.warn = warn;
6520 for (i = 0; i < s->n_preferred_hk; i++) {
6521 if (s->preferred_hk[i] == HK_WARN)
6523 for (j = 0; j < lenof(hostkey_algs); j++) {
6524 if (hostkey_algs[j].id != s->preferred_hk[i])
6526 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6527 hostkey_algs[j].alg->name);
6528 alg->u.hk.hostkey = hostkey_algs[j].alg;
6529 alg->u.hk.warn = warn;
6534 * In subsequent key exchanges, we list only the kex
6535 * algorithm that was selected in the first key exchange,
6536 * so that we keep getting the same host key and hence
6537 * don't have to interrupt the user's session to ask for
6541 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6542 ssh->hostkey->name);
6543 alg->u.hk.hostkey = ssh->hostkey;
6544 alg->u.hk.warn = FALSE;
6546 /* List encryption algorithms (client->server then server->client). */
6547 for (k = KEXLIST_CSCIPHER; k <= KEXLIST_SCCIPHER; k++) {
6550 alg = ssh2_kexinit_addalg(s->kexlists[k], "none");
6551 alg->u.cipher.cipher = NULL;
6552 alg->u.cipher.warn = warn;
6553 #endif /* FUZZING */
6554 for (i = 0; i < s->n_preferred_ciphers; i++) {
6555 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6556 if (!c) warn = TRUE;
6557 else for (j = 0; j < c->nciphers; j++) {
6558 alg = ssh2_kexinit_addalg(s->kexlists[k],
6560 alg->u.cipher.cipher = c->list[j];
6561 alg->u.cipher.warn = warn;
6565 /* List MAC algorithms (client->server then server->client). */
6566 for (j = KEXLIST_CSMAC; j <= KEXLIST_SCMAC; j++) {
6568 alg = ssh2_kexinit_addalg(s->kexlists[j], "none");
6569 alg->u.mac.mac = NULL;
6570 alg->u.mac.etm = FALSE;
6571 #endif /* FUZZING */
6572 for (i = 0; i < s->nmacs; i++) {
6573 alg = ssh2_kexinit_addalg(s->kexlists[j], s->maclist[i]->name);
6574 alg->u.mac.mac = s->maclist[i];
6575 alg->u.mac.etm = FALSE;
6577 for (i = 0; i < s->nmacs; i++)
6578 /* For each MAC, there may also be an ETM version,
6579 * which we list second. */
6580 if (s->maclist[i]->etm_name) {
6581 alg = ssh2_kexinit_addalg(s->kexlists[j],
6582 s->maclist[i]->etm_name);
6583 alg->u.mac.mac = s->maclist[i];
6584 alg->u.mac.etm = TRUE;
6587 /* List client->server compression algorithms,
6588 * then server->client compression algorithms. (We use the
6589 * same set twice.) */
6590 for (j = KEXLIST_CSCOMP; j <= KEXLIST_SCCOMP; j++) {
6591 assert(lenof(compressions) > 1);
6592 /* Prefer non-delayed versions */
6593 alg = ssh2_kexinit_addalg(s->kexlists[j], s->preferred_comp->name);
6594 alg->u.comp = s->preferred_comp;
6595 /* We don't even list delayed versions of algorithms until
6596 * they're allowed to be used, to avoid a race. See the end of
6598 if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
6599 alg = ssh2_kexinit_addalg(s->kexlists[j],
6600 s->preferred_comp->delayed_name);
6601 alg->u.comp = s->preferred_comp;
6603 for (i = 0; i < lenof(compressions); i++) {
6604 const struct ssh_compress *c = compressions[i];
6605 alg = ssh2_kexinit_addalg(s->kexlists[j], c->name);
6607 if (s->userauth_succeeded && c->delayed_name) {
6608 alg = ssh2_kexinit_addalg(s->kexlists[j], c->delayed_name);
6614 * Construct and send our key exchange packet.
6616 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
6617 for (i = 0; i < 16; i++)
6618 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
6619 for (i = 0; i < NKEXLIST; i++) {
6620 ssh2_pkt_addstring_start(s->pktout);
6621 for (j = 0; j < MAXKEXLIST; j++) {
6622 if (s->kexlists[i][j].name == NULL) break;
6623 ssh2_pkt_addstring_commasep(s->pktout, s->kexlists[i][j].name);
6626 /* List client->server languages. Empty list. */
6627 ssh2_pkt_addstring_start(s->pktout);
6628 /* List server->client languages. Empty list. */
6629 ssh2_pkt_addstring_start(s->pktout);
6630 /* First KEX packet does _not_ follow, because we're not that brave. */
6631 ssh2_pkt_addbool(s->pktout, FALSE);
6633 ssh2_pkt_adduint32(s->pktout, 0);
6636 s->our_kexinitlen = s->pktout->length - 5;
6637 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
6638 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
6640 ssh2_pkt_send_noqueue(ssh, s->pktout);
6643 crWaitUntilV(pktin);
6646 * Now examine the other side's KEXINIT to see what we're up
6653 if (pktin->type != SSH2_MSG_KEXINIT) {
6654 bombout(("expected key exchange packet from server"));
6658 ssh->hostkey = NULL;
6659 s->cscipher_tobe = NULL;
6660 s->sccipher_tobe = NULL;
6661 s->csmac_tobe = NULL;
6662 s->scmac_tobe = NULL;
6663 s->cscomp_tobe = NULL;
6664 s->sccomp_tobe = NULL;
6665 s->warn_kex = s->warn_hk = FALSE;
6666 s->warn_cscipher = s->warn_sccipher = FALSE;
6668 pktin->savedpos += 16; /* skip garbage cookie */
6671 for (i = 0; i < NKEXLIST; i++) {
6672 ssh_pkt_getstring(pktin, &str, &len);
6674 bombout(("KEXINIT packet was incomplete"));
6678 /* If we've already selected a cipher which requires a
6679 * particular MAC, then just select that, and don't even
6680 * bother looking through the server's KEXINIT string for
6682 if (i == KEXLIST_CSMAC && s->cscipher_tobe &&
6683 s->cscipher_tobe->required_mac) {
6684 s->csmac_tobe = s->cscipher_tobe->required_mac;
6685 s->csmac_etm_tobe = !!(s->csmac_tobe->etm_name);
6688 if (i == KEXLIST_SCMAC && s->sccipher_tobe &&
6689 s->sccipher_tobe->required_mac) {
6690 s->scmac_tobe = s->sccipher_tobe->required_mac;
6691 s->scmac_etm_tobe = !!(s->scmac_tobe->etm_name);
6695 for (j = 0; j < MAXKEXLIST; j++) {
6696 struct kexinit_algorithm *alg = &s->kexlists[i][j];
6697 if (alg->name == NULL) break;
6698 if (in_commasep_string(alg->name, str, len)) {
6699 /* We've found a matching algorithm. */
6700 if (i == KEXLIST_KEX || i == KEXLIST_HOSTKEY) {
6701 /* Check if we might need to ignore first kex pkt */
6703 !first_in_commasep_string(alg->name, str, len))
6706 if (i == KEXLIST_KEX) {
6707 ssh->kex = alg->u.kex.kex;
6708 s->warn_kex = alg->u.kex.warn;
6709 } else if (i == KEXLIST_HOSTKEY) {
6710 ssh->hostkey = alg->u.hk.hostkey;
6711 s->warn_hk = alg->u.hk.warn;
6712 } else if (i == KEXLIST_CSCIPHER) {
6713 s->cscipher_tobe = alg->u.cipher.cipher;
6714 s->warn_cscipher = alg->u.cipher.warn;
6715 } else if (i == KEXLIST_SCCIPHER) {
6716 s->sccipher_tobe = alg->u.cipher.cipher;
6717 s->warn_sccipher = alg->u.cipher.warn;
6718 } else if (i == KEXLIST_CSMAC) {
6719 s->csmac_tobe = alg->u.mac.mac;
6720 s->csmac_etm_tobe = alg->u.mac.etm;
6721 } else if (i == KEXLIST_SCMAC) {
6722 s->scmac_tobe = alg->u.mac.mac;
6723 s->scmac_etm_tobe = alg->u.mac.etm;
6724 } else if (i == KEXLIST_CSCOMP) {
6725 s->cscomp_tobe = alg->u.comp;
6726 } else if (i == KEXLIST_SCCOMP) {
6727 s->sccomp_tobe = alg->u.comp;
6731 if ((i == KEXLIST_CSCOMP || i == KEXLIST_SCCOMP) &&
6732 in_commasep_string(alg->u.comp->delayed_name, str, len))
6733 s->pending_compression = TRUE; /* try this later */
6735 bombout(("Couldn't agree a %s (available: %.*s)",
6736 kexlist_descr[i], len, str));
6740 if (i == KEXLIST_HOSTKEY) {
6744 * In addition to deciding which host key we're
6745 * actually going to use, we should make a list of the
6746 * host keys offered by the server which we _don't_
6747 * have cached. These will be offered as cross-
6748 * certification options by ssh_get_specials.
6750 * We also count the key we're currently using for KEX
6751 * as one we've already got, because by the time this
6752 * menu becomes visible, it will be.
6754 ssh->n_uncert_hostkeys = 0;
6756 for (j = 0; j < lenof(hostkey_algs); j++) {
6757 if (hostkey_algs[j].alg != ssh->hostkey &&
6758 in_commasep_string(hostkey_algs[j].alg->name,
6760 !have_ssh_host_key(ssh->savedhost, ssh->savedport,
6761 hostkey_algs[j].alg->keytype)) {
6762 ssh->uncert_hostkeys[ssh->n_uncert_hostkeys++] = j;
6768 if (s->pending_compression) {
6769 logevent("Server supports delayed compression; "
6770 "will try this later");
6772 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
6773 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
6774 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
6776 ssh->exhash = ssh->kex->hash->init();
6777 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
6778 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
6779 hash_string(ssh->kex->hash, ssh->exhash,
6780 s->our_kexinit, s->our_kexinitlen);
6781 sfree(s->our_kexinit);
6782 /* Include the type byte in the hash of server's KEXINIT */
6783 hash_string(ssh->kex->hash, ssh->exhash,
6784 pktin->body - 1, pktin->length + 1);
6787 ssh_set_frozen(ssh, 1);
6788 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
6790 ssh_dialog_callback, ssh);
6791 if (s->dlgret < 0) {
6795 bombout(("Unexpected data from server while"
6796 " waiting for user response"));
6799 } while (pktin || inlen > 0);
6800 s->dlgret = ssh->user_response;
6802 ssh_set_frozen(ssh, 0);
6803 if (s->dlgret == 0) {
6804 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
6814 ssh_set_frozen(ssh, 1);
6817 * Change warning box wording depending on why we chose a
6818 * warning-level host key algorithm. If it's because
6819 * that's all we have *cached*, use the askhk mechanism,
6820 * and list the host keys we could usefully cross-certify.
6821 * Otherwise, use askalg for the standard wording.
6824 for (j = 0; j < ssh->n_uncert_hostkeys; j++) {
6825 const struct ssh_signkey_with_user_pref_id *hktype =
6826 &hostkey_algs[ssh->uncert_hostkeys[j]];
6828 for (k = 0; k < HK_MAX; k++) {
6829 int id = conf_get_int_int(ssh->conf, CONF_ssh_hklist, k);
6830 if (id == HK_WARN) {
6832 } else if (id == hktype->id) {
6839 char *old_ba = betteralgs;
6840 betteralgs = dupcat(betteralgs, ",",
6842 (const char *)NULL);
6845 betteralgs = dupstr(hktype->alg->name);
6850 s->dlgret = askhk(ssh->frontend, ssh->hostkey->name,
6851 betteralgs, ssh_dialog_callback, ssh);
6854 s->dlgret = askalg(ssh->frontend, "host key type",
6856 ssh_dialog_callback, ssh);
6858 if (s->dlgret < 0) {
6862 bombout(("Unexpected data from server while"
6863 " waiting for user response"));
6866 } while (pktin || inlen > 0);
6867 s->dlgret = ssh->user_response;
6869 ssh_set_frozen(ssh, 0);
6870 if (s->dlgret == 0) {
6871 ssh_disconnect(ssh, "User aborted at host key warning", NULL,
6877 if (s->warn_cscipher) {
6878 ssh_set_frozen(ssh, 1);
6879 s->dlgret = askalg(ssh->frontend,
6880 "client-to-server cipher",
6881 s->cscipher_tobe->name,
6882 ssh_dialog_callback, ssh);
6883 if (s->dlgret < 0) {
6887 bombout(("Unexpected data from server while"
6888 " waiting for user response"));
6891 } while (pktin || inlen > 0);
6892 s->dlgret = ssh->user_response;
6894 ssh_set_frozen(ssh, 0);
6895 if (s->dlgret == 0) {
6896 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6902 if (s->warn_sccipher) {
6903 ssh_set_frozen(ssh, 1);
6904 s->dlgret = askalg(ssh->frontend,
6905 "server-to-client cipher",
6906 s->sccipher_tobe->name,
6907 ssh_dialog_callback, ssh);
6908 if (s->dlgret < 0) {
6912 bombout(("Unexpected data from server while"
6913 " waiting for user response"));
6916 } while (pktin || inlen > 0);
6917 s->dlgret = ssh->user_response;
6919 ssh_set_frozen(ssh, 0);
6920 if (s->dlgret == 0) {
6921 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6927 if (s->ignorepkt) /* first_kex_packet_follows */
6928 crWaitUntilV(pktin); /* Ignore packet */
6931 if (ssh->kex->main_type == KEXTYPE_DH) {
6933 * Work out the number of bits of key we will need from the
6934 * key exchange. We start with the maximum key length of
6940 csbits = s->cscipher_tobe ? s->cscipher_tobe->real_keybits : 0;
6941 scbits = s->sccipher_tobe ? s->sccipher_tobe->real_keybits : 0;
6942 s->nbits = (csbits > scbits ? csbits : scbits);
6944 /* The keys only have hlen-bit entropy, since they're based on
6945 * a hash. So cap the key size at hlen bits. */
6946 if (s->nbits > ssh->kex->hash->hlen * 8)
6947 s->nbits = ssh->kex->hash->hlen * 8;
6950 * If we're doing Diffie-Hellman group exchange, start by
6951 * requesting a group.
6953 if (dh_is_gex(ssh->kex)) {
6954 logevent("Doing Diffie-Hellman group exchange");
6955 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
6957 * Work out how big a DH group we will need to allow that
6960 s->pbits = 512 << ((s->nbits - 1) / 64);
6961 if (s->pbits < DH_MIN_SIZE)
6962 s->pbits = DH_MIN_SIZE;
6963 if (s->pbits > DH_MAX_SIZE)
6964 s->pbits = DH_MAX_SIZE;
6965 if ((ssh->remote_bugs & BUG_SSH2_OLDGEX)) {
6966 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD);
6967 ssh2_pkt_adduint32(s->pktout, s->pbits);
6969 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
6970 ssh2_pkt_adduint32(s->pktout, DH_MIN_SIZE);
6971 ssh2_pkt_adduint32(s->pktout, s->pbits);
6972 ssh2_pkt_adduint32(s->pktout, DH_MAX_SIZE);
6974 ssh2_pkt_send_noqueue(ssh, s->pktout);
6976 crWaitUntilV(pktin);
6977 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
6978 bombout(("expected key exchange group packet from server"));
6981 s->p = ssh2_pkt_getmp(pktin);
6982 s->g = ssh2_pkt_getmp(pktin);
6983 if (!s->p || !s->g) {
6984 bombout(("unable to read mp-ints from incoming group packet"));
6987 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
6988 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
6989 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
6991 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
6992 ssh->kex_ctx = dh_setup_group(ssh->kex);
6993 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
6994 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
6995 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
6996 ssh->kex->groupname);
6999 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
7000 ssh->kex->hash->text_name);
7002 * Now generate and send e for Diffie-Hellman.
7004 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
7005 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
7006 s->pktout = ssh2_pkt_init(s->kex_init_value);
7007 ssh2_pkt_addmp(s->pktout, s->e);
7008 ssh2_pkt_send_noqueue(ssh, s->pktout);
7010 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
7011 crWaitUntilV(pktin);
7012 if (pktin->type != s->kex_reply_value) {
7013 bombout(("expected key exchange reply packet from server"));
7016 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
7017 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7018 if (!s->hostkeydata) {
7019 bombout(("unable to parse key exchange reply packet"));
7022 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7023 s->hostkeydata, s->hostkeylen);
7024 s->f = ssh2_pkt_getmp(pktin);
7026 bombout(("unable to parse key exchange reply packet"));
7029 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7031 bombout(("unable to parse key exchange reply packet"));
7036 const char *err = dh_validate_f(ssh->kex_ctx, s->f);
7038 bombout(("key exchange reply failed validation: %s", err));
7042 s->K = dh_find_K(ssh->kex_ctx, s->f);
7044 /* We assume everything from now on will be quick, and it might
7045 * involve user interaction. */
7046 set_busy_status(ssh->frontend, BUSY_NOT);
7048 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
7049 if (dh_is_gex(ssh->kex)) {
7050 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
7051 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MIN_SIZE);
7052 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
7053 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
7054 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MAX_SIZE);
7055 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
7056 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
7058 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
7059 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
7061 dh_cleanup(ssh->kex_ctx);
7063 if (dh_is_gex(ssh->kex)) {
7067 } else if (ssh->kex->main_type == KEXTYPE_ECDH) {
7069 logeventf(ssh, "Doing ECDH key exchange with curve %s and hash %s",
7070 ssh_ecdhkex_curve_textname(ssh->kex),
7071 ssh->kex->hash->text_name);
7072 ssh->pkt_kctx = SSH2_PKTCTX_ECDHKEX;
7074 s->eckey = ssh_ecdhkex_newkey(ssh->kex);
7076 bombout(("Unable to generate key for ECDH"));
7082 int publicPointLength;
7083 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
7085 ssh_ecdhkex_freekey(s->eckey);
7086 bombout(("Unable to encode public key for ECDH"));
7089 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_ECDH_INIT);
7090 ssh2_pkt_addstring_start(s->pktout);
7091 ssh2_pkt_addstring_data(s->pktout, publicPoint, publicPointLength);
7095 ssh2_pkt_send_noqueue(ssh, s->pktout);
7097 crWaitUntilV(pktin);
7098 if (pktin->type != SSH2_MSG_KEX_ECDH_REPLY) {
7099 ssh_ecdhkex_freekey(s->eckey);
7100 bombout(("expected ECDH reply packet from server"));
7104 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7105 if (!s->hostkeydata) {
7106 bombout(("unable to parse ECDH reply packet"));
7109 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
7110 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7111 s->hostkeydata, s->hostkeylen);
7115 int publicPointLength;
7116 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
7118 ssh_ecdhkex_freekey(s->eckey);
7119 bombout(("Unable to encode public key for ECDH hash"));
7122 hash_string(ssh->kex->hash, ssh->exhash,
7123 publicPoint, publicPointLength);
7130 ssh_pkt_getstring(pktin, &keydata, &keylen);
7132 bombout(("unable to parse ECDH reply packet"));
7135 hash_string(ssh->kex->hash, ssh->exhash, keydata, keylen);
7136 s->K = ssh_ecdhkex_getkey(s->eckey, keydata, keylen);
7138 ssh_ecdhkex_freekey(s->eckey);
7139 bombout(("point received in ECDH was not valid"));
7144 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7146 bombout(("unable to parse key exchange reply packet"));
7150 ssh_ecdhkex_freekey(s->eckey);
7152 logeventf(ssh, "Doing RSA key exchange with hash %s",
7153 ssh->kex->hash->text_name);
7154 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
7156 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
7159 crWaitUntilV(pktin);
7160 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
7161 bombout(("expected RSA public key packet from server"));
7165 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7166 if (!s->hostkeydata) {
7167 bombout(("unable to parse RSA public key packet"));
7170 hash_string(ssh->kex->hash, ssh->exhash,
7171 s->hostkeydata, s->hostkeylen);
7172 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7173 s->hostkeydata, s->hostkeylen);
7177 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
7179 bombout(("unable to parse RSA public key packet"));
7182 s->rsakeydata = snewn(s->rsakeylen, char);
7183 memcpy(s->rsakeydata, keydata, s->rsakeylen);
7186 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
7188 sfree(s->rsakeydata);
7189 bombout(("unable to parse RSA public key from server"));
7193 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
7196 * Next, set up a shared secret K, of precisely KLEN -
7197 * 2*HLEN - 49 bits, where KLEN is the bit length of the
7198 * RSA key modulus and HLEN is the bit length of the hash
7202 int klen = ssh_rsakex_klen(s->rsakey);
7203 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
7205 unsigned char *kstr1, *kstr2, *outstr;
7206 int kstr1len, kstr2len, outstrlen;
7208 s->K = bn_power_2(nbits - 1);
7210 for (i = 0; i < nbits; i++) {
7212 byte = random_byte();
7214 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
7218 * Encode this as an mpint.
7220 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
7221 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
7222 PUT_32BIT(kstr2, kstr1len);
7223 memcpy(kstr2 + 4, kstr1, kstr1len);
7226 * Encrypt it with the given RSA key.
7228 outstrlen = (klen + 7) / 8;
7229 outstr = snewn(outstrlen, unsigned char);
7230 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
7231 outstr, outstrlen, s->rsakey);
7234 * And send it off in a return packet.
7236 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
7237 ssh2_pkt_addstring_start(s->pktout);
7238 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
7239 ssh2_pkt_send_noqueue(ssh, s->pktout);
7241 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
7248 ssh_rsakex_freekey(s->rsakey);
7250 crWaitUntilV(pktin);
7251 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
7252 sfree(s->rsakeydata);
7253 bombout(("expected signature packet from server"));
7257 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7259 bombout(("unable to parse signature packet"));
7263 sfree(s->rsakeydata);
7266 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
7267 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
7268 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
7270 ssh->kex_ctx = NULL;
7273 debug(("Exchange hash is:\n"));
7274 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
7278 bombout(("Server's host key is invalid"));
7282 if (!ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
7283 (char *)s->exchange_hash,
7284 ssh->kex->hash->hlen)) {
7286 bombout(("Server's host key did not match the signature supplied"));
7291 s->keystr = ssh->hostkey->fmtkey(s->hkey);
7292 if (!s->got_session_id) {
7294 * Make a note of any other host key formats that are available.
7297 int i, j, nkeys = 0;
7299 for (i = 0; i < lenof(hostkey_algs); i++) {
7300 if (hostkey_algs[i].alg == ssh->hostkey)
7303 for (j = 0; j < ssh->n_uncert_hostkeys; j++)
7304 if (ssh->uncert_hostkeys[j] == i)
7307 if (j < ssh->n_uncert_hostkeys) {
7310 newlist = dupprintf("%s/%s", list,
7311 hostkey_algs[i].alg->name);
7313 newlist = dupprintf("%s", hostkey_algs[i].alg->name);
7321 "Server also has %s host key%s, but we "
7322 "don't know %s", list,
7323 nkeys > 1 ? "s" : "",
7324 nkeys > 1 ? "any of them" : "it");
7330 * Authenticate remote host: verify host key. (We've already
7331 * checked the signature of the exchange hash.)
7333 s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
7334 logevent("Host key fingerprint is:");
7335 logevent(s->fingerprint);
7336 /* First check against manually configured host keys. */
7337 s->dlgret = verify_ssh_manual_host_key(ssh, s->fingerprint,
7338 ssh->hostkey, s->hkey);
7339 if (s->dlgret == 0) { /* did not match */
7340 bombout(("Host key did not appear in manually configured list"));
7342 } else if (s->dlgret < 0) { /* none configured; use standard handling */
7343 ssh_set_frozen(ssh, 1);
7344 s->dlgret = verify_ssh_host_key(ssh->frontend,
7345 ssh->savedhost, ssh->savedport,
7346 ssh->hostkey->keytype, s->keystr,
7348 ssh_dialog_callback, ssh);
7352 if (s->dlgret < 0) {
7356 bombout(("Unexpected data from server while waiting"
7357 " for user host key response"));
7360 } while (pktin || inlen > 0);
7361 s->dlgret = ssh->user_response;
7363 ssh_set_frozen(ssh, 0);
7364 if (s->dlgret == 0) {
7365 ssh_disconnect(ssh, "Aborted at host key verification", NULL,
7370 sfree(s->fingerprint);
7372 * Save this host key, to check against the one presented in
7373 * subsequent rekeys.
7375 ssh->hostkey_str = s->keystr;
7376 } else if (ssh->cross_certifying) {
7377 s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
7378 logevent("Storing additional host key for this host:");
7379 logevent(s->fingerprint);
7380 store_host_key(ssh->savedhost, ssh->savedport,
7381 ssh->hostkey->keytype, s->keystr);
7382 ssh->cross_certifying = FALSE;
7384 * Don't forget to store the new key as the one we'll be
7385 * re-checking in future normal rekeys.
7387 ssh->hostkey_str = s->keystr;
7390 * In a rekey, we never present an interactive host key
7391 * verification request to the user. Instead, we simply
7392 * enforce that the key we're seeing this time is identical to
7393 * the one we saw before.
7395 if (strcmp(ssh->hostkey_str, s->keystr)) {
7397 bombout(("Host key was different in repeat key exchange"));
7403 ssh->hostkey->freekey(s->hkey);
7406 * The exchange hash from the very first key exchange is also
7407 * the session id, used in session key construction and
7410 if (!s->got_session_id) {
7411 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
7412 memcpy(ssh->v2_session_id, s->exchange_hash,
7413 sizeof(s->exchange_hash));
7414 ssh->v2_session_id_len = ssh->kex->hash->hlen;
7415 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
7416 s->got_session_id = TRUE;
7420 * Send SSH2_MSG_NEWKEYS.
7422 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
7423 ssh2_pkt_send_noqueue(ssh, s->pktout);
7424 ssh->outgoing_data_size = 0; /* start counting from here */
7427 * We've sent client NEWKEYS, so create and initialise
7428 * client-to-server session keys.
7430 if (ssh->cs_cipher_ctx)
7431 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
7432 ssh->cscipher = s->cscipher_tobe;
7433 if (ssh->cscipher) ssh->cs_cipher_ctx = ssh->cscipher->make_context();
7435 if (ssh->cs_mac_ctx)
7436 ssh->csmac->free_context(ssh->cs_mac_ctx);
7437 ssh->csmac = s->csmac_tobe;
7438 ssh->csmac_etm = s->csmac_etm_tobe;
7440 ssh->cs_mac_ctx = ssh->csmac->make_context(ssh->cs_cipher_ctx);
7442 if (ssh->cs_comp_ctx)
7443 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
7444 ssh->cscomp = s->cscomp_tobe;
7445 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
7448 * Set IVs on client-to-server keys. Here we use the exchange
7449 * hash from the _first_ key exchange.
7451 if (ssh->cscipher) {
7454 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'C',
7455 ssh->cscipher->padded_keybytes);
7456 ssh->cscipher->setkey(ssh->cs_cipher_ctx, key);
7457 smemclr(key, ssh->cscipher->padded_keybytes);
7460 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'A',
7461 ssh->cscipher->blksize);
7462 ssh->cscipher->setiv(ssh->cs_cipher_ctx, key);
7463 smemclr(key, ssh->cscipher->blksize);
7469 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'E',
7470 ssh->csmac->keylen);
7471 ssh->csmac->setkey(ssh->cs_mac_ctx, key);
7472 smemclr(key, ssh->csmac->keylen);
7477 logeventf(ssh, "Initialised %.200s client->server encryption",
7478 ssh->cscipher->text_name);
7480 logeventf(ssh, "Initialised %.200s client->server MAC algorithm%s%s",
7481 ssh->csmac->text_name,
7482 ssh->csmac_etm ? " (in ETM mode)" : "",
7483 ssh->cscipher->required_mac ? " (required by cipher)" : "");
7484 if (ssh->cscomp->text_name)
7485 logeventf(ssh, "Initialised %s compression",
7486 ssh->cscomp->text_name);
7489 * Now our end of the key exchange is complete, we can send all
7490 * our queued higher-layer packets.
7492 ssh->queueing = FALSE;
7493 ssh2_pkt_queuesend(ssh);
7496 * Expect SSH2_MSG_NEWKEYS from server.
7498 crWaitUntilV(pktin);
7499 if (pktin->type != SSH2_MSG_NEWKEYS) {
7500 bombout(("expected new-keys packet from server"));
7503 ssh->incoming_data_size = 0; /* start counting from here */
7506 * We've seen server NEWKEYS, so create and initialise
7507 * server-to-client session keys.
7509 if (ssh->sc_cipher_ctx)
7510 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
7511 if (s->sccipher_tobe) {
7512 ssh->sccipher = s->sccipher_tobe;
7513 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
7516 if (ssh->sc_mac_ctx)
7517 ssh->scmac->free_context(ssh->sc_mac_ctx);
7518 if (s->scmac_tobe) {
7519 ssh->scmac = s->scmac_tobe;
7520 ssh->scmac_etm = s->scmac_etm_tobe;
7521 ssh->sc_mac_ctx = ssh->scmac->make_context(ssh->sc_cipher_ctx);
7524 if (ssh->sc_comp_ctx)
7525 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
7526 ssh->sccomp = s->sccomp_tobe;
7527 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
7530 * Set IVs on server-to-client keys. Here we use the exchange
7531 * hash from the _first_ key exchange.
7533 if (ssh->sccipher) {
7536 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'D',
7537 ssh->sccipher->padded_keybytes);
7538 ssh->sccipher->setkey(ssh->sc_cipher_ctx, key);
7539 smemclr(key, ssh->sccipher->padded_keybytes);
7542 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'B',
7543 ssh->sccipher->blksize);
7544 ssh->sccipher->setiv(ssh->sc_cipher_ctx, key);
7545 smemclr(key, ssh->sccipher->blksize);
7551 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'F',
7552 ssh->scmac->keylen);
7553 ssh->scmac->setkey(ssh->sc_mac_ctx, key);
7554 smemclr(key, ssh->scmac->keylen);
7558 logeventf(ssh, "Initialised %.200s server->client encryption",
7559 ssh->sccipher->text_name);
7561 logeventf(ssh, "Initialised %.200s server->client MAC algorithm%s%s",
7562 ssh->scmac->text_name,
7563 ssh->scmac_etm ? " (in ETM mode)" : "",
7564 ssh->sccipher->required_mac ? " (required by cipher)" : "");
7565 if (ssh->sccomp->text_name)
7566 logeventf(ssh, "Initialised %s decompression",
7567 ssh->sccomp->text_name);
7570 * Free shared secret.
7575 * Update the specials menu to list the remaining uncertified host
7578 update_specials_menu(ssh->frontend);
7581 * Key exchange is over. Loop straight back round if we have a
7582 * deferred rekey reason.
7584 if (ssh->deferred_rekey_reason) {
7585 logevent(ssh->deferred_rekey_reason);
7587 ssh->deferred_rekey_reason = NULL;
7588 goto begin_key_exchange;
7592 * Otherwise, schedule a timer for our next rekey.
7594 ssh->kex_in_progress = FALSE;
7595 ssh->last_rekey = GETTICKCOUNT();
7596 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
7597 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7601 * Now we're encrypting. Begin returning 1 to the protocol main
7602 * function so that other things can run on top of the
7603 * transport. If we ever see a KEXINIT, we must go back to the
7606 * We _also_ go back to the start if we see pktin==NULL and
7607 * inlen negative, because this is a special signal meaning
7608 * `initiate client-driven rekey', and `in' contains a message
7609 * giving the reason for the rekey.
7611 * inlen==-1 means always initiate a rekey;
7612 * inlen==-2 means that userauth has completed successfully and
7613 * we should consider rekeying (for delayed compression).
7615 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
7616 (!pktin && inlen < 0))) {
7618 if (!ssh->protocol_initial_phase_done) {
7619 ssh->protocol_initial_phase_done = TRUE;
7621 * Allow authconn to initialise itself.
7623 do_ssh2_authconn(ssh, NULL, 0, NULL);
7628 logevent("Server initiated key re-exchange");
7632 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
7633 * delayed compression, if it's available.
7635 * draft-miller-secsh-compression-delayed-00 says that you
7636 * negotiate delayed compression in the first key exchange, and
7637 * both sides start compressing when the server has sent
7638 * USERAUTH_SUCCESS. This has a race condition -- the server
7639 * can't know when the client has seen it, and thus which incoming
7640 * packets it should treat as compressed.
7642 * Instead, we do the initial key exchange without offering the
7643 * delayed methods, but note if the server offers them; when we
7644 * get here, if a delayed method was available that was higher
7645 * on our list than what we got, we initiate a rekey in which we
7646 * _do_ list the delayed methods (and hopefully get it as a
7647 * result). Subsequent rekeys will do the same.
7649 assert(!s->userauth_succeeded); /* should only happen once */
7650 s->userauth_succeeded = TRUE;
7651 if (!s->pending_compression)
7652 /* Can't see any point rekeying. */
7653 goto wait_for_rekey; /* this is utterly horrid */
7654 /* else fall through to rekey... */
7655 s->pending_compression = FALSE;
7658 * Now we've decided to rekey.
7660 * Special case: if the server bug is set that doesn't
7661 * allow rekeying, we give a different log message and
7662 * continue waiting. (If such a server _initiates_ a rekey,
7663 * we process it anyway!)
7665 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
7666 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
7668 /* Reset the counters, so that at least this message doesn't
7669 * hit the event log _too_ often. */
7670 ssh->outgoing_data_size = 0;
7671 ssh->incoming_data_size = 0;
7672 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
7674 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7677 goto wait_for_rekey; /* this is still utterly horrid */
7679 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
7682 goto begin_key_exchange;
7688 * Send data on an SSH channel. In SSH-2, this involves buffering it
7691 static int ssh_send_channel_data(struct ssh_channel *c, const char *buf,
7694 if (c->ssh->version == 2) {
7695 bufchain_add(&c->v.v2.outbuffer, buf, len);
7696 return ssh2_try_send(c);
7698 send_packet(c->ssh, SSH1_MSG_CHANNEL_DATA,
7699 PKT_INT, c->remoteid,
7704 * In SSH-1 we can return 0 here - implying that channels are
7705 * never individually throttled - because the only
7706 * circumstance that can cause throttling will be the whole
7707 * SSH connection backing up, in which case _everything_ will
7708 * be throttled as a whole.
7715 * Attempt to send data on an SSH-2 channel.
7717 static int ssh2_try_send(struct ssh_channel *c)
7720 struct Packet *pktout;
7723 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
7726 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
7727 if ((unsigned)len > c->v.v2.remwindow)
7728 len = c->v.v2.remwindow;
7729 if ((unsigned)len > c->v.v2.remmaxpkt)
7730 len = c->v.v2.remmaxpkt;
7731 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
7732 ssh2_pkt_adduint32(pktout, c->remoteid);
7733 ssh2_pkt_addstring_start(pktout);
7734 ssh2_pkt_addstring_data(pktout, data, len);
7735 ssh2_pkt_send(ssh, pktout);
7736 bufchain_consume(&c->v.v2.outbuffer, len);
7737 c->v.v2.remwindow -= len;
7741 * After having sent as much data as we can, return the amount
7744 ret = bufchain_size(&c->v.v2.outbuffer);
7747 * And if there's no data pending but we need to send an EOF, send
7750 if (!ret && c->pending_eof)
7751 ssh_channel_try_eof(c);
7756 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
7759 if (c->closes & CLOSES_SENT_EOF)
7760 return; /* don't send on channels we've EOFed */
7761 bufsize = ssh2_try_send(c);
7764 case CHAN_MAINSESSION:
7765 /* stdin need not receive an unthrottle
7766 * notification since it will be polled */
7769 x11_unthrottle(c->u.x11.xconn);
7772 /* agent sockets are request/response and need no
7773 * buffer management */
7776 pfd_unthrottle(c->u.pfd.pf);
7782 static int ssh_is_simple(Ssh ssh)
7785 * We use the 'simple' variant of the SSH protocol if we're asked
7786 * to, except not if we're also doing connection-sharing (either
7787 * tunnelling our packets over an upstream or expecting to be
7788 * tunnelled over ourselves), since then the assumption that we
7789 * have only one channel to worry about is not true after all.
7791 return (conf_get_int(ssh->conf, CONF_ssh_simple) &&
7792 !ssh->bare_connection && !ssh->connshare);
7796 * Set up most of a new ssh_channel for SSH-2.
7798 static void ssh2_channel_init(struct ssh_channel *c)
7801 c->localid = alloc_channel_id(ssh);
7803 c->pending_eof = FALSE;
7804 c->throttling_conn = FALSE;
7805 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
7806 ssh_is_simple(ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
7807 c->v.v2.chanreq_head = NULL;
7808 c->v.v2.throttle_state = UNTHROTTLED;
7809 bufchain_init(&c->v.v2.outbuffer);
7813 * Construct the common parts of a CHANNEL_OPEN.
7815 static struct Packet *ssh2_chanopen_init(struct ssh_channel *c,
7818 struct Packet *pktout;
7820 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7821 ssh2_pkt_addstring(pktout, type);
7822 ssh2_pkt_adduint32(pktout, c->localid);
7823 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
7824 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7829 * CHANNEL_FAILURE doesn't come with any indication of what message
7830 * caused it, so we have to keep track of the outstanding
7831 * CHANNEL_REQUESTs ourselves.
7833 static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
7834 cchandler_fn_t handler, void *ctx)
7836 struct outstanding_channel_request *ocr =
7837 snew(struct outstanding_channel_request);
7839 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7840 ocr->handler = handler;
7843 if (!c->v.v2.chanreq_head)
7844 c->v.v2.chanreq_head = ocr;
7846 c->v.v2.chanreq_tail->next = ocr;
7847 c->v.v2.chanreq_tail = ocr;
7851 * Construct the common parts of a CHANNEL_REQUEST. If handler is not
7852 * NULL then a reply will be requested and the handler will be called
7853 * when it arrives. The returned packet is ready to have any
7854 * request-specific data added and be sent. Note that if a handler is
7855 * provided, it's essential that the request actually be sent.
7857 * The handler will usually be passed the response packet in pktin. If
7858 * pktin is NULL, this means that no reply will ever be forthcoming
7859 * (e.g. because the entire connection is being destroyed, or because
7860 * the server initiated channel closure before we saw the response)
7861 * and the handler should free any storage it's holding.
7863 static struct Packet *ssh2_chanreq_init(struct ssh_channel *c,
7865 cchandler_fn_t handler, void *ctx)
7867 struct Packet *pktout;
7869 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7870 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7871 ssh2_pkt_adduint32(pktout, c->remoteid);
7872 ssh2_pkt_addstring(pktout, type);
7873 ssh2_pkt_addbool(pktout, handler != NULL);
7874 if (handler != NULL)
7875 ssh2_queue_chanreq_handler(c, handler, ctx);
7879 static void ssh_channel_unthrottle(struct ssh_channel *c, int bufsize)
7884 if (ssh->version == 1) {
7885 buflimit = SSH1_BUFFER_LIMIT;
7887 if (ssh_is_simple(ssh))
7890 buflimit = c->v.v2.locmaxwin;
7891 if (bufsize < buflimit)
7892 ssh2_set_window(c, buflimit - bufsize);
7894 if (c->throttling_conn && bufsize <= buflimit) {
7895 c->throttling_conn = 0;
7896 ssh_throttle_conn(ssh, -1);
7901 * Potentially enlarge the window on an SSH-2 channel.
7903 static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
7905 static void ssh2_set_window(struct ssh_channel *c, int newwin)
7910 * Never send WINDOW_ADJUST for a channel that the remote side has
7911 * already sent EOF on; there's no point, since it won't be
7912 * sending any more data anyway. Ditto if _we've_ already sent
7915 if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
7919 * Also, never widen the window for an X11 channel when we're
7920 * still waiting to see its initial auth and may yet hand it off
7923 if (c->type == CHAN_X11 && c->u.x11.initial)
7927 * If the remote end has a habit of ignoring maxpkt, limit the
7928 * window so that it has no choice (assuming it doesn't ignore the
7931 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
7932 newwin = OUR_V2_MAXPKT;
7935 * Only send a WINDOW_ADJUST if there's significantly more window
7936 * available than the other end thinks there is. This saves us
7937 * sending a WINDOW_ADJUST for every character in a shell session.
7939 * "Significant" is arbitrarily defined as half the window size.
7941 if (newwin / 2 >= c->v.v2.locwindow) {
7942 struct Packet *pktout;
7946 * In order to keep track of how much window the client
7947 * actually has available, we'd like it to acknowledge each
7948 * WINDOW_ADJUST. We can't do that directly, so we accompany
7949 * it with a CHANNEL_REQUEST that has to be acknowledged.
7951 * This is only necessary if we're opening the window wide.
7952 * If we're not, then throughput is being constrained by
7953 * something other than the maximum window size anyway.
7955 if (newwin == c->v.v2.locmaxwin &&
7956 !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
7957 up = snew(unsigned);
7958 *up = newwin - c->v.v2.locwindow;
7959 pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org",
7960 ssh2_handle_winadj_response, up);
7961 ssh2_pkt_send(ssh, pktout);
7963 if (c->v.v2.throttle_state != UNTHROTTLED)
7964 c->v.v2.throttle_state = UNTHROTTLING;
7966 /* Pretend the WINDOW_ADJUST was acked immediately. */
7967 c->v.v2.remlocwin = newwin;
7968 c->v.v2.throttle_state = THROTTLED;
7970 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
7971 ssh2_pkt_adduint32(pktout, c->remoteid);
7972 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
7973 ssh2_pkt_send(ssh, pktout);
7974 c->v.v2.locwindow = newwin;
7979 * Find the channel associated with a message. If there's no channel,
7980 * or it's not properly open, make a noise about it and return NULL.
7982 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
7984 unsigned localid = ssh_pkt_getuint32(pktin);
7985 struct ssh_channel *c;
7987 c = find234(ssh->channels, &localid, ssh_channelfind);
7989 (c->type != CHAN_SHARING && c->halfopen &&
7990 pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
7991 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
7992 char *buf = dupprintf("Received %s for %s channel %u",
7993 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
7995 c ? "half-open" : "nonexistent", localid);
7996 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
8003 static void ssh2_handle_winadj_response(struct ssh_channel *c,
8004 struct Packet *pktin, void *ctx)
8006 unsigned *sizep = ctx;
8009 * Winadj responses should always be failures. However, at least
8010 * one server ("boks_sshd") is known to return SUCCESS for channel
8011 * requests it's never heard of, such as "winadj@putty". Raised
8012 * with foxt.com as bug 090916-090424, but for the sake of a quiet
8013 * life, we don't worry about what kind of response we got.
8016 c->v.v2.remlocwin += *sizep;
8019 * winadj messages are only sent when the window is fully open, so
8020 * if we get an ack of one, we know any pending unthrottle is
8023 if (c->v.v2.throttle_state == UNTHROTTLING)
8024 c->v.v2.throttle_state = UNTHROTTLED;
8027 static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
8029 struct ssh_channel *c = ssh2_channel_msg(ssh, pktin);
8030 struct outstanding_channel_request *ocr;
8033 if (c->type == CHAN_SHARING) {
8034 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8035 pktin->body, pktin->length);
8038 ocr = c->v.v2.chanreq_head;
8040 ssh2_msg_unexpected(ssh, pktin);
8043 ocr->handler(c, pktin, ocr->ctx);
8044 c->v.v2.chanreq_head = ocr->next;
8047 * We may now initiate channel-closing procedures, if that
8048 * CHANNEL_REQUEST was the last thing outstanding before we send
8051 ssh2_channel_check_close(c);
8054 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
8056 struct ssh_channel *c;
8057 c = ssh2_channel_msg(ssh, pktin);
8060 if (c->type == CHAN_SHARING) {
8061 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8062 pktin->body, pktin->length);
8065 if (!(c->closes & CLOSES_SENT_EOF)) {
8066 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
8067 ssh2_try_send_and_unthrottle(ssh, c);
8071 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
8075 struct ssh_channel *c;
8076 c = ssh2_channel_msg(ssh, pktin);
8079 if (c->type == CHAN_SHARING) {
8080 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8081 pktin->body, pktin->length);
8084 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
8085 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
8086 return; /* extended but not stderr */
8087 ssh_pkt_getstring(pktin, &data, &length);
8090 c->v.v2.locwindow -= length;
8091 c->v.v2.remlocwin -= length;
8092 bufsize = ssh_channel_data(c, pktin->type ==
8093 SSH2_MSG_CHANNEL_EXTENDED_DATA,
8096 * If it looks like the remote end hit the end of its window,
8097 * and we didn't want it to do that, think about using a
8100 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
8101 c->v.v2.locmaxwin < 0x40000000)
8102 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
8104 * If we are not buffering too much data,
8105 * enlarge the window again at the remote side.
8106 * If we are buffering too much, we may still
8107 * need to adjust the window if the server's
8110 if (bufsize < c->v.v2.locmaxwin)
8111 ssh2_set_window(c, c->v.v2.locmaxwin - bufsize);
8113 * If we're either buffering way too much data, or if we're
8114 * buffering anything at all and we're in "simple" mode,
8115 * throttle the whole channel.
8117 if ((bufsize > c->v.v2.locmaxwin || (ssh_is_simple(ssh) && bufsize>0))
8118 && !c->throttling_conn) {
8119 c->throttling_conn = 1;
8120 ssh_throttle_conn(ssh, +1);
8125 static void ssh_check_termination(Ssh ssh)
8127 if (ssh->version == 2 &&
8128 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
8129 (ssh->channels && count234(ssh->channels) == 0) &&
8130 !(ssh->connshare && share_ndownstreams(ssh->connshare) > 0)) {
8132 * We used to send SSH_MSG_DISCONNECT here, because I'd
8133 * believed that _every_ conforming SSH-2 connection had to
8134 * end with a disconnect being sent by at least one side;
8135 * apparently I was wrong and it's perfectly OK to
8136 * unceremoniously slam the connection shut when you're done,
8137 * and indeed OpenSSH feels this is more polite than sending a
8138 * DISCONNECT. So now we don't.
8140 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
8144 void ssh_sharing_downstream_connected(Ssh ssh, unsigned id,
8145 const char *peerinfo)
8148 logeventf(ssh, "Connection sharing downstream #%u connected from %s",
8151 logeventf(ssh, "Connection sharing downstream #%u connected", id);
8154 void ssh_sharing_downstream_disconnected(Ssh ssh, unsigned id)
8156 logeventf(ssh, "Connection sharing downstream #%u disconnected", id);
8157 ssh_check_termination(ssh);
8160 void ssh_sharing_logf(Ssh ssh, unsigned id, const char *logfmt, ...)
8165 va_start(ap, logfmt);
8166 buf = dupvprintf(logfmt, ap);
8169 logeventf(ssh, "Connection sharing downstream #%u: %s", id, buf);
8171 logeventf(ssh, "Connection sharing: %s", buf);
8175 static void ssh_channel_destroy(struct ssh_channel *c)
8180 case CHAN_MAINSESSION:
8181 ssh->mainchan = NULL;
8182 update_specials_menu(ssh->frontend);
8185 if (c->u.x11.xconn != NULL)
8186 x11_close(c->u.x11.xconn);
8187 logevent("Forwarded X11 connection terminated");
8190 sfree(c->u.a.message);
8193 if (c->u.pfd.pf != NULL)
8194 pfd_close(c->u.pfd.pf);
8195 logevent("Forwarded port closed");
8199 del234(ssh->channels, c);
8200 if (ssh->version == 2) {
8201 bufchain_clear(&c->v.v2.outbuffer);
8202 assert(c->v.v2.chanreq_head == NULL);
8207 * If that was the last channel left open, we might need to
8210 ssh_check_termination(ssh);
8213 static void ssh2_channel_check_close(struct ssh_channel *c)
8216 struct Packet *pktout;
8220 * If we've sent out our own CHANNEL_OPEN but not yet seen
8221 * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
8222 * it's too early to be sending close messages of any kind.
8227 if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
8228 c->type == CHAN_ZOMBIE) &&
8229 !c->v.v2.chanreq_head &&
8230 !(c->closes & CLOSES_SENT_CLOSE)) {
8232 * We have both sent and received EOF (or the channel is a
8233 * zombie), and we have no outstanding channel requests, which
8234 * means the channel is in final wind-up. But we haven't sent
8235 * CLOSE, so let's do so now.
8237 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
8238 ssh2_pkt_adduint32(pktout, c->remoteid);
8239 ssh2_pkt_send(ssh, pktout);
8240 c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
8243 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
8244 assert(c->v.v2.chanreq_head == NULL);
8246 * We have both sent and received CLOSE, which means we're
8247 * completely done with the channel.
8249 ssh_channel_destroy(c);
8253 static void ssh2_channel_got_eof(struct ssh_channel *c)
8255 if (c->closes & CLOSES_RCVD_EOF)
8256 return; /* already seen EOF */
8257 c->closes |= CLOSES_RCVD_EOF;
8259 if (c->type == CHAN_X11) {
8260 x11_send_eof(c->u.x11.xconn);
8261 } else if (c->type == CHAN_AGENT) {
8262 if (c->u.a.outstanding_requests == 0) {
8263 /* Manufacture an outgoing EOF in response to the incoming one. */
8264 sshfwd_write_eof(c);
8266 } else if (c->type == CHAN_SOCKDATA) {
8267 pfd_send_eof(c->u.pfd.pf);
8268 } else if (c->type == CHAN_MAINSESSION) {
8271 if (!ssh->sent_console_eof &&
8272 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
8274 * Either from_backend_eof told us that the front end
8275 * wants us to close the outgoing side of the connection
8276 * as soon as we see EOF from the far end, or else we've
8277 * unilaterally decided to do that because we've allocated
8278 * a remote pty and hence EOF isn't a particularly
8279 * meaningful concept.
8281 sshfwd_write_eof(c);
8283 ssh->sent_console_eof = TRUE;
8286 ssh2_channel_check_close(c);
8289 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
8291 struct ssh_channel *c;
8293 c = ssh2_channel_msg(ssh, pktin);
8296 if (c->type == CHAN_SHARING) {
8297 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8298 pktin->body, pktin->length);
8301 ssh2_channel_got_eof(c);
8304 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
8306 struct ssh_channel *c;
8308 c = ssh2_channel_msg(ssh, pktin);
8311 if (c->type == CHAN_SHARING) {
8312 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8313 pktin->body, pktin->length);
8318 * When we receive CLOSE on a channel, we assume it comes with an
8319 * implied EOF if we haven't seen EOF yet.
8321 ssh2_channel_got_eof(c);
8323 if (!(ssh->remote_bugs & BUG_SENDS_LATE_REQUEST_REPLY)) {
8325 * It also means we stop expecting to see replies to any
8326 * outstanding channel requests, so clean those up too.
8327 * (ssh_chanreq_init will enforce by assertion that we don't
8328 * subsequently put anything back on this list.)
8330 while (c->v.v2.chanreq_head) {
8331 struct outstanding_channel_request *ocr = c->v.v2.chanreq_head;
8332 ocr->handler(c, NULL, ocr->ctx);
8333 c->v.v2.chanreq_head = ocr->next;
8339 * And we also send an outgoing EOF, if we haven't already, on the
8340 * assumption that CLOSE is a pretty forceful announcement that
8341 * the remote side is doing away with the entire channel. (If it
8342 * had wanted to send us EOF and continue receiving data from us,
8343 * it would have just sent CHANNEL_EOF.)
8345 if (!(c->closes & CLOSES_SENT_EOF)) {
8347 * Make sure we don't read any more from whatever our local
8348 * data source is for this channel.
8351 case CHAN_MAINSESSION:
8352 ssh->send_ok = 0; /* stop trying to read from stdin */
8355 x11_override_throttle(c->u.x11.xconn, 1);
8358 pfd_override_throttle(c->u.pfd.pf, 1);
8363 * Abandon any buffered data we still wanted to send to this
8364 * channel. Receiving a CHANNEL_CLOSE is an indication that
8365 * the server really wants to get on and _destroy_ this
8366 * channel, and it isn't going to send us any further
8367 * WINDOW_ADJUSTs to permit us to send pending stuff.
8369 bufchain_clear(&c->v.v2.outbuffer);
8372 * Send outgoing EOF.
8374 sshfwd_write_eof(c);
8378 * Now process the actual close.
8380 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
8381 c->closes |= CLOSES_RCVD_CLOSE;
8382 ssh2_channel_check_close(c);
8386 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
8388 struct ssh_channel *c;
8390 c = ssh2_channel_msg(ssh, pktin);
8393 if (c->type == CHAN_SHARING) {
8394 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8395 pktin->body, pktin->length);
8398 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
8399 c->remoteid = ssh_pkt_getuint32(pktin);
8400 c->halfopen = FALSE;
8401 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8402 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8404 if (c->type == CHAN_SOCKDATA_DORMANT) {
8405 c->type = CHAN_SOCKDATA;
8407 pfd_confirm(c->u.pfd.pf);
8408 } else if (c->type == CHAN_ZOMBIE) {
8410 * This case can occur if a local socket error occurred
8411 * between us sending out CHANNEL_OPEN and receiving
8412 * OPEN_CONFIRMATION. In this case, all we can do is
8413 * immediately initiate close proceedings now that we know the
8414 * server's id to put in the close message.
8416 ssh2_channel_check_close(c);
8419 * We never expect to receive OPEN_CONFIRMATION for any
8420 * *other* channel type (since only local-to-remote port
8421 * forwardings cause us to send CHANNEL_OPEN after the main
8422 * channel is live - all other auxiliary channel types are
8423 * initiated from the server end). It's safe to enforce this
8424 * by assertion rather than by ssh_disconnect, because the
8425 * real point is that we never constructed a half-open channel
8426 * structure in the first place with any type other than the
8429 assert(!"Funny channel type in ssh2_msg_channel_open_confirmation");
8433 ssh_channel_try_eof(c); /* in case we had a pending EOF */
8436 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
8438 static const char *const reasons[] = {
8439 "<unknown reason code>",
8440 "Administratively prohibited",
8442 "Unknown channel type",
8443 "Resource shortage",
8445 unsigned reason_code;
8446 char *reason_string;
8448 struct ssh_channel *c;
8450 c = ssh2_channel_msg(ssh, pktin);
8453 if (c->type == CHAN_SHARING) {
8454 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8455 pktin->body, pktin->length);
8458 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
8460 if (c->type == CHAN_SOCKDATA_DORMANT) {
8461 reason_code = ssh_pkt_getuint32(pktin);
8462 if (reason_code >= lenof(reasons))
8463 reason_code = 0; /* ensure reasons[reason_code] in range */
8464 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
8465 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
8466 reasons[reason_code], reason_length,
8467 NULLTOEMPTY(reason_string));
8469 pfd_close(c->u.pfd.pf);
8470 } else if (c->type == CHAN_ZOMBIE) {
8472 * This case can occur if a local socket error occurred
8473 * between us sending out CHANNEL_OPEN and receiving
8474 * OPEN_FAILURE. In this case, we need do nothing except allow
8475 * the code below to throw the half-open channel away.
8479 * We never expect to receive OPEN_FAILURE for any *other*
8480 * channel type (since only local-to-remote port forwardings
8481 * cause us to send CHANNEL_OPEN after the main channel is
8482 * live - all other auxiliary channel types are initiated from
8483 * the server end). It's safe to enforce this by assertion
8484 * rather than by ssh_disconnect, because the real point is
8485 * that we never constructed a half-open channel structure in
8486 * the first place with any type other than the above.
8488 assert(!"Funny channel type in ssh2_msg_channel_open_failure");
8491 del234(ssh->channels, c);
8495 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
8498 int typelen, want_reply;
8499 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
8500 struct ssh_channel *c;
8501 struct Packet *pktout;
8503 c = ssh2_channel_msg(ssh, pktin);
8506 if (c->type == CHAN_SHARING) {
8507 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8508 pktin->body, pktin->length);
8511 ssh_pkt_getstring(pktin, &type, &typelen);
8512 want_reply = ssh2_pkt_getbool(pktin);
8514 if (c->closes & CLOSES_SENT_CLOSE) {
8516 * We don't reply to channel requests after we've sent
8517 * CHANNEL_CLOSE for the channel, because our reply might
8518 * cross in the network with the other side's CHANNEL_CLOSE
8519 * and arrive after they have wound the channel up completely.
8525 * Having got the channel number, we now look at
8526 * the request type string to see if it's something
8529 if (c == ssh->mainchan) {
8531 * We recognise "exit-status" and "exit-signal" on
8532 * the primary channel.
8534 if (typelen == 11 &&
8535 !memcmp(type, "exit-status", 11)) {
8537 ssh->exitcode = ssh_pkt_getuint32(pktin);
8538 logeventf(ssh, "Server sent command exit status %d",
8540 reply = SSH2_MSG_CHANNEL_SUCCESS;
8542 } else if (typelen == 11 &&
8543 !memcmp(type, "exit-signal", 11)) {
8545 int is_plausible = TRUE, is_int = FALSE;
8546 char *fmt_sig = NULL, *fmt_msg = NULL;
8548 int msglen = 0, core = FALSE;
8549 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
8550 * provide an `int' for the signal, despite its
8551 * having been a `string' in the drafts of RFC 4254 since at
8552 * least 2001. (Fixed in session.c 1.147.) Try to
8553 * infer which we can safely parse it as. */
8555 unsigned char *p = pktin->body +
8557 long len = pktin->length - pktin->savedpos;
8558 unsigned long num = GET_32BIT(p); /* what is it? */
8559 /* If it's 0, it hardly matters; assume string */
8563 int maybe_int = FALSE, maybe_str = FALSE;
8564 #define CHECK_HYPOTHESIS(offset, result) \
8567 int q = toint(offset); \
8568 if (q >= 0 && q+4 <= len) { \
8569 q = toint(q + 4 + GET_32BIT(p+q)); \
8570 if (q >= 0 && q+4 <= len && \
8571 ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
8576 CHECK_HYPOTHESIS(4+1, maybe_int);
8577 CHECK_HYPOTHESIS(4+num+1, maybe_str);
8578 #undef CHECK_HYPOTHESIS
8579 if (maybe_int && !maybe_str)
8581 else if (!maybe_int && maybe_str)
8584 /* Crikey. Either or neither. Panic. */
8585 is_plausible = FALSE;
8588 ssh->exitcode = 128; /* means `unknown signal' */
8591 /* Old non-standard OpenSSH. */
8592 int signum = ssh_pkt_getuint32(pktin);
8593 fmt_sig = dupprintf(" %d", signum);
8594 ssh->exitcode = 128 + signum;
8596 /* As per RFC 4254. */
8599 ssh_pkt_getstring(pktin, &sig, &siglen);
8600 /* Signal name isn't supposed to be blank, but
8601 * let's cope gracefully if it is. */
8603 fmt_sig = dupprintf(" \"%.*s\"",
8608 * Really hideous method of translating the
8609 * signal description back into a locally
8610 * meaningful number.
8615 #define TRANSLATE_SIGNAL(s) \
8616 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
8617 ssh->exitcode = 128 + SIG ## s
8619 TRANSLATE_SIGNAL(ABRT);
8622 TRANSLATE_SIGNAL(ALRM);
8625 TRANSLATE_SIGNAL(FPE);
8628 TRANSLATE_SIGNAL(HUP);
8631 TRANSLATE_SIGNAL(ILL);
8634 TRANSLATE_SIGNAL(INT);
8637 TRANSLATE_SIGNAL(KILL);
8640 TRANSLATE_SIGNAL(PIPE);
8643 TRANSLATE_SIGNAL(QUIT);
8646 TRANSLATE_SIGNAL(SEGV);
8649 TRANSLATE_SIGNAL(TERM);
8652 TRANSLATE_SIGNAL(USR1);
8655 TRANSLATE_SIGNAL(USR2);
8657 #undef TRANSLATE_SIGNAL
8659 ssh->exitcode = 128;
8661 core = ssh2_pkt_getbool(pktin);
8662 ssh_pkt_getstring(pktin, &msg, &msglen);
8664 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
8666 /* ignore lang tag */
8667 } /* else don't attempt to parse */
8668 logeventf(ssh, "Server exited on signal%s%s%s",
8669 fmt_sig ? fmt_sig : "",
8670 core ? " (core dumped)" : "",
8671 fmt_msg ? fmt_msg : "");
8674 reply = SSH2_MSG_CHANNEL_SUCCESS;
8679 * This is a channel request we don't know
8680 * about, so we now either ignore the request
8681 * or respond with CHANNEL_FAILURE, depending
8684 reply = SSH2_MSG_CHANNEL_FAILURE;
8687 pktout = ssh2_pkt_init(reply);
8688 ssh2_pkt_adduint32(pktout, c->remoteid);
8689 ssh2_pkt_send(ssh, pktout);
8693 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
8696 int typelen, want_reply;
8697 struct Packet *pktout;
8699 ssh_pkt_getstring(pktin, &type, &typelen);
8700 want_reply = ssh2_pkt_getbool(pktin);
8703 * We currently don't support any global requests
8704 * at all, so we either ignore the request or
8705 * respond with REQUEST_FAILURE, depending on
8709 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
8710 ssh2_pkt_send(ssh, pktout);
8714 struct X11FakeAuth *ssh_sharing_add_x11_display(Ssh ssh, int authtype,
8718 struct X11FakeAuth *auth;
8721 * Make up a new set of fake X11 auth data, and add it to the tree
8722 * of currently valid ones with an indication of the sharing
8723 * context that it's relevant to.
8725 auth = x11_invent_fake_auth(ssh->x11authtree, authtype);
8726 auth->share_cs = share_cs;
8727 auth->share_chan = share_chan;
8732 void ssh_sharing_remove_x11_display(Ssh ssh, struct X11FakeAuth *auth)
8734 del234(ssh->x11authtree, auth);
8735 x11_free_fake_auth(auth);
8738 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
8745 const char *error = NULL;
8746 struct ssh_channel *c;
8747 unsigned remid, winsize, pktsize;
8748 unsigned our_winsize_override = 0;
8749 struct Packet *pktout;
8751 ssh_pkt_getstring(pktin, &type, &typelen);
8752 c = snew(struct ssh_channel);
8755 remid = ssh_pkt_getuint32(pktin);
8756 winsize = ssh_pkt_getuint32(pktin);
8757 pktsize = ssh_pkt_getuint32(pktin);
8759 if (typelen == 3 && !memcmp(type, "x11", 3)) {
8762 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8763 addrstr = dupprintf("%.*s", peeraddrlen, NULLTOEMPTY(peeraddr));
8764 peerport = ssh_pkt_getuint32(pktin);
8766 logeventf(ssh, "Received X11 connect request from %s:%d",
8769 if (!ssh->X11_fwd_enabled && !ssh->connshare)
8770 error = "X11 forwarding is not enabled";
8772 c->u.x11.xconn = x11_init(ssh->x11authtree, c,
8775 c->u.x11.initial = TRUE;
8778 * If we are a connection-sharing upstream, then we should
8779 * initially present a very small window, adequate to take
8780 * the X11 initial authorisation packet but not much more.
8781 * Downstream will then present us a larger window (by
8782 * fiat of the connection-sharing protocol) and we can
8783 * guarantee to send a positive-valued WINDOW_ADJUST.
8786 our_winsize_override = 128;
8788 logevent("Opened X11 forward channel");
8792 } else if (typelen == 15 &&
8793 !memcmp(type, "forwarded-tcpip", 15)) {
8794 struct ssh_rportfwd pf, *realpf;
8797 ssh_pkt_getstring(pktin, &shost, &shostlen);/* skip address */
8798 pf.shost = dupprintf("%.*s", shostlen, NULLTOEMPTY(shost));
8799 pf.sport = ssh_pkt_getuint32(pktin);
8800 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8801 peerport = ssh_pkt_getuint32(pktin);
8802 realpf = find234(ssh->rportfwds, &pf, NULL);
8803 logeventf(ssh, "Received remote port %s:%d open request "
8804 "from %.*s:%d", pf.shost, pf.sport,
8805 peeraddrlen, NULLTOEMPTY(peeraddr), peerport);
8808 if (realpf == NULL) {
8809 error = "Remote port is not recognised";
8813 if (realpf->share_ctx) {
8815 * This port forwarding is on behalf of a
8816 * connection-sharing downstream, so abandon our own
8817 * channel-open procedure and just pass the message on
8820 share_got_pkt_from_server(realpf->share_ctx, pktin->type,
8821 pktin->body, pktin->length);
8826 err = pfd_connect(&c->u.pfd.pf, realpf->dhost, realpf->dport,
8827 c, ssh->conf, realpf->pfrec->addressfamily);
8828 logeventf(ssh, "Attempting to forward remote port to "
8829 "%s:%d", realpf->dhost, realpf->dport);
8831 logeventf(ssh, "Port open failed: %s", err);
8833 error = "Port open failed";
8835 logevent("Forwarded port opened successfully");
8836 c->type = CHAN_SOCKDATA;
8839 } else if (typelen == 22 &&
8840 !memcmp(type, "auth-agent@openssh.com", 22)) {
8841 if (!ssh->agentfwd_enabled)
8842 error = "Agent forwarding is not enabled";
8844 c->type = CHAN_AGENT; /* identify channel type */
8845 c->u.a.lensofar = 0;
8846 c->u.a.message = NULL;
8847 c->u.a.outstanding_requests = 0;
8850 error = "Unsupported channel type requested";
8853 c->remoteid = remid;
8854 c->halfopen = FALSE;
8856 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
8857 ssh2_pkt_adduint32(pktout, c->remoteid);
8858 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
8859 ssh2_pkt_addstring(pktout, error);
8860 ssh2_pkt_addstring(pktout, "en"); /* language tag */
8861 ssh2_pkt_send(ssh, pktout);
8862 logeventf(ssh, "Rejected channel open: %s", error);
8865 ssh2_channel_init(c);
8866 c->v.v2.remwindow = winsize;
8867 c->v.v2.remmaxpkt = pktsize;
8868 if (our_winsize_override) {
8869 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
8870 our_winsize_override;
8872 add234(ssh->channels, c);
8873 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
8874 ssh2_pkt_adduint32(pktout, c->remoteid);
8875 ssh2_pkt_adduint32(pktout, c->localid);
8876 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
8877 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
8878 ssh2_pkt_send(ssh, pktout);
8882 void sshfwd_x11_sharing_handover(struct ssh_channel *c,
8883 void *share_cs, void *share_chan,
8884 const char *peer_addr, int peer_port,
8885 int endian, int protomajor, int protominor,
8886 const void *initial_data, int initial_len)
8889 * This function is called when we've just discovered that an X
8890 * forwarding channel on which we'd been handling the initial auth
8891 * ourselves turns out to be destined for a connection-sharing
8892 * downstream. So we turn the channel into a CHAN_SHARING, meaning
8893 * that we completely stop tracking windows and buffering data and
8894 * just pass more or less unmodified SSH messages back and forth.
8896 c->type = CHAN_SHARING;
8897 c->u.sharing.ctx = share_cs;
8898 share_setup_x11_channel(share_cs, share_chan,
8899 c->localid, c->remoteid, c->v.v2.remwindow,
8900 c->v.v2.remmaxpkt, c->v.v2.locwindow,
8901 peer_addr, peer_port, endian,
8902 protomajor, protominor,
8903 initial_data, initial_len);
8906 void sshfwd_x11_is_local(struct ssh_channel *c)
8909 * This function is called when we've just discovered that an X
8910 * forwarding channel is _not_ destined for a connection-sharing
8911 * downstream but we're going to handle it ourselves. We stop
8912 * presenting a cautiously small window and go into ordinary data
8915 c->u.x11.initial = FALSE;
8916 ssh2_set_window(c, ssh_is_simple(c->ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE);
8920 * Buffer banner messages for later display at some convenient point,
8921 * if we're going to display them.
8923 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
8925 /* Arbitrary limit to prevent unbounded inflation of buffer */
8926 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
8927 bufchain_size(&ssh->banner) <= 131072) {
8928 char *banner = NULL;
8930 ssh_pkt_getstring(pktin, &banner, &size);
8932 bufchain_add(&ssh->banner, banner, size);
8936 /* Helper function to deal with sending tty modes for "pty-req" */
8937 static void ssh2_send_ttymode(void *data,
8938 const struct ssh_ttymode *mode, char *val)
8940 struct Packet *pktout = (struct Packet *)data;
8941 unsigned int arg = 0;
8943 switch (mode->type) {
8945 arg = ssh_tty_parse_specchar(val);
8948 arg = ssh_tty_parse_boolean(val);
8951 ssh2_pkt_addbyte(pktout, mode->opcode);
8952 ssh2_pkt_adduint32(pktout, arg);
8955 static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
8958 struct ssh2_setup_x11_state {
8962 struct Packet *pktout;
8963 crStateP(ssh2_setup_x11_state, ctx);
8967 logevent("Requesting X11 forwarding");
8968 pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
8970 ssh2_pkt_addbool(pktout, 0); /* many connections */
8971 ssh2_pkt_addstring(pktout, ssh->x11auth->protoname);
8972 ssh2_pkt_addstring(pktout, ssh->x11auth->datastring);
8973 ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
8974 ssh2_pkt_send(ssh, pktout);
8976 /* Wait to be called back with either a response packet, or NULL
8977 * meaning clean up and free our data */
8981 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8982 logevent("X11 forwarding enabled");
8983 ssh->X11_fwd_enabled = TRUE;
8985 logevent("X11 forwarding refused");
8991 static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
8994 struct ssh2_setup_agent_state {
8998 struct Packet *pktout;
8999 crStateP(ssh2_setup_agent_state, ctx);
9003 logevent("Requesting OpenSSH-style agent forwarding");
9004 pktout = ssh2_chanreq_init(ssh->mainchan, "auth-agent-req@openssh.com",
9005 ssh2_setup_agent, s);
9006 ssh2_pkt_send(ssh, pktout);
9008 /* Wait to be called back with either a response packet, or NULL
9009 * meaning clean up and free our data */
9013 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
9014 logevent("Agent forwarding enabled");
9015 ssh->agentfwd_enabled = TRUE;
9017 logevent("Agent forwarding refused");
9023 static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
9026 struct ssh2_setup_pty_state {
9030 struct Packet *pktout;
9031 crStateP(ssh2_setup_pty_state, ctx);
9035 /* Unpick the terminal-speed string. */
9036 /* XXX perhaps we should allow no speeds to be sent. */
9037 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
9038 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
9039 /* Build the pty request. */
9040 pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
9042 ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
9043 ssh2_pkt_adduint32(pktout, ssh->term_width);
9044 ssh2_pkt_adduint32(pktout, ssh->term_height);
9045 ssh2_pkt_adduint32(pktout, 0); /* pixel width */
9046 ssh2_pkt_adduint32(pktout, 0); /* pixel height */
9047 ssh2_pkt_addstring_start(pktout);
9048 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
9049 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
9050 ssh2_pkt_adduint32(pktout, ssh->ispeed);
9051 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
9052 ssh2_pkt_adduint32(pktout, ssh->ospeed);
9053 ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
9054 ssh2_pkt_send(ssh, pktout);
9055 ssh->state = SSH_STATE_INTERMED;
9057 /* Wait to be called back with either a response packet, or NULL
9058 * meaning clean up and free our data */
9062 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
9063 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
9064 ssh->ospeed, ssh->ispeed);
9065 ssh->got_pty = TRUE;
9067 c_write_str(ssh, "Server refused to allocate pty\r\n");
9068 ssh->editing = ssh->echoing = 1;
9075 static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
9078 struct ssh2_setup_env_state {
9080 int num_env, env_left, env_ok;
9083 struct Packet *pktout;
9084 crStateP(ssh2_setup_env_state, ctx);
9089 * Send environment variables.
9091 * Simplest thing here is to send all the requests at once, and
9092 * then wait for a whole bunch of successes or failures.
9098 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
9100 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
9101 pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
9102 ssh2_pkt_addstring(pktout, key);
9103 ssh2_pkt_addstring(pktout, val);
9104 ssh2_pkt_send(ssh, pktout);
9109 logeventf(ssh, "Sent %d environment variables", s->num_env);
9114 s->env_left = s->num_env;
9116 while (s->env_left > 0) {
9117 /* Wait to be called back with either a response packet,
9118 * or NULL meaning clean up and free our data */
9120 if (!pktin) goto out;
9121 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
9126 if (s->env_ok == s->num_env) {
9127 logevent("All environment variables successfully set");
9128 } else if (s->env_ok == 0) {
9129 logevent("All environment variables refused");
9130 c_write_str(ssh, "Server refused to set environment variables\r\n");
9132 logeventf(ssh, "%d environment variables refused",
9133 s->num_env - s->env_ok);
9134 c_write_str(ssh, "Server refused to set all environment variables\r\n");
9142 * Handle the SSH-2 userauth and connection layers.
9144 static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
9146 do_ssh2_authconn(ssh, NULL, 0, pktin);
9149 static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
9153 do_ssh2_authconn(c->ssh, NULL, 0, pktin);
9156 static void do_ssh2_authconn(Ssh ssh, const unsigned char *in, int inlen,
9157 struct Packet *pktin)
9159 struct do_ssh2_authconn_state {
9163 AUTH_TYPE_PUBLICKEY,
9164 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
9165 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
9167 AUTH_TYPE_GSSAPI, /* always QUIET */
9168 AUTH_TYPE_KEYBOARD_INTERACTIVE,
9169 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
9171 int done_service_req;
9172 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
9173 int tried_pubkey_config, done_agent;
9178 int kbd_inter_refused;
9179 int we_are_in, userauth_success;
9180 prompts_t *cur_prompt;
9185 void *publickey_blob;
9186 int publickey_bloblen;
9187 int privatekey_available, privatekey_encrypted;
9188 char *publickey_algorithm;
9189 char *publickey_comment;
9190 unsigned char agent_request[5], *agent_response, *agentp;
9191 int agent_responselen;
9192 unsigned char *pkblob_in_agent;
9194 char *pkblob, *alg, *commentp;
9195 int pklen, alglen, commentlen;
9196 int siglen, retlen, len;
9197 char *q, *agentreq, *ret;
9198 struct Packet *pktout;
9201 struct ssh_gss_library *gsslib;
9202 Ssh_gss_ctx gss_ctx;
9203 Ssh_gss_buf gss_buf;
9204 Ssh_gss_buf gss_rcvtok, gss_sndtok;
9205 Ssh_gss_name gss_srv_name;
9206 Ssh_gss_stat gss_stat;
9209 crState(do_ssh2_authconn_state);
9213 /* Register as a handler for all the messages this coroutine handles. */
9214 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
9215 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
9216 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
9217 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
9218 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
9219 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
9220 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
9221 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
9222 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
9223 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
9224 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
9225 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
9226 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
9227 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
9228 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
9229 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
9230 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
9231 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
9232 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
9233 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
9235 s->done_service_req = FALSE;
9236 s->we_are_in = s->userauth_success = FALSE;
9237 s->agent_response = NULL;
9239 s->tried_gssapi = FALSE;
9242 if (!ssh->bare_connection) {
9243 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
9245 * Request userauth protocol, and await a response to it.
9247 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
9248 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
9249 ssh2_pkt_send(ssh, s->pktout);
9250 crWaitUntilV(pktin);
9251 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
9252 s->done_service_req = TRUE;
9254 if (!s->done_service_req) {
9256 * Request connection protocol directly, without authentication.
9258 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
9259 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9260 ssh2_pkt_send(ssh, s->pktout);
9261 crWaitUntilV(pktin);
9262 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
9263 s->we_are_in = TRUE; /* no auth required */
9265 bombout(("Server refused service request"));
9270 s->we_are_in = TRUE;
9273 /* Arrange to be able to deal with any BANNERs that come in.
9274 * (We do this now as packets may come in during the next bit.) */
9275 bufchain_init(&ssh->banner);
9276 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
9277 ssh2_msg_userauth_banner;
9280 * Misc one-time setup for authentication.
9282 s->publickey_blob = NULL;
9283 if (!s->we_are_in) {
9286 * Load the public half of any configured public key file
9289 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9290 if (!filename_is_null(s->keyfile)) {
9292 logeventf(ssh, "Reading key file \"%.150s\"",
9293 filename_to_str(s->keyfile));
9294 keytype = key_type(s->keyfile);
9295 if (keytype == SSH_KEYTYPE_SSH2 ||
9296 keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 ||
9297 keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
9300 ssh2_userkey_loadpub(s->keyfile,
9301 &s->publickey_algorithm,
9302 &s->publickey_bloblen,
9303 &s->publickey_comment, &error);
9304 if (s->publickey_blob) {
9305 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH2);
9306 if (!s->privatekey_available)
9307 logeventf(ssh, "Key file contains public key only");
9308 s->privatekey_encrypted =
9309 ssh2_userkey_encrypted(s->keyfile, NULL);
9312 logeventf(ssh, "Unable to load key (%s)",
9314 msgbuf = dupprintf("Unable to load key file "
9315 "\"%.150s\" (%s)\r\n",
9316 filename_to_str(s->keyfile),
9318 c_write_str(ssh, msgbuf);
9323 logeventf(ssh, "Unable to use this key file (%s)",
9324 key_type_to_str(keytype));
9325 msgbuf = dupprintf("Unable to use key file \"%.150s\""
9327 filename_to_str(s->keyfile),
9328 key_type_to_str(keytype));
9329 c_write_str(ssh, msgbuf);
9331 s->publickey_blob = NULL;
9336 * Find out about any keys Pageant has (but if there's a
9337 * public key configured, filter out all others).
9340 s->agent_response = NULL;
9341 s->pkblob_in_agent = NULL;
9342 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
9346 logevent("Pageant is running. Requesting keys.");
9348 /* Request the keys held by the agent. */
9349 PUT_32BIT(s->agent_request, 1);
9350 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
9351 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
9352 ssh_agent_callback, ssh)) {
9356 bombout(("Unexpected data from server while"
9357 " waiting for agent response"));
9360 } while (pktin || inlen > 0);
9361 r = ssh->agent_response;
9362 s->agent_responselen = ssh->agent_response_len;
9364 s->agent_response = (unsigned char *) r;
9365 if (s->agent_response && s->agent_responselen >= 5 &&
9366 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
9369 p = s->agent_response + 5;
9370 s->nkeys = toint(GET_32BIT(p));
9373 * Vet the Pageant response to ensure that the key
9374 * count and blob lengths make sense.
9377 logeventf(ssh, "Pageant response contained a negative"
9378 " key count %d", s->nkeys);
9380 goto done_agent_query;
9382 unsigned char *q = p + 4;
9383 int lenleft = s->agent_responselen - 5 - 4;
9385 for (keyi = 0; keyi < s->nkeys; keyi++) {
9386 int bloblen, commentlen;
9388 logeventf(ssh, "Pageant response was truncated");
9390 goto done_agent_query;
9392 bloblen = toint(GET_32BIT(q));
9393 if (bloblen < 0 || bloblen > lenleft) {
9394 logeventf(ssh, "Pageant response was truncated");
9396 goto done_agent_query;
9398 lenleft -= 4 + bloblen;
9400 commentlen = toint(GET_32BIT(q));
9401 if (commentlen < 0 || commentlen > lenleft) {
9402 logeventf(ssh, "Pageant response was truncated");
9404 goto done_agent_query;
9406 lenleft -= 4 + commentlen;
9407 q += 4 + commentlen;
9412 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
9413 if (s->publickey_blob) {
9414 /* See if configured key is in agent. */
9415 for (keyi = 0; keyi < s->nkeys; keyi++) {
9416 s->pklen = toint(GET_32BIT(p));
9417 if (s->pklen == s->publickey_bloblen &&
9418 !memcmp(p+4, s->publickey_blob,
9419 s->publickey_bloblen)) {
9420 logeventf(ssh, "Pageant key #%d matches "
9421 "configured key file", keyi);
9423 s->pkblob_in_agent = p;
9427 p += toint(GET_32BIT(p)) + 4; /* comment */
9429 if (!s->pkblob_in_agent) {
9430 logevent("Configured key file not in Pageant");
9435 logevent("Failed to get reply from Pageant");
9443 * We repeat this whole loop, including the username prompt,
9444 * until we manage a successful authentication. If the user
9445 * types the wrong _password_, they can be sent back to the
9446 * beginning to try another username, if this is configured on.
9447 * (If they specify a username in the config, they are never
9448 * asked, even if they do give a wrong password.)
9450 * I think this best serves the needs of
9452 * - the people who have no configuration, no keys, and just
9453 * want to try repeated (username,password) pairs until they
9454 * type both correctly
9456 * - people who have keys and configuration but occasionally
9457 * need to fall back to passwords
9459 * - people with a key held in Pageant, who might not have
9460 * logged in to a particular machine before; so they want to
9461 * type a username, and then _either_ their key will be
9462 * accepted, _or_ they will type a password. If they mistype
9463 * the username they will want to be able to get back and
9466 s->got_username = FALSE;
9467 while (!s->we_are_in) {
9471 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
9473 * We got a username last time round this loop, and
9474 * with change_username turned off we don't try to get
9477 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
9478 int ret; /* need not be kept over crReturn */
9479 s->cur_prompt = new_prompts(ssh->frontend);
9480 s->cur_prompt->to_server = TRUE;
9481 s->cur_prompt->name = dupstr("SSH login name");
9482 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
9483 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9486 crWaitUntilV(!pktin);
9487 ret = get_userpass_input(s->cur_prompt, in, inlen);
9492 * get_userpass_input() failed to get a username.
9495 free_prompts(s->cur_prompt);
9496 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
9499 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
9500 free_prompts(s->cur_prompt);
9503 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
9504 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
9505 c_write_str(ssh, stuff);
9509 s->got_username = TRUE;
9512 * Send an authentication request using method "none": (a)
9513 * just in case it succeeds, and (b) so that we know what
9514 * authentication methods we can usefully try next.
9516 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9518 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9519 ssh2_pkt_addstring(s->pktout, ssh->username);
9520 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
9521 ssh2_pkt_addstring(s->pktout, "none"); /* method */
9522 ssh2_pkt_send(ssh, s->pktout);
9523 s->type = AUTH_TYPE_NONE;
9525 s->we_are_in = FALSE;
9527 s->tried_pubkey_config = FALSE;
9528 s->kbd_inter_refused = FALSE;
9530 /* Reset agent request state. */
9531 s->done_agent = FALSE;
9532 if (s->agent_response) {
9533 if (s->pkblob_in_agent) {
9534 s->agentp = s->pkblob_in_agent;
9536 s->agentp = s->agent_response + 5 + 4;
9542 char *methods = NULL;
9546 * Wait for the result of the last authentication request.
9549 crWaitUntilV(pktin);
9551 * Now is a convenient point to spew any banner material
9552 * that we've accumulated. (This should ensure that when
9553 * we exit the auth loop, we haven't any left to deal
9557 int size = bufchain_size(&ssh->banner);
9559 * Don't show the banner if we're operating in
9560 * non-verbose non-interactive mode. (It's probably
9561 * a script, which means nobody will read the
9562 * banner _anyway_, and moreover the printing of
9563 * the banner will screw up processing on the
9564 * output of (say) plink.)
9566 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
9567 char *banner = snewn(size, char);
9568 bufchain_fetch(&ssh->banner, banner, size);
9569 c_write_untrusted(ssh, banner, size);
9572 bufchain_clear(&ssh->banner);
9574 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
9575 logevent("Access granted");
9576 s->we_are_in = s->userauth_success = TRUE;
9580 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
9581 bombout(("Strange packet received during authentication: "
9582 "type %d", pktin->type));
9589 * OK, we're now sitting on a USERAUTH_FAILURE message, so
9590 * we can look at the string in it and know what we can
9591 * helpfully try next.
9593 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
9594 ssh_pkt_getstring(pktin, &methods, &methlen);
9595 if (!ssh2_pkt_getbool(pktin)) {
9597 * We have received an unequivocal Access
9598 * Denied. This can translate to a variety of
9599 * messages, or no message at all.
9601 * For forms of authentication which are attempted
9602 * implicitly, by which I mean without printing
9603 * anything in the window indicating that we're
9604 * trying them, we should never print 'Access
9607 * If we do print a message saying that we're
9608 * attempting some kind of authentication, it's OK
9609 * to print a followup message saying it failed -
9610 * but the message may sometimes be more specific
9611 * than simply 'Access denied'.
9613 * Additionally, if we'd just tried password
9614 * authentication, we should break out of this
9615 * whole loop so as to go back to the username
9616 * prompt (iff we're configured to allow
9617 * username change attempts).
9619 if (s->type == AUTH_TYPE_NONE) {
9621 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
9622 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
9623 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
9624 c_write_str(ssh, "Server refused our key\r\n");
9625 logevent("Server refused our key");
9626 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
9627 /* This _shouldn't_ happen except by a
9628 * protocol bug causing client and server to
9629 * disagree on what is a correct signature. */
9630 c_write_str(ssh, "Server refused public-key signature"
9631 " despite accepting key!\r\n");
9632 logevent("Server refused public-key signature"
9633 " despite accepting key!");
9634 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
9635 /* quiet, so no c_write */
9636 logevent("Server refused keyboard-interactive authentication");
9637 } else if (s->type==AUTH_TYPE_GSSAPI) {
9638 /* always quiet, so no c_write */
9639 /* also, the code down in the GSSAPI block has
9640 * already logged this in the Event Log */
9641 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
9642 logevent("Keyboard-interactive authentication failed");
9643 c_write_str(ssh, "Access denied\r\n");
9645 assert(s->type == AUTH_TYPE_PASSWORD);
9646 logevent("Password authentication failed");
9647 c_write_str(ssh, "Access denied\r\n");
9649 if (conf_get_int(ssh->conf, CONF_change_username)) {
9650 /* XXX perhaps we should allow
9651 * keyboard-interactive to do this too? */
9652 s->we_are_in = FALSE;
9657 c_write_str(ssh, "Further authentication required\r\n");
9658 logevent("Further authentication required");
9662 in_commasep_string("publickey", methods, methlen);
9664 in_commasep_string("password", methods, methlen);
9665 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
9666 in_commasep_string("keyboard-interactive", methods, methlen);
9668 if (conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
9669 in_commasep_string("gssapi-with-mic", methods, methlen)) {
9670 /* Try loading the GSS libraries and see if we
9673 ssh->gsslibs = ssh_gss_setup(ssh->conf);
9674 s->can_gssapi = (ssh->gsslibs->nlibraries > 0);
9676 /* No point in even bothering to try to load the
9677 * GSS libraries, if the user configuration and
9678 * server aren't both prepared to attempt GSSAPI
9679 * auth in the first place. */
9680 s->can_gssapi = FALSE;
9685 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9687 if (s->can_pubkey && !s->done_agent && s->nkeys) {
9690 * Attempt public-key authentication using a key from Pageant.
9693 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9695 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
9697 /* Unpack key from agent response */
9698 s->pklen = toint(GET_32BIT(s->agentp));
9700 s->pkblob = (char *)s->agentp;
9701 s->agentp += s->pklen;
9702 s->alglen = toint(GET_32BIT(s->pkblob));
9703 s->alg = s->pkblob + 4;
9704 s->commentlen = toint(GET_32BIT(s->agentp));
9706 s->commentp = (char *)s->agentp;
9707 s->agentp += s->commentlen;
9708 /* s->agentp now points at next key, if any */
9710 /* See if server will accept it */
9711 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9712 ssh2_pkt_addstring(s->pktout, ssh->username);
9713 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9714 /* service requested */
9715 ssh2_pkt_addstring(s->pktout, "publickey");
9717 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
9718 ssh2_pkt_addstring_start(s->pktout);
9719 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9720 ssh2_pkt_addstring_start(s->pktout);
9721 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9722 ssh2_pkt_send(ssh, s->pktout);
9723 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
9725 crWaitUntilV(pktin);
9726 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9728 /* Offer of key refused. */
9735 if (flags & FLAG_VERBOSE) {
9736 c_write_str(ssh, "Authenticating with "
9738 c_write(ssh, s->commentp, s->commentlen);
9739 c_write_str(ssh, "\" from agent\r\n");
9743 * Server is willing to accept the key.
9744 * Construct a SIGN_REQUEST.
9746 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9747 ssh2_pkt_addstring(s->pktout, ssh->username);
9748 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9749 /* service requested */
9750 ssh2_pkt_addstring(s->pktout, "publickey");
9752 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
9753 ssh2_pkt_addstring_start(s->pktout);
9754 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9755 ssh2_pkt_addstring_start(s->pktout);
9756 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9758 /* Ask agent for signature. */
9759 s->siglen = s->pktout->length - 5 + 4 +
9760 ssh->v2_session_id_len;
9761 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9763 s->len = 1; /* message type */
9764 s->len += 4 + s->pklen; /* key blob */
9765 s->len += 4 + s->siglen; /* data to sign */
9766 s->len += 4; /* flags */
9767 s->agentreq = snewn(4 + s->len, char);
9768 PUT_32BIT(s->agentreq, s->len);
9769 s->q = s->agentreq + 4;
9770 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
9771 PUT_32BIT(s->q, s->pklen);
9773 memcpy(s->q, s->pkblob, s->pklen);
9775 PUT_32BIT(s->q, s->siglen);
9777 /* Now the data to be signed... */
9778 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9779 PUT_32BIT(s->q, ssh->v2_session_id_len);
9782 memcpy(s->q, ssh->v2_session_id,
9783 ssh->v2_session_id_len);
9784 s->q += ssh->v2_session_id_len;
9785 memcpy(s->q, s->pktout->data + 5,
9786 s->pktout->length - 5);
9787 s->q += s->pktout->length - 5;
9788 /* And finally the (zero) flags word. */
9790 if (!agent_query(s->agentreq, s->len + 4,
9792 ssh_agent_callback, ssh)) {
9796 bombout(("Unexpected data from server"
9797 " while waiting for agent"
9801 } while (pktin || inlen > 0);
9802 vret = ssh->agent_response;
9803 s->retlen = ssh->agent_response_len;
9808 if (s->retlen >= 9 &&
9809 s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
9810 GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
9811 logevent("Sending Pageant's response");
9812 ssh2_add_sigblob(ssh, s->pktout,
9813 s->pkblob, s->pklen,
9815 GET_32BIT(s->ret + 5));
9816 ssh2_pkt_send(ssh, s->pktout);
9817 s->type = AUTH_TYPE_PUBLICKEY;
9819 /* FIXME: less drastic response */
9820 bombout(("Pageant failed to answer challenge"));
9826 /* Do we have any keys left to try? */
9827 if (s->pkblob_in_agent) {
9828 s->done_agent = TRUE;
9829 s->tried_pubkey_config = TRUE;
9832 if (s->keyi >= s->nkeys)
9833 s->done_agent = TRUE;
9836 } else if (s->can_pubkey && s->publickey_blob &&
9837 s->privatekey_available && !s->tried_pubkey_config) {
9839 struct ssh2_userkey *key; /* not live over crReturn */
9840 char *passphrase; /* not live over crReturn */
9842 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9844 s->tried_pubkey_config = TRUE;
9847 * Try the public key supplied in the configuration.
9849 * First, offer the public blob to see if the server is
9850 * willing to accept it.
9852 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9853 ssh2_pkt_addstring(s->pktout, ssh->username);
9854 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9855 /* service requested */
9856 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
9857 ssh2_pkt_addbool(s->pktout, FALSE);
9858 /* no signature included */
9859 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
9860 ssh2_pkt_addstring_start(s->pktout);
9861 ssh2_pkt_addstring_data(s->pktout,
9862 (char *)s->publickey_blob,
9863 s->publickey_bloblen);
9864 ssh2_pkt_send(ssh, s->pktout);
9865 logevent("Offered public key");
9867 crWaitUntilV(pktin);
9868 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9869 /* Key refused. Give up. */
9870 s->gotit = TRUE; /* reconsider message next loop */
9871 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
9872 continue; /* process this new message */
9874 logevent("Offer of public key accepted");
9877 * Actually attempt a serious authentication using
9880 if (flags & FLAG_VERBOSE) {
9881 c_write_str(ssh, "Authenticating with public key \"");
9882 c_write_str(ssh, s->publickey_comment);
9883 c_write_str(ssh, "\"\r\n");
9887 const char *error; /* not live over crReturn */
9888 if (s->privatekey_encrypted) {
9890 * Get a passphrase from the user.
9892 int ret; /* need not be kept over crReturn */
9893 s->cur_prompt = new_prompts(ssh->frontend);
9894 s->cur_prompt->to_server = FALSE;
9895 s->cur_prompt->name = dupstr("SSH key passphrase");
9896 add_prompt(s->cur_prompt,
9897 dupprintf("Passphrase for key \"%.100s\": ",
9898 s->publickey_comment),
9900 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9903 crWaitUntilV(!pktin);
9904 ret = get_userpass_input(s->cur_prompt,
9909 /* Failed to get a passphrase. Terminate. */
9910 free_prompts(s->cur_prompt);
9911 ssh_disconnect(ssh, NULL,
9912 "Unable to authenticate",
9913 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9918 dupstr(s->cur_prompt->prompts[0]->result);
9919 free_prompts(s->cur_prompt);
9921 passphrase = NULL; /* no passphrase needed */
9925 * Try decrypting the key.
9927 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9928 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
9930 /* burn the evidence */
9931 smemclr(passphrase, strlen(passphrase));
9934 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
9936 (key == SSH2_WRONG_PASSPHRASE)) {
9937 c_write_str(ssh, "Wrong passphrase\r\n");
9939 /* and loop again */
9941 c_write_str(ssh, "Unable to load private key (");
9942 c_write_str(ssh, error);
9943 c_write_str(ssh, ")\r\n");
9945 break; /* try something else */
9951 unsigned char *pkblob, *sigblob, *sigdata;
9952 int pkblob_len, sigblob_len, sigdata_len;
9956 * We have loaded the private key and the server
9957 * has announced that it's willing to accept it.
9958 * Hallelujah. Generate a signature and send it.
9960 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9961 ssh2_pkt_addstring(s->pktout, ssh->username);
9962 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9963 /* service requested */
9964 ssh2_pkt_addstring(s->pktout, "publickey");
9966 ssh2_pkt_addbool(s->pktout, TRUE);
9967 /* signature follows */
9968 ssh2_pkt_addstring(s->pktout, key->alg->name);
9969 pkblob = key->alg->public_blob(key->data,
9971 ssh2_pkt_addstring_start(s->pktout);
9972 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
9976 * The data to be signed is:
9980 * followed by everything so far placed in the
9983 sigdata_len = s->pktout->length - 5 + 4 +
9984 ssh->v2_session_id_len;
9985 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9987 sigdata = snewn(sigdata_len, unsigned char);
9989 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9990 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
9993 memcpy(sigdata+p, ssh->v2_session_id,
9994 ssh->v2_session_id_len);
9995 p += ssh->v2_session_id_len;
9996 memcpy(sigdata+p, s->pktout->data + 5,
9997 s->pktout->length - 5);
9998 p += s->pktout->length - 5;
9999 assert(p == sigdata_len);
10000 sigblob = key->alg->sign(key->data, (char *)sigdata,
10001 sigdata_len, &sigblob_len);
10002 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
10003 sigblob, sigblob_len);
10008 ssh2_pkt_send(ssh, s->pktout);
10009 logevent("Sent public key signature");
10010 s->type = AUTH_TYPE_PUBLICKEY;
10011 key->alg->freekey(key->data);
10012 sfree(key->comment);
10017 } else if (s->can_gssapi && !s->tried_gssapi) {
10019 /* GSSAPI Authentication */
10021 int micoffset, len;
10024 s->type = AUTH_TYPE_GSSAPI;
10025 s->tried_gssapi = TRUE;
10027 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
10030 * Pick the highest GSS library on the preference
10036 for (i = 0; i < ngsslibs; i++) {
10037 int want_id = conf_get_int_int(ssh->conf,
10038 CONF_ssh_gsslist, i);
10039 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
10040 if (ssh->gsslibs->libraries[j].id == want_id) {
10041 s->gsslib = &ssh->gsslibs->libraries[j];
10042 goto got_gsslib; /* double break */
10047 * We always expect to have found something in
10048 * the above loop: we only came here if there
10049 * was at least one viable GSS library, and the
10050 * preference list should always mention
10051 * everything and only change the order.
10056 if (s->gsslib->gsslogmsg)
10057 logevent(s->gsslib->gsslogmsg);
10059 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
10060 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10061 ssh2_pkt_addstring(s->pktout, ssh->username);
10062 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10063 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
10064 logevent("Attempting GSSAPI authentication");
10066 /* add mechanism info */
10067 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
10069 /* number of GSSAPI mechanisms */
10070 ssh2_pkt_adduint32(s->pktout,1);
10072 /* length of OID + 2 */
10073 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
10074 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
10076 /* length of OID */
10077 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
10079 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
10080 s->gss_buf.length);
10081 ssh2_pkt_send(ssh, s->pktout);
10082 crWaitUntilV(pktin);
10083 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
10084 logevent("GSSAPI authentication request refused");
10088 /* check returned packet ... */
10090 ssh_pkt_getstring(pktin, &data, &len);
10091 s->gss_rcvtok.value = data;
10092 s->gss_rcvtok.length = len;
10093 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
10094 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
10095 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
10096 memcmp((char *)s->gss_rcvtok.value + 2,
10097 s->gss_buf.value,s->gss_buf.length) ) {
10098 logevent("GSSAPI authentication - wrong response from server");
10102 /* now start running */
10103 s->gss_stat = s->gsslib->import_name(s->gsslib,
10106 if (s->gss_stat != SSH_GSS_OK) {
10107 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
10108 logevent("GSSAPI import name failed - Bad service name");
10110 logevent("GSSAPI import name failed");
10114 /* fetch TGT into GSS engine */
10115 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
10117 if (s->gss_stat != SSH_GSS_OK) {
10118 logevent("GSSAPI authentication failed to get credentials");
10119 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10123 /* initial tokens are empty */
10124 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
10125 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
10127 /* now enter the loop */
10129 s->gss_stat = s->gsslib->init_sec_context
10133 conf_get_int(ssh->conf, CONF_gssapifwd),
10137 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
10138 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
10139 logevent("GSSAPI authentication initialisation failed");
10141 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
10142 &s->gss_buf) == SSH_GSS_OK) {
10143 logevent(s->gss_buf.value);
10144 sfree(s->gss_buf.value);
10149 logevent("GSSAPI authentication initialised");
10151 /* Client and server now exchange tokens until GSSAPI
10152 * no longer says CONTINUE_NEEDED */
10154 if (s->gss_sndtok.length != 0) {
10155 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
10156 ssh_pkt_addstring_start(s->pktout);
10157 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
10158 ssh2_pkt_send(ssh, s->pktout);
10159 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
10162 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
10163 crWaitUntilV(pktin);
10164 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
10165 logevent("GSSAPI authentication - bad server response");
10166 s->gss_stat = SSH_GSS_FAILURE;
10169 ssh_pkt_getstring(pktin, &data, &len);
10170 s->gss_rcvtok.value = data;
10171 s->gss_rcvtok.length = len;
10173 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
10175 if (s->gss_stat != SSH_GSS_OK) {
10176 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10177 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
10180 logevent("GSSAPI authentication loop finished OK");
10182 /* Now send the MIC */
10184 s->pktout = ssh2_pkt_init(0);
10185 micoffset = s->pktout->length;
10186 ssh_pkt_addstring_start(s->pktout);
10187 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
10188 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
10189 ssh_pkt_addstring(s->pktout, ssh->username);
10190 ssh_pkt_addstring(s->pktout, "ssh-connection");
10191 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
10193 s->gss_buf.value = (char *)s->pktout->data + micoffset;
10194 s->gss_buf.length = s->pktout->length - micoffset;
10196 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
10197 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
10198 ssh_pkt_addstring_start(s->pktout);
10199 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
10200 ssh2_pkt_send(ssh, s->pktout);
10201 s->gsslib->free_mic(s->gsslib, &mic);
10205 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10206 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
10209 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
10212 * Keyboard-interactive authentication.
10215 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
10217 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
10219 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10220 ssh2_pkt_addstring(s->pktout, ssh->username);
10221 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10222 /* service requested */
10223 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
10225 ssh2_pkt_addstring(s->pktout, ""); /* lang */
10226 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
10227 ssh2_pkt_send(ssh, s->pktout);
10229 logevent("Attempting keyboard-interactive authentication");
10231 crWaitUntilV(pktin);
10232 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
10233 /* Server is not willing to do keyboard-interactive
10234 * at all (or, bizarrely but legally, accepts the
10235 * user without actually issuing any prompts).
10236 * Give up on it entirely. */
10238 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
10239 s->kbd_inter_refused = TRUE; /* don't try it again */
10244 * Loop while the server continues to send INFO_REQUESTs.
10246 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
10248 char *name, *inst, *lang;
10249 int name_len, inst_len, lang_len;
10253 * We've got a fresh USERAUTH_INFO_REQUEST.
10254 * Get the preamble and start building a prompt.
10256 ssh_pkt_getstring(pktin, &name, &name_len);
10257 ssh_pkt_getstring(pktin, &inst, &inst_len);
10258 ssh_pkt_getstring(pktin, &lang, &lang_len);
10259 s->cur_prompt = new_prompts(ssh->frontend);
10260 s->cur_prompt->to_server = TRUE;
10263 * Get any prompt(s) from the packet.
10265 s->num_prompts = ssh_pkt_getuint32(pktin);
10266 for (i = 0; i < s->num_prompts; i++) {
10270 static char noprompt[] =
10271 "<server failed to send prompt>: ";
10273 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10274 echo = ssh2_pkt_getbool(pktin);
10277 prompt_len = lenof(noprompt)-1;
10279 add_prompt(s->cur_prompt,
10280 dupprintf("%.*s", prompt_len, prompt),
10285 /* FIXME: better prefix to distinguish from
10286 * local prompts? */
10287 s->cur_prompt->name =
10288 dupprintf("SSH server: %.*s", name_len, name);
10289 s->cur_prompt->name_reqd = TRUE;
10291 s->cur_prompt->name =
10292 dupstr("SSH server authentication");
10293 s->cur_prompt->name_reqd = FALSE;
10295 /* We add a prefix to try to make it clear that a prompt
10296 * has come from the server.
10297 * FIXME: ugly to print "Using..." in prompt _every_
10298 * time round. Can this be done more subtly? */
10299 /* Special case: for reasons best known to themselves,
10300 * some servers send k-i requests with no prompts and
10301 * nothing to display. Keep quiet in this case. */
10302 if (s->num_prompts || name_len || inst_len) {
10303 s->cur_prompt->instruction =
10304 dupprintf("Using keyboard-interactive authentication.%s%.*s",
10305 inst_len ? "\n" : "", inst_len, inst);
10306 s->cur_prompt->instr_reqd = TRUE;
10308 s->cur_prompt->instr_reqd = FALSE;
10312 * Display any instructions, and get the user's
10316 int ret; /* not live over crReturn */
10317 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10320 crWaitUntilV(!pktin);
10321 ret = get_userpass_input(s->cur_prompt, in, inlen);
10326 * Failed to get responses. Terminate.
10328 free_prompts(s->cur_prompt);
10329 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10330 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10337 * Send the response(s) to the server.
10339 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
10340 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
10341 for (i=0; i < s->num_prompts; i++) {
10342 ssh2_pkt_addstring(s->pktout,
10343 s->cur_prompt->prompts[i]->result);
10345 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10348 * Free the prompts structure from this iteration.
10349 * If there's another, a new one will be allocated
10350 * when we return to the top of this while loop.
10352 free_prompts(s->cur_prompt);
10355 * Get the next packet in case it's another
10358 crWaitUntilV(pktin);
10363 * We should have SUCCESS or FAILURE now.
10367 } else if (s->can_passwd) {
10370 * Plain old password authentication.
10372 int ret; /* not live over crReturn */
10373 int changereq_first_time; /* not live over crReturn */
10375 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
10377 s->cur_prompt = new_prompts(ssh->frontend);
10378 s->cur_prompt->to_server = TRUE;
10379 s->cur_prompt->name = dupstr("SSH password");
10380 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
10385 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10388 crWaitUntilV(!pktin);
10389 ret = get_userpass_input(s->cur_prompt, in, inlen);
10394 * Failed to get responses. Terminate.
10396 free_prompts(s->cur_prompt);
10397 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10398 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10403 * Squirrel away the password. (We may need it later if
10404 * asked to change it.)
10406 s->password = dupstr(s->cur_prompt->prompts[0]->result);
10407 free_prompts(s->cur_prompt);
10410 * Send the password packet.
10412 * We pad out the password packet to 256 bytes to make
10413 * it harder for an attacker to find the length of the
10416 * Anyone using a password longer than 256 bytes
10417 * probably doesn't have much to worry about from
10418 * people who find out how long their password is!
10420 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10421 ssh2_pkt_addstring(s->pktout, ssh->username);
10422 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10423 /* service requested */
10424 ssh2_pkt_addstring(s->pktout, "password");
10425 ssh2_pkt_addbool(s->pktout, FALSE);
10426 ssh2_pkt_addstring(s->pktout, s->password);
10427 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10428 logevent("Sent password");
10429 s->type = AUTH_TYPE_PASSWORD;
10432 * Wait for next packet, in case it's a password change
10435 crWaitUntilV(pktin);
10436 changereq_first_time = TRUE;
10438 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
10441 * We're being asked for a new password
10442 * (perhaps not for the first time).
10443 * Loop until the server accepts it.
10446 int got_new = FALSE; /* not live over crReturn */
10447 char *prompt; /* not live over crReturn */
10448 int prompt_len; /* not live over crReturn */
10452 if (changereq_first_time)
10453 msg = "Server requested password change";
10455 msg = "Server rejected new password";
10457 c_write_str(ssh, msg);
10458 c_write_str(ssh, "\r\n");
10461 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10463 s->cur_prompt = new_prompts(ssh->frontend);
10464 s->cur_prompt->to_server = TRUE;
10465 s->cur_prompt->name = dupstr("New SSH password");
10466 s->cur_prompt->instruction =
10467 dupprintf("%.*s", prompt_len, NULLTOEMPTY(prompt));
10468 s->cur_prompt->instr_reqd = TRUE;
10470 * There's no explicit requirement in the protocol
10471 * for the "old" passwords in the original and
10472 * password-change messages to be the same, and
10473 * apparently some Cisco kit supports password change
10474 * by the user entering a blank password originally
10475 * and the real password subsequently, so,
10476 * reluctantly, we prompt for the old password again.
10478 * (On the other hand, some servers don't even bother
10479 * to check this field.)
10481 add_prompt(s->cur_prompt,
10482 dupstr("Current password (blank for previously entered password): "),
10484 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
10486 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
10490 * Loop until the user manages to enter the same
10495 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10498 crWaitUntilV(!pktin);
10499 ret = get_userpass_input(s->cur_prompt, in, inlen);
10504 * Failed to get responses. Terminate.
10506 /* burn the evidence */
10507 free_prompts(s->cur_prompt);
10508 smemclr(s->password, strlen(s->password));
10509 sfree(s->password);
10510 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10511 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10517 * If the user specified a new original password
10518 * (IYSWIM), overwrite any previously specified
10520 * (A side effect is that the user doesn't have to
10521 * re-enter it if they louse up the new password.)
10523 if (s->cur_prompt->prompts[0]->result[0]) {
10524 smemclr(s->password, strlen(s->password));
10525 /* burn the evidence */
10526 sfree(s->password);
10528 dupstr(s->cur_prompt->prompts[0]->result);
10532 * Check the two new passwords match.
10534 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
10535 s->cur_prompt->prompts[2]->result)
10538 /* They don't. Silly user. */
10539 c_write_str(ssh, "Passwords do not match\r\n");
10544 * Send the new password (along with the old one).
10545 * (see above for padding rationale)
10547 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10548 ssh2_pkt_addstring(s->pktout, ssh->username);
10549 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10550 /* service requested */
10551 ssh2_pkt_addstring(s->pktout, "password");
10552 ssh2_pkt_addbool(s->pktout, TRUE);
10553 ssh2_pkt_addstring(s->pktout, s->password);
10554 ssh2_pkt_addstring(s->pktout,
10555 s->cur_prompt->prompts[1]->result);
10556 free_prompts(s->cur_prompt);
10557 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10558 logevent("Sent new password");
10561 * Now see what the server has to say about it.
10562 * (If it's CHANGEREQ again, it's not happy with the
10565 crWaitUntilV(pktin);
10566 changereq_first_time = FALSE;
10571 * We need to reexamine the current pktin at the top
10572 * of the loop. Either:
10573 * - we weren't asked to change password at all, in
10574 * which case it's a SUCCESS or FAILURE with the
10576 * - we sent a new password, and the server was
10577 * either OK with it (SUCCESS or FAILURE w/partial
10578 * success) or unhappy with the _old_ password
10579 * (FAILURE w/o partial success)
10580 * In any of these cases, we go back to the top of
10581 * the loop and start again.
10586 * We don't need the old password any more, in any
10587 * case. Burn the evidence.
10589 smemclr(s->password, strlen(s->password));
10590 sfree(s->password);
10593 char *str = dupprintf("No supported authentication methods available"
10594 " (server sent: %.*s)",
10597 ssh_disconnect(ssh, str,
10598 "No supported authentication methods available",
10599 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
10609 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
10611 /* Clear up various bits and pieces from authentication. */
10612 if (s->publickey_blob) {
10613 sfree(s->publickey_algorithm);
10614 sfree(s->publickey_blob);
10615 sfree(s->publickey_comment);
10617 if (s->agent_response)
10618 sfree(s->agent_response);
10620 if (s->userauth_success && !ssh->bare_connection) {
10622 * We've just received USERAUTH_SUCCESS, and we haven't sent any
10623 * packets since. Signal the transport layer to consider enacting
10624 * delayed compression.
10626 * (Relying on we_are_in is not sufficient, as
10627 * draft-miller-secsh-compression-delayed is quite clear that it
10628 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
10629 * become set for other reasons.)
10631 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
10634 ssh->channels = newtree234(ssh_channelcmp);
10637 * Set up handlers for some connection protocol messages, so we
10638 * don't have to handle them repeatedly in this coroutine.
10640 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
10641 ssh2_msg_channel_window_adjust;
10642 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
10643 ssh2_msg_global_request;
10646 * Create the main session channel.
10648 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
10649 ssh->mainchan = NULL;
10651 ssh->mainchan = snew(struct ssh_channel);
10652 ssh->mainchan->ssh = ssh;
10653 ssh2_channel_init(ssh->mainchan);
10655 if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
10657 * Just start a direct-tcpip channel and use it as the main
10660 ssh_send_port_open(ssh->mainchan,
10661 conf_get_str(ssh->conf, CONF_ssh_nc_host),
10662 conf_get_int(ssh->conf, CONF_ssh_nc_port),
10664 ssh->ncmode = TRUE;
10666 s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
10667 logevent("Opening session as main channel");
10668 ssh2_pkt_send(ssh, s->pktout);
10669 ssh->ncmode = FALSE;
10671 crWaitUntilV(pktin);
10672 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
10673 bombout(("Server refused to open channel"));
10675 /* FIXME: error data comes back in FAILURE packet */
10677 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
10678 bombout(("Server's channel confirmation cited wrong channel"));
10681 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
10682 ssh->mainchan->halfopen = FALSE;
10683 ssh->mainchan->type = CHAN_MAINSESSION;
10684 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
10685 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
10686 add234(ssh->channels, ssh->mainchan);
10687 update_specials_menu(ssh->frontend);
10688 logevent("Opened main channel");
10692 * Now we have a channel, make dispatch table entries for
10693 * general channel-based messages.
10695 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
10696 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
10697 ssh2_msg_channel_data;
10698 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
10699 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
10700 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
10701 ssh2_msg_channel_open_confirmation;
10702 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
10703 ssh2_msg_channel_open_failure;
10704 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
10705 ssh2_msg_channel_request;
10706 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
10707 ssh2_msg_channel_open;
10708 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
10709 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
10712 * Now the connection protocol is properly up and running, with
10713 * all those dispatch table entries, so it's safe to let
10714 * downstreams start trying to open extra channels through us.
10716 if (ssh->connshare)
10717 share_activate(ssh->connshare, ssh->v_s);
10719 if (ssh->mainchan && ssh_is_simple(ssh)) {
10721 * This message indicates to the server that we promise
10722 * not to try to run any other channel in parallel with
10723 * this one, so it's safe for it to advertise a very large
10724 * window and leave the flow control to TCP.
10726 s->pktout = ssh2_chanreq_init(ssh->mainchan,
10727 "simple@putty.projects.tartarus.org",
10729 ssh2_pkt_send(ssh, s->pktout);
10733 * Enable port forwardings.
10735 ssh_setup_portfwd(ssh, ssh->conf);
10737 if (ssh->mainchan && !ssh->ncmode) {
10739 * Send the CHANNEL_REQUESTS for the main session channel.
10740 * Each one is handled by its own little asynchronous
10744 /* Potentially enable X11 forwarding. */
10745 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
10747 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
10749 if (!ssh->x11disp) {
10750 /* FIXME: return an error message from x11_setup_display */
10751 logevent("X11 forwarding not enabled: unable to"
10752 " initialise X display");
10754 ssh->x11auth = x11_invent_fake_auth
10755 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
10756 ssh->x11auth->disp = ssh->x11disp;
10758 ssh2_setup_x11(ssh->mainchan, NULL, NULL);
10762 /* Potentially enable agent forwarding. */
10763 if (ssh_agent_forwarding_permitted(ssh))
10764 ssh2_setup_agent(ssh->mainchan, NULL, NULL);
10766 /* Now allocate a pty for the session. */
10767 if (!conf_get_int(ssh->conf, CONF_nopty))
10768 ssh2_setup_pty(ssh->mainchan, NULL, NULL);
10770 /* Send environment variables. */
10771 ssh2_setup_env(ssh->mainchan, NULL, NULL);
10774 * Start a shell or a remote command. We may have to attempt
10775 * this twice if the config data has provided a second choice
10782 if (ssh->fallback_cmd) {
10783 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
10784 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
10786 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
10787 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
10791 s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
10792 ssh2_response_authconn, NULL);
10793 ssh2_pkt_addstring(s->pktout, cmd);
10795 s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
10796 ssh2_response_authconn, NULL);
10797 ssh2_pkt_addstring(s->pktout, cmd);
10799 s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
10800 ssh2_response_authconn, NULL);
10802 ssh2_pkt_send(ssh, s->pktout);
10804 crWaitUntilV(pktin);
10806 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
10807 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
10808 bombout(("Unexpected response to shell/command request:"
10809 " packet type %d", pktin->type));
10813 * We failed to start the command. If this is the
10814 * fallback command, we really are finished; if it's
10815 * not, and if the fallback command exists, try falling
10816 * back to it before complaining.
10818 if (!ssh->fallback_cmd &&
10819 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
10820 logevent("Primary command failed; attempting fallback");
10821 ssh->fallback_cmd = TRUE;
10824 bombout(("Server refused to start a shell/command"));
10827 logevent("Started a shell/command");
10832 ssh->editing = ssh->echoing = TRUE;
10835 ssh->state = SSH_STATE_SESSION;
10836 if (ssh->size_needed)
10837 ssh_size(ssh, ssh->term_width, ssh->term_height);
10838 if (ssh->eof_needed)
10839 ssh_special(ssh, TS_EOF);
10845 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
10853 * _All_ the connection-layer packets we expect to
10854 * receive are now handled by the dispatch table.
10855 * Anything that reaches here must be bogus.
10858 bombout(("Strange packet received: type %d", pktin->type));
10860 } else if (ssh->mainchan) {
10862 * We have spare data. Add it to the channel buffer.
10864 ssh_send_channel_data(ssh->mainchan, (char *)in, inlen);
10872 * Handlers for SSH-2 messages that might arrive at any moment.
10874 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
10876 /* log reason code in disconnect message */
10878 int reason, msglen;
10880 reason = ssh_pkt_getuint32(pktin);
10881 ssh_pkt_getstring(pktin, &msg, &msglen);
10883 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
10884 buf = dupprintf("Received disconnect message (%s)",
10885 ssh2_disconnect_reasons[reason]);
10887 buf = dupprintf("Received disconnect message (unknown"
10888 " type %d)", reason);
10892 buf = dupprintf("Disconnection message text: %.*s",
10893 msglen, NULLTOEMPTY(msg));
10895 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
10897 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
10898 ssh2_disconnect_reasons[reason] : "unknown",
10899 msglen, NULLTOEMPTY(msg)));
10903 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
10905 /* log the debug message */
10909 /* XXX maybe we should actually take notice of the return value */
10910 ssh2_pkt_getbool(pktin);
10911 ssh_pkt_getstring(pktin, &msg, &msglen);
10913 logeventf(ssh, "Remote debug message: %.*s", msglen, NULLTOEMPTY(msg));
10916 static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
10918 do_ssh2_transport(ssh, NULL, 0, pktin);
10922 * Called if we receive a packet that isn't allowed by the protocol.
10923 * This only applies to packets whose meaning PuTTY understands.
10924 * Entirely unknown packets are handled below.
10926 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
10928 char *buf = dupprintf("Server protocol violation: unexpected %s packet",
10929 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
10931 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
10935 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
10937 struct Packet *pktout;
10938 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
10939 ssh2_pkt_adduint32(pktout, pktin->sequence);
10941 * UNIMPLEMENTED messages MUST appear in the same order as the
10942 * messages they respond to. Hence, never queue them.
10944 ssh2_pkt_send_noqueue(ssh, pktout);
10948 * Handle the top-level SSH-2 protocol.
10950 static void ssh2_protocol_setup(Ssh ssh)
10955 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10957 for (i = 0; i < 256; i++)
10958 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10961 * Initially, we only accept transport messages (and a few generic
10962 * ones). do_ssh2_authconn will add more when it starts.
10963 * Messages that are understood but not currently acceptable go to
10964 * ssh2_msg_unexpected.
10966 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10967 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
10968 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
10969 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
10970 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
10971 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
10972 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
10973 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
10974 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
10975 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
10976 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
10977 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
10978 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
10979 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
10980 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
10981 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
10982 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
10983 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
10984 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
10985 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10986 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10987 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10988 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10989 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10990 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10991 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10992 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10993 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10994 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10995 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10996 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10997 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10998 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
11001 * These messages have a special handler from the start.
11003 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
11004 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
11005 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
11008 static void ssh2_bare_connection_protocol_setup(Ssh ssh)
11013 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
11015 for (i = 0; i < 256; i++)
11016 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
11019 * Initially, we set all ssh-connection messages to 'unexpected';
11020 * do_ssh2_authconn will fill things in properly. We also handle a
11021 * couple of messages from the transport protocol which aren't
11022 * related to key exchange (UNIMPLEMENTED, IGNORE, DEBUG,
11025 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
11026 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
11027 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
11028 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
11029 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
11030 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
11031 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
11032 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
11033 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
11034 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
11035 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
11036 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
11037 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
11038 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
11040 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
11043 * These messages have a special handler from the start.
11045 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
11046 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore;
11047 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
11050 static void ssh2_timer(void *ctx, unsigned long now)
11052 Ssh ssh = (Ssh)ctx;
11054 if (ssh->state == SSH_STATE_CLOSED)
11057 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11058 conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
11059 now == ssh->next_rekey) {
11060 do_ssh2_transport(ssh, "timeout", -1, NULL);
11064 static void ssh2_protocol(Ssh ssh, const void *vin, int inlen,
11065 struct Packet *pktin)
11067 const unsigned char *in = (const unsigned char *)vin;
11068 if (ssh->state == SSH_STATE_CLOSED)
11072 ssh->incoming_data_size += pktin->encrypted_len;
11073 if (!ssh->kex_in_progress &&
11074 ssh->max_data_size != 0 &&
11075 ssh->incoming_data_size > ssh->max_data_size)
11076 do_ssh2_transport(ssh, "too much data received", -1, NULL);
11080 ssh->packet_dispatch[pktin->type](ssh, pktin);
11081 else if (!ssh->protocol_initial_phase_done)
11082 do_ssh2_transport(ssh, in, inlen, pktin);
11084 do_ssh2_authconn(ssh, in, inlen, pktin);
11087 static void ssh2_bare_connection_protocol(Ssh ssh, const void *vin, int inlen,
11088 struct Packet *pktin)
11090 const unsigned char *in = (const unsigned char *)vin;
11091 if (ssh->state == SSH_STATE_CLOSED)
11095 ssh->packet_dispatch[pktin->type](ssh, pktin);
11097 do_ssh2_authconn(ssh, in, inlen, pktin);
11100 static void ssh_cache_conf_values(Ssh ssh)
11102 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
11106 * Called to set up the connection.
11108 * Returns an error message, or NULL on success.
11110 static const char *ssh_init(void *frontend_handle, void **backend_handle,
11112 const char *host, int port, char **realhost,
11113 int nodelay, int keepalive)
11118 ssh = snew(struct ssh_tag);
11119 ssh->conf = conf_copy(conf);
11120 ssh_cache_conf_values(ssh);
11121 ssh->version = 0; /* when not ready yet */
11123 ssh->cipher = NULL;
11124 ssh->v1_cipher_ctx = NULL;
11125 ssh->crcda_ctx = NULL;
11126 ssh->cscipher = NULL;
11127 ssh->cs_cipher_ctx = NULL;
11128 ssh->sccipher = NULL;
11129 ssh->sc_cipher_ctx = NULL;
11131 ssh->cs_mac_ctx = NULL;
11133 ssh->sc_mac_ctx = NULL;
11134 ssh->cscomp = NULL;
11135 ssh->cs_comp_ctx = NULL;
11136 ssh->sccomp = NULL;
11137 ssh->sc_comp_ctx = NULL;
11139 ssh->kex_ctx = NULL;
11140 ssh->hostkey = NULL;
11141 ssh->hostkey_str = NULL;
11142 ssh->exitcode = -1;
11143 ssh->close_expected = FALSE;
11144 ssh->clean_exit = FALSE;
11145 ssh->state = SSH_STATE_PREPACKET;
11146 ssh->size_needed = FALSE;
11147 ssh->eof_needed = FALSE;
11149 ssh->logctx = NULL;
11150 ssh->deferred_send_data = NULL;
11151 ssh->deferred_len = 0;
11152 ssh->deferred_size = 0;
11153 ssh->fallback_cmd = 0;
11154 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
11155 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
11156 ssh->x11disp = NULL;
11157 ssh->x11auth = NULL;
11158 ssh->x11authtree = newtree234(x11_authcmp);
11159 ssh->v1_compressing = FALSE;
11160 ssh->v2_outgoing_sequence = 0;
11161 ssh->ssh1_rdpkt_crstate = 0;
11162 ssh->ssh2_rdpkt_crstate = 0;
11163 ssh->ssh2_bare_rdpkt_crstate = 0;
11164 ssh->ssh_gotdata_crstate = 0;
11165 ssh->do_ssh1_connection_crstate = 0;
11166 ssh->do_ssh_init_state = NULL;
11167 ssh->do_ssh_connection_init_state = NULL;
11168 ssh->do_ssh1_login_state = NULL;
11169 ssh->do_ssh2_transport_state = NULL;
11170 ssh->do_ssh2_authconn_state = NULL;
11173 ssh->mainchan = NULL;
11174 ssh->throttled_all = 0;
11175 ssh->v1_stdout_throttling = 0;
11177 ssh->queuelen = ssh->queuesize = 0;
11178 ssh->queueing = FALSE;
11179 ssh->qhead = ssh->qtail = NULL;
11180 ssh->deferred_rekey_reason = NULL;
11181 bufchain_init(&ssh->queued_incoming_data);
11182 ssh->frozen = FALSE;
11183 ssh->username = NULL;
11184 ssh->sent_console_eof = FALSE;
11185 ssh->got_pty = FALSE;
11186 ssh->bare_connection = FALSE;
11187 ssh->X11_fwd_enabled = FALSE;
11188 ssh->connshare = NULL;
11189 ssh->attempting_connshare = FALSE;
11190 ssh->session_started = FALSE;
11191 ssh->specials = NULL;
11192 ssh->n_uncert_hostkeys = 0;
11193 ssh->cross_certifying = FALSE;
11195 *backend_handle = ssh;
11198 if (crypto_startup() == 0)
11199 return "Microsoft high encryption pack not installed!";
11202 ssh->frontend = frontend_handle;
11203 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
11204 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
11206 ssh->channels = NULL;
11207 ssh->rportfwds = NULL;
11208 ssh->portfwds = NULL;
11213 ssh->conn_throttle_count = 0;
11214 ssh->overall_bufsize = 0;
11215 ssh->fallback_cmd = 0;
11217 ssh->protocol = NULL;
11219 ssh->protocol_initial_phase_done = FALSE;
11221 ssh->pinger = NULL;
11223 ssh->incoming_data_size = ssh->outgoing_data_size =
11224 ssh->deferred_data_size = 0L;
11225 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11226 CONF_ssh_rekey_data));
11227 ssh->kex_in_progress = FALSE;
11230 ssh->gsslibs = NULL;
11233 random_ref(); /* do this now - may be needed by sharing setup code */
11235 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
11244 static void ssh_free(void *handle)
11246 Ssh ssh = (Ssh) handle;
11247 struct ssh_channel *c;
11248 struct ssh_rportfwd *pf;
11249 struct X11FakeAuth *auth;
11251 if (ssh->v1_cipher_ctx)
11252 ssh->cipher->free_context(ssh->v1_cipher_ctx);
11253 if (ssh->cs_cipher_ctx)
11254 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
11255 if (ssh->sc_cipher_ctx)
11256 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
11257 if (ssh->cs_mac_ctx)
11258 ssh->csmac->free_context(ssh->cs_mac_ctx);
11259 if (ssh->sc_mac_ctx)
11260 ssh->scmac->free_context(ssh->sc_mac_ctx);
11261 if (ssh->cs_comp_ctx) {
11263 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
11265 zlib_compress_cleanup(ssh->cs_comp_ctx);
11267 if (ssh->sc_comp_ctx) {
11269 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
11271 zlib_decompress_cleanup(ssh->sc_comp_ctx);
11274 dh_cleanup(ssh->kex_ctx);
11275 sfree(ssh->savedhost);
11277 while (ssh->queuelen-- > 0)
11278 ssh_free_packet(ssh->queue[ssh->queuelen]);
11281 while (ssh->qhead) {
11282 struct queued_handler *qh = ssh->qhead;
11283 ssh->qhead = qh->next;
11286 ssh->qhead = ssh->qtail = NULL;
11288 if (ssh->channels) {
11289 while ((c = delpos234(ssh->channels, 0)) != NULL) {
11292 if (c->u.x11.xconn != NULL)
11293 x11_close(c->u.x11.xconn);
11295 case CHAN_SOCKDATA:
11296 case CHAN_SOCKDATA_DORMANT:
11297 if (c->u.pfd.pf != NULL)
11298 pfd_close(c->u.pfd.pf);
11301 if (ssh->version == 2) {
11302 struct outstanding_channel_request *ocr, *nocr;
11303 ocr = c->v.v2.chanreq_head;
11305 ocr->handler(c, NULL, ocr->ctx);
11310 bufchain_clear(&c->v.v2.outbuffer);
11314 freetree234(ssh->channels);
11315 ssh->channels = NULL;
11318 if (ssh->connshare)
11319 sharestate_free(ssh->connshare);
11321 if (ssh->rportfwds) {
11322 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
11324 freetree234(ssh->rportfwds);
11325 ssh->rportfwds = NULL;
11327 sfree(ssh->deferred_send_data);
11329 x11_free_display(ssh->x11disp);
11330 while ((auth = delpos234(ssh->x11authtree, 0)) != NULL)
11331 x11_free_fake_auth(auth);
11332 freetree234(ssh->x11authtree);
11333 sfree(ssh->do_ssh_init_state);
11334 sfree(ssh->do_ssh1_login_state);
11335 sfree(ssh->do_ssh2_transport_state);
11336 sfree(ssh->do_ssh2_authconn_state);
11339 sfree(ssh->fullhostname);
11340 sfree(ssh->hostkey_str);
11341 sfree(ssh->specials);
11342 if (ssh->crcda_ctx) {
11343 crcda_free_context(ssh->crcda_ctx);
11344 ssh->crcda_ctx = NULL;
11347 ssh_do_close(ssh, TRUE);
11348 expire_timer_context(ssh);
11350 pinger_free(ssh->pinger);
11351 bufchain_clear(&ssh->queued_incoming_data);
11352 sfree(ssh->username);
11353 conf_free(ssh->conf);
11356 ssh_gss_cleanup(ssh->gsslibs);
11364 * Reconfigure the SSH backend.
11366 static void ssh_reconfig(void *handle, Conf *conf)
11368 Ssh ssh = (Ssh) handle;
11369 const char *rekeying = NULL;
11370 int rekey_mandatory = FALSE;
11371 unsigned long old_max_data_size;
11374 pinger_reconfig(ssh->pinger, ssh->conf, conf);
11376 ssh_setup_portfwd(ssh, conf);
11378 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
11379 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
11381 unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
11382 unsigned long now = GETTICKCOUNT();
11384 if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
11385 rekeying = "timeout shortened";
11387 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
11391 old_max_data_size = ssh->max_data_size;
11392 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11393 CONF_ssh_rekey_data));
11394 if (old_max_data_size != ssh->max_data_size &&
11395 ssh->max_data_size != 0) {
11396 if (ssh->outgoing_data_size > ssh->max_data_size ||
11397 ssh->incoming_data_size > ssh->max_data_size)
11398 rekeying = "data limit lowered";
11401 if (conf_get_int(ssh->conf, CONF_compression) !=
11402 conf_get_int(conf, CONF_compression)) {
11403 rekeying = "compression setting changed";
11404 rekey_mandatory = TRUE;
11407 for (i = 0; i < CIPHER_MAX; i++)
11408 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
11409 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
11410 rekeying = "cipher settings changed";
11411 rekey_mandatory = TRUE;
11413 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
11414 conf_get_int(conf, CONF_ssh2_des_cbc)) {
11415 rekeying = "cipher settings changed";
11416 rekey_mandatory = TRUE;
11419 conf_free(ssh->conf);
11420 ssh->conf = conf_copy(conf);
11421 ssh_cache_conf_values(ssh);
11423 if (!ssh->bare_connection && rekeying) {
11424 if (!ssh->kex_in_progress) {
11425 do_ssh2_transport(ssh, rekeying, -1, NULL);
11426 } else if (rekey_mandatory) {
11427 ssh->deferred_rekey_reason = rekeying;
11433 * Called to send data down the SSH connection.
11435 static int ssh_send(void *handle, const char *buf, int len)
11437 Ssh ssh = (Ssh) handle;
11439 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11442 ssh->protocol(ssh, (const unsigned char *)buf, len, 0);
11444 return ssh_sendbuffer(ssh);
11448 * Called to query the current amount of buffered stdin data.
11450 static int ssh_sendbuffer(void *handle)
11452 Ssh ssh = (Ssh) handle;
11453 int override_value;
11455 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11459 * If the SSH socket itself has backed up, add the total backup
11460 * size on that to any individual buffer on the stdin channel.
11462 override_value = 0;
11463 if (ssh->throttled_all)
11464 override_value = ssh->overall_bufsize;
11466 if (ssh->version == 1) {
11467 return override_value;
11468 } else if (ssh->version == 2) {
11469 if (!ssh->mainchan)
11470 return override_value;
11472 return (override_value +
11473 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
11480 * Called to set the size of the window from SSH's POV.
11482 static void ssh_size(void *handle, int width, int height)
11484 Ssh ssh = (Ssh) handle;
11485 struct Packet *pktout;
11487 ssh->term_width = width;
11488 ssh->term_height = height;
11490 switch (ssh->state) {
11491 case SSH_STATE_BEFORE_SIZE:
11492 case SSH_STATE_PREPACKET:
11493 case SSH_STATE_CLOSED:
11494 break; /* do nothing */
11495 case SSH_STATE_INTERMED:
11496 ssh->size_needed = TRUE; /* buffer for later */
11498 case SSH_STATE_SESSION:
11499 if (!conf_get_int(ssh->conf, CONF_nopty)) {
11500 if (ssh->version == 1) {
11501 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
11502 PKT_INT, ssh->term_height,
11503 PKT_INT, ssh->term_width,
11504 PKT_INT, 0, PKT_INT, 0, PKT_END);
11505 } else if (ssh->mainchan) {
11506 pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
11508 ssh2_pkt_adduint32(pktout, ssh->term_width);
11509 ssh2_pkt_adduint32(pktout, ssh->term_height);
11510 ssh2_pkt_adduint32(pktout, 0);
11511 ssh2_pkt_adduint32(pktout, 0);
11512 ssh2_pkt_send(ssh, pktout);
11520 * Return a list of the special codes that make sense in this
11523 static const struct telnet_special *ssh_get_specials(void *handle)
11525 static const struct telnet_special ssh1_ignore_special[] = {
11526 {"IGNORE message", TS_NOP}
11528 static const struct telnet_special ssh2_ignore_special[] = {
11529 {"IGNORE message", TS_NOP},
11531 static const struct telnet_special ssh2_rekey_special[] = {
11532 {"Repeat key exchange", TS_REKEY},
11534 static const struct telnet_special ssh2_session_specials[] = {
11537 /* These are the signal names defined by RFC 4254.
11538 * They include all the ISO C signals, but are a subset of the POSIX
11539 * required signals. */
11540 {"SIGINT (Interrupt)", TS_SIGINT},
11541 {"SIGTERM (Terminate)", TS_SIGTERM},
11542 {"SIGKILL (Kill)", TS_SIGKILL},
11543 {"SIGQUIT (Quit)", TS_SIGQUIT},
11544 {"SIGHUP (Hangup)", TS_SIGHUP},
11545 {"More signals", TS_SUBMENU},
11546 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
11547 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
11548 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
11549 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
11550 {NULL, TS_EXITMENU}
11552 static const struct telnet_special specials_end[] = {
11553 {NULL, TS_EXITMENU}
11556 struct telnet_special *specials = NULL;
11557 int nspecials = 0, specialsize = 0;
11559 Ssh ssh = (Ssh) handle;
11561 sfree(ssh->specials);
11563 #define ADD_SPECIALS(name) do \
11565 int len = lenof(name); \
11566 if (nspecials + len > specialsize) { \
11567 specialsize = (nspecials + len) * 5 / 4 + 32; \
11568 specials = sresize(specials, specialsize, struct telnet_special); \
11570 memcpy(specials+nspecials, name, len*sizeof(struct telnet_special)); \
11571 nspecials += len; \
11574 if (ssh->version == 1) {
11575 /* Don't bother offering IGNORE if we've decided the remote
11576 * won't cope with it, since we wouldn't bother sending it if
11578 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11579 ADD_SPECIALS(ssh1_ignore_special);
11580 } else if (ssh->version == 2) {
11581 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
11582 ADD_SPECIALS(ssh2_ignore_special);
11583 if (!(ssh->remote_bugs & BUG_SSH2_REKEY) && !ssh->bare_connection)
11584 ADD_SPECIALS(ssh2_rekey_special);
11586 ADD_SPECIALS(ssh2_session_specials);
11588 if (ssh->n_uncert_hostkeys) {
11589 static const struct telnet_special uncert_start[] = {
11591 {"Cache new host key type", TS_SUBMENU},
11593 static const struct telnet_special uncert_end[] = {
11594 {NULL, TS_EXITMENU},
11598 ADD_SPECIALS(uncert_start);
11599 for (i = 0; i < ssh->n_uncert_hostkeys; i++) {
11600 struct telnet_special uncert[1];
11601 const struct ssh_signkey *alg =
11602 hostkey_algs[ssh->uncert_hostkeys[i]].alg;
11603 uncert[0].name = alg->name;
11604 uncert[0].code = TS_LOCALSTART + ssh->uncert_hostkeys[i];
11605 ADD_SPECIALS(uncert);
11607 ADD_SPECIALS(uncert_end);
11609 } /* else we're not ready yet */
11612 ADD_SPECIALS(specials_end);
11614 ssh->specials = specials;
11621 #undef ADD_SPECIALS
11625 * Send special codes. TS_EOF is useful for `plink', so you
11626 * can send an EOF and collect resulting output (e.g. `plink
11629 static void ssh_special(void *handle, Telnet_Special code)
11631 Ssh ssh = (Ssh) handle;
11632 struct Packet *pktout;
11634 if (code == TS_EOF) {
11635 if (ssh->state != SSH_STATE_SESSION) {
11637 * Buffer the EOF in case we are pre-SESSION, so we can
11638 * send it as soon as we reach SESSION.
11640 if (code == TS_EOF)
11641 ssh->eof_needed = TRUE;
11644 if (ssh->version == 1) {
11645 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
11646 } else if (ssh->mainchan) {
11647 sshfwd_write_eof(ssh->mainchan);
11648 ssh->send_ok = 0; /* now stop trying to read from stdin */
11650 logevent("Sent EOF message");
11651 } else if (code == TS_PING || code == TS_NOP) {
11652 if (ssh->state == SSH_STATE_CLOSED
11653 || ssh->state == SSH_STATE_PREPACKET) return;
11654 if (ssh->version == 1) {
11655 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11656 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
11658 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
11659 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
11660 ssh2_pkt_addstring_start(pktout);
11661 ssh2_pkt_send_noqueue(ssh, pktout);
11664 } else if (code == TS_REKEY) {
11665 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11666 ssh->version == 2) {
11667 do_ssh2_transport(ssh, "at user request", -1, NULL);
11669 } else if (code >= TS_LOCALSTART) {
11670 ssh->hostkey = hostkey_algs[code - TS_LOCALSTART].alg;
11671 ssh->cross_certifying = TRUE;
11672 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11673 ssh->version == 2) {
11674 do_ssh2_transport(ssh, "cross-certifying new host key", -1, NULL);
11676 } else if (code == TS_BRK) {
11677 if (ssh->state == SSH_STATE_CLOSED
11678 || ssh->state == SSH_STATE_PREPACKET) return;
11679 if (ssh->version == 1) {
11680 logevent("Unable to send BREAK signal in SSH-1");
11681 } else if (ssh->mainchan) {
11682 pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
11683 ssh2_pkt_adduint32(pktout, 0); /* default break length */
11684 ssh2_pkt_send(ssh, pktout);
11687 /* Is is a POSIX signal? */
11688 const char *signame = NULL;
11689 if (code == TS_SIGABRT) signame = "ABRT";
11690 if (code == TS_SIGALRM) signame = "ALRM";
11691 if (code == TS_SIGFPE) signame = "FPE";
11692 if (code == TS_SIGHUP) signame = "HUP";
11693 if (code == TS_SIGILL) signame = "ILL";
11694 if (code == TS_SIGINT) signame = "INT";
11695 if (code == TS_SIGKILL) signame = "KILL";
11696 if (code == TS_SIGPIPE) signame = "PIPE";
11697 if (code == TS_SIGQUIT) signame = "QUIT";
11698 if (code == TS_SIGSEGV) signame = "SEGV";
11699 if (code == TS_SIGTERM) signame = "TERM";
11700 if (code == TS_SIGUSR1) signame = "USR1";
11701 if (code == TS_SIGUSR2) signame = "USR2";
11702 /* The SSH-2 protocol does in principle support arbitrary named
11703 * signals, including signame@domain, but we don't support those. */
11705 /* It's a signal. */
11706 if (ssh->version == 2 && ssh->mainchan) {
11707 pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
11708 ssh2_pkt_addstring(pktout, signame);
11709 ssh2_pkt_send(ssh, pktout);
11710 logeventf(ssh, "Sent signal SIG%s", signame);
11713 /* Never heard of it. Do nothing */
11718 void *new_sock_channel(void *handle, struct PortForwarding *pf)
11720 Ssh ssh = (Ssh) handle;
11721 struct ssh_channel *c;
11722 c = snew(struct ssh_channel);
11725 ssh2_channel_init(c);
11726 c->halfopen = TRUE;
11727 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
11729 add234(ssh->channels, c);
11733 unsigned ssh_alloc_sharing_channel(Ssh ssh, void *sharing_ctx)
11735 struct ssh_channel *c;
11736 c = snew(struct ssh_channel);
11739 ssh2_channel_init(c);
11740 c->type = CHAN_SHARING;
11741 c->u.sharing.ctx = sharing_ctx;
11742 add234(ssh->channels, c);
11746 void ssh_delete_sharing_channel(Ssh ssh, unsigned localid)
11748 struct ssh_channel *c;
11750 c = find234(ssh->channels, &localid, ssh_channelfind);
11752 ssh_channel_destroy(c);
11755 void ssh_send_packet_from_downstream(Ssh ssh, unsigned id, int type,
11756 const void *data, int datalen,
11757 const char *additional_log_text)
11759 struct Packet *pkt;
11761 pkt = ssh2_pkt_init(type);
11762 pkt->downstream_id = id;
11763 pkt->additional_log_text = additional_log_text;
11764 ssh2_pkt_adddata(pkt, data, datalen);
11765 ssh2_pkt_send(ssh, pkt);
11769 * This is called when stdout/stderr (the entity to which
11770 * from_backend sends data) manages to clear some backlog.
11772 static void ssh_unthrottle(void *handle, int bufsize)
11774 Ssh ssh = (Ssh) handle;
11776 if (ssh->version == 1) {
11777 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
11778 ssh->v1_stdout_throttling = 0;
11779 ssh_throttle_conn(ssh, -1);
11783 ssh_channel_unthrottle(ssh->mainchan, bufsize);
11787 * Now process any SSH connection data that was stashed in our
11788 * queue while we were frozen.
11790 ssh_process_queued_incoming_data(ssh);
11793 void ssh_send_port_open(void *channel, const char *hostname, int port,
11796 struct ssh_channel *c = (struct ssh_channel *)channel;
11798 struct Packet *pktout;
11800 logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
11802 if (ssh->version == 1) {
11803 send_packet(ssh, SSH1_MSG_PORT_OPEN,
11804 PKT_INT, c->localid,
11807 /* PKT_STR, <org:orgport>, */
11810 pktout = ssh2_chanopen_init(c, "direct-tcpip");
11812 char *trimmed_host = host_strduptrim(hostname);
11813 ssh2_pkt_addstring(pktout, trimmed_host);
11814 sfree(trimmed_host);
11816 ssh2_pkt_adduint32(pktout, port);
11818 * We make up values for the originator data; partly it's
11819 * too much hassle to keep track, and partly I'm not
11820 * convinced the server should be told details like that
11821 * about my local network configuration.
11822 * The "originator IP address" is syntactically a numeric
11823 * IP address, and some servers (e.g., Tectia) get upset
11824 * if it doesn't match this syntax.
11826 ssh2_pkt_addstring(pktout, "0.0.0.0");
11827 ssh2_pkt_adduint32(pktout, 0);
11828 ssh2_pkt_send(ssh, pktout);
11832 static int ssh_connected(void *handle)
11834 Ssh ssh = (Ssh) handle;
11835 return ssh->s != NULL;
11838 static int ssh_sendok(void *handle)
11840 Ssh ssh = (Ssh) handle;
11841 return ssh->send_ok;
11844 static int ssh_ldisc(void *handle, int option)
11846 Ssh ssh = (Ssh) handle;
11847 if (option == LD_ECHO)
11848 return ssh->echoing;
11849 if (option == LD_EDIT)
11850 return ssh->editing;
11854 static void ssh_provide_ldisc(void *handle, void *ldisc)
11856 Ssh ssh = (Ssh) handle;
11857 ssh->ldisc = ldisc;
11860 static void ssh_provide_logctx(void *handle, void *logctx)
11862 Ssh ssh = (Ssh) handle;
11863 ssh->logctx = logctx;
11866 static int ssh_return_exitcode(void *handle)
11868 Ssh ssh = (Ssh) handle;
11869 if (ssh->s != NULL)
11872 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
11876 * cfg_info for SSH is the protocol running in this session.
11877 * (1 or 2 for the full SSH-1 or SSH-2 protocol; -1 for the bare
11878 * SSH-2 connection protocol, i.e. a downstream; 0 for not-decided-yet.)
11880 static int ssh_cfg_info(void *handle)
11882 Ssh ssh = (Ssh) handle;
11883 if (ssh->version == 0)
11884 return 0; /* don't know yet */
11885 else if (ssh->bare_connection)
11888 return ssh->version;
11892 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
11893 * that fails. This variable is the means by which scp.c can reach
11894 * into the SSH code and find out which one it got.
11896 extern int ssh_fallback_cmd(void *handle)
11898 Ssh ssh = (Ssh) handle;
11899 return ssh->fallback_cmd;
11902 Backend ssh_backend = {
11912 ssh_return_exitcode,
11916 ssh_provide_logctx,
11919 ssh_test_for_upstream,