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 ssh_channel_init(struct ssh_channel *c);
368 static struct ssh_channel *ssh_channel_msg(Ssh ssh, struct Packet *pktin);
369 static void ssh_channel_got_eof(struct ssh_channel *c);
370 static void ssh2_channel_check_close(struct ssh_channel *c);
371 static void ssh_channel_close_local(struct ssh_channel *c, char const *reason);
372 static void ssh_channel_destroy(struct ssh_channel *c);
373 static void ssh_channel_unthrottle(struct ssh_channel *c, int bufsize);
374 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin);
377 * Buffer management constants. There are several of these for
378 * various different purposes:
380 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
381 * on a local data stream before we throttle the whole SSH
382 * connection (in SSH-1 only). Throttling the whole connection is
383 * pretty drastic so we set this high in the hope it won't
386 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
387 * on the SSH connection itself before we defensively throttle
388 * _all_ local data streams. This is pretty drastic too (though
389 * thankfully unlikely in SSH-2 since the window mechanism should
390 * ensure that the server never has any need to throttle its end
391 * of the connection), so we set this high as well.
393 * - OUR_V2_WINSIZE is the default window size we present on SSH-2
396 * - OUR_V2_BIGWIN is the window size we advertise for the only
397 * channel in a simple connection. It must be <= INT_MAX.
399 * - OUR_V2_MAXPKT is the official "maximum packet size" we send
400 * to the remote side. This actually has nothing to do with the
401 * size of the _packet_, but is instead a limit on the amount
402 * of data we're willing to receive in a single SSH2 channel
405 * - OUR_V2_PACKETLIMIT is actually the maximum size of SSH
406 * _packet_ we're prepared to cope with. It must be a multiple
407 * of the cipher block size, and must be at least 35000.
410 #define SSH1_BUFFER_LIMIT 32768
411 #define SSH_MAX_BACKLOG 32768
412 #define OUR_V2_WINSIZE 16384
413 #define OUR_V2_BIGWIN 0x7fffffff
414 #define OUR_V2_MAXPKT 0x4000UL
415 #define OUR_V2_PACKETLIMIT 0x9000UL
417 struct ssh_signkey_with_user_pref_id {
418 const struct ssh_signkey *alg;
421 const static struct ssh_signkey_with_user_pref_id hostkey_algs[] = {
422 { &ssh_ecdsa_ed25519, HK_ED25519 },
423 { &ssh_ecdsa_nistp256, HK_ECDSA },
424 { &ssh_ecdsa_nistp384, HK_ECDSA },
425 { &ssh_ecdsa_nistp521, HK_ECDSA },
426 { &ssh_dss, HK_DSA },
427 { &ssh_rsa, HK_RSA },
430 const static struct ssh_mac *const macs[] = {
431 &ssh_hmac_sha256, &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
433 const static struct ssh_mac *const buggymacs[] = {
434 &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
437 static void *ssh_comp_none_init(void)
441 static void ssh_comp_none_cleanup(void *handle)
444 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
445 unsigned char **outblock, int *outlen)
449 static int ssh_comp_none_disable(void *handle)
453 const static struct ssh_compress ssh_comp_none = {
455 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
456 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
457 ssh_comp_none_disable, NULL
459 extern const struct ssh_compress ssh_zlib;
460 const static struct ssh_compress *const compressions[] = {
461 &ssh_zlib, &ssh_comp_none
464 enum { /* channel types */
470 * CHAN_SHARING indicates a channel which is tracked here on
471 * behalf of a connection-sharing downstream. We do almost nothing
472 * with these channels ourselves: all messages relating to them
473 * get thrown straight to sshshare.c and passed on almost
474 * unmodified to downstream.
478 * CHAN_ZOMBIE is used to indicate a channel for which we've
479 * already destroyed the local data source: for instance, if a
480 * forwarded port experiences a socket error on the local side, we
481 * immediately destroy its local socket and turn the SSH channel
487 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
488 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
489 typedef void (*cchandler_fn_t)(struct ssh_channel *, struct Packet *, void *);
492 * Each channel has a queue of outstanding CHANNEL_REQUESTS and their
495 struct outstanding_channel_request {
496 cchandler_fn_t handler;
498 struct outstanding_channel_request *next;
502 * 2-3-4 tree storing channels.
505 Ssh ssh; /* pointer back to main context */
506 unsigned remoteid, localid;
508 /* True if we opened this channel but server hasn't confirmed. */
511 * In SSH-1, this value contains four bits:
513 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
514 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
515 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
516 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
518 * A channel is completely finished with when all four bits are set.
520 * In SSH-2, the four bits mean:
522 * 1 We have sent SSH2_MSG_CHANNEL_EOF.
523 * 2 We have sent SSH2_MSG_CHANNEL_CLOSE.
524 * 4 We have received SSH2_MSG_CHANNEL_EOF.
525 * 8 We have received SSH2_MSG_CHANNEL_CLOSE.
527 * A channel is completely finished with when we have both sent
528 * and received CLOSE.
530 * The symbolic constants below use the SSH-2 terminology, which
531 * is a bit confusing in SSH-1, but we have to use _something_.
533 #define CLOSES_SENT_EOF 1
534 #define CLOSES_SENT_CLOSE 2
535 #define CLOSES_RCVD_EOF 4
536 #define CLOSES_RCVD_CLOSE 8
540 * This flag indicates that an EOF is pending on the outgoing side
541 * of the channel: that is, wherever we're getting the data for
542 * this channel has sent us some data followed by EOF. We can't
543 * actually send the EOF until we've finished sending the data, so
544 * we set this flag instead to remind us to do so once our buffer
550 * True if this channel is causing the underlying connection to be
555 struct ssh2_data_channel {
557 unsigned remwindow, remmaxpkt;
558 /* locwindow is signed so we can cope with excess data. */
559 int locwindow, locmaxwin;
561 * remlocwin is the amount of local window that we think
562 * the remote end had available to it after it sent the
563 * last data packet or window adjust ack.
567 * These store the list of channel requests that haven't
570 struct outstanding_channel_request *chanreq_head, *chanreq_tail;
571 enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
575 struct ssh_agent_channel {
576 unsigned char *message;
577 unsigned char msglen[4];
578 unsigned lensofar, totallen;
579 int outstanding_requests;
580 agent_pending_query *pending;
582 struct ssh_x11_channel {
583 struct X11Connection *xconn;
586 struct ssh_pfd_channel {
587 struct PortForwarding *pf;
589 struct ssh_sharing_channel {
596 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
597 * use this structure in different ways, reflecting SSH-2's
598 * altogether saner approach to port forwarding.
600 * In SSH-1, you arrange a remote forwarding by sending the server
601 * the remote port number, and the local destination host:port.
602 * When a connection comes in, the server sends you back that
603 * host:port pair, and you connect to it. This is a ready-made
604 * security hole if you're not on the ball: a malicious server
605 * could send you back _any_ host:port pair, so if you trustingly
606 * connect to the address it gives you then you've just opened the
607 * entire inside of your corporate network just by connecting
608 * through it to a dodgy SSH server. Hence, we must store a list of
609 * host:port pairs we _are_ trying to forward to, and reject a
610 * connection request from the server if it's not in the list.
612 * In SSH-2, each side of the connection minds its own business and
613 * doesn't send unnecessary information to the other. You arrange a
614 * remote forwarding by sending the server just the remote port
615 * number. When a connection comes in, the server tells you which
616 * of its ports was connected to; and _you_ have to remember what
617 * local host:port pair went with that port number.
619 * Hence, in SSH-1 this structure is indexed by destination
620 * host:port pair, whereas in SSH-2 it is indexed by source port.
622 struct ssh_portfwd; /* forward declaration */
624 struct ssh_rportfwd {
625 unsigned sport, dport;
629 struct ssh_portfwd *pfrec;
632 static void free_rportfwd(struct ssh_rportfwd *pf)
635 sfree(pf->sportdesc);
643 * Separately to the rportfwd tree (which is for looking up port
644 * open requests from the server), a tree of _these_ structures is
645 * used to keep track of all the currently open port forwardings,
646 * so that we can reconfigure in mid-session if the user requests
650 enum { DESTROY, KEEP, CREATE } status;
652 unsigned sport, dport;
655 struct ssh_rportfwd *remote;
657 struct PortListener *local;
659 #define free_portfwd(pf) ( \
660 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
661 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
664 long length; /* length of packet: see below */
665 long forcepad; /* SSH-2: force padding to at least this length */
666 int type; /* only used for incoming packets */
667 unsigned long sequence; /* SSH-2 incoming sequence number */
668 unsigned char *data; /* allocated storage */
669 unsigned char *body; /* offset of payload within `data' */
670 long savedpos; /* dual-purpose saved packet position: see below */
671 long maxlen; /* amount of storage allocated for `data' */
672 long encrypted_len; /* for SSH-2 total-size counting */
675 * A note on the 'length' and 'savedpos' fields above.
677 * Incoming packets are set up so that pkt->length is measured
678 * relative to pkt->body, which itself points to a few bytes after
679 * pkt->data (skipping some uninteresting header fields including
680 * the packet type code). The ssh_pkt_get* functions all expect
681 * this setup, and they also use pkt->savedpos to indicate how far
682 * through the packet being decoded they've got - and that, too,
683 * is an offset from pkt->body rather than pkt->data.
685 * During construction of an outgoing packet, however, pkt->length
686 * is measured relative to the base pointer pkt->data, and
687 * pkt->body is not really used for anything until the packet is
688 * ready for sending. In this mode, pkt->savedpos is reused as a
689 * temporary variable by the addstring functions, which write out
690 * a string length field and then keep going back and updating it
691 * as more data is appended to the subsequent string data field;
692 * pkt->savedpos stores the offset (again relative to pkt->data)
693 * of the start of the string data field.
696 /* Extra metadata used in SSH packet logging mode, allowing us to
697 * log in the packet header line that the packet came from a
698 * connection-sharing downstream and what if anything unusual was
699 * done to it. The additional_log_text field is expected to be a
700 * static string - it will not be freed. */
701 unsigned downstream_id;
702 const char *additional_log_text;
705 static void ssh1_protocol(Ssh ssh, const void *vin, int inlen,
706 struct Packet *pktin);
707 static void ssh2_protocol(Ssh ssh, const void *vin, int inlen,
708 struct Packet *pktin);
709 static void ssh2_bare_connection_protocol(Ssh ssh, const void *vin, int inlen,
710 struct Packet *pktin);
711 static void ssh1_protocol_setup(Ssh ssh);
712 static void ssh2_protocol_setup(Ssh ssh);
713 static void ssh2_bare_connection_protocol_setup(Ssh ssh);
714 static void ssh_size(void *handle, int width, int height);
715 static void ssh_special(void *handle, Telnet_Special);
716 static int ssh2_try_send(struct ssh_channel *c);
717 static int ssh_send_channel_data(struct ssh_channel *c,
718 const char *buf, int len);
719 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
720 static void ssh2_set_window(struct ssh_channel *c, int newwin);
721 static int ssh_sendbuffer(void *handle);
722 static int ssh_do_close(Ssh ssh, int notify_exit);
723 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
724 static int ssh2_pkt_getbool(struct Packet *pkt);
725 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
726 static void ssh2_timer(void *ctx, unsigned long now);
727 static void do_ssh2_transport(Ssh ssh, const void *vin, int inlen,
728 struct Packet *pktin);
729 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin);
731 struct rdpkt1_state_tag {
732 long len, pad, biglen, to_read;
733 unsigned long realcrc, gotcrc;
737 struct Packet *pktin;
740 struct rdpkt2_state_tag {
741 long len, pad, payload, packetlen, maclen;
744 unsigned long incoming_sequence;
745 struct Packet *pktin;
748 struct rdpkt2_bare_state_tag {
752 unsigned long incoming_sequence;
753 struct Packet *pktin;
756 struct queued_handler;
757 struct queued_handler {
759 chandler_fn_t handler;
761 struct queued_handler *next;
765 const struct plug_function_table *fn;
766 /* the above field _must_ be first in the structure */
776 unsigned char session_key[32];
778 int v1_remote_protoflags;
779 int v1_local_protoflags;
780 int agentfwd_enabled;
783 const struct ssh_cipher *cipher;
786 const struct ssh2_cipher *cscipher, *sccipher;
787 void *cs_cipher_ctx, *sc_cipher_ctx;
788 const struct ssh_mac *csmac, *scmac;
789 int csmac_etm, scmac_etm;
790 void *cs_mac_ctx, *sc_mac_ctx;
791 const struct ssh_compress *cscomp, *sccomp;
792 void *cs_comp_ctx, *sc_comp_ctx;
793 const struct ssh_kex *kex;
794 const struct ssh_signkey *hostkey;
795 char *hostkey_str; /* string representation, for easy checking in rekeys */
796 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
797 int v2_session_id_len;
801 int attempting_connshare;
807 int echoing, editing;
812 int ospeed, ispeed; /* temporaries */
813 int term_width, term_height;
815 tree234 *channels; /* indexed by local id */
816 struct ssh_channel *mainchan; /* primary session channel */
817 int ncmode; /* is primary channel direct-tcpip? */
822 tree234 *rportfwds, *portfwds;
826 SSH_STATE_BEFORE_SIZE,
832 int size_needed, eof_needed;
833 int sent_console_eof;
834 int got_pty; /* affects EOF behaviour on main channel */
836 struct Packet **queue;
837 int queuelen, queuesize;
839 unsigned char *deferred_send_data;
840 int deferred_len, deferred_size;
843 * Gross hack: pscp will try to start SFTP but fall back to
844 * scp1 if that fails. This variable is the means by which
845 * scp.c can reach into the SSH code and find out which one it
850 bufchain banner; /* accumulates banners during do_ssh2_authconn */
855 struct X11Display *x11disp;
856 struct X11FakeAuth *x11auth;
857 tree234 *x11authtree;
860 int conn_throttle_count;
863 int v1_stdout_throttling;
864 unsigned long v2_outgoing_sequence;
866 int ssh1_rdpkt_crstate;
867 int ssh2_rdpkt_crstate;
868 int ssh2_bare_rdpkt_crstate;
869 int ssh_gotdata_crstate;
870 int do_ssh1_connection_crstate;
872 void *do_ssh_init_state;
873 void *do_ssh1_login_state;
874 void *do_ssh2_transport_state;
875 void *do_ssh2_authconn_state;
876 void *do_ssh_connection_init_state;
878 struct rdpkt1_state_tag rdpkt1_state;
879 struct rdpkt2_state_tag rdpkt2_state;
880 struct rdpkt2_bare_state_tag rdpkt2_bare_state;
882 /* SSH-1 and SSH-2 use this for different things, but both use it */
883 int protocol_initial_phase_done;
885 void (*protocol) (Ssh ssh, const void *vin, int inlen,
887 struct Packet *(*s_rdpkt) (Ssh ssh, const unsigned char **data,
889 int (*do_ssh_init)(Ssh ssh, unsigned char c);
892 * We maintain our own copy of a Conf structure here. That way,
893 * when we're passed a new one for reconfiguration, we can check
894 * the differences and potentially reconfigure port forwardings
895 * etc in mid-session.
900 * Values cached out of conf so as to avoid the tree234 lookup
901 * cost every time they're used.
906 * Dynamically allocated username string created during SSH
907 * login. Stored in here rather than in the coroutine state so
908 * that it'll be reliably freed if we shut down the SSH session
909 * at some unexpected moment.
914 * Used to transfer data back from async callbacks.
916 void *agent_response;
917 int agent_response_len;
921 * The SSH connection can be set as `frozen', meaning we are
922 * not currently accepting incoming data from the network. This
923 * is slightly more serious than setting the _socket_ as
924 * frozen, because we may already have had data passed to us
925 * from the network which we need to delay processing until
926 * after the freeze is lifted, so we also need a bufchain to
930 bufchain queued_incoming_data;
933 * Dispatch table for packet types that we may have to deal
936 handler_fn_t packet_dispatch[256];
939 * Queues of one-off handler functions for success/failure
940 * indications from a request.
942 struct queued_handler *qhead, *qtail;
943 handler_fn_t q_saved_handler1, q_saved_handler2;
946 * This module deals with sending keepalives.
951 * Track incoming and outgoing data sizes and time, for
954 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
955 unsigned long max_data_size;
957 unsigned long next_rekey, last_rekey;
958 const char *deferred_rekey_reason;
961 * Fully qualified host name, which we need if doing GSSAPI.
967 * GSSAPI libraries for this session.
969 struct ssh_gss_liblist *gsslibs;
973 * The last list returned from get_specials.
975 struct telnet_special *specials;
978 * List of host key algorithms for which we _don't_ have a stored
979 * host key. These are indices into the main hostkey_algs[] array
981 int uncert_hostkeys[lenof(hostkey_algs)];
982 int n_uncert_hostkeys;
985 * Flag indicating that the current rekey is intended to finish
986 * with a newly cross-certified host key.
988 int cross_certifying;
991 * Any asynchronous query to our SSH agent that we might have in
992 * flight from the main authentication loop. (Queries from
993 * agent-forwarding channels live in their channel structure.)
995 agent_pending_query *auth_agent_query;
998 static const char *ssh_pkt_type(Ssh ssh, int type)
1000 if (ssh->version == 1)
1001 return ssh1_pkt_type(type);
1003 return ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, type);
1006 #define logevent(s) logevent(ssh->frontend, s)
1008 /* logevent, only printf-formatted. */
1009 static void logeventf(Ssh ssh, const char *fmt, ...)
1015 buf = dupvprintf(fmt, ap);
1021 static void bomb_out(Ssh ssh, char *text)
1023 ssh_do_close(ssh, FALSE);
1025 connection_fatal(ssh->frontend, "%s", text);
1029 #define bombout(msg) bomb_out(ssh, dupprintf msg)
1031 /* Helper function for common bits of parsing ttymodes. */
1032 static void parse_ttymodes(Ssh ssh,
1033 void (*do_mode)(void *data,
1034 const struct ssh_ttymode *mode,
1039 const struct ssh_ttymode *mode;
1041 char default_val[2];
1043 strcpy(default_val, "A");
1045 for (i = 0; i < lenof(ssh_ttymodes); i++) {
1046 mode = ssh_ttymodes + i;
1047 val = conf_get_str_str_opt(ssh->conf, CONF_ttymodes, mode->mode);
1052 * val[0] is either 'V', indicating that an explicit value
1053 * follows it, or 'A' indicating that we should pass the
1054 * value through from the local environment via get_ttymode.
1056 if (val[0] == 'A') {
1057 val = get_ttymode(ssh->frontend, mode->mode);
1059 do_mode(data, mode, val);
1063 do_mode(data, mode, val + 1); /* skip the 'V' */
1067 static int ssh_channelcmp(void *av, void *bv)
1069 struct ssh_channel *a = (struct ssh_channel *) av;
1070 struct ssh_channel *b = (struct ssh_channel *) bv;
1071 if (a->localid < b->localid)
1073 if (a->localid > b->localid)
1077 static int ssh_channelfind(void *av, void *bv)
1079 unsigned *a = (unsigned *) av;
1080 struct ssh_channel *b = (struct ssh_channel *) bv;
1081 if (*a < b->localid)
1083 if (*a > b->localid)
1088 static int ssh_rportcmp_ssh1(void *av, void *bv)
1090 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1091 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1093 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
1094 return i < 0 ? -1 : +1;
1095 if (a->dport > b->dport)
1097 if (a->dport < b->dport)
1102 static int ssh_rportcmp_ssh2(void *av, void *bv)
1104 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1105 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1107 if ( (i = strcmp(a->shost, b->shost)) != 0)
1108 return i < 0 ? -1 : +1;
1109 if (a->sport > b->sport)
1111 if (a->sport < b->sport)
1117 * Special form of strcmp which can cope with NULL inputs. NULL is
1118 * defined to sort before even the empty string.
1120 static int nullstrcmp(const char *a, const char *b)
1122 if (a == NULL && b == NULL)
1128 return strcmp(a, b);
1131 static int ssh_portcmp(void *av, void *bv)
1133 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1134 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1136 if (a->type > b->type)
1138 if (a->type < b->type)
1140 if (a->addressfamily > b->addressfamily)
1142 if (a->addressfamily < b->addressfamily)
1144 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1145 return i < 0 ? -1 : +1;
1146 if (a->sport > b->sport)
1148 if (a->sport < b->sport)
1150 if (a->type != 'D') {
1151 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1152 return i < 0 ? -1 : +1;
1153 if (a->dport > b->dport)
1155 if (a->dport < b->dport)
1161 static int alloc_channel_id(Ssh ssh)
1163 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1164 unsigned low, high, mid;
1166 struct ssh_channel *c;
1169 * First-fit allocation of channel numbers: always pick the
1170 * lowest unused one. To do this, binary-search using the
1171 * counted B-tree to find the largest channel ID which is in a
1172 * contiguous sequence from the beginning. (Precisely
1173 * everything in that sequence must have ID equal to its tree
1174 * index plus CHANNEL_NUMBER_OFFSET.)
1176 tsize = count234(ssh->channels);
1180 while (high - low > 1) {
1181 mid = (high + low) / 2;
1182 c = index234(ssh->channels, mid);
1183 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1184 low = mid; /* this one is fine */
1186 high = mid; /* this one is past it */
1189 * Now low points to either -1, or the tree index of the
1190 * largest ID in the initial sequence.
1193 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1194 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1196 return low + 1 + CHANNEL_NUMBER_OFFSET;
1199 static void c_write_stderr(int trusted, const char *buf, int len)
1202 for (i = 0; i < len; i++)
1203 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1204 fputc(buf[i], stderr);
1207 static void c_write(Ssh ssh, const char *buf, int len)
1209 if (flags & FLAG_STDERR)
1210 c_write_stderr(1, buf, len);
1212 from_backend(ssh->frontend, 1, buf, len);
1215 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1217 if (flags & FLAG_STDERR)
1218 c_write_stderr(0, buf, len);
1220 from_backend_untrusted(ssh->frontend, buf, len);
1223 static void c_write_str(Ssh ssh, const char *buf)
1225 c_write(ssh, buf, strlen(buf));
1228 static void ssh_free_packet(struct Packet *pkt)
1233 static struct Packet *ssh_new_packet(void)
1235 struct Packet *pkt = snew(struct Packet);
1237 pkt->body = pkt->data = NULL;
1243 static void ssh1_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1246 struct logblank_t blanks[4];
1252 if (ssh->logomitdata &&
1253 (pkt->type == SSH1_SMSG_STDOUT_DATA ||
1254 pkt->type == SSH1_SMSG_STDERR_DATA ||
1255 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1256 /* "Session data" packets - omit the data string. */
1257 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1258 ssh_pkt_getuint32(pkt); /* skip channel id */
1259 blanks[nblanks].offset = pkt->savedpos + 4;
1260 blanks[nblanks].type = PKTLOG_OMIT;
1261 ssh_pkt_getstring(pkt, &str, &slen);
1263 blanks[nblanks].len = slen;
1267 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1268 ssh1_pkt_type(pkt->type),
1269 pkt->body, pkt->length, nblanks, blanks, NULL,
1273 static void ssh1_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1276 struct logblank_t blanks[4];
1281 * For outgoing packets, pkt->length represents the length of the
1282 * whole packet starting at pkt->data (including some header), and
1283 * pkt->body refers to the point within that where the log-worthy
1284 * payload begins. However, incoming packets expect pkt->length to
1285 * represent only the payload length (that is, it's measured from
1286 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1287 * packet to conform to the incoming-packet semantics, so that we
1288 * can analyse it with the ssh_pkt_get functions.
1290 pkt->length -= (pkt->body - pkt->data);
1293 if (ssh->logomitdata &&
1294 (pkt->type == SSH1_CMSG_STDIN_DATA ||
1295 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1296 /* "Session data" packets - omit the data string. */
1297 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1298 ssh_pkt_getuint32(pkt); /* skip channel id */
1299 blanks[nblanks].offset = pkt->savedpos + 4;
1300 blanks[nblanks].type = PKTLOG_OMIT;
1301 ssh_pkt_getstring(pkt, &str, &slen);
1303 blanks[nblanks].len = slen;
1308 if ((pkt->type == SSH1_CMSG_AUTH_PASSWORD ||
1309 pkt->type == SSH1_CMSG_AUTH_TIS_RESPONSE ||
1310 pkt->type == SSH1_CMSG_AUTH_CCARD_RESPONSE) &&
1311 conf_get_int(ssh->conf, CONF_logomitpass)) {
1312 /* If this is a password or similar packet, blank the password(s). */
1313 blanks[nblanks].offset = 0;
1314 blanks[nblanks].len = pkt->length;
1315 blanks[nblanks].type = PKTLOG_BLANK;
1317 } else if (pkt->type == SSH1_CMSG_X11_REQUEST_FORWARDING &&
1318 conf_get_int(ssh->conf, CONF_logomitpass)) {
1320 * If this is an X forwarding request packet, blank the fake
1323 * Note that while we blank the X authentication data here, we
1324 * don't take any special action to blank the start of an X11
1325 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1326 * an X connection without having session blanking enabled is
1327 * likely to leak your cookie into the log.
1330 ssh_pkt_getstring(pkt, &str, &slen);
1331 blanks[nblanks].offset = pkt->savedpos;
1332 blanks[nblanks].type = PKTLOG_BLANK;
1333 ssh_pkt_getstring(pkt, &str, &slen);
1335 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1340 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1341 ssh1_pkt_type(pkt->data[12]),
1342 pkt->body, pkt->length,
1343 nblanks, blanks, NULL, 0, NULL);
1346 * Undo the above adjustment of pkt->length, to put the packet
1347 * back in the state we found it.
1349 pkt->length += (pkt->body - pkt->data);
1353 * Collect incoming data in the incoming packet buffer.
1354 * Decipher and verify the packet when it is completely read.
1355 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1356 * Update the *data and *datalen variables.
1357 * Return a Packet structure when a packet is completed.
1359 static struct Packet *ssh1_rdpkt(Ssh ssh, const unsigned char **data,
1362 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1364 crBegin(ssh->ssh1_rdpkt_crstate);
1366 st->pktin = ssh_new_packet();
1368 st->pktin->type = 0;
1369 st->pktin->length = 0;
1371 for (st->i = st->len = 0; st->i < 4; st->i++) {
1372 while ((*datalen) == 0)
1374 st->len = (st->len << 8) + **data;
1375 (*data)++, (*datalen)--;
1378 st->pad = 8 - (st->len % 8);
1379 st->biglen = st->len + st->pad;
1380 st->pktin->length = st->len - 5;
1382 if (st->biglen < 0) {
1383 bombout(("Extremely large packet length from server suggests"
1384 " data stream corruption"));
1385 ssh_free_packet(st->pktin);
1389 st->pktin->maxlen = st->biglen;
1390 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1392 st->to_read = st->biglen;
1393 st->p = st->pktin->data;
1394 while (st->to_read > 0) {
1395 st->chunk = st->to_read;
1396 while ((*datalen) == 0)
1398 if (st->chunk > (*datalen))
1399 st->chunk = (*datalen);
1400 memcpy(st->p, *data, st->chunk);
1402 *datalen -= st->chunk;
1404 st->to_read -= st->chunk;
1407 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1408 st->biglen, NULL)) {
1409 bombout(("Network attack (CRC compensation) detected!"));
1410 ssh_free_packet(st->pktin);
1415 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1417 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1418 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1419 if (st->gotcrc != st->realcrc) {
1420 bombout(("Incorrect CRC received on packet"));
1421 ssh_free_packet(st->pktin);
1425 st->pktin->body = st->pktin->data + st->pad + 1;
1427 if (ssh->v1_compressing) {
1428 unsigned char *decompblk;
1430 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1431 st->pktin->body - 1, st->pktin->length + 1,
1432 &decompblk, &decomplen)) {
1433 bombout(("Zlib decompression encountered invalid data"));
1434 ssh_free_packet(st->pktin);
1438 if (st->pktin->maxlen < st->pad + decomplen) {
1439 st->pktin->maxlen = st->pad + decomplen;
1440 st->pktin->data = sresize(st->pktin->data,
1441 st->pktin->maxlen + APIEXTRA,
1443 st->pktin->body = st->pktin->data + st->pad + 1;
1446 memcpy(st->pktin->body - 1, decompblk, decomplen);
1448 st->pktin->length = decomplen - 1;
1451 st->pktin->type = st->pktin->body[-1];
1454 * Now pktin->body and pktin->length identify the semantic content
1455 * of the packet, excluding the initial type byte.
1459 ssh1_log_incoming_packet(ssh, st->pktin);
1461 st->pktin->savedpos = 0;
1463 crFinish(st->pktin);
1466 static void ssh2_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1469 struct logblank_t blanks[4];
1475 if (ssh->logomitdata &&
1476 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1477 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1478 /* "Session data" packets - omit the data string. */
1479 ssh_pkt_getuint32(pkt); /* skip channel id */
1480 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1481 ssh_pkt_getuint32(pkt); /* skip extended data type */
1482 blanks[nblanks].offset = pkt->savedpos + 4;
1483 blanks[nblanks].type = PKTLOG_OMIT;
1484 ssh_pkt_getstring(pkt, &str, &slen);
1486 blanks[nblanks].len = slen;
1491 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1492 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->type),
1493 pkt->body, pkt->length, nblanks, blanks, &pkt->sequence,
1497 static void ssh2_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1500 struct logblank_t blanks[4];
1505 * For outgoing packets, pkt->length represents the length of the
1506 * whole packet starting at pkt->data (including some header), and
1507 * pkt->body refers to the point within that where the log-worthy
1508 * payload begins. However, incoming packets expect pkt->length to
1509 * represent only the payload length (that is, it's measured from
1510 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1511 * packet to conform to the incoming-packet semantics, so that we
1512 * can analyse it with the ssh_pkt_get functions.
1514 pkt->length -= (pkt->body - pkt->data);
1517 if (ssh->logomitdata &&
1518 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1519 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1520 /* "Session data" packets - omit the data string. */
1521 ssh_pkt_getuint32(pkt); /* skip channel id */
1522 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1523 ssh_pkt_getuint32(pkt); /* skip extended data type */
1524 blanks[nblanks].offset = pkt->savedpos + 4;
1525 blanks[nblanks].type = PKTLOG_OMIT;
1526 ssh_pkt_getstring(pkt, &str, &slen);
1528 blanks[nblanks].len = slen;
1533 if (pkt->type == SSH2_MSG_USERAUTH_REQUEST &&
1534 conf_get_int(ssh->conf, CONF_logomitpass)) {
1535 /* If this is a password packet, blank the password(s). */
1537 ssh_pkt_getstring(pkt, &str, &slen);
1538 ssh_pkt_getstring(pkt, &str, &slen);
1539 ssh_pkt_getstring(pkt, &str, &slen);
1540 if (slen == 8 && !memcmp(str, "password", 8)) {
1541 ssh2_pkt_getbool(pkt);
1542 /* Blank the password field. */
1543 blanks[nblanks].offset = pkt->savedpos;
1544 blanks[nblanks].type = PKTLOG_BLANK;
1545 ssh_pkt_getstring(pkt, &str, &slen);
1547 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1549 /* If there's another password field beyond it (change of
1550 * password), blank that too. */
1551 ssh_pkt_getstring(pkt, &str, &slen);
1553 blanks[nblanks-1].len =
1554 pkt->savedpos - blanks[nblanks].offset;
1557 } else if (ssh->pkt_actx == SSH2_PKTCTX_KBDINTER &&
1558 pkt->type == SSH2_MSG_USERAUTH_INFO_RESPONSE &&
1559 conf_get_int(ssh->conf, CONF_logomitpass)) {
1560 /* If this is a keyboard-interactive response packet, blank
1563 ssh_pkt_getuint32(pkt);
1564 blanks[nblanks].offset = pkt->savedpos;
1565 blanks[nblanks].type = PKTLOG_BLANK;
1567 ssh_pkt_getstring(pkt, &str, &slen);
1571 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1573 } else if (pkt->type == SSH2_MSG_CHANNEL_REQUEST &&
1574 conf_get_int(ssh->conf, CONF_logomitpass)) {
1576 * If this is an X forwarding request packet, blank the fake
1579 * Note that while we blank the X authentication data here, we
1580 * don't take any special action to blank the start of an X11
1581 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1582 * an X connection without having session blanking enabled is
1583 * likely to leak your cookie into the log.
1586 ssh_pkt_getuint32(pkt);
1587 ssh_pkt_getstring(pkt, &str, &slen);
1588 if (slen == 7 && !memcmp(str, "x11-req", 0)) {
1589 ssh2_pkt_getbool(pkt);
1590 ssh2_pkt_getbool(pkt);
1591 ssh_pkt_getstring(pkt, &str, &slen);
1592 blanks[nblanks].offset = pkt->savedpos;
1593 blanks[nblanks].type = PKTLOG_BLANK;
1594 ssh_pkt_getstring(pkt, &str, &slen);
1596 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1602 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1603 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1604 pkt->body, pkt->length, nblanks, blanks,
1605 &ssh->v2_outgoing_sequence,
1606 pkt->downstream_id, pkt->additional_log_text);
1609 * Undo the above adjustment of pkt->length, to put the packet
1610 * back in the state we found it.
1612 pkt->length += (pkt->body - pkt->data);
1615 static struct Packet *ssh2_rdpkt(Ssh ssh, const unsigned char **data,
1618 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1620 crBegin(ssh->ssh2_rdpkt_crstate);
1622 st->pktin = ssh_new_packet();
1624 st->pktin->type = 0;
1625 st->pktin->length = 0;
1627 st->cipherblk = ssh->sccipher->blksize;
1630 if (st->cipherblk < 8)
1632 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1634 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1635 ssh->scmac && !ssh->scmac_etm) {
1637 * When dealing with a CBC-mode cipher, we want to avoid the
1638 * possibility of an attacker's tweaking the ciphertext stream
1639 * so as to cause us to feed the same block to the block
1640 * cipher more than once and thus leak information
1641 * (VU#958563). The way we do this is not to take any
1642 * decisions on the basis of anything we've decrypted until
1643 * we've verified it with a MAC. That includes the packet
1644 * length, so we just read data and check the MAC repeatedly,
1645 * and when the MAC passes, see if the length we've got is
1648 * This defence is unnecessary in OpenSSH ETM mode, because
1649 * the whole point of ETM mode is that the attacker can't
1650 * tweak the ciphertext stream at all without the MAC
1651 * detecting it before we decrypt anything.
1654 /* May as well allocate the whole lot now. */
1655 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1658 /* Read an amount corresponding to the MAC. */
1659 for (st->i = 0; st->i < st->maclen; st->i++) {
1660 while ((*datalen) == 0)
1662 st->pktin->data[st->i] = *(*data)++;
1668 unsigned char seq[4];
1669 ssh->scmac->start(ssh->sc_mac_ctx);
1670 PUT_32BIT(seq, st->incoming_sequence);
1671 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1674 for (;;) { /* Once around this loop per cipher block. */
1675 /* Read another cipher-block's worth, and tack it onto the end. */
1676 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1677 while ((*datalen) == 0)
1679 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1682 /* Decrypt one more block (a little further back in the stream). */
1683 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1684 st->pktin->data + st->packetlen,
1686 /* Feed that block to the MAC. */
1687 ssh->scmac->bytes(ssh->sc_mac_ctx,
1688 st->pktin->data + st->packetlen, st->cipherblk);
1689 st->packetlen += st->cipherblk;
1690 /* See if that gives us a valid packet. */
1691 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1692 st->pktin->data + st->packetlen) &&
1693 ((st->len = toint(GET_32BIT(st->pktin->data))) ==
1696 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1697 bombout(("No valid incoming packet found"));
1698 ssh_free_packet(st->pktin);
1702 st->pktin->maxlen = st->packetlen + st->maclen;
1703 st->pktin->data = sresize(st->pktin->data,
1704 st->pktin->maxlen + APIEXTRA,
1706 } else if (ssh->scmac && ssh->scmac_etm) {
1707 st->pktin->data = snewn(4 + APIEXTRA, unsigned char);
1710 * OpenSSH encrypt-then-MAC mode: the packet length is
1711 * unencrypted, unless the cipher supports length encryption.
1713 for (st->i = st->len = 0; st->i < 4; st->i++) {
1714 while ((*datalen) == 0)
1716 st->pktin->data[st->i] = *(*data)++;
1719 /* Cipher supports length decryption, so do it */
1720 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_SEPARATE_LENGTH)) {
1721 /* Keep the packet the same though, so the MAC passes */
1722 unsigned char len[4];
1723 memcpy(len, st->pktin->data, 4);
1724 ssh->sccipher->decrypt_length(ssh->sc_cipher_ctx, len, 4, st->incoming_sequence);
1725 st->len = toint(GET_32BIT(len));
1727 st->len = toint(GET_32BIT(st->pktin->data));
1731 * _Completely_ silly lengths should be stomped on before they
1732 * do us any more damage.
1734 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1735 st->len % st->cipherblk != 0) {
1736 bombout(("Incoming packet length field was garbled"));
1737 ssh_free_packet(st->pktin);
1742 * So now we can work out the total packet length.
1744 st->packetlen = st->len + 4;
1747 * Allocate memory for the rest of the packet.
1749 st->pktin->maxlen = st->packetlen + st->maclen;
1750 st->pktin->data = sresize(st->pktin->data,
1751 st->pktin->maxlen + APIEXTRA,
1755 * Read the remainder of the packet.
1757 for (st->i = 4; st->i < st->packetlen + st->maclen; st->i++) {
1758 while ((*datalen) == 0)
1760 st->pktin->data[st->i] = *(*data)++;
1768 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1769 st->len + 4, st->incoming_sequence)) {
1770 bombout(("Incorrect MAC received on packet"));
1771 ssh_free_packet(st->pktin);
1775 /* Decrypt everything between the length field and the MAC. */
1777 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1778 st->pktin->data + 4,
1781 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1784 * Acquire and decrypt the first block of the packet. This will
1785 * contain the length and padding details.
1787 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1788 while ((*datalen) == 0)
1790 st->pktin->data[st->i] = *(*data)++;
1795 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1796 st->pktin->data, st->cipherblk);
1799 * Now get the length figure.
1801 st->len = toint(GET_32BIT(st->pktin->data));
1804 * _Completely_ silly lengths should be stomped on before they
1805 * do us any more damage.
1807 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1808 (st->len + 4) % st->cipherblk != 0) {
1809 bombout(("Incoming packet was garbled on decryption"));
1810 ssh_free_packet(st->pktin);
1815 * So now we can work out the total packet length.
1817 st->packetlen = st->len + 4;
1820 * Allocate memory for the rest of the packet.
1822 st->pktin->maxlen = st->packetlen + st->maclen;
1823 st->pktin->data = sresize(st->pktin->data,
1824 st->pktin->maxlen + APIEXTRA,
1828 * Read and decrypt the remainder of the packet.
1830 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1832 while ((*datalen) == 0)
1834 st->pktin->data[st->i] = *(*data)++;
1837 /* Decrypt everything _except_ the MAC. */
1839 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1840 st->pktin->data + st->cipherblk,
1841 st->packetlen - st->cipherblk);
1847 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1848 st->len + 4, st->incoming_sequence)) {
1849 bombout(("Incorrect MAC received on packet"));
1850 ssh_free_packet(st->pktin);
1854 /* Get and sanity-check the amount of random padding. */
1855 st->pad = st->pktin->data[4];
1856 if (st->pad < 4 || st->len - st->pad < 1) {
1857 bombout(("Invalid padding length on received packet"));
1858 ssh_free_packet(st->pktin);
1862 * This enables us to deduce the payload length.
1864 st->payload = st->len - st->pad - 1;
1866 st->pktin->length = st->payload + 5;
1867 st->pktin->encrypted_len = st->packetlen;
1869 st->pktin->sequence = st->incoming_sequence++;
1871 st->pktin->length = st->packetlen - st->pad;
1872 assert(st->pktin->length >= 0);
1875 * Decompress packet payload.
1878 unsigned char *newpayload;
1881 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1882 st->pktin->data + 5, st->pktin->length - 5,
1883 &newpayload, &newlen)) {
1884 if (st->pktin->maxlen < newlen + 5) {
1885 st->pktin->maxlen = newlen + 5;
1886 st->pktin->data = sresize(st->pktin->data,
1887 st->pktin->maxlen + APIEXTRA,
1890 st->pktin->length = 5 + newlen;
1891 memcpy(st->pktin->data + 5, newpayload, newlen);
1897 * RFC 4253 doesn't explicitly say that completely empty packets
1898 * with no type byte are forbidden, so treat them as deserving
1899 * an SSH_MSG_UNIMPLEMENTED.
1901 if (st->pktin->length <= 5) { /* == 5 we hope, but robustness */
1902 ssh2_msg_something_unimplemented(ssh, st->pktin);
1906 * pktin->body and pktin->length should identify the semantic
1907 * content of the packet, excluding the initial type byte.
1909 st->pktin->type = st->pktin->data[5];
1910 st->pktin->body = st->pktin->data + 6;
1911 st->pktin->length -= 6;
1912 assert(st->pktin->length >= 0); /* one last double-check */
1915 ssh2_log_incoming_packet(ssh, st->pktin);
1917 st->pktin->savedpos = 0;
1919 crFinish(st->pktin);
1922 static struct Packet *ssh2_bare_connection_rdpkt(Ssh ssh,
1923 const unsigned char **data,
1926 struct rdpkt2_bare_state_tag *st = &ssh->rdpkt2_bare_state;
1928 crBegin(ssh->ssh2_bare_rdpkt_crstate);
1931 * Read the packet length field.
1933 for (st->i = 0; st->i < 4; st->i++) {
1934 while ((*datalen) == 0)
1936 st->length[st->i] = *(*data)++;
1940 st->packetlen = toint(GET_32BIT_MSB_FIRST(st->length));
1941 if (st->packetlen <= 0 || st->packetlen >= OUR_V2_PACKETLIMIT) {
1942 bombout(("Invalid packet length received"));
1946 st->pktin = ssh_new_packet();
1947 st->pktin->data = snewn(st->packetlen, unsigned char);
1949 st->pktin->encrypted_len = st->packetlen;
1951 st->pktin->sequence = st->incoming_sequence++;
1954 * Read the remainder of the packet.
1956 for (st->i = 0; st->i < st->packetlen; st->i++) {
1957 while ((*datalen) == 0)
1959 st->pktin->data[st->i] = *(*data)++;
1964 * pktin->body and pktin->length should identify the semantic
1965 * content of the packet, excluding the initial type byte.
1967 st->pktin->type = st->pktin->data[0];
1968 st->pktin->body = st->pktin->data + 1;
1969 st->pktin->length = st->packetlen - 1;
1972 * Log incoming packet, possibly omitting sensitive fields.
1975 ssh2_log_incoming_packet(ssh, st->pktin);
1977 st->pktin->savedpos = 0;
1979 crFinish(st->pktin);
1982 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1984 int pad, biglen, i, pktoffs;
1988 * XXX various versions of SC (including 8.8.4) screw up the
1989 * register allocation in this function and use the same register
1990 * (D6) for len and as a temporary, with predictable results. The
1991 * following sledgehammer prevents this.
1998 ssh1_log_outgoing_packet(ssh, pkt);
2000 if (ssh->v1_compressing) {
2001 unsigned char *compblk;
2003 zlib_compress_block(ssh->cs_comp_ctx,
2004 pkt->data + 12, pkt->length - 12,
2005 &compblk, &complen);
2006 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
2007 memcpy(pkt->data + 12, compblk, complen);
2009 pkt->length = complen + 12;
2012 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
2014 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
2015 pad = 8 - (len % 8);
2017 biglen = len + pad; /* len(padding+type+data+CRC) */
2019 for (i = pktoffs; i < 4+8; i++)
2020 pkt->data[i] = random_byte();
2021 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
2022 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
2023 PUT_32BIT(pkt->data + pktoffs, len);
2026 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
2027 pkt->data + pktoffs + 4, biglen);
2029 if (offset_p) *offset_p = pktoffs;
2030 return biglen + 4; /* len(length+padding+type+data+CRC) */
2033 static int s_write(Ssh ssh, void *data, int len)
2036 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
2037 0, NULL, NULL, 0, NULL);
2040 return sk_write(ssh->s, (char *)data, len);
2043 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
2045 int len, backlog, offset;
2046 len = s_wrpkt_prepare(ssh, pkt, &offset);
2047 backlog = s_write(ssh, pkt->data + offset, len);
2048 if (backlog > SSH_MAX_BACKLOG)
2049 ssh_throttle_all(ssh, 1, backlog);
2050 ssh_free_packet(pkt);
2053 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
2056 len = s_wrpkt_prepare(ssh, pkt, &offset);
2057 if (ssh->deferred_len + len > ssh->deferred_size) {
2058 ssh->deferred_size = ssh->deferred_len + len + 128;
2059 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2063 memcpy(ssh->deferred_send_data + ssh->deferred_len,
2064 pkt->data + offset, len);
2065 ssh->deferred_len += len;
2066 ssh_free_packet(pkt);
2070 * Construct a SSH-1 packet with the specified contents.
2071 * (This all-at-once interface used to be the only one, but now SSH-1
2072 * packets can also be constructed incrementally.)
2074 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
2080 pkt = ssh1_pkt_init(pkttype);
2082 while ((argtype = va_arg(ap, int)) != PKT_END) {
2083 unsigned char *argp, argchar;
2085 unsigned long argint;
2088 /* Actual fields in the packet */
2090 argint = va_arg(ap, int);
2091 ssh_pkt_adduint32(pkt, argint);
2094 argchar = (unsigned char) va_arg(ap, int);
2095 ssh_pkt_addbyte(pkt, argchar);
2098 argp = va_arg(ap, unsigned char *);
2099 arglen = va_arg(ap, int);
2100 ssh_pkt_adddata(pkt, argp, arglen);
2103 sargp = va_arg(ap, char *);
2104 ssh_pkt_addstring(pkt, sargp);
2107 bn = va_arg(ap, Bignum);
2108 ssh1_pkt_addmp(pkt, bn);
2116 static void send_packet(Ssh ssh, int pkttype, ...)
2120 va_start(ap, pkttype);
2121 pkt = construct_packet(ssh, pkttype, ap);
2126 static void defer_packet(Ssh ssh, int pkttype, ...)
2130 va_start(ap, pkttype);
2131 pkt = construct_packet(ssh, pkttype, ap);
2133 s_wrpkt_defer(ssh, pkt);
2136 static int ssh_versioncmp(const char *a, const char *b)
2139 unsigned long av, bv;
2141 av = strtoul(a, &ae, 10);
2142 bv = strtoul(b, &be, 10);
2144 return (av < bv ? -1 : +1);
2149 av = strtoul(ae, &ae, 10);
2150 bv = strtoul(be, &be, 10);
2152 return (av < bv ? -1 : +1);
2157 * Utility routines for putting an SSH-protocol `string' and
2158 * `uint32' into a hash state.
2160 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
2162 unsigned char lenblk[4];
2163 PUT_32BIT(lenblk, len);
2164 h->bytes(s, lenblk, 4);
2165 h->bytes(s, str, len);
2168 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
2170 unsigned char intblk[4];
2171 PUT_32BIT(intblk, i);
2172 h->bytes(s, intblk, 4);
2176 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
2178 static void ssh_pkt_ensure(struct Packet *pkt, int length)
2180 if (pkt->maxlen < length) {
2181 unsigned char *body = pkt->body;
2182 int offset = body ? body - pkt->data : 0;
2183 pkt->maxlen = length + 256;
2184 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
2185 if (body) pkt->body = pkt->data + offset;
2188 static void ssh_pkt_adddata(struct Packet *pkt, const void *data, int len)
2191 ssh_pkt_ensure(pkt, pkt->length);
2192 memcpy(pkt->data + pkt->length - len, data, len);
2194 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
2196 ssh_pkt_adddata(pkt, &byte, 1);
2198 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
2200 ssh_pkt_adddata(pkt, &value, 1);
2202 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
2205 PUT_32BIT(x, value);
2206 ssh_pkt_adddata(pkt, x, 4);
2208 static void ssh_pkt_addstring_start(struct Packet *pkt)
2210 ssh_pkt_adduint32(pkt, 0);
2211 pkt->savedpos = pkt->length;
2213 static void ssh_pkt_addstring_data(struct Packet *pkt, const char *data,
2216 ssh_pkt_adddata(pkt, data, len);
2217 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
2219 static void ssh_pkt_addstring_str(struct Packet *pkt, const char *data)
2221 ssh_pkt_addstring_data(pkt, data, strlen(data));
2223 static void ssh_pkt_addstring(struct Packet *pkt, const char *data)
2225 ssh_pkt_addstring_start(pkt);
2226 ssh_pkt_addstring_str(pkt, data);
2228 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
2230 int len = ssh1_bignum_length(b);
2231 unsigned char *data = snewn(len, unsigned char);
2232 (void) ssh1_write_bignum(data, b);
2233 ssh_pkt_adddata(pkt, data, len);
2236 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
2239 int i, n = (bignum_bitcount(b) + 7) / 8;
2240 p = snewn(n + 1, unsigned char);
2242 for (i = 1; i <= n; i++)
2243 p[i] = bignum_byte(b, n - i);
2245 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
2247 memmove(p, p + i, n + 1 - i);
2251 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
2255 p = ssh2_mpint_fmt(b, &len);
2256 ssh_pkt_addstring_start(pkt);
2257 ssh_pkt_addstring_data(pkt, (char *)p, len);
2261 static struct Packet *ssh1_pkt_init(int pkt_type)
2263 struct Packet *pkt = ssh_new_packet();
2264 pkt->length = 4 + 8; /* space for length + max padding */
2265 ssh_pkt_addbyte(pkt, pkt_type);
2266 pkt->body = pkt->data + pkt->length;
2267 pkt->type = pkt_type;
2268 pkt->downstream_id = 0;
2269 pkt->additional_log_text = NULL;
2273 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
2274 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
2275 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
2276 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
2277 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
2278 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
2279 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
2280 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
2281 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
2283 static struct Packet *ssh2_pkt_init(int pkt_type)
2285 struct Packet *pkt = ssh_new_packet();
2286 pkt->length = 5; /* space for packet length + padding length */
2288 pkt->type = pkt_type;
2289 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
2290 pkt->body = pkt->data + pkt->length; /* after packet type */
2291 pkt->downstream_id = 0;
2292 pkt->additional_log_text = NULL;
2297 * Construct an SSH-2 final-form packet: compress it, encrypt it,
2298 * put the MAC on it. Final packet, ready to be sent, is stored in
2299 * pkt->data. Total length is returned.
2301 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
2303 int cipherblk, maclen, padding, unencrypted_prefix, i;
2306 ssh2_log_outgoing_packet(ssh, pkt);
2308 if (ssh->bare_connection) {
2310 * Trivial packet construction for the bare connection
2313 PUT_32BIT(pkt->data + 1, pkt->length - 5);
2314 pkt->body = pkt->data + 1;
2315 ssh->v2_outgoing_sequence++; /* only for diagnostics, really */
2316 return pkt->length - 1;
2320 * Compress packet payload.
2323 unsigned char *newpayload;
2326 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
2328 &newpayload, &newlen)) {
2330 ssh2_pkt_adddata(pkt, newpayload, newlen);
2336 * Add padding. At least four bytes, and must also bring total
2337 * length (minus MAC) up to a multiple of the block size.
2338 * If pkt->forcepad is set, make sure the packet is at least that size
2341 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
2342 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
2344 unencrypted_prefix = (ssh->csmac && ssh->csmac_etm) ? 4 : 0;
2345 if (pkt->length + padding < pkt->forcepad)
2346 padding = pkt->forcepad - pkt->length;
2348 (cipherblk - (pkt->length - unencrypted_prefix + padding) % cipherblk)
2350 assert(padding <= 255);
2351 maclen = ssh->csmac ? ssh->csmac->len : 0;
2352 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
2353 pkt->data[4] = padding;
2354 for (i = 0; i < padding; i++)
2355 pkt->data[pkt->length + i] = random_byte();
2356 PUT_32BIT(pkt->data, pkt->length + padding - 4);
2358 /* Encrypt length if the scheme requires it */
2359 if (ssh->cscipher && (ssh->cscipher->flags & SSH_CIPHER_SEPARATE_LENGTH)) {
2360 ssh->cscipher->encrypt_length(ssh->cs_cipher_ctx, pkt->data, 4,
2361 ssh->v2_outgoing_sequence);
2364 if (ssh->csmac && ssh->csmac_etm) {
2366 * OpenSSH-defined encrypt-then-MAC protocol.
2369 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2370 pkt->data + 4, pkt->length + padding - 4);
2371 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2372 pkt->length + padding,
2373 ssh->v2_outgoing_sequence);
2376 * SSH-2 standard protocol.
2379 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2380 pkt->length + padding,
2381 ssh->v2_outgoing_sequence);
2383 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2384 pkt->data, pkt->length + padding);
2387 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
2388 pkt->encrypted_len = pkt->length + padding;
2390 /* Ready-to-send packet starts at pkt->data. We return length. */
2391 pkt->body = pkt->data;
2392 return pkt->length + padding + maclen;
2396 * Routines called from the main SSH code to send packets. There
2397 * are quite a few of these, because we have two separate
2398 * mechanisms for delaying the sending of packets:
2400 * - In order to send an IGNORE message and a password message in
2401 * a single fixed-length blob, we require the ability to
2402 * concatenate the encrypted forms of those two packets _into_ a
2403 * single blob and then pass it to our <network.h> transport
2404 * layer in one go. Hence, there's a deferment mechanism which
2405 * works after packet encryption.
2407 * - In order to avoid sending any connection-layer messages
2408 * during repeat key exchange, we have to queue up any such
2409 * outgoing messages _before_ they are encrypted (and in
2410 * particular before they're allocated sequence numbers), and
2411 * then send them once we've finished.
2413 * I call these mechanisms `defer' and `queue' respectively, so as
2414 * to distinguish them reasonably easily.
2416 * The functions send_noqueue() and defer_noqueue() free the packet
2417 * structure they are passed. Every outgoing packet goes through
2418 * precisely one of these functions in its life; packets passed to
2419 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
2420 * these or get queued, and then when the queue is later emptied
2421 * the packets are all passed to defer_noqueue().
2423 * When using a CBC-mode cipher, it's necessary to ensure that an
2424 * attacker can't provide data to be encrypted using an IV that they
2425 * know. We ensure this by prefixing each packet that might contain
2426 * user data with an SSH_MSG_IGNORE. This is done using the deferral
2427 * mechanism, so in this case send_noqueue() ends up redirecting to
2428 * defer_noqueue(). If you don't like this inefficiency, don't use
2432 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
2433 static void ssh_pkt_defersend(Ssh);
2436 * Send an SSH-2 packet immediately, without queuing or deferring.
2438 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
2442 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
2443 /* We need to send two packets, so use the deferral mechanism. */
2444 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2445 ssh_pkt_defersend(ssh);
2448 len = ssh2_pkt_construct(ssh, pkt);
2449 backlog = s_write(ssh, pkt->body, len);
2450 if (backlog > SSH_MAX_BACKLOG)
2451 ssh_throttle_all(ssh, 1, backlog);
2453 ssh->outgoing_data_size += pkt->encrypted_len;
2454 if (!ssh->kex_in_progress &&
2455 !ssh->bare_connection &&
2456 ssh->max_data_size != 0 &&
2457 ssh->outgoing_data_size > ssh->max_data_size)
2458 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2460 ssh_free_packet(pkt);
2464 * Defer an SSH-2 packet.
2466 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2469 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2470 ssh->deferred_len == 0 && !noignore &&
2471 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2473 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2474 * get encrypted with a known IV.
2476 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2477 ssh2_pkt_addstring_start(ipkt);
2478 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2480 len = ssh2_pkt_construct(ssh, pkt);
2481 if (ssh->deferred_len + len > ssh->deferred_size) {
2482 ssh->deferred_size = ssh->deferred_len + len + 128;
2483 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2487 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->body, len);
2488 ssh->deferred_len += len;
2489 ssh->deferred_data_size += pkt->encrypted_len;
2490 ssh_free_packet(pkt);
2494 * Queue an SSH-2 packet.
2496 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2498 assert(ssh->queueing);
2500 if (ssh->queuelen >= ssh->queuesize) {
2501 ssh->queuesize = ssh->queuelen + 32;
2502 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2505 ssh->queue[ssh->queuelen++] = pkt;
2509 * Either queue or send a packet, depending on whether queueing is
2512 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2515 ssh2_pkt_queue(ssh, pkt);
2517 ssh2_pkt_send_noqueue(ssh, pkt);
2521 * Either queue or defer a packet, depending on whether queueing is
2524 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2527 ssh2_pkt_queue(ssh, pkt);
2529 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2533 * Send the whole deferred data block constructed by
2534 * ssh2_pkt_defer() or SSH-1's defer_packet().
2536 * The expected use of the defer mechanism is that you call
2537 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2538 * not currently queueing, this simply sets up deferred_send_data
2539 * and then sends it. If we _are_ currently queueing, the calls to
2540 * ssh2_pkt_defer() put the deferred packets on to the queue
2541 * instead, and therefore ssh_pkt_defersend() has no deferred data
2542 * to send. Hence, there's no need to make it conditional on
2545 static void ssh_pkt_defersend(Ssh ssh)
2548 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2549 ssh->deferred_len = ssh->deferred_size = 0;
2550 sfree(ssh->deferred_send_data);
2551 ssh->deferred_send_data = NULL;
2552 if (backlog > SSH_MAX_BACKLOG)
2553 ssh_throttle_all(ssh, 1, backlog);
2555 if (ssh->version == 2) {
2556 ssh->outgoing_data_size += ssh->deferred_data_size;
2557 ssh->deferred_data_size = 0;
2558 if (!ssh->kex_in_progress &&
2559 !ssh->bare_connection &&
2560 ssh->max_data_size != 0 &&
2561 ssh->outgoing_data_size > ssh->max_data_size)
2562 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2567 * Send a packet whose length needs to be disguised (typically
2568 * passwords or keyboard-interactive responses).
2570 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2576 * The simplest way to do this is to adjust the
2577 * variable-length padding field in the outgoing packet.
2579 * Currently compiled out, because some Cisco SSH servers
2580 * don't like excessively padded packets (bah, why's it
2583 pkt->forcepad = padsize;
2584 ssh2_pkt_send(ssh, pkt);
2589 * If we can't do that, however, an alternative approach is
2590 * to use the pkt_defer mechanism to bundle the packet
2591 * tightly together with an SSH_MSG_IGNORE such that their
2592 * combined length is a constant. So first we construct the
2593 * final form of this packet and defer its sending.
2595 ssh2_pkt_defer(ssh, pkt);
2598 * Now construct an SSH_MSG_IGNORE which includes a string
2599 * that's an exact multiple of the cipher block size. (If
2600 * the cipher is NULL so that the block size is
2601 * unavailable, we don't do this trick at all, because we
2602 * gain nothing by it.)
2604 if (ssh->cscipher &&
2605 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2608 stringlen = (256 - ssh->deferred_len);
2609 stringlen += ssh->cscipher->blksize - 1;
2610 stringlen -= (stringlen % ssh->cscipher->blksize);
2613 * Temporarily disable actual compression, so we
2614 * can guarantee to get this string exactly the
2615 * length we want it. The compression-disabling
2616 * routine should return an integer indicating how
2617 * many bytes we should adjust our string length
2621 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2623 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2624 ssh2_pkt_addstring_start(pkt);
2625 for (i = 0; i < stringlen; i++) {
2626 char c = (char) random_byte();
2627 ssh2_pkt_addstring_data(pkt, &c, 1);
2629 ssh2_pkt_defer(ssh, pkt);
2631 ssh_pkt_defersend(ssh);
2636 * Send all queued SSH-2 packets. We send them by means of
2637 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2638 * packets that needed to be lumped together.
2640 static void ssh2_pkt_queuesend(Ssh ssh)
2644 assert(!ssh->queueing);
2646 for (i = 0; i < ssh->queuelen; i++)
2647 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2650 ssh_pkt_defersend(ssh);
2654 void bndebug(char *string, Bignum b)
2658 p = ssh2_mpint_fmt(b, &len);
2659 debug(("%s", string));
2660 for (i = 0; i < len; i++)
2661 debug((" %02x", p[i]));
2667 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2671 p = ssh2_mpint_fmt(b, &len);
2672 hash_string(h, s, p, len);
2677 * Packet decode functions for both SSH-1 and SSH-2.
2679 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2681 unsigned long value;
2682 if (pkt->length - pkt->savedpos < 4)
2683 return 0; /* arrgh, no way to decline (FIXME?) */
2684 value = GET_32BIT(pkt->body + pkt->savedpos);
2688 static int ssh2_pkt_getbool(struct Packet *pkt)
2690 unsigned long value;
2691 if (pkt->length - pkt->savedpos < 1)
2692 return 0; /* arrgh, no way to decline (FIXME?) */
2693 value = pkt->body[pkt->savedpos] != 0;
2697 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2702 if (pkt->length - pkt->savedpos < 4)
2704 len = toint(GET_32BIT(pkt->body + pkt->savedpos));
2709 if (pkt->length - pkt->savedpos < *length)
2711 *p = (char *)(pkt->body + pkt->savedpos);
2712 pkt->savedpos += *length;
2714 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2716 if (pkt->length - pkt->savedpos < length)
2718 pkt->savedpos += length;
2719 return pkt->body + (pkt->savedpos - length);
2721 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2722 const unsigned char **keystr)
2726 j = makekey(pkt->body + pkt->savedpos,
2727 pkt->length - pkt->savedpos,
2734 assert(pkt->savedpos < pkt->length);
2738 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2743 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2744 pkt->length - pkt->savedpos, &b);
2752 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2758 ssh_pkt_getstring(pkt, &p, &length);
2763 b = bignum_from_bytes((unsigned char *)p, length);
2768 * Helper function to add an SSH-2 signature blob to a packet.
2769 * Expects to be shown the public key blob as well as the signature
2770 * blob. Normally works just like ssh2_pkt_addstring, but will
2771 * fiddle with the signature packet if necessary for
2772 * BUG_SSH2_RSA_PADDING.
2774 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2775 void *pkblob_v, int pkblob_len,
2776 void *sigblob_v, int sigblob_len)
2778 unsigned char *pkblob = (unsigned char *)pkblob_v;
2779 unsigned char *sigblob = (unsigned char *)sigblob_v;
2781 /* dmemdump(pkblob, pkblob_len); */
2782 /* dmemdump(sigblob, sigblob_len); */
2785 * See if this is in fact an ssh-rsa signature and a buggy
2786 * server; otherwise we can just do this the easy way.
2788 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) && pkblob_len > 4+7+4 &&
2789 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2790 int pos, len, siglen;
2793 * Find the byte length of the modulus.
2796 pos = 4+7; /* skip over "ssh-rsa" */
2797 len = toint(GET_32BIT(pkblob+pos)); /* get length of exponent */
2798 if (len < 0 || len > pkblob_len - pos - 4)
2800 pos += 4 + len; /* skip over exponent */
2801 if (pkblob_len - pos < 4)
2803 len = toint(GET_32BIT(pkblob+pos)); /* find length of modulus */
2804 if (len < 0 || len > pkblob_len - pos - 4)
2806 pos += 4; /* find modulus itself */
2807 while (len > 0 && pkblob[pos] == 0)
2809 /* debug(("modulus length is %d\n", len)); */
2812 * Now find the signature integer.
2814 pos = 4+7; /* skip over "ssh-rsa" */
2815 if (sigblob_len < pos+4)
2817 siglen = toint(GET_32BIT(sigblob+pos));
2818 if (siglen != sigblob_len - pos - 4)
2820 /* debug(("signature length is %d\n", siglen)); */
2822 if (len != siglen) {
2823 unsigned char newlen[4];
2824 ssh2_pkt_addstring_start(pkt);
2825 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2826 /* dmemdump(sigblob, pos); */
2827 pos += 4; /* point to start of actual sig */
2828 PUT_32BIT(newlen, len);
2829 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2830 /* dmemdump(newlen, 4); */
2832 while (len-- > siglen) {
2833 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2834 /* dmemdump(newlen, 1); */
2836 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2837 /* dmemdump(sigblob+pos, siglen); */
2841 /* Otherwise fall through and do it the easy way. We also come
2842 * here as a fallback if we discover above that the key blob
2843 * is misformatted in some way. */
2847 ssh2_pkt_addstring_start(pkt);
2848 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2852 * Examine the remote side's version string and compare it against
2853 * a list of known buggy implementations.
2855 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2857 char *imp; /* pointer to implementation part */
2859 imp += strcspn(imp, "-");
2861 imp += strcspn(imp, "-");
2864 ssh->remote_bugs = 0;
2867 * General notes on server version strings:
2868 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2869 * here -- in particular, we've heard of one that's perfectly happy
2870 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2871 * so we can't distinguish them.
2873 if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
2874 (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
2875 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2876 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2877 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2878 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2880 * These versions don't support SSH1_MSG_IGNORE, so we have
2881 * to use a different defence against password length
2884 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2885 logevent("We believe remote version has SSH-1 ignore bug");
2888 if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
2889 (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
2890 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2892 * These versions need a plain password sent; they can't
2893 * handle having a null and a random length of data after
2896 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2897 logevent("We believe remote version needs a plain SSH-1 password");
2900 if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
2901 (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
2902 (!strcmp(imp, "Cisco-1.25")))) {
2904 * These versions apparently have no clue whatever about
2905 * RSA authentication and will panic and die if they see
2906 * an AUTH_RSA message.
2908 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2909 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2912 if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
2913 (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
2914 !wc_match("* VShell", imp) &&
2915 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2916 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2917 wc_match("2.1 *", imp)))) {
2919 * These versions have the HMAC bug.
2921 ssh->remote_bugs |= BUG_SSH2_HMAC;
2922 logevent("We believe remote version has SSH-2 HMAC bug");
2925 if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
2926 (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
2927 !wc_match("* VShell", imp) &&
2928 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2930 * These versions have the key-derivation bug (failing to
2931 * include the literal shared secret in the hashes that
2932 * generate the keys).
2934 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2935 logevent("We believe remote version has SSH-2 key-derivation bug");
2938 if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
2939 (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
2940 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2941 wc_match("OpenSSH_3.[0-2]*", imp) ||
2942 wc_match("mod_sftp/0.[0-8]*", imp) ||
2943 wc_match("mod_sftp/0.9.[0-8]", imp)))) {
2945 * These versions have the SSH-2 RSA padding bug.
2947 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2948 logevent("We believe remote version has SSH-2 RSA padding bug");
2951 if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
2952 (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
2953 wc_match("OpenSSH_2.[0-2]*", imp))) {
2955 * These versions have the SSH-2 session-ID bug in
2956 * public-key authentication.
2958 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2959 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2962 if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
2963 (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
2964 (wc_match("DigiSSH_2.0", imp) ||
2965 wc_match("OpenSSH_2.[0-4]*", imp) ||
2966 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2967 wc_match("Sun_SSH_1.0", imp) ||
2968 wc_match("Sun_SSH_1.0.1", imp) ||
2969 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2970 wc_match("WeOnlyDo-*", imp)))) {
2972 * These versions have the SSH-2 rekey bug.
2974 ssh->remote_bugs |= BUG_SSH2_REKEY;
2975 logevent("We believe remote version has SSH-2 rekey bug");
2978 if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
2979 (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
2980 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2981 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2983 * This version ignores our makpkt and needs to be throttled.
2985 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2986 logevent("We believe remote version ignores SSH-2 maximum packet size");
2989 if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
2991 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2992 * none detected automatically.
2994 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2995 logevent("We believe remote version has SSH-2 ignore bug");
2998 if (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == FORCE_ON ||
2999 (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == AUTO &&
3000 (wc_match("OpenSSH_2.[235]*", imp)))) {
3002 * These versions only support the original (pre-RFC4419)
3003 * SSH-2 GEX request, and disconnect with a protocol error if
3004 * we use the newer version.
3006 ssh->remote_bugs |= BUG_SSH2_OLDGEX;
3007 logevent("We believe remote version has outdated SSH-2 GEX");
3010 if (conf_get_int(ssh->conf, CONF_sshbug_winadj) == FORCE_ON) {
3012 * Servers that don't support our winadj request for one
3013 * reason or another. Currently, none detected automatically.
3015 ssh->remote_bugs |= BUG_CHOKES_ON_WINADJ;
3016 logevent("We believe remote version has winadj bug");
3019 if (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == FORCE_ON ||
3020 (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == AUTO &&
3021 (wc_match("OpenSSH_[2-5].*", imp) ||
3022 wc_match("OpenSSH_6.[0-6]*", imp) ||
3023 wc_match("dropbear_0.[2-4][0-9]*", imp) ||
3024 wc_match("dropbear_0.5[01]*", imp)))) {
3026 * These versions have the SSH-2 channel request bug.
3027 * OpenSSH 6.7 and above do not:
3028 * https://bugzilla.mindrot.org/show_bug.cgi?id=1818
3029 * dropbear_0.52 and above do not:
3030 * https://secure.ucc.asn.au/hg/dropbear/rev/cd02449b709c
3032 ssh->remote_bugs |= BUG_SENDS_LATE_REQUEST_REPLY;
3033 logevent("We believe remote version has SSH-2 channel request bug");
3038 * The `software version' part of an SSH version string is required
3039 * to contain no spaces or minus signs.
3041 static void ssh_fix_verstring(char *str)
3043 /* Eat "<protoversion>-". */
3044 while (*str && *str != '-') str++;
3045 assert(*str == '-'); str++;
3047 /* Convert minus signs and spaces in the remaining string into
3050 if (*str == '-' || *str == ' ')
3057 * Send an appropriate SSH version string.
3059 static void ssh_send_verstring(Ssh ssh, const char *protoname, char *svers)
3063 if (ssh->version == 2) {
3065 * Construct a v2 version string.
3067 verstring = dupprintf("%s2.0-%s\015\012", protoname, sshver);
3070 * Construct a v1 version string.
3072 assert(!strcmp(protoname, "SSH-")); /* no v1 bare connection protocol */
3073 verstring = dupprintf("SSH-%s-%s\012",
3074 (ssh_versioncmp(svers, "1.5") <= 0 ?
3079 ssh_fix_verstring(verstring + strlen(protoname));
3081 /* FUZZING make PuTTY insecure, so make live use difficult. */
3085 if (ssh->version == 2) {
3088 * Record our version string.
3090 len = strcspn(verstring, "\015\012");
3091 ssh->v_c = snewn(len + 1, char);
3092 memcpy(ssh->v_c, verstring, len);
3096 logeventf(ssh, "We claim version: %.*s",
3097 strcspn(verstring, "\015\012"), verstring);
3098 s_write(ssh, verstring, strlen(verstring));
3102 static int do_ssh_init(Ssh ssh, unsigned char c)
3104 static const char protoname[] = "SSH-";
3106 struct do_ssh_init_state {
3115 crState(do_ssh_init_state);
3119 /* Search for a line beginning with the protocol name prefix in
3122 for (s->i = 0; protoname[s->i]; s->i++) {
3123 if ((char)c != protoname[s->i]) goto no;
3133 ssh->session_started = TRUE;
3135 s->vstrsize = sizeof(protoname) + 16;
3136 s->vstring = snewn(s->vstrsize, char);
3137 strcpy(s->vstring, protoname);
3138 s->vslen = strlen(protoname);
3141 if (s->vslen >= s->vstrsize - 1) {
3143 s->vstring = sresize(s->vstring, s->vstrsize, char);
3145 s->vstring[s->vslen++] = c;
3148 s->version[s->i] = '\0';
3150 } else if (s->i < sizeof(s->version) - 1)
3151 s->version[s->i++] = c;
3152 } else if (c == '\012')
3154 crReturn(1); /* get another char */
3157 ssh->agentfwd_enabled = FALSE;
3158 ssh->rdpkt2_state.incoming_sequence = 0;
3160 s->vstring[s->vslen] = 0;
3161 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3162 logeventf(ssh, "Server version: %s", s->vstring);
3163 ssh_detect_bugs(ssh, s->vstring);
3166 * Decide which SSH protocol version to support.
3169 /* Anything strictly below "2.0" means protocol 1 is supported. */
3170 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
3171 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
3172 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
3174 if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
3176 bombout(("SSH protocol version 1 required by our configuration "
3177 "but not provided by server"));
3180 } else if (conf_get_int(ssh->conf, CONF_sshprot) == 3) {
3182 bombout(("SSH protocol version 2 required by our configuration "
3183 "but server only provides (old, insecure) SSH-1"));
3187 /* No longer support values 1 or 2 for CONF_sshprot */
3188 assert(!"Unexpected value for CONF_sshprot");
3191 if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
3196 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
3198 /* Send the version string, if we haven't already */
3199 if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
3200 ssh_send_verstring(ssh, protoname, s->version);
3202 if (ssh->version == 2) {
3205 * Record their version string.
3207 len = strcspn(s->vstring, "\015\012");
3208 ssh->v_s = snewn(len + 1, char);
3209 memcpy(ssh->v_s, s->vstring, len);
3213 * Initialise SSH-2 protocol.
3215 ssh->protocol = ssh2_protocol;
3216 ssh2_protocol_setup(ssh);
3217 ssh->s_rdpkt = ssh2_rdpkt;
3220 * Initialise SSH-1 protocol.
3222 ssh->protocol = ssh1_protocol;
3223 ssh1_protocol_setup(ssh);
3224 ssh->s_rdpkt = ssh1_rdpkt;
3226 if (ssh->version == 2)
3227 do_ssh2_transport(ssh, NULL, -1, NULL);
3229 update_specials_menu(ssh->frontend);
3230 ssh->state = SSH_STATE_BEFORE_SIZE;
3231 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3238 static int do_ssh_connection_init(Ssh ssh, unsigned char c)
3241 * Ordinary SSH begins with the banner "SSH-x.y-...". This is just
3242 * the ssh-connection part, extracted and given a trivial binary
3243 * packet protocol, so we replace 'SSH-' at the start with a new
3244 * name. In proper SSH style (though of course this part of the
3245 * proper SSH protocol _isn't_ subject to this kind of
3246 * DNS-domain-based extension), we define the new name in our
3249 static const char protoname[] =
3250 "SSHCONNECTION@putty.projects.tartarus.org-";
3252 struct do_ssh_connection_init_state {
3260 crState(do_ssh_connection_init_state);
3264 /* Search for a line beginning with the protocol name prefix in
3267 for (s->i = 0; protoname[s->i]; s->i++) {
3268 if ((char)c != protoname[s->i]) goto no;
3278 s->vstrsize = sizeof(protoname) + 16;
3279 s->vstring = snewn(s->vstrsize, char);
3280 strcpy(s->vstring, protoname);
3281 s->vslen = strlen(protoname);
3284 if (s->vslen >= s->vstrsize - 1) {
3286 s->vstring = sresize(s->vstring, s->vstrsize, char);
3288 s->vstring[s->vslen++] = c;
3291 s->version[s->i] = '\0';
3293 } else if (s->i < sizeof(s->version) - 1)
3294 s->version[s->i++] = c;
3295 } else if (c == '\012')
3297 crReturn(1); /* get another char */
3300 ssh->agentfwd_enabled = FALSE;
3301 ssh->rdpkt2_bare_state.incoming_sequence = 0;
3303 s->vstring[s->vslen] = 0;
3304 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3305 logeventf(ssh, "Server version: %s", s->vstring);
3306 ssh_detect_bugs(ssh, s->vstring);
3309 * Decide which SSH protocol version to support. This is easy in
3310 * bare ssh-connection mode: only 2.0 is legal.
3312 if (ssh_versioncmp(s->version, "2.0") < 0) {
3313 bombout(("Server announces compatibility with SSH-1 in bare ssh-connection protocol"));
3316 if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
3317 bombout(("Bare ssh-connection protocol cannot be run in SSH-1-only mode"));
3323 logeventf(ssh, "Using bare ssh-connection protocol");
3325 /* Send the version string, if we haven't already */
3326 ssh_send_verstring(ssh, protoname, s->version);
3329 * Initialise bare connection protocol.
3331 ssh->protocol = ssh2_bare_connection_protocol;
3332 ssh2_bare_connection_protocol_setup(ssh);
3333 ssh->s_rdpkt = ssh2_bare_connection_rdpkt;
3335 update_specials_menu(ssh->frontend);
3336 ssh->state = SSH_STATE_BEFORE_SIZE;
3337 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3340 * Get authconn (really just conn) under way.
3342 do_ssh2_authconn(ssh, NULL, 0, NULL);
3349 static void ssh_process_incoming_data(Ssh ssh,
3350 const unsigned char **data, int *datalen)
3352 struct Packet *pktin;
3354 pktin = ssh->s_rdpkt(ssh, data, datalen);
3356 ssh->protocol(ssh, NULL, 0, pktin);
3357 ssh_free_packet(pktin);
3361 static void ssh_queue_incoming_data(Ssh ssh,
3362 const unsigned char **data, int *datalen)
3364 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
3369 static void ssh_process_queued_incoming_data(Ssh ssh)
3372 const unsigned char *data;
3375 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
3376 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
3380 while (!ssh->frozen && len > 0)
3381 ssh_process_incoming_data(ssh, &data, &len);
3384 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
3388 static void ssh_set_frozen(Ssh ssh, int frozen)
3391 sk_set_frozen(ssh->s, frozen);
3392 ssh->frozen = frozen;
3395 static void ssh_gotdata(Ssh ssh, const unsigned char *data, int datalen)
3397 /* Log raw data, if we're in that mode. */
3399 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
3400 0, NULL, NULL, 0, NULL);
3402 crBegin(ssh->ssh_gotdata_crstate);
3405 * To begin with, feed the characters one by one to the
3406 * protocol initialisation / selection function do_ssh_init().
3407 * When that returns 0, we're done with the initial greeting
3408 * exchange and can move on to packet discipline.
3411 int ret; /* need not be kept across crReturn */
3413 crReturnV; /* more data please */
3414 ret = ssh->do_ssh_init(ssh, *data);
3422 * We emerge from that loop when the initial negotiation is
3423 * over and we have selected an s_rdpkt function. Now pass
3424 * everything to s_rdpkt, and then pass the resulting packets
3425 * to the proper protocol handler.
3429 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
3431 ssh_queue_incoming_data(ssh, &data, &datalen);
3432 /* This uses up all data and cannot cause anything interesting
3433 * to happen; indeed, for anything to happen at all, we must
3434 * return, so break out. */
3436 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
3437 /* This uses up some or all data, and may freeze the
3439 ssh_process_queued_incoming_data(ssh);
3441 /* This uses up some or all data, and may freeze the
3443 ssh_process_incoming_data(ssh, &data, &datalen);
3445 /* FIXME this is probably EBW. */
3446 if (ssh->state == SSH_STATE_CLOSED)
3449 /* We're out of data. Go and get some more. */
3455 static int ssh_do_close(Ssh ssh, int notify_exit)
3458 struct ssh_channel *c;
3460 ssh->state = SSH_STATE_CLOSED;
3461 expire_timer_context(ssh);
3466 notify_remote_exit(ssh->frontend);
3471 * Now we must shut down any port- and X-forwarded channels going
3472 * through this connection.
3474 if (ssh->channels) {
3475 while (NULL != (c = index234(ssh->channels, 0))) {
3476 ssh_channel_close_local(c, NULL);
3477 del234(ssh->channels, c); /* moving next one to index 0 */
3478 if (ssh->version == 2)
3479 bufchain_clear(&c->v.v2.outbuffer);
3484 * Go through port-forwardings, and close any associated
3485 * listening sockets.
3487 if (ssh->portfwds) {
3488 struct ssh_portfwd *pf;
3489 while (NULL != (pf = index234(ssh->portfwds, 0))) {
3490 /* Dispose of any listening socket. */
3492 pfl_terminate(pf->local);
3493 del234(ssh->portfwds, pf); /* moving next one to index 0 */
3496 freetree234(ssh->portfwds);
3497 ssh->portfwds = NULL;
3501 * Also stop attempting to connection-share.
3503 if (ssh->connshare) {
3504 sharestate_free(ssh->connshare);
3505 ssh->connshare = NULL;
3511 static void ssh_socket_log(Plug plug, int type, SockAddr addr, int port,
3512 const char *error_msg, int error_code)
3514 Ssh ssh = (Ssh) plug;
3517 * While we're attempting connection sharing, don't loudly log
3518 * everything that happens. Real TCP connections need to be logged
3519 * when we _start_ trying to connect, because it might be ages
3520 * before they respond if something goes wrong; but connection
3521 * sharing is local and quick to respond, and it's sufficient to
3522 * simply wait and see whether it worked afterwards.
3525 if (!ssh->attempting_connshare)
3526 backend_socket_log(ssh->frontend, type, addr, port,
3527 error_msg, error_code, ssh->conf,
3528 ssh->session_started);
3531 void ssh_connshare_log(Ssh ssh, int event, const char *logtext,
3532 const char *ds_err, const char *us_err)
3534 if (event == SHARE_NONE) {
3535 /* In this case, 'logtext' is an error message indicating a
3536 * reason why connection sharing couldn't be set up _at all_.
3537 * Failing that, ds_err and us_err indicate why we couldn't be
3538 * a downstream and an upstream respectively. */
3540 logeventf(ssh, "Could not set up connection sharing: %s", logtext);
3543 logeventf(ssh, "Could not set up connection sharing"
3544 " as downstream: %s", ds_err);
3546 logeventf(ssh, "Could not set up connection sharing"
3547 " as upstream: %s", us_err);
3549 } else if (event == SHARE_DOWNSTREAM) {
3550 /* In this case, 'logtext' is a local endpoint address */
3551 logeventf(ssh, "Using existing shared connection at %s", logtext);
3552 /* Also we should mention this in the console window to avoid
3553 * confusing users as to why this window doesn't behave the
3555 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
3556 c_write_str(ssh,"Reusing a shared connection to this server.\r\n");
3558 } else if (event == SHARE_UPSTREAM) {
3559 /* In this case, 'logtext' is a local endpoint address too */
3560 logeventf(ssh, "Sharing this connection at %s", logtext);
3564 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
3567 Ssh ssh = (Ssh) plug;
3568 int need_notify = ssh_do_close(ssh, FALSE);
3571 if (!ssh->close_expected)
3572 error_msg = "Server unexpectedly closed network connection";
3574 error_msg = "Server closed network connection";
3577 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
3581 notify_remote_exit(ssh->frontend);
3584 logevent(error_msg);
3585 if (!ssh->close_expected || !ssh->clean_exit)
3586 connection_fatal(ssh->frontend, "%s", error_msg);
3590 static int ssh_receive(Plug plug, int urgent, char *data, int len)
3592 Ssh ssh = (Ssh) plug;
3593 ssh_gotdata(ssh, (unsigned char *)data, len);
3594 if (ssh->state == SSH_STATE_CLOSED) {
3595 ssh_do_close(ssh, TRUE);
3601 static void ssh_sent(Plug plug, int bufsize)
3603 Ssh ssh = (Ssh) plug;
3605 * If the send backlog on the SSH socket itself clears, we
3606 * should unthrottle the whole world if it was throttled.
3608 if (bufsize < SSH_MAX_BACKLOG)
3609 ssh_throttle_all(ssh, 0, bufsize);
3612 static void ssh_hostport_setup(const char *host, int port, Conf *conf,
3613 char **savedhost, int *savedport,
3616 char *loghost = conf_get_str(conf, CONF_loghost);
3618 *loghost_ret = loghost;
3624 tmphost = dupstr(loghost);
3625 *savedport = 22; /* default ssh port */
3628 * A colon suffix on the hostname string also lets us affect
3629 * savedport. (Unless there are multiple colons, in which case
3630 * we assume this is an unbracketed IPv6 literal.)
3632 colon = host_strrchr(tmphost, ':');
3633 if (colon && colon == host_strchr(tmphost, ':')) {
3636 *savedport = atoi(colon);
3639 *savedhost = host_strduptrim(tmphost);
3642 *savedhost = host_strduptrim(host);
3644 port = 22; /* default ssh port */
3649 static int ssh_test_for_upstream(const char *host, int port, Conf *conf)
3655 random_ref(); /* platform may need this to determine share socket name */
3656 ssh_hostport_setup(host, port, conf, &savedhost, &savedport, NULL);
3657 ret = ssh_share_test_for_upstream(savedhost, savedport, conf);
3665 * Connect to specified host and port.
3666 * Returns an error message, or NULL on success.
3667 * Also places the canonical host name into `realhost'. It must be
3668 * freed by the caller.
3670 static const char *connect_to_host(Ssh ssh, const char *host, int port,
3671 char **realhost, int nodelay, int keepalive)
3673 static const struct plug_function_table fn_table = {
3684 int addressfamily, sshprot;
3686 ssh_hostport_setup(host, port, ssh->conf,
3687 &ssh->savedhost, &ssh->savedport, &loghost);
3689 ssh->fn = &fn_table; /* make 'ssh' usable as a Plug */
3692 * Try connection-sharing, in case that means we don't open a
3693 * socket after all. ssh_connection_sharing_init will connect to a
3694 * previously established upstream if it can, and failing that,
3695 * establish a listening socket for _us_ to be the upstream. In
3696 * the latter case it will return NULL just as if it had done
3697 * nothing, because here we only need to care if we're a
3698 * downstream and need to do our connection setup differently.
3700 ssh->connshare = NULL;
3701 ssh->attempting_connshare = TRUE; /* affects socket logging behaviour */
3702 ssh->s = ssh_connection_sharing_init(ssh->savedhost, ssh->savedport,
3703 ssh->conf, ssh, &ssh->connshare);
3704 ssh->attempting_connshare = FALSE;
3705 if (ssh->s != NULL) {
3707 * We are a downstream.
3709 ssh->bare_connection = TRUE;
3710 ssh->do_ssh_init = do_ssh_connection_init;
3711 ssh->fullhostname = NULL;
3712 *realhost = dupstr(host); /* best we can do */
3715 * We're not a downstream, so open a normal socket.
3717 ssh->do_ssh_init = do_ssh_init;
3722 addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
3723 addr = name_lookup(host, port, realhost, ssh->conf, addressfamily,
3724 ssh->frontend, "SSH connection");
3725 if ((err = sk_addr_error(addr)) != NULL) {
3729 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
3731 ssh->s = new_connection(addr, *realhost, port,
3732 0, 1, nodelay, keepalive,
3733 (Plug) ssh, ssh->conf);
3734 if ((err = sk_socket_error(ssh->s)) != NULL) {
3736 notify_remote_exit(ssh->frontend);
3742 * The SSH version number is always fixed (since we no longer support
3743 * fallback between versions), so set it now, and if it's SSH-2,
3744 * send the version string now too.
3746 sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3747 assert(sshprot == 0 || sshprot == 3);
3751 if (sshprot == 3 && !ssh->bare_connection) {
3754 ssh_send_verstring(ssh, "SSH-", NULL);
3758 * loghost, if configured, overrides realhost.
3762 *realhost = dupstr(loghost);
3769 * Throttle or unthrottle the SSH connection.
3771 static void ssh_throttle_conn(Ssh ssh, int adjust)
3773 int old_count = ssh->conn_throttle_count;
3774 ssh->conn_throttle_count += adjust;
3775 assert(ssh->conn_throttle_count >= 0);
3776 if (ssh->conn_throttle_count && !old_count) {
3777 ssh_set_frozen(ssh, 1);
3778 } else if (!ssh->conn_throttle_count && old_count) {
3779 ssh_set_frozen(ssh, 0);
3784 * Throttle or unthrottle _all_ local data streams (for when sends
3785 * on the SSH connection itself back up).
3787 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3790 struct ssh_channel *c;
3792 if (enable == ssh->throttled_all)
3794 ssh->throttled_all = enable;
3795 ssh->overall_bufsize = bufsize;
3798 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3800 case CHAN_MAINSESSION:
3802 * This is treated separately, outside the switch.
3806 x11_override_throttle(c->u.x11.xconn, enable);
3809 /* Agent channels require no buffer management. */
3812 pfd_override_throttle(c->u.pfd.pf, enable);
3818 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3820 Ssh ssh = (Ssh) sshv;
3822 ssh->auth_agent_query = NULL;
3824 ssh->agent_response = reply;
3825 ssh->agent_response_len = replylen;
3827 if (ssh->version == 1)
3828 do_ssh1_login(ssh, NULL, -1, NULL);
3830 do_ssh2_authconn(ssh, NULL, -1, NULL);
3833 static void ssh_dialog_callback(void *sshv, int ret)
3835 Ssh ssh = (Ssh) sshv;
3837 ssh->user_response = ret;
3839 if (ssh->version == 1)
3840 do_ssh1_login(ssh, NULL, -1, NULL);
3842 do_ssh2_transport(ssh, NULL, -1, NULL);
3845 * This may have unfrozen the SSH connection, so do a
3848 ssh_process_queued_incoming_data(ssh);
3851 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3853 struct ssh_channel *c = (struct ssh_channel *)cv;
3854 const void *sentreply = reply;
3856 c->u.a.pending = NULL;
3857 c->u.a.outstanding_requests--;
3859 /* Fake SSH_AGENT_FAILURE. */
3860 sentreply = "\0\0\0\1\5";
3863 ssh_send_channel_data(c, sentreply, replylen);
3867 * If we've already seen an incoming EOF but haven't sent an
3868 * outgoing one, this may be the moment to send it.
3870 if (c->u.a.outstanding_requests == 0 && (c->closes & CLOSES_RCVD_EOF))
3871 sshfwd_write_eof(c);
3875 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3876 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3877 * => log `wire_reason'.
3879 static void ssh_disconnect(Ssh ssh, const char *client_reason,
3880 const char *wire_reason,
3881 int code, int clean_exit)
3885 client_reason = wire_reason;
3887 error = dupprintf("Disconnected: %s", client_reason);
3889 error = dupstr("Disconnected");
3891 if (ssh->version == 1) {
3892 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3894 } else if (ssh->version == 2) {
3895 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3896 ssh2_pkt_adduint32(pktout, code);
3897 ssh2_pkt_addstring(pktout, wire_reason);
3898 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3899 ssh2_pkt_send_noqueue(ssh, pktout);
3902 ssh->close_expected = TRUE;
3903 ssh->clean_exit = clean_exit;
3904 ssh_closing((Plug)ssh, error, 0, 0);
3908 int verify_ssh_manual_host_key(Ssh ssh, const char *fingerprint,
3909 const struct ssh_signkey *ssh2keytype,
3912 if (!conf_get_str_nthstrkey(ssh->conf, CONF_ssh_manual_hostkeys, 0)) {
3913 return -1; /* no manual keys configured */
3918 * The fingerprint string we've been given will have things
3919 * like 'ssh-rsa 2048' at the front of it. Strip those off and
3920 * narrow down to just the colon-separated hex block at the
3921 * end of the string.
3923 const char *p = strrchr(fingerprint, ' ');
3924 fingerprint = p ? p+1 : fingerprint;
3925 /* Quick sanity checks, including making sure it's in lowercase */
3926 assert(strlen(fingerprint) == 16*3 - 1);
3927 assert(fingerprint[2] == ':');
3928 assert(fingerprint[strspn(fingerprint, "0123456789abcdef:")] == 0);
3930 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3932 return 1; /* success */
3937 * Construct the base64-encoded public key blob and see if
3940 unsigned char *binblob;
3942 int binlen, atoms, i;
3943 binblob = ssh2keytype->public_blob(ssh2keydata, &binlen);
3944 atoms = (binlen + 2) / 3;
3945 base64blob = snewn(atoms * 4 + 1, char);
3946 for (i = 0; i < atoms; i++)
3947 base64_encode_atom(binblob + 3*i, binlen - 3*i, base64blob + 4*i);
3948 base64blob[atoms * 4] = '\0';
3950 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3953 return 1; /* success */
3962 * Handle the key exchange and user authentication phases.
3964 static int do_ssh1_login(Ssh ssh, const unsigned char *in, int inlen,
3965 struct Packet *pktin)
3968 unsigned char cookie[8], *ptr;
3969 struct MD5Context md5c;
3970 struct do_ssh1_login_state {
3973 unsigned char *rsabuf;
3974 const unsigned char *keystr1, *keystr2;
3975 unsigned long supported_ciphers_mask, supported_auths_mask;
3976 int tried_publickey, tried_agent;
3977 int tis_auth_refused, ccard_auth_refused;
3978 unsigned char session_id[16];
3980 void *publickey_blob;
3981 int publickey_bloblen;
3982 char *publickey_comment;
3983 int privatekey_available, privatekey_encrypted;
3984 prompts_t *cur_prompt;
3987 unsigned char request[5], *response, *p;
3997 struct RSAKey servkey, hostkey;
3999 crState(do_ssh1_login_state);
4006 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
4007 bombout(("Public key packet not received"));
4011 logevent("Received public keys");
4013 ptr = ssh_pkt_getdata(pktin, 8);
4015 bombout(("SSH-1 public key packet stopped before random cookie"));
4018 memcpy(cookie, ptr, 8);
4020 if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
4021 !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) {
4022 bombout(("Failed to read SSH-1 public keys from public key packet"));
4027 * Log the host key fingerprint.
4031 logevent("Host key fingerprint is:");
4032 strcpy(logmsg, " ");
4033 s->hostkey.comment = NULL;
4034 rsa_fingerprint(logmsg + strlen(logmsg),
4035 sizeof(logmsg) - strlen(logmsg), &s->hostkey);
4039 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
4040 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
4041 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
4042 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
4043 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
4045 ssh->v1_local_protoflags =
4046 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
4047 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
4050 MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
4051 MD5Update(&md5c, s->keystr1, s->servkey.bytes);
4052 MD5Update(&md5c, cookie, 8);
4053 MD5Final(s->session_id, &md5c);
4055 for (i = 0; i < 32; i++)
4056 ssh->session_key[i] = random_byte();
4059 * Verify that the `bits' and `bytes' parameters match.
4061 if (s->hostkey.bits > s->hostkey.bytes * 8 ||
4062 s->servkey.bits > s->servkey.bytes * 8) {
4063 bombout(("SSH-1 public keys were badly formatted"));
4067 s->len = (s->hostkey.bytes > s->servkey.bytes ?
4068 s->hostkey.bytes : s->servkey.bytes);
4070 s->rsabuf = snewn(s->len, unsigned char);
4073 * Verify the host key.
4077 * First format the key into a string.
4079 int len = rsastr_len(&s->hostkey);
4080 char fingerprint[100];
4081 char *keystr = snewn(len, char);
4082 rsastr_fmt(keystr, &s->hostkey);
4083 rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
4085 /* First check against manually configured host keys. */
4086 s->dlgret = verify_ssh_manual_host_key(ssh, fingerprint, NULL, NULL);
4087 if (s->dlgret == 0) { /* did not match */
4088 bombout(("Host key did not appear in manually configured list"));
4091 } else if (s->dlgret < 0) { /* none configured; use standard handling */
4092 ssh_set_frozen(ssh, 1);
4093 s->dlgret = verify_ssh_host_key(ssh->frontend,
4094 ssh->savedhost, ssh->savedport,
4095 "rsa", keystr, fingerprint,
4096 ssh_dialog_callback, ssh);
4101 if (s->dlgret < 0) {
4105 bombout(("Unexpected data from server while waiting"
4106 " for user host key response"));
4109 } while (pktin || inlen > 0);
4110 s->dlgret = ssh->user_response;
4112 ssh_set_frozen(ssh, 0);
4114 if (s->dlgret == 0) {
4115 ssh_disconnect(ssh, "User aborted at host key verification",
4124 for (i = 0; i < 32; i++) {
4125 s->rsabuf[i] = ssh->session_key[i];
4127 s->rsabuf[i] ^= s->session_id[i];
4130 if (s->hostkey.bytes > s->servkey.bytes) {
4131 ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
4133 ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
4135 ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
4137 ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
4140 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
4144 logevent("Encrypted session key");
4147 int cipher_chosen = 0, warn = 0;
4148 const char *cipher_string = NULL;
4150 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
4151 int next_cipher = conf_get_int_int(ssh->conf,
4152 CONF_ssh_cipherlist, i);
4153 if (next_cipher == CIPHER_WARN) {
4154 /* If/when we choose a cipher, warn about it */
4156 } else if (next_cipher == CIPHER_AES) {
4157 /* XXX Probably don't need to mention this. */
4158 logevent("AES not supported in SSH-1, skipping");
4160 switch (next_cipher) {
4161 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
4162 cipher_string = "3DES"; break;
4163 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
4164 cipher_string = "Blowfish"; break;
4165 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
4166 cipher_string = "single-DES"; break;
4168 if (s->supported_ciphers_mask & (1 << s->cipher_type))
4172 if (!cipher_chosen) {
4173 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
4174 bombout(("Server violates SSH-1 protocol by not "
4175 "supporting 3DES encryption"));
4177 /* shouldn't happen */
4178 bombout(("No supported ciphers found"));
4182 /* Warn about chosen cipher if necessary. */
4184 ssh_set_frozen(ssh, 1);
4185 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
4186 ssh_dialog_callback, ssh);
4187 if (s->dlgret < 0) {
4191 bombout(("Unexpected data from server while waiting"
4192 " for user response"));
4195 } while (pktin || inlen > 0);
4196 s->dlgret = ssh->user_response;
4198 ssh_set_frozen(ssh, 0);
4199 if (s->dlgret == 0) {
4200 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
4207 switch (s->cipher_type) {
4208 case SSH_CIPHER_3DES:
4209 logevent("Using 3DES encryption");
4211 case SSH_CIPHER_DES:
4212 logevent("Using single-DES encryption");
4214 case SSH_CIPHER_BLOWFISH:
4215 logevent("Using Blowfish encryption");
4219 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
4220 PKT_CHAR, s->cipher_type,
4221 PKT_DATA, cookie, 8,
4222 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
4223 PKT_DATA, s->rsabuf, s->len,
4224 PKT_INT, ssh->v1_local_protoflags, PKT_END);
4226 logevent("Trying to enable encryption...");
4230 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
4231 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
4233 ssh->v1_cipher_ctx = ssh->cipher->make_context();
4234 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
4235 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
4237 ssh->crcda_ctx = crcda_make_context();
4238 logevent("Installing CRC compensation attack detector");
4240 if (s->servkey.modulus) {
4241 sfree(s->servkey.modulus);
4242 s->servkey.modulus = NULL;
4244 if (s->servkey.exponent) {
4245 sfree(s->servkey.exponent);
4246 s->servkey.exponent = NULL;
4248 if (s->hostkey.modulus) {
4249 sfree(s->hostkey.modulus);
4250 s->hostkey.modulus = NULL;
4252 if (s->hostkey.exponent) {
4253 sfree(s->hostkey.exponent);
4254 s->hostkey.exponent = NULL;
4258 if (pktin->type != SSH1_SMSG_SUCCESS) {
4259 bombout(("Encryption not successfully enabled"));
4263 logevent("Successfully started encryption");
4265 fflush(stdout); /* FIXME eh? */
4267 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
4268 int ret; /* need not be kept over crReturn */
4269 s->cur_prompt = new_prompts(ssh->frontend);
4270 s->cur_prompt->to_server = TRUE;
4271 s->cur_prompt->name = dupstr("SSH login name");
4272 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
4273 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4276 crWaitUntil(!pktin);
4277 ret = get_userpass_input(s->cur_prompt, in, inlen);
4282 * Failed to get a username. Terminate.
4284 free_prompts(s->cur_prompt);
4285 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
4288 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
4289 free_prompts(s->cur_prompt);
4292 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
4294 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
4296 if (flags & FLAG_INTERACTIVE &&
4297 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
4298 c_write_str(ssh, userlog);
4299 c_write_str(ssh, "\r\n");
4307 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
4308 /* We must not attempt PK auth. Pretend we've already tried it. */
4309 s->tried_publickey = s->tried_agent = 1;
4311 s->tried_publickey = s->tried_agent = 0;
4313 s->tis_auth_refused = s->ccard_auth_refused = 0;
4315 * Load the public half of any configured keyfile for later use.
4317 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4318 if (!filename_is_null(s->keyfile)) {
4320 logeventf(ssh, "Reading key file \"%.150s\"",
4321 filename_to_str(s->keyfile));
4322 keytype = key_type(s->keyfile);
4323 if (keytype == SSH_KEYTYPE_SSH1 ||
4324 keytype == SSH_KEYTYPE_SSH1_PUBLIC) {
4326 if (rsakey_pubblob(s->keyfile,
4327 &s->publickey_blob, &s->publickey_bloblen,
4328 &s->publickey_comment, &error)) {
4329 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH1);
4330 if (!s->privatekey_available)
4331 logeventf(ssh, "Key file contains public key only");
4332 s->privatekey_encrypted = rsakey_encrypted(s->keyfile,
4336 logeventf(ssh, "Unable to load key (%s)", error);
4337 msgbuf = dupprintf("Unable to load key file "
4338 "\"%.150s\" (%s)\r\n",
4339 filename_to_str(s->keyfile),
4341 c_write_str(ssh, msgbuf);
4343 s->publickey_blob = NULL;
4347 logeventf(ssh, "Unable to use this key file (%s)",
4348 key_type_to_str(keytype));
4349 msgbuf = dupprintf("Unable to use key file \"%.150s\""
4351 filename_to_str(s->keyfile),
4352 key_type_to_str(keytype));
4353 c_write_str(ssh, msgbuf);
4355 s->publickey_blob = NULL;
4358 s->publickey_blob = NULL;
4360 while (pktin->type == SSH1_SMSG_FAILURE) {
4361 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
4363 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
4365 * Attempt RSA authentication using Pageant.
4371 logevent("Pageant is running. Requesting keys.");
4373 /* Request the keys held by the agent. */
4374 PUT_32BIT(s->request, 1);
4375 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
4376 ssh->auth_agent_query = agent_query(
4377 s->request, 5, &r, &s->responselen, ssh_agent_callback, ssh);
4378 if (ssh->auth_agent_query) {
4382 bombout(("Unexpected data from server while waiting"
4383 " for agent response"));
4386 } while (pktin || inlen > 0);
4387 r = ssh->agent_response;
4388 s->responselen = ssh->agent_response_len;
4390 s->response = (unsigned char *) r;
4391 if (s->response && s->responselen >= 5 &&
4392 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
4393 s->p = s->response + 5;
4394 s->nkeys = toint(GET_32BIT(s->p));
4396 logeventf(ssh, "Pageant reported negative key count %d",
4401 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
4402 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
4403 unsigned char *pkblob = s->p;
4407 do { /* do while (0) to make breaking easy */
4408 n = ssh1_read_bignum
4409 (s->p, toint(s->responselen-(s->p-s->response)),
4414 n = ssh1_read_bignum
4415 (s->p, toint(s->responselen-(s->p-s->response)),
4420 if (s->responselen - (s->p-s->response) < 4)
4422 s->commentlen = toint(GET_32BIT(s->p));
4424 if (s->commentlen < 0 ||
4425 toint(s->responselen - (s->p-s->response)) <
4428 s->commentp = (char *)s->p;
4429 s->p += s->commentlen;
4433 logevent("Pageant key list packet was truncated");
4437 if (s->publickey_blob) {
4438 if (!memcmp(pkblob, s->publickey_blob,
4439 s->publickey_bloblen)) {
4440 logeventf(ssh, "Pageant key #%d matches "
4441 "configured key file", s->keyi);
4442 s->tried_publickey = 1;
4444 /* Skip non-configured key */
4447 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
4448 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4449 PKT_BIGNUM, s->key.modulus, PKT_END);
4451 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4452 logevent("Key refused");
4455 logevent("Received RSA challenge");
4456 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4457 bombout(("Server's RSA challenge was badly formatted"));
4462 char *agentreq, *q, *ret;
4465 len = 1 + 4; /* message type, bit count */
4466 len += ssh1_bignum_length(s->key.exponent);
4467 len += ssh1_bignum_length(s->key.modulus);
4468 len += ssh1_bignum_length(s->challenge);
4469 len += 16; /* session id */
4470 len += 4; /* response format */
4471 agentreq = snewn(4 + len, char);
4472 PUT_32BIT(agentreq, len);
4474 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
4475 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
4477 q += ssh1_write_bignum(q, s->key.exponent);
4478 q += ssh1_write_bignum(q, s->key.modulus);
4479 q += ssh1_write_bignum(q, s->challenge);
4480 memcpy(q, s->session_id, 16);
4482 PUT_32BIT(q, 1); /* response format */
4483 ssh->auth_agent_query = agent_query(
4484 agentreq, len + 4, &vret, &retlen,
4485 ssh_agent_callback, ssh);
4486 if (ssh->auth_agent_query) {
4491 bombout(("Unexpected data from server"
4492 " while waiting for agent"
4496 } while (pktin || inlen > 0);
4497 vret = ssh->agent_response;
4498 retlen = ssh->agent_response_len;
4503 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
4504 logevent("Sending Pageant's response");
4505 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4506 PKT_DATA, ret + 5, 16,
4510 if (pktin->type == SSH1_SMSG_SUCCESS) {
4512 ("Pageant's response accepted");
4513 if (flags & FLAG_VERBOSE) {
4514 c_write_str(ssh, "Authenticated using"
4516 c_write(ssh, s->commentp,
4518 c_write_str(ssh, "\" from agent\r\n");
4523 ("Pageant's response not accepted");
4526 ("Pageant failed to answer challenge");
4530 logevent("No reply received from Pageant");
4533 freebn(s->key.exponent);
4534 freebn(s->key.modulus);
4535 freebn(s->challenge);
4540 if (s->publickey_blob && !s->tried_publickey)
4541 logevent("Configured key file not in Pageant");
4543 logevent("Failed to get reply from Pageant");
4548 if (s->publickey_blob && s->privatekey_available &&
4549 !s->tried_publickey) {
4551 * Try public key authentication with the specified
4554 int got_passphrase; /* need not be kept over crReturn */
4555 if (flags & FLAG_VERBOSE)
4556 c_write_str(ssh, "Trying public key authentication.\r\n");
4557 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4558 logeventf(ssh, "Trying public key \"%s\"",
4559 filename_to_str(s->keyfile));
4560 s->tried_publickey = 1;
4561 got_passphrase = FALSE;
4562 while (!got_passphrase) {
4564 * Get a passphrase, if necessary.
4566 char *passphrase = NULL; /* only written after crReturn */
4568 if (!s->privatekey_encrypted) {
4569 if (flags & FLAG_VERBOSE)
4570 c_write_str(ssh, "No passphrase required.\r\n");
4573 int ret; /* need not be kept over crReturn */
4574 s->cur_prompt = new_prompts(ssh->frontend);
4575 s->cur_prompt->to_server = FALSE;
4576 s->cur_prompt->name = dupstr("SSH key passphrase");
4577 add_prompt(s->cur_prompt,
4578 dupprintf("Passphrase for key \"%.100s\": ",
4579 s->publickey_comment), FALSE);
4580 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4583 crWaitUntil(!pktin);
4584 ret = get_userpass_input(s->cur_prompt, in, inlen);
4588 /* Failed to get a passphrase. Terminate. */
4589 free_prompts(s->cur_prompt);
4590 ssh_disconnect(ssh, NULL, "Unable to authenticate",
4594 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
4595 free_prompts(s->cur_prompt);
4598 * Try decrypting key with passphrase.
4600 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4601 ret = loadrsakey(s->keyfile, &s->key, passphrase,
4604 smemclr(passphrase, strlen(passphrase));
4608 /* Correct passphrase. */
4609 got_passphrase = TRUE;
4610 } else if (ret == 0) {
4611 c_write_str(ssh, "Couldn't load private key from ");
4612 c_write_str(ssh, filename_to_str(s->keyfile));
4613 c_write_str(ssh, " (");
4614 c_write_str(ssh, error);
4615 c_write_str(ssh, ").\r\n");
4616 got_passphrase = FALSE;
4617 break; /* go and try something else */
4618 } else if (ret == -1) {
4619 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
4620 got_passphrase = FALSE;
4623 assert(0 && "unexpected return from loadrsakey()");
4624 got_passphrase = FALSE; /* placate optimisers */
4628 if (got_passphrase) {
4631 * Send a public key attempt.
4633 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4634 PKT_BIGNUM, s->key.modulus, PKT_END);
4637 if (pktin->type == SSH1_SMSG_FAILURE) {
4638 c_write_str(ssh, "Server refused our public key.\r\n");
4639 continue; /* go and try something else */
4641 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4642 bombout(("Bizarre response to offer of public key"));
4648 unsigned char buffer[32];
4649 Bignum challenge, response;
4651 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4652 bombout(("Server's RSA challenge was badly formatted"));
4655 response = rsadecrypt(challenge, &s->key);
4656 freebn(s->key.private_exponent);/* burn the evidence */
4658 for (i = 0; i < 32; i++) {
4659 buffer[i] = bignum_byte(response, 31 - i);
4663 MD5Update(&md5c, buffer, 32);
4664 MD5Update(&md5c, s->session_id, 16);
4665 MD5Final(buffer, &md5c);
4667 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4668 PKT_DATA, buffer, 16, PKT_END);
4675 if (pktin->type == SSH1_SMSG_FAILURE) {
4676 if (flags & FLAG_VERBOSE)
4677 c_write_str(ssh, "Failed to authenticate with"
4678 " our public key.\r\n");
4679 continue; /* go and try something else */
4680 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4681 bombout(("Bizarre response to RSA authentication response"));
4685 break; /* we're through! */
4691 * Otherwise, try various forms of password-like authentication.
4693 s->cur_prompt = new_prompts(ssh->frontend);
4695 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4696 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
4697 !s->tis_auth_refused) {
4698 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
4699 logevent("Requested TIS authentication");
4700 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
4702 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
4703 logevent("TIS authentication declined");
4704 if (flags & FLAG_INTERACTIVE)
4705 c_write_str(ssh, "TIS authentication refused.\r\n");
4706 s->tis_auth_refused = 1;
4711 char *instr_suf, *prompt;
4713 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4715 bombout(("TIS challenge packet was badly formed"));
4718 logevent("Received TIS challenge");
4719 s->cur_prompt->to_server = TRUE;
4720 s->cur_prompt->name = dupstr("SSH TIS authentication");
4721 /* Prompt heuristic comes from OpenSSH */
4722 if (memchr(challenge, '\n', challengelen)) {
4723 instr_suf = dupstr("");
4724 prompt = dupprintf("%.*s", challengelen, challenge);
4726 instr_suf = dupprintf("%.*s", challengelen, challenge);
4727 prompt = dupstr("Response: ");
4729 s->cur_prompt->instruction =
4730 dupprintf("Using TIS authentication.%s%s",
4731 (*instr_suf) ? "\n" : "",
4733 s->cur_prompt->instr_reqd = TRUE;
4734 add_prompt(s->cur_prompt, prompt, FALSE);
4738 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4739 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
4740 !s->ccard_auth_refused) {
4741 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
4742 logevent("Requested CryptoCard authentication");
4743 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
4745 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
4746 logevent("CryptoCard authentication declined");
4747 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
4748 s->ccard_auth_refused = 1;
4753 char *instr_suf, *prompt;
4755 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4757 bombout(("CryptoCard challenge packet was badly formed"));
4760 logevent("Received CryptoCard challenge");
4761 s->cur_prompt->to_server = TRUE;
4762 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4763 s->cur_prompt->name_reqd = FALSE;
4764 /* Prompt heuristic comes from OpenSSH */
4765 if (memchr(challenge, '\n', challengelen)) {
4766 instr_suf = dupstr("");
4767 prompt = dupprintf("%.*s", challengelen, challenge);
4769 instr_suf = dupprintf("%.*s", challengelen, challenge);
4770 prompt = dupstr("Response: ");
4772 s->cur_prompt->instruction =
4773 dupprintf("Using CryptoCard authentication.%s%s",
4774 (*instr_suf) ? "\n" : "",
4776 s->cur_prompt->instr_reqd = TRUE;
4777 add_prompt(s->cur_prompt, prompt, FALSE);
4781 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4782 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4783 bombout(("No supported authentication methods available"));
4786 s->cur_prompt->to_server = TRUE;
4787 s->cur_prompt->name = dupstr("SSH password");
4788 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4789 ssh->username, ssh->savedhost),
4794 * Show password prompt, having first obtained it via a TIS
4795 * or CryptoCard exchange if we're doing TIS or CryptoCard
4799 int ret; /* need not be kept over crReturn */
4800 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4803 crWaitUntil(!pktin);
4804 ret = get_userpass_input(s->cur_prompt, in, inlen);
4809 * Failed to get a password (for example
4810 * because one was supplied on the command line
4811 * which has already failed to work). Terminate.
4813 free_prompts(s->cur_prompt);
4814 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4819 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4821 * Defence against traffic analysis: we send a
4822 * whole bunch of packets containing strings of
4823 * different lengths. One of these strings is the
4824 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4825 * The others are all random data in
4826 * SSH1_MSG_IGNORE packets. This way a passive
4827 * listener can't tell which is the password, and
4828 * hence can't deduce the password length.
4830 * Anybody with a password length greater than 16
4831 * bytes is going to have enough entropy in their
4832 * password that a listener won't find it _that_
4833 * much help to know how long it is. So what we'll
4836 * - if password length < 16, we send 15 packets
4837 * containing string lengths 1 through 15
4839 * - otherwise, we let N be the nearest multiple
4840 * of 8 below the password length, and send 8
4841 * packets containing string lengths N through
4842 * N+7. This won't obscure the order of
4843 * magnitude of the password length, but it will
4844 * introduce a bit of extra uncertainty.
4846 * A few servers can't deal with SSH1_MSG_IGNORE, at
4847 * least in this context. For these servers, we need
4848 * an alternative defence. We make use of the fact
4849 * that the password is interpreted as a C string:
4850 * so we can append a NUL, then some random data.
4852 * A few servers can deal with neither SSH1_MSG_IGNORE
4853 * here _nor_ a padded password string.
4854 * For these servers we are left with no defences
4855 * against password length sniffing.
4857 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4858 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4860 * The server can deal with SSH1_MSG_IGNORE, so
4861 * we can use the primary defence.
4863 int bottom, top, pwlen, i;
4866 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4868 bottom = 0; /* zero length passwords are OK! :-) */
4871 bottom = pwlen & ~7;
4875 assert(pwlen >= bottom && pwlen <= top);
4877 randomstr = snewn(top + 1, char);
4879 for (i = bottom; i <= top; i++) {
4881 defer_packet(ssh, s->pwpkt_type,
4882 PKT_STR,s->cur_prompt->prompts[0]->result,
4885 for (j = 0; j < i; j++) {
4887 randomstr[j] = random_byte();
4888 } while (randomstr[j] == '\0');
4890 randomstr[i] = '\0';
4891 defer_packet(ssh, SSH1_MSG_IGNORE,
4892 PKT_STR, randomstr, PKT_END);
4895 logevent("Sending password with camouflage packets");
4896 ssh_pkt_defersend(ssh);
4899 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4901 * The server can't deal with SSH1_MSG_IGNORE
4902 * but can deal with padded passwords, so we
4903 * can use the secondary defence.
4909 len = strlen(s->cur_prompt->prompts[0]->result);
4910 if (len < sizeof(string)) {
4912 strcpy(string, s->cur_prompt->prompts[0]->result);
4913 len++; /* cover the zero byte */
4914 while (len < sizeof(string)) {
4915 string[len++] = (char) random_byte();
4918 ss = s->cur_prompt->prompts[0]->result;
4920 logevent("Sending length-padded password");
4921 send_packet(ssh, s->pwpkt_type,
4922 PKT_INT, len, PKT_DATA, ss, len,
4926 * The server is believed unable to cope with
4927 * any of our password camouflage methods.
4930 len = strlen(s->cur_prompt->prompts[0]->result);
4931 logevent("Sending unpadded password");
4932 send_packet(ssh, s->pwpkt_type,
4934 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4938 send_packet(ssh, s->pwpkt_type,
4939 PKT_STR, s->cur_prompt->prompts[0]->result,
4942 logevent("Sent password");
4943 free_prompts(s->cur_prompt);
4945 if (pktin->type == SSH1_SMSG_FAILURE) {
4946 if (flags & FLAG_VERBOSE)
4947 c_write_str(ssh, "Access denied\r\n");
4948 logevent("Authentication refused");
4949 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4950 bombout(("Strange packet received, type %d", pktin->type));
4956 if (s->publickey_blob) {
4957 sfree(s->publickey_blob);
4958 sfree(s->publickey_comment);
4961 logevent("Authentication successful");
4966 static void ssh_channel_try_eof(struct ssh_channel *c)
4969 assert(c->pending_eof); /* precondition for calling us */
4971 return; /* can't close: not even opened yet */
4972 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4973 return; /* can't send EOF: pending outgoing data */
4975 c->pending_eof = FALSE; /* we're about to send it */
4976 if (ssh->version == 1) {
4977 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4979 c->closes |= CLOSES_SENT_EOF;
4981 struct Packet *pktout;
4982 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4983 ssh2_pkt_adduint32(pktout, c->remoteid);
4984 ssh2_pkt_send(ssh, pktout);
4985 c->closes |= CLOSES_SENT_EOF;
4986 ssh2_channel_check_close(c);
4990 Conf *sshfwd_get_conf(struct ssh_channel *c)
4996 void sshfwd_write_eof(struct ssh_channel *c)
5000 if (ssh->state == SSH_STATE_CLOSED)
5003 if (c->closes & CLOSES_SENT_EOF)
5006 c->pending_eof = TRUE;
5007 ssh_channel_try_eof(c);
5010 void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
5015 if (ssh->state == SSH_STATE_CLOSED)
5018 reason = dupprintf("due to local error: %s", err);
5019 ssh_channel_close_local(c, reason);
5021 c->pending_eof = FALSE; /* this will confuse a zombie channel */
5023 ssh2_channel_check_close(c);
5026 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
5030 if (ssh->state == SSH_STATE_CLOSED)
5033 return ssh_send_channel_data(c, buf, len);
5036 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
5040 if (ssh->state == SSH_STATE_CLOSED)
5043 ssh_channel_unthrottle(c, bufsize);
5046 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
5048 struct queued_handler *qh = ssh->qhead;
5052 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
5055 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
5056 ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
5059 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
5060 ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
5064 ssh->qhead = qh->next;
5066 if (ssh->qhead->msg1 > 0) {
5067 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5068 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
5070 if (ssh->qhead->msg2 > 0) {
5071 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5072 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
5075 ssh->qhead = ssh->qtail = NULL;
5078 qh->handler(ssh, pktin, qh->ctx);
5083 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
5084 chandler_fn_t handler, void *ctx)
5086 struct queued_handler *qh;
5088 qh = snew(struct queued_handler);
5091 qh->handler = handler;
5095 if (ssh->qtail == NULL) {
5099 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5100 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
5103 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5104 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
5107 ssh->qtail->next = qh;
5112 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
5114 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
5116 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
5117 SSH2_MSG_REQUEST_SUCCESS)) {
5118 logeventf(ssh, "Remote port forwarding from %s enabled",
5121 logeventf(ssh, "Remote port forwarding from %s refused",
5124 rpf = del234(ssh->rportfwds, pf);
5126 pf->pfrec->remote = NULL;
5131 int ssh_alloc_sharing_rportfwd(Ssh ssh, const char *shost, int sport,
5134 struct ssh_rportfwd *pf = snew(struct ssh_rportfwd);
5137 pf->share_ctx = share_ctx;
5138 pf->shost = dupstr(shost);
5140 pf->sportdesc = NULL;
5141 if (!ssh->rportfwds) {
5142 assert(ssh->version == 2);
5143 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5145 if (add234(ssh->rportfwds, pf) != pf) {
5153 static void ssh_sharing_global_request_response(Ssh ssh, struct Packet *pktin,
5156 share_got_pkt_from_server(ctx, pktin->type,
5157 pktin->body, pktin->length);
5160 void ssh_sharing_queue_global_request(Ssh ssh, void *share_ctx)
5162 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE,
5163 ssh_sharing_global_request_response, share_ctx);
5166 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
5168 struct ssh_portfwd *epf;
5172 if (!ssh->portfwds) {
5173 ssh->portfwds = newtree234(ssh_portcmp);
5176 * Go through the existing port forwardings and tag them
5177 * with status==DESTROY. Any that we want to keep will be
5178 * re-enabled (status==KEEP) as we go through the
5179 * configuration and find out which bits are the same as
5182 struct ssh_portfwd *epf;
5184 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5185 epf->status = DESTROY;
5188 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
5190 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
5191 char *kp, *kp2, *vp, *vp2;
5192 char address_family, type;
5193 int sport,dport,sserv,dserv;
5194 char *sports, *dports, *saddr, *host;
5198 address_family = 'A';
5200 if (*kp == 'A' || *kp == '4' || *kp == '6')
5201 address_family = *kp++;
5202 if (*kp == 'L' || *kp == 'R')
5205 if ((kp2 = host_strchr(kp, ':')) != NULL) {
5207 * There's a colon in the middle of the source port
5208 * string, which means that the part before it is
5209 * actually a source address.
5211 char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp);
5212 saddr = host_strduptrim(saddr_tmp);
5219 sport = atoi(sports);
5223 sport = net_service_lookup(sports);
5225 logeventf(ssh, "Service lookup failed for source"
5226 " port \"%s\"", sports);
5230 if (type == 'L' && !strcmp(val, "D")) {
5231 /* dynamic forwarding */
5238 /* ordinary forwarding */
5240 vp2 = vp + host_strcspn(vp, ":");
5241 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
5245 dport = atoi(dports);
5249 dport = net_service_lookup(dports);
5251 logeventf(ssh, "Service lookup failed for destination"
5252 " port \"%s\"", dports);
5257 if (sport && dport) {
5258 /* Set up a description of the source port. */
5259 struct ssh_portfwd *pfrec, *epfrec;
5261 pfrec = snew(struct ssh_portfwd);
5263 pfrec->saddr = saddr;
5264 pfrec->sserv = sserv ? dupstr(sports) : NULL;
5265 pfrec->sport = sport;
5266 pfrec->daddr = host;
5267 pfrec->dserv = dserv ? dupstr(dports) : NULL;
5268 pfrec->dport = dport;
5269 pfrec->local = NULL;
5270 pfrec->remote = NULL;
5271 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
5272 address_family == '6' ? ADDRTYPE_IPV6 :
5275 epfrec = add234(ssh->portfwds, pfrec);
5276 if (epfrec != pfrec) {
5277 if (epfrec->status == DESTROY) {
5279 * We already have a port forwarding up and running
5280 * with precisely these parameters. Hence, no need
5281 * to do anything; simply re-tag the existing one
5284 epfrec->status = KEEP;
5287 * Anything else indicates that there was a duplicate
5288 * in our input, which we'll silently ignore.
5290 free_portfwd(pfrec);
5292 pfrec->status = CREATE;
5301 * Now go through and destroy any port forwardings which were
5304 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5305 if (epf->status == DESTROY) {
5308 message = dupprintf("%s port forwarding from %s%s%d",
5309 epf->type == 'L' ? "local" :
5310 epf->type == 'R' ? "remote" : "dynamic",
5311 epf->saddr ? epf->saddr : "",
5312 epf->saddr ? ":" : "",
5315 if (epf->type != 'D') {
5316 char *msg2 = dupprintf("%s to %s:%d", message,
5317 epf->daddr, epf->dport);
5322 logeventf(ssh, "Cancelling %s", message);
5325 /* epf->remote or epf->local may be NULL if setting up a
5326 * forwarding failed. */
5328 struct ssh_rportfwd *rpf = epf->remote;
5329 struct Packet *pktout;
5332 * Cancel the port forwarding at the server
5335 if (ssh->version == 1) {
5337 * We cannot cancel listening ports on the
5338 * server side in SSH-1! There's no message
5339 * to support it. Instead, we simply remove
5340 * the rportfwd record from the local end
5341 * so that any connections the server tries
5342 * to make on it are rejected.
5345 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5346 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
5347 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
5349 ssh2_pkt_addstring(pktout, epf->saddr);
5350 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5351 /* XXX: rport_acceptall may not represent
5352 * what was used to open the original connection,
5353 * since it's reconfigurable. */
5354 ssh2_pkt_addstring(pktout, "");
5356 ssh2_pkt_addstring(pktout, "localhost");
5358 ssh2_pkt_adduint32(pktout, epf->sport);
5359 ssh2_pkt_send(ssh, pktout);
5362 del234(ssh->rportfwds, rpf);
5364 } else if (epf->local) {
5365 pfl_terminate(epf->local);
5368 delpos234(ssh->portfwds, i);
5370 i--; /* so we don't skip one in the list */
5374 * And finally, set up any new port forwardings (status==CREATE).
5376 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5377 if (epf->status == CREATE) {
5378 char *sportdesc, *dportdesc;
5379 sportdesc = dupprintf("%s%s%s%s%d%s",
5380 epf->saddr ? epf->saddr : "",
5381 epf->saddr ? ":" : "",
5382 epf->sserv ? epf->sserv : "",
5383 epf->sserv ? "(" : "",
5385 epf->sserv ? ")" : "");
5386 if (epf->type == 'D') {
5389 dportdesc = dupprintf("%s:%s%s%d%s",
5391 epf->dserv ? epf->dserv : "",
5392 epf->dserv ? "(" : "",
5394 epf->dserv ? ")" : "");
5397 if (epf->type == 'L') {
5398 char *err = pfl_listen(epf->daddr, epf->dport,
5399 epf->saddr, epf->sport,
5400 ssh, conf, &epf->local,
5401 epf->addressfamily);
5403 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
5404 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5405 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5406 sportdesc, dportdesc,
5407 err ? " failed: " : "", err ? err : "");
5410 } else if (epf->type == 'D') {
5411 char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport,
5412 ssh, conf, &epf->local,
5413 epf->addressfamily);
5415 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
5416 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5417 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5419 err ? " failed: " : "", err ? err : "");
5424 struct ssh_rportfwd *pf;
5427 * Ensure the remote port forwardings tree exists.
5429 if (!ssh->rportfwds) {
5430 if (ssh->version == 1)
5431 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
5433 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5436 pf = snew(struct ssh_rportfwd);
5437 pf->share_ctx = NULL;
5438 pf->dhost = dupstr(epf->daddr);
5439 pf->dport = epf->dport;
5441 pf->shost = dupstr(epf->saddr);
5442 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5443 pf->shost = dupstr("");
5445 pf->shost = dupstr("localhost");
5447 pf->sport = epf->sport;
5448 if (add234(ssh->rportfwds, pf) != pf) {
5449 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
5450 epf->daddr, epf->dport);
5453 logeventf(ssh, "Requesting remote port %s"
5454 " forward to %s", sportdesc, dportdesc);
5456 pf->sportdesc = sportdesc;
5461 if (ssh->version == 1) {
5462 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
5463 PKT_INT, epf->sport,
5464 PKT_STR, epf->daddr,
5465 PKT_INT, epf->dport,
5467 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
5469 ssh_rportfwd_succfail, pf);
5471 struct Packet *pktout;
5472 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5473 ssh2_pkt_addstring(pktout, "tcpip-forward");
5474 ssh2_pkt_addbool(pktout, 1);/* want reply */
5475 ssh2_pkt_addstring(pktout, pf->shost);
5476 ssh2_pkt_adduint32(pktout, pf->sport);
5477 ssh2_pkt_send(ssh, pktout);
5479 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
5480 SSH2_MSG_REQUEST_FAILURE,
5481 ssh_rportfwd_succfail, pf);
5490 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
5493 int stringlen, bufsize;
5495 ssh_pkt_getstring(pktin, &string, &stringlen);
5496 if (string == NULL) {
5497 bombout(("Incoming terminal data packet was badly formed"));
5501 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
5503 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
5504 ssh->v1_stdout_throttling = 1;
5505 ssh_throttle_conn(ssh, +1);
5509 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
5511 /* Remote side is trying to open a channel to talk to our
5512 * X-Server. Give them back a local channel number. */
5513 struct ssh_channel *c;
5514 int remoteid = ssh_pkt_getuint32(pktin);
5516 logevent("Received X11 connect request");
5517 /* Refuse if X11 forwarding is disabled. */
5518 if (!ssh->X11_fwd_enabled) {
5519 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5520 PKT_INT, remoteid, PKT_END);
5521 logevent("Rejected X11 connect request");
5523 c = snew(struct ssh_channel);
5526 ssh_channel_init(c);
5527 c->u.x11.xconn = x11_init(ssh->x11authtree, c, NULL, -1);
5528 c->remoteid = remoteid;
5529 c->halfopen = FALSE;
5530 c->type = CHAN_X11; /* identify channel type */
5531 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5532 PKT_INT, c->remoteid, PKT_INT,
5533 c->localid, PKT_END);
5534 logevent("Opened X11 forward channel");
5538 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
5540 /* Remote side is trying to open a channel to talk to our
5541 * agent. Give them back a local channel number. */
5542 struct ssh_channel *c;
5543 int remoteid = ssh_pkt_getuint32(pktin);
5545 /* Refuse if agent forwarding is disabled. */
5546 if (!ssh->agentfwd_enabled) {
5547 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5548 PKT_INT, remoteid, PKT_END);
5550 c = snew(struct ssh_channel);
5552 ssh_channel_init(c);
5553 c->remoteid = remoteid;
5554 c->halfopen = FALSE;
5555 c->type = CHAN_AGENT; /* identify channel type */
5556 c->u.a.lensofar = 0;
5557 c->u.a.message = NULL;
5558 c->u.a.pending = NULL;
5559 c->u.a.outstanding_requests = 0;
5560 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5561 PKT_INT, c->remoteid, PKT_INT, c->localid,
5566 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
5568 /* Remote side is trying to open a channel to talk to a
5569 * forwarded port. Give them back a local channel number. */
5570 struct ssh_rportfwd pf, *pfp;
5576 remoteid = ssh_pkt_getuint32(pktin);
5577 ssh_pkt_getstring(pktin, &host, &hostsize);
5578 port = ssh_pkt_getuint32(pktin);
5580 pf.dhost = dupprintf("%.*s", hostsize, NULLTOEMPTY(host));
5582 pfp = find234(ssh->rportfwds, &pf, NULL);
5585 logeventf(ssh, "Rejected remote port open request for %s:%d",
5587 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5588 PKT_INT, remoteid, PKT_END);
5590 struct ssh_channel *c = snew(struct ssh_channel);
5593 logeventf(ssh, "Received remote port open request for %s:%d",
5595 err = pfd_connect(&c->u.pfd.pf, pf.dhost, port,
5596 c, ssh->conf, pfp->pfrec->addressfamily);
5598 logeventf(ssh, "Port open failed: %s", err);
5601 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5602 PKT_INT, remoteid, PKT_END);
5604 ssh_channel_init(c);
5605 c->remoteid = remoteid;
5606 c->halfopen = FALSE;
5607 c->type = CHAN_SOCKDATA; /* identify channel type */
5608 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5609 PKT_INT, c->remoteid, PKT_INT,
5610 c->localid, PKT_END);
5611 logevent("Forwarded port opened successfully");
5618 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
5620 struct ssh_channel *c;
5622 c = ssh_channel_msg(ssh, pktin);
5623 if (c && c->type == CHAN_SOCKDATA) {
5624 c->remoteid = ssh_pkt_getuint32(pktin);
5625 c->halfopen = FALSE;
5626 c->throttling_conn = 0;
5627 pfd_confirm(c->u.pfd.pf);
5630 if (c && c->pending_eof) {
5632 * We have a pending close on this channel,
5633 * which we decided on before the server acked
5634 * the channel open. So now we know the
5635 * remoteid, we can close it again.
5637 ssh_channel_try_eof(c);
5641 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
5643 struct ssh_channel *c;
5645 c = ssh_channel_msg(ssh, pktin);
5646 if (c && c->type == CHAN_SOCKDATA) {
5647 logevent("Forwarded connection refused by server");
5648 pfd_close(c->u.pfd.pf);
5649 del234(ssh->channels, c);
5654 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
5656 /* Remote side closes a channel. */
5657 struct ssh_channel *c;
5659 c = ssh_channel_msg(ssh, pktin);
5662 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE) {
5664 * Received CHANNEL_CLOSE, which we translate into
5667 ssh_channel_got_eof(c);
5670 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
5671 !(c->closes & CLOSES_RCVD_CLOSE)) {
5673 if (!(c->closes & CLOSES_SENT_EOF)) {
5674 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %u"
5675 " for which we never sent CHANNEL_CLOSE\n",
5679 c->closes |= CLOSES_RCVD_CLOSE;
5682 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
5683 !(c->closes & CLOSES_SENT_CLOSE)) {
5684 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
5685 PKT_INT, c->remoteid, PKT_END);
5686 c->closes |= CLOSES_SENT_CLOSE;
5689 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
5690 ssh_channel_destroy(c);
5695 * Handle incoming data on an SSH-1 or SSH-2 agent-forwarding channel.
5697 static int ssh_agent_channel_data(struct ssh_channel *c, char *data,
5700 while (length > 0) {
5701 if (c->u.a.lensofar < 4) {
5702 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)length);
5703 memcpy(c->u.a.msglen + c->u.a.lensofar, data, l);
5706 c->u.a.lensofar += l;
5708 if (c->u.a.lensofar == 4) {
5709 c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
5710 c->u.a.message = snewn(c->u.a.totallen, unsigned char);
5711 memcpy(c->u.a.message, c->u.a.msglen, 4);
5713 if (c->u.a.lensofar >= 4 && length > 0) {
5714 unsigned int l = min(c->u.a.totallen - c->u.a.lensofar,
5716 memcpy(c->u.a.message + c->u.a.lensofar, data, l);
5719 c->u.a.lensofar += l;
5721 if (c->u.a.lensofar == c->u.a.totallen) {
5724 c->u.a.outstanding_requests++;
5725 c->u.a.pending = agent_query(
5726 c->u.a.message, c->u.a.totallen, &reply, &replylen,
5727 ssh_agentf_callback, c);
5728 if (!c->u.a.pending)
5729 ssh_agentf_callback(c, reply, replylen);
5730 sfree(c->u.a.message);
5731 c->u.a.message = NULL;
5732 c->u.a.lensofar = 0;
5735 return 0; /* agent channels never back up */
5738 static int ssh_channel_data(struct ssh_channel *c, int is_stderr,
5739 char *data, int length)
5742 case CHAN_MAINSESSION:
5743 return from_backend(c->ssh->frontend, is_stderr, data, length);
5745 return x11_send(c->u.x11.xconn, data, length);
5747 return pfd_send(c->u.pfd.pf, data, length);
5749 return ssh_agent_channel_data(c, data, length);
5754 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
5756 /* Data sent down one of our channels. */
5759 struct ssh_channel *c;
5761 c = ssh_channel_msg(ssh, pktin);
5762 ssh_pkt_getstring(pktin, &p, &len);
5765 int bufsize = ssh_channel_data(c, FALSE, p, len);
5766 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5767 c->throttling_conn = 1;
5768 ssh_throttle_conn(ssh, +1);
5773 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5775 ssh->exitcode = ssh_pkt_getuint32(pktin);
5776 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5777 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5779 * In case `helpful' firewalls or proxies tack
5780 * extra human-readable text on the end of the
5781 * session which we might mistake for another
5782 * encrypted packet, we close the session once
5783 * we've sent EXIT_CONFIRMATION.
5785 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5788 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5789 static void ssh1_send_ttymode(void *data,
5790 const struct ssh_ttymode *mode, char *val)
5792 struct Packet *pktout = (struct Packet *)data;
5793 unsigned int arg = 0;
5795 switch (mode->type) {
5797 arg = ssh_tty_parse_specchar(val);
5800 arg = ssh_tty_parse_boolean(val);
5803 ssh2_pkt_addbyte(pktout, mode->opcode);
5804 ssh2_pkt_addbyte(pktout, arg);
5807 int ssh_agent_forwarding_permitted(Ssh ssh)
5809 return conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists();
5812 static void do_ssh1_connection(Ssh ssh, const unsigned char *in, int inlen,
5813 struct Packet *pktin)
5815 crBegin(ssh->do_ssh1_connection_crstate);
5817 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5818 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5819 ssh1_smsg_stdout_stderr_data;
5821 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5822 ssh1_msg_channel_open_confirmation;
5823 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5824 ssh1_msg_channel_open_failure;
5825 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5826 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5827 ssh1_msg_channel_close;
5828 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5829 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5831 if (ssh_agent_forwarding_permitted(ssh)) {
5832 logevent("Requesting agent forwarding");
5833 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5837 if (pktin->type != SSH1_SMSG_SUCCESS
5838 && pktin->type != SSH1_SMSG_FAILURE) {
5839 bombout(("Protocol confusion"));
5841 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5842 logevent("Agent forwarding refused");
5844 logevent("Agent forwarding enabled");
5845 ssh->agentfwd_enabled = TRUE;
5846 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5850 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
5852 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5854 if (!ssh->x11disp) {
5855 /* FIXME: return an error message from x11_setup_display */
5856 logevent("X11 forwarding not enabled: unable to"
5857 " initialise X display");
5859 ssh->x11auth = x11_invent_fake_auth
5860 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
5861 ssh->x11auth->disp = ssh->x11disp;
5863 logevent("Requesting X11 forwarding");
5864 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5865 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5866 PKT_STR, ssh->x11auth->protoname,
5867 PKT_STR, ssh->x11auth->datastring,
5868 PKT_INT, ssh->x11disp->screennum,
5871 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5872 PKT_STR, ssh->x11auth->protoname,
5873 PKT_STR, ssh->x11auth->datastring,
5879 if (pktin->type != SSH1_SMSG_SUCCESS
5880 && pktin->type != SSH1_SMSG_FAILURE) {
5881 bombout(("Protocol confusion"));
5883 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5884 logevent("X11 forwarding refused");
5886 logevent("X11 forwarding enabled");
5887 ssh->X11_fwd_enabled = TRUE;
5888 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5893 ssh_setup_portfwd(ssh, ssh->conf);
5894 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5896 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5898 /* Unpick the terminal-speed string. */
5899 /* XXX perhaps we should allow no speeds to be sent. */
5900 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5901 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5902 /* Send the pty request. */
5903 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5904 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5905 ssh_pkt_adduint32(pkt, ssh->term_height);
5906 ssh_pkt_adduint32(pkt, ssh->term_width);
5907 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5908 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5909 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5910 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5911 ssh_pkt_adduint32(pkt, ssh->ispeed);
5912 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5913 ssh_pkt_adduint32(pkt, ssh->ospeed);
5914 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5916 ssh->state = SSH_STATE_INTERMED;
5920 if (pktin->type != SSH1_SMSG_SUCCESS
5921 && pktin->type != SSH1_SMSG_FAILURE) {
5922 bombout(("Protocol confusion"));
5924 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5925 c_write_str(ssh, "Server refused to allocate pty\r\n");
5926 ssh->editing = ssh->echoing = 1;
5928 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5929 ssh->ospeed, ssh->ispeed);
5930 ssh->got_pty = TRUE;
5933 ssh->editing = ssh->echoing = 1;
5936 if (conf_get_int(ssh->conf, CONF_compression)) {
5937 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5941 if (pktin->type != SSH1_SMSG_SUCCESS
5942 && pktin->type != SSH1_SMSG_FAILURE) {
5943 bombout(("Protocol confusion"));
5945 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5946 c_write_str(ssh, "Server refused to compress\r\n");
5948 logevent("Started compression");
5949 ssh->v1_compressing = TRUE;
5950 ssh->cs_comp_ctx = zlib_compress_init();
5951 logevent("Initialised zlib (RFC1950) compression");
5952 ssh->sc_comp_ctx = zlib_decompress_init();
5953 logevent("Initialised zlib (RFC1950) decompression");
5957 * Start the shell or command.
5959 * Special case: if the first-choice command is an SSH-2
5960 * subsystem (hence not usable here) and the second choice
5961 * exists, we fall straight back to that.
5964 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
5966 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
5967 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
5968 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
5969 ssh->fallback_cmd = TRUE;
5972 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
5974 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
5975 logevent("Started session");
5978 ssh->state = SSH_STATE_SESSION;
5979 if (ssh->size_needed)
5980 ssh_size(ssh, ssh->term_width, ssh->term_height);
5981 if (ssh->eof_needed)
5982 ssh_special(ssh, TS_EOF);
5985 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
5987 ssh->channels = newtree234(ssh_channelcmp);
5991 * By this point, most incoming packets are already being
5992 * handled by the dispatch table, and we need only pay
5993 * attention to the unusual ones.
5998 if (pktin->type == SSH1_SMSG_SUCCESS) {
5999 /* may be from EXEC_SHELL on some servers */
6000 } else if (pktin->type == SSH1_SMSG_FAILURE) {
6001 /* may be from EXEC_SHELL on some servers
6002 * if no pty is available or in other odd cases. Ignore */
6004 bombout(("Strange packet received: type %d", pktin->type));
6009 int len = min(inlen, 512);
6010 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
6011 PKT_INT, len, PKT_DATA, in, len,
6023 * Handle the top-level SSH-2 protocol.
6025 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
6030 ssh_pkt_getstring(pktin, &msg, &msglen);
6031 logeventf(ssh, "Remote debug message: %.*s", msglen, NULLTOEMPTY(msg));
6034 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
6036 /* log reason code in disconnect message */
6040 ssh_pkt_getstring(pktin, &msg, &msglen);
6041 bombout(("Server sent disconnect message:\n\"%.*s\"",
6042 msglen, NULLTOEMPTY(msg)));
6045 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
6047 /* Do nothing, because we're ignoring it! Duhh. */
6050 static void ssh1_protocol_setup(Ssh ssh)
6055 * Most messages are handled by the coroutines.
6057 for (i = 0; i < 256; i++)
6058 ssh->packet_dispatch[i] = NULL;
6061 * These special message types we install handlers for.
6063 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
6064 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
6065 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
6068 static void ssh1_protocol(Ssh ssh, const void *vin, int inlen,
6069 struct Packet *pktin)
6071 const unsigned char *in = (const unsigned char *)vin;
6072 if (ssh->state == SSH_STATE_CLOSED)
6075 if (pktin && ssh->packet_dispatch[pktin->type]) {
6076 ssh->packet_dispatch[pktin->type](ssh, pktin);
6080 if (!ssh->protocol_initial_phase_done) {
6081 if (do_ssh1_login(ssh, in, inlen, pktin))
6082 ssh->protocol_initial_phase_done = TRUE;
6087 do_ssh1_connection(ssh, in, inlen, pktin);
6091 * Utility routines for decoding comma-separated strings in KEXINIT.
6093 static int first_in_commasep_string(char const *needle, char const *haystack,
6097 if (!needle || !haystack) /* protect against null pointers */
6099 needlen = strlen(needle);
6101 if (haylen >= needlen && /* haystack is long enough */
6102 !memcmp(needle, haystack, needlen) && /* initial match */
6103 (haylen == needlen || haystack[needlen] == ',')
6104 /* either , or EOS follows */
6110 static int in_commasep_string(char const *needle, char const *haystack,
6115 if (!needle || !haystack) /* protect against null pointers */
6118 * Is it at the start of the string?
6120 if (first_in_commasep_string(needle, haystack, haylen))
6123 * If not, search for the next comma and resume after that.
6124 * If no comma found, terminate.
6126 p = memchr(haystack, ',', haylen);
6128 /* + 1 to skip over comma */
6129 return in_commasep_string(needle, p + 1, haylen - (p + 1 - haystack));
6133 * Add a value to the comma-separated string at the end of the packet.
6135 static void ssh2_pkt_addstring_commasep(struct Packet *pkt, const char *data)
6137 if (pkt->length - pkt->savedpos > 0)
6138 ssh_pkt_addstring_str(pkt, ",");
6139 ssh_pkt_addstring_str(pkt, data);
6144 * SSH-2 key derivation (RFC 4253 section 7.2).
6146 static unsigned char *ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H,
6147 char chr, int keylen)
6149 const struct ssh_hash *h = ssh->kex->hash;
6157 /* Round up to the next multiple of hash length. */
6158 keylen_padded = ((keylen + h->hlen - 1) / h->hlen) * h->hlen;
6160 key = snewn(keylen_padded, unsigned char);
6162 /* First hlen bytes. */
6164 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6165 hash_mpint(h, s, K);
6166 h->bytes(s, H, h->hlen);
6167 h->bytes(s, &chr, 1);
6168 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
6171 /* Subsequent blocks of hlen bytes. */
6172 if (keylen_padded > h->hlen) {
6176 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6177 hash_mpint(h, s, K);
6178 h->bytes(s, H, h->hlen);
6180 for (offset = h->hlen; offset < keylen_padded; offset += h->hlen) {
6181 h->bytes(s, key + offset - h->hlen, h->hlen);
6183 h->final(s2, key + offset);
6189 /* Now clear any extra bytes of key material beyond the length
6190 * we're officially returning, because the caller won't know to
6192 if (keylen_padded > keylen)
6193 smemclr(key + keylen, keylen_padded - keylen);
6199 * Structure for constructing KEXINIT algorithm lists.
6201 #define MAXKEXLIST 16
6202 struct kexinit_algorithm {
6206 const struct ssh_kex *kex;
6210 const struct ssh_signkey *hostkey;
6214 const struct ssh2_cipher *cipher;
6218 const struct ssh_mac *mac;
6221 const struct ssh_compress *comp;
6226 * Find a slot in a KEXINIT algorithm list to use for a new algorithm.
6227 * If the algorithm is already in the list, return a pointer to its
6228 * entry, otherwise return an entry from the end of the list.
6229 * This assumes that every time a particular name is passed in, it
6230 * comes from the same string constant. If this isn't true, this
6231 * function may need to be rewritten to use strcmp() instead.
6233 static struct kexinit_algorithm *ssh2_kexinit_addalg(struct kexinit_algorithm
6234 *list, const char *name)
6238 for (i = 0; i < MAXKEXLIST; i++)
6239 if (list[i].name == NULL || list[i].name == name) {
6240 list[i].name = name;
6243 assert(!"No space in KEXINIT list");
6248 * Handle the SSH-2 transport layer.
6250 static void do_ssh2_transport(Ssh ssh, const void *vin, int inlen,
6251 struct Packet *pktin)
6253 const unsigned char *in = (const unsigned char *)vin;
6255 KEXLIST_KEX, KEXLIST_HOSTKEY, KEXLIST_CSCIPHER, KEXLIST_SCCIPHER,
6256 KEXLIST_CSMAC, KEXLIST_SCMAC, KEXLIST_CSCOMP, KEXLIST_SCCOMP,
6259 const char * kexlist_descr[NKEXLIST] = {
6260 "key exchange algorithm", "host key algorithm",
6261 "client-to-server cipher", "server-to-client cipher",
6262 "client-to-server MAC", "server-to-client MAC",
6263 "client-to-server compression method",
6264 "server-to-client compression method" };
6265 struct do_ssh2_transport_state {
6267 int nbits, pbits, warn_kex, warn_hk, warn_cscipher, warn_sccipher;
6268 Bignum p, g, e, f, K;
6271 int kex_init_value, kex_reply_value;
6272 const struct ssh_mac *const *maclist;
6274 const struct ssh2_cipher *cscipher_tobe;
6275 const struct ssh2_cipher *sccipher_tobe;
6276 const struct ssh_mac *csmac_tobe;
6277 const struct ssh_mac *scmac_tobe;
6278 int csmac_etm_tobe, scmac_etm_tobe;
6279 const struct ssh_compress *cscomp_tobe;
6280 const struct ssh_compress *sccomp_tobe;
6281 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
6282 int hostkeylen, siglen, rsakeylen;
6283 void *hkey; /* actual host key */
6284 void *rsakey; /* for RSA kex */
6285 void *eckey; /* for ECDH kex */
6286 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
6287 int n_preferred_kex;
6288 const struct ssh_kexes *preferred_kex[KEX_MAX];
6290 int preferred_hk[HK_MAX];
6291 int n_preferred_ciphers;
6292 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
6293 const struct ssh_compress *preferred_comp;
6294 int userauth_succeeded; /* for delayed compression */
6295 int pending_compression;
6296 int got_session_id, activated_authconn;
6297 struct Packet *pktout;
6301 struct kexinit_algorithm kexlists[NKEXLIST][MAXKEXLIST];
6303 crState(do_ssh2_transport_state);
6305 assert(!ssh->bare_connection);
6306 assert(ssh->version == 2);
6310 s->cscipher_tobe = s->sccipher_tobe = NULL;
6311 s->csmac_tobe = s->scmac_tobe = NULL;
6312 s->cscomp_tobe = s->sccomp_tobe = NULL;
6314 s->got_session_id = s->activated_authconn = FALSE;
6315 s->userauth_succeeded = FALSE;
6316 s->pending_compression = FALSE;
6319 * Be prepared to work around the buggy MAC problem.
6321 if (ssh->remote_bugs & BUG_SSH2_HMAC)
6322 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
6324 s->maclist = macs, s->nmacs = lenof(macs);
6327 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
6330 struct kexinit_algorithm *alg;
6333 * Set up the preferred key exchange. (NULL => warn below here)
6335 s->n_preferred_kex = 0;
6336 for (i = 0; i < KEX_MAX; i++) {
6337 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
6339 s->preferred_kex[s->n_preferred_kex++] =
6340 &ssh_diffiehellman_gex;
6343 s->preferred_kex[s->n_preferred_kex++] =
6344 &ssh_diffiehellman_group14;
6347 s->preferred_kex[s->n_preferred_kex++] =
6348 &ssh_diffiehellman_group1;
6351 s->preferred_kex[s->n_preferred_kex++] =
6355 s->preferred_kex[s->n_preferred_kex++] =
6359 /* Flag for later. Don't bother if it's the last in
6361 if (i < KEX_MAX - 1) {
6362 s->preferred_kex[s->n_preferred_kex++] = NULL;
6369 * Set up the preferred host key types. These are just the ids
6370 * in the enum in putty.h, so 'warn below here' is indicated
6373 s->n_preferred_hk = 0;
6374 for (i = 0; i < HK_MAX; i++) {
6375 int id = conf_get_int_int(ssh->conf, CONF_ssh_hklist, i);
6376 /* As above, don't bother with HK_WARN if it's last in the
6378 if (id != HK_WARN || i < HK_MAX - 1)
6379 s->preferred_hk[s->n_preferred_hk++] = id;
6383 * Set up the preferred ciphers. (NULL => warn below here)
6385 s->n_preferred_ciphers = 0;
6386 for (i = 0; i < CIPHER_MAX; i++) {
6387 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
6388 case CIPHER_BLOWFISH:
6389 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
6392 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
6393 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
6397 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
6400 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
6402 case CIPHER_ARCFOUR:
6403 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
6405 case CIPHER_CHACHA20:
6406 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_ccp;
6409 /* Flag for later. Don't bother if it's the last in
6411 if (i < CIPHER_MAX - 1) {
6412 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
6419 * Set up preferred compression.
6421 if (conf_get_int(ssh->conf, CONF_compression))
6422 s->preferred_comp = &ssh_zlib;
6424 s->preferred_comp = &ssh_comp_none;
6427 * Enable queueing of outgoing auth- or connection-layer
6428 * packets while we are in the middle of a key exchange.
6430 ssh->queueing = TRUE;
6433 * Flag that KEX is in progress.
6435 ssh->kex_in_progress = TRUE;
6437 for (i = 0; i < NKEXLIST; i++)
6438 for (j = 0; j < MAXKEXLIST; j++)
6439 s->kexlists[i][j].name = NULL;
6440 /* List key exchange algorithms. */
6442 for (i = 0; i < s->n_preferred_kex; i++) {
6443 const struct ssh_kexes *k = s->preferred_kex[i];
6444 if (!k) warn = TRUE;
6445 else for (j = 0; j < k->nkexes; j++) {
6446 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_KEX],
6448 alg->u.kex.kex = k->list[j];
6449 alg->u.kex.warn = warn;
6452 /* List server host key algorithms. */
6453 if (!s->got_session_id) {
6455 * In the first key exchange, we list all the algorithms
6456 * we're prepared to cope with, but prefer those algorithms
6457 * for which we have a host key for this host.
6459 * If the host key algorithm is below the warning
6460 * threshold, we warn even if we did already have a key
6461 * for it, on the basis that if the user has just
6462 * reconfigured that host key type to be warned about,
6463 * they surely _do_ want to be alerted that a server
6464 * they're actually connecting to is using it.
6467 for (i = 0; i < s->n_preferred_hk; i++) {
6468 if (s->preferred_hk[i] == HK_WARN)
6470 for (j = 0; j < lenof(hostkey_algs); j++) {
6471 if (hostkey_algs[j].id != s->preferred_hk[i])
6473 if (have_ssh_host_key(ssh->savedhost, ssh->savedport,
6474 hostkey_algs[j].alg->keytype)) {
6475 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6476 hostkey_algs[j].alg->name);
6477 alg->u.hk.hostkey = hostkey_algs[j].alg;
6478 alg->u.hk.warn = warn;
6483 for (i = 0; i < s->n_preferred_hk; i++) {
6484 if (s->preferred_hk[i] == HK_WARN)
6486 for (j = 0; j < lenof(hostkey_algs); j++) {
6487 if (hostkey_algs[j].id != s->preferred_hk[i])
6489 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6490 hostkey_algs[j].alg->name);
6491 alg->u.hk.hostkey = hostkey_algs[j].alg;
6492 alg->u.hk.warn = warn;
6497 * In subsequent key exchanges, we list only the kex
6498 * algorithm that was selected in the first key exchange,
6499 * so that we keep getting the same host key and hence
6500 * don't have to interrupt the user's session to ask for
6504 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6505 ssh->hostkey->name);
6506 alg->u.hk.hostkey = ssh->hostkey;
6507 alg->u.hk.warn = FALSE;
6509 /* List encryption algorithms (client->server then server->client). */
6510 for (k = KEXLIST_CSCIPHER; k <= KEXLIST_SCCIPHER; k++) {
6513 alg = ssh2_kexinit_addalg(s->kexlists[k], "none");
6514 alg->u.cipher.cipher = NULL;
6515 alg->u.cipher.warn = warn;
6516 #endif /* FUZZING */
6517 for (i = 0; i < s->n_preferred_ciphers; i++) {
6518 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6519 if (!c) warn = TRUE;
6520 else for (j = 0; j < c->nciphers; j++) {
6521 alg = ssh2_kexinit_addalg(s->kexlists[k],
6523 alg->u.cipher.cipher = c->list[j];
6524 alg->u.cipher.warn = warn;
6528 /* List MAC algorithms (client->server then server->client). */
6529 for (j = KEXLIST_CSMAC; j <= KEXLIST_SCMAC; j++) {
6531 alg = ssh2_kexinit_addalg(s->kexlists[j], "none");
6532 alg->u.mac.mac = NULL;
6533 alg->u.mac.etm = FALSE;
6534 #endif /* FUZZING */
6535 for (i = 0; i < s->nmacs; i++) {
6536 alg = ssh2_kexinit_addalg(s->kexlists[j], s->maclist[i]->name);
6537 alg->u.mac.mac = s->maclist[i];
6538 alg->u.mac.etm = FALSE;
6540 for (i = 0; i < s->nmacs; i++)
6541 /* For each MAC, there may also be an ETM version,
6542 * which we list second. */
6543 if (s->maclist[i]->etm_name) {
6544 alg = ssh2_kexinit_addalg(s->kexlists[j],
6545 s->maclist[i]->etm_name);
6546 alg->u.mac.mac = s->maclist[i];
6547 alg->u.mac.etm = TRUE;
6550 /* List client->server compression algorithms,
6551 * then server->client compression algorithms. (We use the
6552 * same set twice.) */
6553 for (j = KEXLIST_CSCOMP; j <= KEXLIST_SCCOMP; j++) {
6554 assert(lenof(compressions) > 1);
6555 /* Prefer non-delayed versions */
6556 alg = ssh2_kexinit_addalg(s->kexlists[j], s->preferred_comp->name);
6557 alg->u.comp = s->preferred_comp;
6558 /* We don't even list delayed versions of algorithms until
6559 * they're allowed to be used, to avoid a race. See the end of
6561 if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
6562 alg = ssh2_kexinit_addalg(s->kexlists[j],
6563 s->preferred_comp->delayed_name);
6564 alg->u.comp = s->preferred_comp;
6566 for (i = 0; i < lenof(compressions); i++) {
6567 const struct ssh_compress *c = compressions[i];
6568 alg = ssh2_kexinit_addalg(s->kexlists[j], c->name);
6570 if (s->userauth_succeeded && c->delayed_name) {
6571 alg = ssh2_kexinit_addalg(s->kexlists[j], c->delayed_name);
6577 * Construct and send our key exchange packet.
6579 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
6580 for (i = 0; i < 16; i++)
6581 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
6582 for (i = 0; i < NKEXLIST; i++) {
6583 ssh2_pkt_addstring_start(s->pktout);
6584 for (j = 0; j < MAXKEXLIST; j++) {
6585 if (s->kexlists[i][j].name == NULL) break;
6586 ssh2_pkt_addstring_commasep(s->pktout, s->kexlists[i][j].name);
6589 /* List client->server languages. Empty list. */
6590 ssh2_pkt_addstring_start(s->pktout);
6591 /* List server->client languages. Empty list. */
6592 ssh2_pkt_addstring_start(s->pktout);
6593 /* First KEX packet does _not_ follow, because we're not that brave. */
6594 ssh2_pkt_addbool(s->pktout, FALSE);
6596 ssh2_pkt_adduint32(s->pktout, 0);
6599 s->our_kexinitlen = s->pktout->length - 5;
6600 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
6601 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
6603 ssh2_pkt_send_noqueue(ssh, s->pktout);
6606 crWaitUntilV(pktin);
6609 * Now examine the other side's KEXINIT to see what we're up
6616 if (pktin->type != SSH2_MSG_KEXINIT) {
6617 bombout(("expected key exchange packet from server"));
6621 ssh->hostkey = NULL;
6622 s->cscipher_tobe = NULL;
6623 s->sccipher_tobe = NULL;
6624 s->csmac_tobe = NULL;
6625 s->scmac_tobe = NULL;
6626 s->cscomp_tobe = NULL;
6627 s->sccomp_tobe = NULL;
6628 s->warn_kex = s->warn_hk = FALSE;
6629 s->warn_cscipher = s->warn_sccipher = FALSE;
6631 pktin->savedpos += 16; /* skip garbage cookie */
6634 for (i = 0; i < NKEXLIST; i++) {
6635 ssh_pkt_getstring(pktin, &str, &len);
6637 bombout(("KEXINIT packet was incomplete"));
6641 /* If we've already selected a cipher which requires a
6642 * particular MAC, then just select that, and don't even
6643 * bother looking through the server's KEXINIT string for
6645 if (i == KEXLIST_CSMAC && s->cscipher_tobe &&
6646 s->cscipher_tobe->required_mac) {
6647 s->csmac_tobe = s->cscipher_tobe->required_mac;
6648 s->csmac_etm_tobe = !!(s->csmac_tobe->etm_name);
6651 if (i == KEXLIST_SCMAC && s->sccipher_tobe &&
6652 s->sccipher_tobe->required_mac) {
6653 s->scmac_tobe = s->sccipher_tobe->required_mac;
6654 s->scmac_etm_tobe = !!(s->scmac_tobe->etm_name);
6658 for (j = 0; j < MAXKEXLIST; j++) {
6659 struct kexinit_algorithm *alg = &s->kexlists[i][j];
6660 if (alg->name == NULL) break;
6661 if (in_commasep_string(alg->name, str, len)) {
6662 /* We've found a matching algorithm. */
6663 if (i == KEXLIST_KEX || i == KEXLIST_HOSTKEY) {
6664 /* Check if we might need to ignore first kex pkt */
6666 !first_in_commasep_string(alg->name, str, len))
6669 if (i == KEXLIST_KEX) {
6670 ssh->kex = alg->u.kex.kex;
6671 s->warn_kex = alg->u.kex.warn;
6672 } else if (i == KEXLIST_HOSTKEY) {
6673 ssh->hostkey = alg->u.hk.hostkey;
6674 s->warn_hk = alg->u.hk.warn;
6675 } else if (i == KEXLIST_CSCIPHER) {
6676 s->cscipher_tobe = alg->u.cipher.cipher;
6677 s->warn_cscipher = alg->u.cipher.warn;
6678 } else if (i == KEXLIST_SCCIPHER) {
6679 s->sccipher_tobe = alg->u.cipher.cipher;
6680 s->warn_sccipher = alg->u.cipher.warn;
6681 } else if (i == KEXLIST_CSMAC) {
6682 s->csmac_tobe = alg->u.mac.mac;
6683 s->csmac_etm_tobe = alg->u.mac.etm;
6684 } else if (i == KEXLIST_SCMAC) {
6685 s->scmac_tobe = alg->u.mac.mac;
6686 s->scmac_etm_tobe = alg->u.mac.etm;
6687 } else if (i == KEXLIST_CSCOMP) {
6688 s->cscomp_tobe = alg->u.comp;
6689 } else if (i == KEXLIST_SCCOMP) {
6690 s->sccomp_tobe = alg->u.comp;
6694 if ((i == KEXLIST_CSCOMP || i == KEXLIST_SCCOMP) &&
6695 in_commasep_string(alg->u.comp->delayed_name, str, len))
6696 s->pending_compression = TRUE; /* try this later */
6698 bombout(("Couldn't agree a %s (available: %.*s)",
6699 kexlist_descr[i], len, str));
6703 if (i == KEXLIST_HOSTKEY) {
6707 * In addition to deciding which host key we're
6708 * actually going to use, we should make a list of the
6709 * host keys offered by the server which we _don't_
6710 * have cached. These will be offered as cross-
6711 * certification options by ssh_get_specials.
6713 * We also count the key we're currently using for KEX
6714 * as one we've already got, because by the time this
6715 * menu becomes visible, it will be.
6717 ssh->n_uncert_hostkeys = 0;
6719 for (j = 0; j < lenof(hostkey_algs); j++) {
6720 if (hostkey_algs[j].alg != ssh->hostkey &&
6721 in_commasep_string(hostkey_algs[j].alg->name,
6723 !have_ssh_host_key(ssh->savedhost, ssh->savedport,
6724 hostkey_algs[j].alg->keytype)) {
6725 ssh->uncert_hostkeys[ssh->n_uncert_hostkeys++] = j;
6731 if (s->pending_compression) {
6732 logevent("Server supports delayed compression; "
6733 "will try this later");
6735 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
6736 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
6737 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
6739 ssh->exhash = ssh->kex->hash->init();
6740 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
6741 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
6742 hash_string(ssh->kex->hash, ssh->exhash,
6743 s->our_kexinit, s->our_kexinitlen);
6744 sfree(s->our_kexinit);
6745 /* Include the type byte in the hash of server's KEXINIT */
6746 hash_string(ssh->kex->hash, ssh->exhash,
6747 pktin->body - 1, pktin->length + 1);
6750 ssh_set_frozen(ssh, 1);
6751 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
6753 ssh_dialog_callback, ssh);
6754 if (s->dlgret < 0) {
6758 bombout(("Unexpected data from server while"
6759 " waiting for user response"));
6762 } while (pktin || inlen > 0);
6763 s->dlgret = ssh->user_response;
6765 ssh_set_frozen(ssh, 0);
6766 if (s->dlgret == 0) {
6767 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
6777 ssh_set_frozen(ssh, 1);
6780 * Change warning box wording depending on why we chose a
6781 * warning-level host key algorithm. If it's because
6782 * that's all we have *cached*, use the askhk mechanism,
6783 * and list the host keys we could usefully cross-certify.
6784 * Otherwise, use askalg for the standard wording.
6787 for (j = 0; j < ssh->n_uncert_hostkeys; j++) {
6788 const struct ssh_signkey_with_user_pref_id *hktype =
6789 &hostkey_algs[ssh->uncert_hostkeys[j]];
6791 for (k = 0; k < HK_MAX; k++) {
6792 int id = conf_get_int_int(ssh->conf, CONF_ssh_hklist, k);
6793 if (id == HK_WARN) {
6795 } else if (id == hktype->id) {
6802 char *old_ba = betteralgs;
6803 betteralgs = dupcat(betteralgs, ",",
6805 (const char *)NULL);
6808 betteralgs = dupstr(hktype->alg->name);
6813 s->dlgret = askhk(ssh->frontend, ssh->hostkey->name,
6814 betteralgs, ssh_dialog_callback, ssh);
6817 s->dlgret = askalg(ssh->frontend, "host key type",
6819 ssh_dialog_callback, ssh);
6821 if (s->dlgret < 0) {
6825 bombout(("Unexpected data from server while"
6826 " waiting for user response"));
6829 } while (pktin || inlen > 0);
6830 s->dlgret = ssh->user_response;
6832 ssh_set_frozen(ssh, 0);
6833 if (s->dlgret == 0) {
6834 ssh_disconnect(ssh, "User aborted at host key warning", NULL,
6840 if (s->warn_cscipher) {
6841 ssh_set_frozen(ssh, 1);
6842 s->dlgret = askalg(ssh->frontend,
6843 "client-to-server cipher",
6844 s->cscipher_tobe->name,
6845 ssh_dialog_callback, ssh);
6846 if (s->dlgret < 0) {
6850 bombout(("Unexpected data from server while"
6851 " waiting for user response"));
6854 } while (pktin || inlen > 0);
6855 s->dlgret = ssh->user_response;
6857 ssh_set_frozen(ssh, 0);
6858 if (s->dlgret == 0) {
6859 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6865 if (s->warn_sccipher) {
6866 ssh_set_frozen(ssh, 1);
6867 s->dlgret = askalg(ssh->frontend,
6868 "server-to-client cipher",
6869 s->sccipher_tobe->name,
6870 ssh_dialog_callback, ssh);
6871 if (s->dlgret < 0) {
6875 bombout(("Unexpected data from server while"
6876 " waiting for user response"));
6879 } while (pktin || inlen > 0);
6880 s->dlgret = ssh->user_response;
6882 ssh_set_frozen(ssh, 0);
6883 if (s->dlgret == 0) {
6884 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6890 if (s->ignorepkt) /* first_kex_packet_follows */
6891 crWaitUntilV(pktin); /* Ignore packet */
6894 if (ssh->kex->main_type == KEXTYPE_DH) {
6896 * Work out the number of bits of key we will need from the
6897 * key exchange. We start with the maximum key length of
6903 csbits = s->cscipher_tobe ? s->cscipher_tobe->real_keybits : 0;
6904 scbits = s->sccipher_tobe ? s->sccipher_tobe->real_keybits : 0;
6905 s->nbits = (csbits > scbits ? csbits : scbits);
6907 /* The keys only have hlen-bit entropy, since they're based on
6908 * a hash. So cap the key size at hlen bits. */
6909 if (s->nbits > ssh->kex->hash->hlen * 8)
6910 s->nbits = ssh->kex->hash->hlen * 8;
6913 * If we're doing Diffie-Hellman group exchange, start by
6914 * requesting a group.
6916 if (dh_is_gex(ssh->kex)) {
6917 logevent("Doing Diffie-Hellman group exchange");
6918 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
6920 * Work out how big a DH group we will need to allow that
6923 s->pbits = 512 << ((s->nbits - 1) / 64);
6924 if (s->pbits < DH_MIN_SIZE)
6925 s->pbits = DH_MIN_SIZE;
6926 if (s->pbits > DH_MAX_SIZE)
6927 s->pbits = DH_MAX_SIZE;
6928 if ((ssh->remote_bugs & BUG_SSH2_OLDGEX)) {
6929 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD);
6930 ssh2_pkt_adduint32(s->pktout, s->pbits);
6932 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
6933 ssh2_pkt_adduint32(s->pktout, DH_MIN_SIZE);
6934 ssh2_pkt_adduint32(s->pktout, s->pbits);
6935 ssh2_pkt_adduint32(s->pktout, DH_MAX_SIZE);
6937 ssh2_pkt_send_noqueue(ssh, s->pktout);
6939 crWaitUntilV(pktin);
6940 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
6941 bombout(("expected key exchange group packet from server"));
6944 s->p = ssh2_pkt_getmp(pktin);
6945 s->g = ssh2_pkt_getmp(pktin);
6946 if (!s->p || !s->g) {
6947 bombout(("unable to read mp-ints from incoming group packet"));
6950 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
6951 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
6952 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
6954 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
6955 ssh->kex_ctx = dh_setup_group(ssh->kex);
6956 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
6957 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
6958 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
6959 ssh->kex->groupname);
6962 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
6963 ssh->kex->hash->text_name);
6965 * Now generate and send e for Diffie-Hellman.
6967 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
6968 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
6969 s->pktout = ssh2_pkt_init(s->kex_init_value);
6970 ssh2_pkt_addmp(s->pktout, s->e);
6971 ssh2_pkt_send_noqueue(ssh, s->pktout);
6973 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
6974 crWaitUntilV(pktin);
6975 if (pktin->type != s->kex_reply_value) {
6976 bombout(("expected key exchange reply packet from server"));
6979 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
6980 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6981 if (!s->hostkeydata) {
6982 bombout(("unable to parse key exchange reply packet"));
6985 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
6986 s->hostkeydata, s->hostkeylen);
6987 s->f = ssh2_pkt_getmp(pktin);
6989 bombout(("unable to parse key exchange reply packet"));
6992 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6994 bombout(("unable to parse key exchange reply packet"));
6999 const char *err = dh_validate_f(ssh->kex_ctx, s->f);
7001 bombout(("key exchange reply failed validation: %s", err));
7005 s->K = dh_find_K(ssh->kex_ctx, s->f);
7007 /* We assume everything from now on will be quick, and it might
7008 * involve user interaction. */
7009 set_busy_status(ssh->frontend, BUSY_NOT);
7011 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
7012 if (dh_is_gex(ssh->kex)) {
7013 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
7014 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MIN_SIZE);
7015 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
7016 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
7017 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MAX_SIZE);
7018 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
7019 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
7021 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
7022 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
7024 dh_cleanup(ssh->kex_ctx);
7026 if (dh_is_gex(ssh->kex)) {
7030 } else if (ssh->kex->main_type == KEXTYPE_ECDH) {
7032 logeventf(ssh, "Doing ECDH key exchange with curve %s and hash %s",
7033 ssh_ecdhkex_curve_textname(ssh->kex),
7034 ssh->kex->hash->text_name);
7035 ssh->pkt_kctx = SSH2_PKTCTX_ECDHKEX;
7037 s->eckey = ssh_ecdhkex_newkey(ssh->kex);
7039 bombout(("Unable to generate key for ECDH"));
7045 int publicPointLength;
7046 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
7048 ssh_ecdhkex_freekey(s->eckey);
7049 bombout(("Unable to encode public key for ECDH"));
7052 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_ECDH_INIT);
7053 ssh2_pkt_addstring_start(s->pktout);
7054 ssh2_pkt_addstring_data(s->pktout, publicPoint, publicPointLength);
7058 ssh2_pkt_send_noqueue(ssh, s->pktout);
7060 crWaitUntilV(pktin);
7061 if (pktin->type != SSH2_MSG_KEX_ECDH_REPLY) {
7062 ssh_ecdhkex_freekey(s->eckey);
7063 bombout(("expected ECDH reply packet from server"));
7067 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7068 if (!s->hostkeydata) {
7069 bombout(("unable to parse ECDH reply packet"));
7072 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
7073 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7074 s->hostkeydata, s->hostkeylen);
7078 int publicPointLength;
7079 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
7081 ssh_ecdhkex_freekey(s->eckey);
7082 bombout(("Unable to encode public key for ECDH hash"));
7085 hash_string(ssh->kex->hash, ssh->exhash,
7086 publicPoint, publicPointLength);
7093 ssh_pkt_getstring(pktin, &keydata, &keylen);
7095 bombout(("unable to parse ECDH reply packet"));
7098 hash_string(ssh->kex->hash, ssh->exhash, keydata, keylen);
7099 s->K = ssh_ecdhkex_getkey(s->eckey, keydata, keylen);
7101 ssh_ecdhkex_freekey(s->eckey);
7102 bombout(("point received in ECDH was not valid"));
7107 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7109 bombout(("unable to parse key exchange reply packet"));
7113 ssh_ecdhkex_freekey(s->eckey);
7115 logeventf(ssh, "Doing RSA key exchange with hash %s",
7116 ssh->kex->hash->text_name);
7117 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
7119 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
7122 crWaitUntilV(pktin);
7123 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
7124 bombout(("expected RSA public key packet from server"));
7128 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7129 if (!s->hostkeydata) {
7130 bombout(("unable to parse RSA public key packet"));
7133 hash_string(ssh->kex->hash, ssh->exhash,
7134 s->hostkeydata, s->hostkeylen);
7135 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7136 s->hostkeydata, s->hostkeylen);
7140 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
7142 bombout(("unable to parse RSA public key packet"));
7145 s->rsakeydata = snewn(s->rsakeylen, char);
7146 memcpy(s->rsakeydata, keydata, s->rsakeylen);
7149 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
7151 sfree(s->rsakeydata);
7152 bombout(("unable to parse RSA public key from server"));
7156 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
7159 * Next, set up a shared secret K, of precisely KLEN -
7160 * 2*HLEN - 49 bits, where KLEN is the bit length of the
7161 * RSA key modulus and HLEN is the bit length of the hash
7165 int klen = ssh_rsakex_klen(s->rsakey);
7166 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
7168 unsigned char *kstr1, *kstr2, *outstr;
7169 int kstr1len, kstr2len, outstrlen;
7171 s->K = bn_power_2(nbits - 1);
7173 for (i = 0; i < nbits; i++) {
7175 byte = random_byte();
7177 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
7181 * Encode this as an mpint.
7183 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
7184 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
7185 PUT_32BIT(kstr2, kstr1len);
7186 memcpy(kstr2 + 4, kstr1, kstr1len);
7189 * Encrypt it with the given RSA key.
7191 outstrlen = (klen + 7) / 8;
7192 outstr = snewn(outstrlen, unsigned char);
7193 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
7194 outstr, outstrlen, s->rsakey);
7197 * And send it off in a return packet.
7199 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
7200 ssh2_pkt_addstring_start(s->pktout);
7201 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
7202 ssh2_pkt_send_noqueue(ssh, s->pktout);
7204 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
7211 ssh_rsakex_freekey(s->rsakey);
7213 crWaitUntilV(pktin);
7214 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
7215 sfree(s->rsakeydata);
7216 bombout(("expected signature packet from server"));
7220 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7222 bombout(("unable to parse signature packet"));
7226 sfree(s->rsakeydata);
7229 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
7230 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
7231 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
7233 ssh->kex_ctx = NULL;
7236 debug(("Exchange hash is:\n"));
7237 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
7241 bombout(("Server's host key is invalid"));
7245 if (!ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
7246 (char *)s->exchange_hash,
7247 ssh->kex->hash->hlen)) {
7249 bombout(("Server's host key did not match the signature supplied"));
7254 s->keystr = ssh->hostkey->fmtkey(s->hkey);
7255 if (!s->got_session_id) {
7257 * Make a note of any other host key formats that are available.
7260 int i, j, nkeys = 0;
7262 for (i = 0; i < lenof(hostkey_algs); i++) {
7263 if (hostkey_algs[i].alg == ssh->hostkey)
7266 for (j = 0; j < ssh->n_uncert_hostkeys; j++)
7267 if (ssh->uncert_hostkeys[j] == i)
7270 if (j < ssh->n_uncert_hostkeys) {
7273 newlist = dupprintf("%s/%s", list,
7274 hostkey_algs[i].alg->name);
7276 newlist = dupprintf("%s", hostkey_algs[i].alg->name);
7284 "Server also has %s host key%s, but we "
7285 "don't know %s", list,
7286 nkeys > 1 ? "s" : "",
7287 nkeys > 1 ? "any of them" : "it");
7293 * Authenticate remote host: verify host key. (We've already
7294 * checked the signature of the exchange hash.)
7296 s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
7297 logevent("Host key fingerprint is:");
7298 logevent(s->fingerprint);
7299 /* First check against manually configured host keys. */
7300 s->dlgret = verify_ssh_manual_host_key(ssh, s->fingerprint,
7301 ssh->hostkey, s->hkey);
7302 if (s->dlgret == 0) { /* did not match */
7303 bombout(("Host key did not appear in manually configured list"));
7305 } else if (s->dlgret < 0) { /* none configured; use standard handling */
7306 ssh_set_frozen(ssh, 1);
7307 s->dlgret = verify_ssh_host_key(ssh->frontend,
7308 ssh->savedhost, ssh->savedport,
7309 ssh->hostkey->keytype, s->keystr,
7311 ssh_dialog_callback, ssh);
7315 if (s->dlgret < 0) {
7319 bombout(("Unexpected data from server while waiting"
7320 " for user host key response"));
7323 } while (pktin || inlen > 0);
7324 s->dlgret = ssh->user_response;
7326 ssh_set_frozen(ssh, 0);
7327 if (s->dlgret == 0) {
7328 ssh_disconnect(ssh, "Aborted at host key verification", NULL,
7333 sfree(s->fingerprint);
7335 * Save this host key, to check against the one presented in
7336 * subsequent rekeys.
7338 ssh->hostkey_str = s->keystr;
7339 } else if (ssh->cross_certifying) {
7340 s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
7341 logevent("Storing additional host key for this host:");
7342 logevent(s->fingerprint);
7343 sfree(s->fingerprint);
7344 store_host_key(ssh->savedhost, ssh->savedport,
7345 ssh->hostkey->keytype, s->keystr);
7346 ssh->cross_certifying = FALSE;
7348 * Don't forget to store the new key as the one we'll be
7349 * re-checking in future normal rekeys.
7351 ssh->hostkey_str = s->keystr;
7354 * In a rekey, we never present an interactive host key
7355 * verification request to the user. Instead, we simply
7356 * enforce that the key we're seeing this time is identical to
7357 * the one we saw before.
7359 if (strcmp(ssh->hostkey_str, s->keystr)) {
7361 bombout(("Host key was different in repeat key exchange"));
7367 ssh->hostkey->freekey(s->hkey);
7370 * The exchange hash from the very first key exchange is also
7371 * the session id, used in session key construction and
7374 if (!s->got_session_id) {
7375 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
7376 memcpy(ssh->v2_session_id, s->exchange_hash,
7377 sizeof(s->exchange_hash));
7378 ssh->v2_session_id_len = ssh->kex->hash->hlen;
7379 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
7380 s->got_session_id = TRUE;
7384 * Send SSH2_MSG_NEWKEYS.
7386 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
7387 ssh2_pkt_send_noqueue(ssh, s->pktout);
7388 ssh->outgoing_data_size = 0; /* start counting from here */
7391 * We've sent client NEWKEYS, so create and initialise
7392 * client-to-server session keys.
7394 if (ssh->cs_cipher_ctx)
7395 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
7396 ssh->cscipher = s->cscipher_tobe;
7397 if (ssh->cscipher) ssh->cs_cipher_ctx = ssh->cscipher->make_context();
7399 if (ssh->cs_mac_ctx)
7400 ssh->csmac->free_context(ssh->cs_mac_ctx);
7401 ssh->csmac = s->csmac_tobe;
7402 ssh->csmac_etm = s->csmac_etm_tobe;
7404 ssh->cs_mac_ctx = ssh->csmac->make_context(ssh->cs_cipher_ctx);
7406 if (ssh->cs_comp_ctx)
7407 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
7408 ssh->cscomp = s->cscomp_tobe;
7409 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
7412 * Set IVs on client-to-server keys. Here we use the exchange
7413 * hash from the _first_ key exchange.
7415 if (ssh->cscipher) {
7418 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'C',
7419 ssh->cscipher->padded_keybytes);
7420 ssh->cscipher->setkey(ssh->cs_cipher_ctx, key);
7421 smemclr(key, ssh->cscipher->padded_keybytes);
7424 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'A',
7425 ssh->cscipher->blksize);
7426 ssh->cscipher->setiv(ssh->cs_cipher_ctx, key);
7427 smemclr(key, ssh->cscipher->blksize);
7433 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'E',
7434 ssh->csmac->keylen);
7435 ssh->csmac->setkey(ssh->cs_mac_ctx, key);
7436 smemclr(key, ssh->csmac->keylen);
7441 logeventf(ssh, "Initialised %.200s client->server encryption",
7442 ssh->cscipher->text_name);
7444 logeventf(ssh, "Initialised %.200s client->server MAC algorithm%s%s",
7445 ssh->csmac->text_name,
7446 ssh->csmac_etm ? " (in ETM mode)" : "",
7447 ssh->cscipher->required_mac ? " (required by cipher)" : "");
7448 if (ssh->cscomp->text_name)
7449 logeventf(ssh, "Initialised %s compression",
7450 ssh->cscomp->text_name);
7453 * Now our end of the key exchange is complete, we can send all
7454 * our queued higher-layer packets.
7456 ssh->queueing = FALSE;
7457 ssh2_pkt_queuesend(ssh);
7460 * Expect SSH2_MSG_NEWKEYS from server.
7462 crWaitUntilV(pktin);
7463 if (pktin->type != SSH2_MSG_NEWKEYS) {
7464 bombout(("expected new-keys packet from server"));
7467 ssh->incoming_data_size = 0; /* start counting from here */
7470 * We've seen server NEWKEYS, so create and initialise
7471 * server-to-client session keys.
7473 if (ssh->sc_cipher_ctx)
7474 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
7475 if (s->sccipher_tobe) {
7476 ssh->sccipher = s->sccipher_tobe;
7477 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
7480 if (ssh->sc_mac_ctx)
7481 ssh->scmac->free_context(ssh->sc_mac_ctx);
7482 if (s->scmac_tobe) {
7483 ssh->scmac = s->scmac_tobe;
7484 ssh->scmac_etm = s->scmac_etm_tobe;
7485 ssh->sc_mac_ctx = ssh->scmac->make_context(ssh->sc_cipher_ctx);
7488 if (ssh->sc_comp_ctx)
7489 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
7490 ssh->sccomp = s->sccomp_tobe;
7491 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
7494 * Set IVs on server-to-client keys. Here we use the exchange
7495 * hash from the _first_ key exchange.
7497 if (ssh->sccipher) {
7500 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'D',
7501 ssh->sccipher->padded_keybytes);
7502 ssh->sccipher->setkey(ssh->sc_cipher_ctx, key);
7503 smemclr(key, ssh->sccipher->padded_keybytes);
7506 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'B',
7507 ssh->sccipher->blksize);
7508 ssh->sccipher->setiv(ssh->sc_cipher_ctx, key);
7509 smemclr(key, ssh->sccipher->blksize);
7515 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'F',
7516 ssh->scmac->keylen);
7517 ssh->scmac->setkey(ssh->sc_mac_ctx, key);
7518 smemclr(key, ssh->scmac->keylen);
7522 logeventf(ssh, "Initialised %.200s server->client encryption",
7523 ssh->sccipher->text_name);
7525 logeventf(ssh, "Initialised %.200s server->client MAC algorithm%s%s",
7526 ssh->scmac->text_name,
7527 ssh->scmac_etm ? " (in ETM mode)" : "",
7528 ssh->sccipher->required_mac ? " (required by cipher)" : "");
7529 if (ssh->sccomp->text_name)
7530 logeventf(ssh, "Initialised %s decompression",
7531 ssh->sccomp->text_name);
7534 * Free shared secret.
7539 * Update the specials menu to list the remaining uncertified host
7542 update_specials_menu(ssh->frontend);
7545 * Key exchange is over. Loop straight back round if we have a
7546 * deferred rekey reason.
7548 if (ssh->deferred_rekey_reason) {
7549 logevent(ssh->deferred_rekey_reason);
7551 ssh->deferred_rekey_reason = NULL;
7552 goto begin_key_exchange;
7556 * Otherwise, schedule a timer for our next rekey.
7558 ssh->kex_in_progress = FALSE;
7559 ssh->last_rekey = GETTICKCOUNT();
7560 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
7561 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7565 * Now we're encrypting. Begin returning 1 to the protocol main
7566 * function so that other things can run on top of the
7567 * transport. If we ever see a KEXINIT, we must go back to the
7570 * We _also_ go back to the start if we see pktin==NULL and
7571 * inlen negative, because this is a special signal meaning
7572 * `initiate client-driven rekey', and `in' contains a message
7573 * giving the reason for the rekey.
7575 * inlen==-1 means always initiate a rekey;
7576 * inlen==-2 means that userauth has completed successfully and
7577 * we should consider rekeying (for delayed compression).
7579 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
7580 (!pktin && inlen < 0))) {
7582 if (!ssh->protocol_initial_phase_done) {
7583 ssh->protocol_initial_phase_done = TRUE;
7585 * Allow authconn to initialise itself.
7587 do_ssh2_authconn(ssh, NULL, 0, NULL);
7592 logevent("Server initiated key re-exchange");
7596 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
7597 * delayed compression, if it's available.
7599 * draft-miller-secsh-compression-delayed-00 says that you
7600 * negotiate delayed compression in the first key exchange, and
7601 * both sides start compressing when the server has sent
7602 * USERAUTH_SUCCESS. This has a race condition -- the server
7603 * can't know when the client has seen it, and thus which incoming
7604 * packets it should treat as compressed.
7606 * Instead, we do the initial key exchange without offering the
7607 * delayed methods, but note if the server offers them; when we
7608 * get here, if a delayed method was available that was higher
7609 * on our list than what we got, we initiate a rekey in which we
7610 * _do_ list the delayed methods (and hopefully get it as a
7611 * result). Subsequent rekeys will do the same.
7613 assert(!s->userauth_succeeded); /* should only happen once */
7614 s->userauth_succeeded = TRUE;
7615 if (!s->pending_compression)
7616 /* Can't see any point rekeying. */
7617 goto wait_for_rekey; /* this is utterly horrid */
7618 /* else fall through to rekey... */
7619 s->pending_compression = FALSE;
7622 * Now we've decided to rekey.
7624 * Special case: if the server bug is set that doesn't
7625 * allow rekeying, we give a different log message and
7626 * continue waiting. (If such a server _initiates_ a rekey,
7627 * we process it anyway!)
7629 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
7630 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
7632 /* Reset the counters, so that at least this message doesn't
7633 * hit the event log _too_ often. */
7634 ssh->outgoing_data_size = 0;
7635 ssh->incoming_data_size = 0;
7636 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
7638 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7641 goto wait_for_rekey; /* this is still utterly horrid */
7643 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
7646 goto begin_key_exchange;
7652 * Send data on an SSH channel. In SSH-2, this involves buffering it
7655 static int ssh_send_channel_data(struct ssh_channel *c, const char *buf,
7658 if (c->ssh->version == 2) {
7659 bufchain_add(&c->v.v2.outbuffer, buf, len);
7660 return ssh2_try_send(c);
7662 send_packet(c->ssh, SSH1_MSG_CHANNEL_DATA,
7663 PKT_INT, c->remoteid,
7668 * In SSH-1 we can return 0 here - implying that channels are
7669 * never individually throttled - because the only
7670 * circumstance that can cause throttling will be the whole
7671 * SSH connection backing up, in which case _everything_ will
7672 * be throttled as a whole.
7679 * Attempt to send data on an SSH-2 channel.
7681 static int ssh2_try_send(struct ssh_channel *c)
7684 struct Packet *pktout;
7687 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
7690 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
7691 if ((unsigned)len > c->v.v2.remwindow)
7692 len = c->v.v2.remwindow;
7693 if ((unsigned)len > c->v.v2.remmaxpkt)
7694 len = c->v.v2.remmaxpkt;
7695 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
7696 ssh2_pkt_adduint32(pktout, c->remoteid);
7697 ssh2_pkt_addstring_start(pktout);
7698 ssh2_pkt_addstring_data(pktout, data, len);
7699 ssh2_pkt_send(ssh, pktout);
7700 bufchain_consume(&c->v.v2.outbuffer, len);
7701 c->v.v2.remwindow -= len;
7705 * After having sent as much data as we can, return the amount
7708 ret = bufchain_size(&c->v.v2.outbuffer);
7711 * And if there's no data pending but we need to send an EOF, send
7714 if (!ret && c->pending_eof)
7715 ssh_channel_try_eof(c);
7720 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
7723 if (c->closes & CLOSES_SENT_EOF)
7724 return; /* don't send on channels we've EOFed */
7725 bufsize = ssh2_try_send(c);
7728 case CHAN_MAINSESSION:
7729 /* stdin need not receive an unthrottle
7730 * notification since it will be polled */
7733 x11_unthrottle(c->u.x11.xconn);
7736 /* agent sockets are request/response and need no
7737 * buffer management */
7740 pfd_unthrottle(c->u.pfd.pf);
7746 static int ssh_is_simple(Ssh ssh)
7749 * We use the 'simple' variant of the SSH protocol if we're asked
7750 * to, except not if we're also doing connection-sharing (either
7751 * tunnelling our packets over an upstream or expecting to be
7752 * tunnelled over ourselves), since then the assumption that we
7753 * have only one channel to worry about is not true after all.
7755 return (conf_get_int(ssh->conf, CONF_ssh_simple) &&
7756 !ssh->bare_connection && !ssh->connshare);
7760 * Set up most of a new ssh_channel.
7762 static void ssh_channel_init(struct ssh_channel *c)
7765 c->localid = alloc_channel_id(ssh);
7767 c->pending_eof = FALSE;
7768 c->throttling_conn = FALSE;
7769 if (ssh->version == 2) {
7770 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
7771 ssh_is_simple(ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
7772 c->v.v2.chanreq_head = NULL;
7773 c->v.v2.throttle_state = UNTHROTTLED;
7774 bufchain_init(&c->v.v2.outbuffer);
7776 add234(ssh->channels, c);
7780 * Construct the common parts of a CHANNEL_OPEN.
7782 static struct Packet *ssh2_chanopen_init(struct ssh_channel *c,
7785 struct Packet *pktout;
7787 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7788 ssh2_pkt_addstring(pktout, type);
7789 ssh2_pkt_adduint32(pktout, c->localid);
7790 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
7791 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7796 * CHANNEL_FAILURE doesn't come with any indication of what message
7797 * caused it, so we have to keep track of the outstanding
7798 * CHANNEL_REQUESTs ourselves.
7800 static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
7801 cchandler_fn_t handler, void *ctx)
7803 struct outstanding_channel_request *ocr =
7804 snew(struct outstanding_channel_request);
7806 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7807 ocr->handler = handler;
7810 if (!c->v.v2.chanreq_head)
7811 c->v.v2.chanreq_head = ocr;
7813 c->v.v2.chanreq_tail->next = ocr;
7814 c->v.v2.chanreq_tail = ocr;
7818 * Construct the common parts of a CHANNEL_REQUEST. If handler is not
7819 * NULL then a reply will be requested and the handler will be called
7820 * when it arrives. The returned packet is ready to have any
7821 * request-specific data added and be sent. Note that if a handler is
7822 * provided, it's essential that the request actually be sent.
7824 * The handler will usually be passed the response packet in pktin. If
7825 * pktin is NULL, this means that no reply will ever be forthcoming
7826 * (e.g. because the entire connection is being destroyed, or because
7827 * the server initiated channel closure before we saw the response)
7828 * and the handler should free any storage it's holding.
7830 static struct Packet *ssh2_chanreq_init(struct ssh_channel *c,
7832 cchandler_fn_t handler, void *ctx)
7834 struct Packet *pktout;
7836 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7837 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7838 ssh2_pkt_adduint32(pktout, c->remoteid);
7839 ssh2_pkt_addstring(pktout, type);
7840 ssh2_pkt_addbool(pktout, handler != NULL);
7841 if (handler != NULL)
7842 ssh2_queue_chanreq_handler(c, handler, ctx);
7846 static void ssh_channel_unthrottle(struct ssh_channel *c, int bufsize)
7851 if (ssh->version == 1) {
7852 buflimit = SSH1_BUFFER_LIMIT;
7854 if (ssh_is_simple(ssh))
7857 buflimit = c->v.v2.locmaxwin;
7858 if (bufsize < buflimit)
7859 ssh2_set_window(c, buflimit - bufsize);
7861 if (c->throttling_conn && bufsize <= buflimit) {
7862 c->throttling_conn = 0;
7863 ssh_throttle_conn(ssh, -1);
7868 * Potentially enlarge the window on an SSH-2 channel.
7870 static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
7872 static void ssh2_set_window(struct ssh_channel *c, int newwin)
7877 * Never send WINDOW_ADJUST for a channel that the remote side has
7878 * already sent EOF on; there's no point, since it won't be
7879 * sending any more data anyway. Ditto if _we've_ already sent
7882 if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
7886 * Also, never widen the window for an X11 channel when we're
7887 * still waiting to see its initial auth and may yet hand it off
7890 if (c->type == CHAN_X11 && c->u.x11.initial)
7894 * If the remote end has a habit of ignoring maxpkt, limit the
7895 * window so that it has no choice (assuming it doesn't ignore the
7898 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
7899 newwin = OUR_V2_MAXPKT;
7902 * Only send a WINDOW_ADJUST if there's significantly more window
7903 * available than the other end thinks there is. This saves us
7904 * sending a WINDOW_ADJUST for every character in a shell session.
7906 * "Significant" is arbitrarily defined as half the window size.
7908 if (newwin / 2 >= c->v.v2.locwindow) {
7909 struct Packet *pktout;
7913 * In order to keep track of how much window the client
7914 * actually has available, we'd like it to acknowledge each
7915 * WINDOW_ADJUST. We can't do that directly, so we accompany
7916 * it with a CHANNEL_REQUEST that has to be acknowledged.
7918 * This is only necessary if we're opening the window wide.
7919 * If we're not, then throughput is being constrained by
7920 * something other than the maximum window size anyway.
7922 if (newwin == c->v.v2.locmaxwin &&
7923 !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
7924 up = snew(unsigned);
7925 *up = newwin - c->v.v2.locwindow;
7926 pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org",
7927 ssh2_handle_winadj_response, up);
7928 ssh2_pkt_send(ssh, pktout);
7930 if (c->v.v2.throttle_state != UNTHROTTLED)
7931 c->v.v2.throttle_state = UNTHROTTLING;
7933 /* Pretend the WINDOW_ADJUST was acked immediately. */
7934 c->v.v2.remlocwin = newwin;
7935 c->v.v2.throttle_state = THROTTLED;
7937 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
7938 ssh2_pkt_adduint32(pktout, c->remoteid);
7939 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
7940 ssh2_pkt_send(ssh, pktout);
7941 c->v.v2.locwindow = newwin;
7946 * Find the channel associated with a message. If there's no channel,
7947 * or it's not properly open, make a noise about it and return NULL.
7948 * If the channel is shared, pass the message on to downstream and
7949 * also return NULL (meaning the caller should ignore this message).
7951 static struct ssh_channel *ssh_channel_msg(Ssh ssh, struct Packet *pktin)
7953 unsigned localid = ssh_pkt_getuint32(pktin);
7954 struct ssh_channel *c;
7957 /* Is this message OK on a half-open connection? */
7958 if (ssh->version == 1)
7959 halfopen_ok = (pktin->type == SSH1_MSG_CHANNEL_OPEN_CONFIRMATION ||
7960 pktin->type == SSH1_MSG_CHANNEL_OPEN_FAILURE);
7962 halfopen_ok = (pktin->type == SSH2_MSG_CHANNEL_OPEN_CONFIRMATION ||
7963 pktin->type == SSH2_MSG_CHANNEL_OPEN_FAILURE);
7964 c = find234(ssh->channels, &localid, ssh_channelfind);
7965 if (!c || (c->type != CHAN_SHARING && (c->halfopen != halfopen_ok))) {
7966 char *buf = dupprintf("Received %s for %s channel %u",
7967 ssh_pkt_type(ssh, pktin->type),
7968 !c ? "nonexistent" :
7969 c->halfopen ? "half-open" : "open",
7971 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
7975 if (c->type == CHAN_SHARING) {
7976 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7977 pktin->body, pktin->length);
7983 static void ssh2_handle_winadj_response(struct ssh_channel *c,
7984 struct Packet *pktin, void *ctx)
7986 unsigned *sizep = ctx;
7989 * Winadj responses should always be failures. However, at least
7990 * one server ("boks_sshd") is known to return SUCCESS for channel
7991 * requests it's never heard of, such as "winadj@putty". Raised
7992 * with foxt.com as bug 090916-090424, but for the sake of a quiet
7993 * life, we don't worry about what kind of response we got.
7996 c->v.v2.remlocwin += *sizep;
7999 * winadj messages are only sent when the window is fully open, so
8000 * if we get an ack of one, we know any pending unthrottle is
8003 if (c->v.v2.throttle_state == UNTHROTTLING)
8004 c->v.v2.throttle_state = UNTHROTTLED;
8007 static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
8009 struct ssh_channel *c = ssh_channel_msg(ssh, pktin);
8010 struct outstanding_channel_request *ocr;
8013 ocr = c->v.v2.chanreq_head;
8015 ssh2_msg_unexpected(ssh, pktin);
8018 ocr->handler(c, pktin, ocr->ctx);
8019 c->v.v2.chanreq_head = ocr->next;
8022 * We may now initiate channel-closing procedures, if that
8023 * CHANNEL_REQUEST was the last thing outstanding before we send
8026 ssh2_channel_check_close(c);
8029 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
8031 struct ssh_channel *c;
8032 c = ssh_channel_msg(ssh, pktin);
8035 if (!(c->closes & CLOSES_SENT_EOF)) {
8036 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
8037 ssh2_try_send_and_unthrottle(ssh, c);
8041 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
8045 unsigned ext_type = 0; /* 0 means not extended */
8046 struct ssh_channel *c;
8047 c = ssh_channel_msg(ssh, pktin);
8050 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
8051 ext_type = ssh_pkt_getuint32(pktin);
8052 ssh_pkt_getstring(pktin, &data, &length);
8055 c->v.v2.locwindow -= length;
8056 c->v.v2.remlocwin -= length;
8057 if (ext_type != 0 && ext_type != SSH2_EXTENDED_DATA_STDERR)
8058 length = 0; /* Don't do anything with unknown extended data. */
8059 bufsize = ssh_channel_data(c, ext_type == SSH2_EXTENDED_DATA_STDERR,
8062 * If it looks like the remote end hit the end of its window,
8063 * and we didn't want it to do that, think about using a
8066 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
8067 c->v.v2.locmaxwin < 0x40000000)
8068 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
8070 * If we are not buffering too much data,
8071 * enlarge the window again at the remote side.
8072 * If we are buffering too much, we may still
8073 * need to adjust the window if the server's
8076 if (bufsize < c->v.v2.locmaxwin)
8077 ssh2_set_window(c, c->v.v2.locmaxwin - bufsize);
8079 * If we're either buffering way too much data, or if we're
8080 * buffering anything at all and we're in "simple" mode,
8081 * throttle the whole channel.
8083 if ((bufsize > c->v.v2.locmaxwin || (ssh_is_simple(ssh) && bufsize>0))
8084 && !c->throttling_conn) {
8085 c->throttling_conn = 1;
8086 ssh_throttle_conn(ssh, +1);
8091 static void ssh_check_termination(Ssh ssh)
8093 if (ssh->version == 2 &&
8094 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
8095 (ssh->channels && count234(ssh->channels) == 0) &&
8096 !(ssh->connshare && share_ndownstreams(ssh->connshare) > 0)) {
8098 * We used to send SSH_MSG_DISCONNECT here, because I'd
8099 * believed that _every_ conforming SSH-2 connection had to
8100 * end with a disconnect being sent by at least one side;
8101 * apparently I was wrong and it's perfectly OK to
8102 * unceremoniously slam the connection shut when you're done,
8103 * and indeed OpenSSH feels this is more polite than sending a
8104 * DISCONNECT. So now we don't.
8106 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
8110 void ssh_sharing_downstream_connected(Ssh ssh, unsigned id,
8111 const char *peerinfo)
8114 logeventf(ssh, "Connection sharing downstream #%u connected from %s",
8117 logeventf(ssh, "Connection sharing downstream #%u connected", id);
8120 void ssh_sharing_downstream_disconnected(Ssh ssh, unsigned id)
8122 logeventf(ssh, "Connection sharing downstream #%u disconnected", id);
8123 ssh_check_termination(ssh);
8126 void ssh_sharing_logf(Ssh ssh, unsigned id, const char *logfmt, ...)
8131 va_start(ap, logfmt);
8132 buf = dupvprintf(logfmt, ap);
8135 logeventf(ssh, "Connection sharing downstream #%u: %s", id, buf);
8137 logeventf(ssh, "Connection sharing: %s", buf);
8142 * Close any local socket and free any local resources associated with
8143 * a channel. This converts the channel into a CHAN_ZOMBIE.
8145 static void ssh_channel_close_local(struct ssh_channel *c, char const *reason)
8148 char const *msg = NULL;
8151 case CHAN_MAINSESSION:
8152 ssh->mainchan = NULL;
8153 update_specials_menu(ssh->frontend);
8156 assert(c->u.x11.xconn != NULL);
8157 x11_close(c->u.x11.xconn);
8158 msg = "Forwarded X11 connection terminated";
8162 agent_cancel_query(c->u.a.pending);
8163 sfree(c->u.a.message);
8166 assert(c->u.pfd.pf != NULL);
8167 pfd_close(c->u.pfd.pf);
8168 msg = "Forwarded port closed";
8171 c->type = CHAN_ZOMBIE;
8174 logeventf(ssh, "%s %s", msg, reason);
8180 static void ssh_channel_destroy(struct ssh_channel *c)
8184 ssh_channel_close_local(c, NULL);
8186 del234(ssh->channels, c);
8187 if (ssh->version == 2) {
8188 bufchain_clear(&c->v.v2.outbuffer);
8189 assert(c->v.v2.chanreq_head == NULL);
8194 * If that was the last channel left open, we might need to
8197 ssh_check_termination(ssh);
8200 static void ssh2_channel_check_close(struct ssh_channel *c)
8203 struct Packet *pktout;
8205 assert(ssh->version == 2);
8208 * If we've sent out our own CHANNEL_OPEN but not yet seen
8209 * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
8210 * it's too early to be sending close messages of any kind.
8215 if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
8216 c->type == CHAN_ZOMBIE) &&
8217 !c->v.v2.chanreq_head &&
8218 !(c->closes & CLOSES_SENT_CLOSE)) {
8220 * We have both sent and received EOF (or the channel is a
8221 * zombie), and we have no outstanding channel requests, which
8222 * means the channel is in final wind-up. But we haven't sent
8223 * CLOSE, so let's do so now.
8225 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
8226 ssh2_pkt_adduint32(pktout, c->remoteid);
8227 ssh2_pkt_send(ssh, pktout);
8228 c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
8231 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
8232 assert(c->v.v2.chanreq_head == NULL);
8234 * We have both sent and received CLOSE, which means we're
8235 * completely done with the channel.
8237 ssh_channel_destroy(c);
8241 static void ssh_channel_got_eof(struct ssh_channel *c)
8243 if (c->closes & CLOSES_RCVD_EOF)
8244 return; /* already seen EOF */
8245 c->closes |= CLOSES_RCVD_EOF;
8247 if (c->type == CHAN_X11) {
8248 assert(c->u.x11.xconn != NULL);
8249 x11_send_eof(c->u.x11.xconn);
8250 } else if (c->type == CHAN_AGENT) {
8251 if (c->u.a.outstanding_requests == 0) {
8252 /* Manufacture an outgoing EOF in response to the incoming one. */
8253 sshfwd_write_eof(c);
8255 } else if (c->type == CHAN_SOCKDATA) {
8256 assert(c->u.pfd.pf != NULL);
8257 pfd_send_eof(c->u.pfd.pf);
8258 } else if (c->type == CHAN_MAINSESSION) {
8261 if (!ssh->sent_console_eof &&
8262 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
8264 * Either from_backend_eof told us that the front end
8265 * wants us to close the outgoing side of the connection
8266 * as soon as we see EOF from the far end, or else we've
8267 * unilaterally decided to do that because we've allocated
8268 * a remote pty and hence EOF isn't a particularly
8269 * meaningful concept.
8271 sshfwd_write_eof(c);
8273 ssh->sent_console_eof = TRUE;
8277 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
8279 struct ssh_channel *c;
8281 c = ssh_channel_msg(ssh, pktin);
8284 ssh_channel_got_eof(c);
8285 ssh2_channel_check_close(c);
8288 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
8290 struct ssh_channel *c;
8292 c = ssh_channel_msg(ssh, pktin);
8297 * When we receive CLOSE on a channel, we assume it comes with an
8298 * implied EOF if we haven't seen EOF yet.
8300 ssh_channel_got_eof(c);
8302 if (!(ssh->remote_bugs & BUG_SENDS_LATE_REQUEST_REPLY)) {
8304 * It also means we stop expecting to see replies to any
8305 * outstanding channel requests, so clean those up too.
8306 * (ssh_chanreq_init will enforce by assertion that we don't
8307 * subsequently put anything back on this list.)
8309 while (c->v.v2.chanreq_head) {
8310 struct outstanding_channel_request *ocr = c->v.v2.chanreq_head;
8311 ocr->handler(c, NULL, ocr->ctx);
8312 c->v.v2.chanreq_head = ocr->next;
8318 * And we also send an outgoing EOF, if we haven't already, on the
8319 * assumption that CLOSE is a pretty forceful announcement that
8320 * the remote side is doing away with the entire channel. (If it
8321 * had wanted to send us EOF and continue receiving data from us,
8322 * it would have just sent CHANNEL_EOF.)
8324 if (!(c->closes & CLOSES_SENT_EOF)) {
8326 * Make sure we don't read any more from whatever our local
8327 * data source is for this channel.
8330 case CHAN_MAINSESSION:
8331 ssh->send_ok = 0; /* stop trying to read from stdin */
8334 x11_override_throttle(c->u.x11.xconn, 1);
8337 pfd_override_throttle(c->u.pfd.pf, 1);
8342 * Abandon any buffered data we still wanted to send to this
8343 * channel. Receiving a CHANNEL_CLOSE is an indication that
8344 * the server really wants to get on and _destroy_ this
8345 * channel, and it isn't going to send us any further
8346 * WINDOW_ADJUSTs to permit us to send pending stuff.
8348 bufchain_clear(&c->v.v2.outbuffer);
8351 * Send outgoing EOF.
8353 sshfwd_write_eof(c);
8357 * Now process the actual close.
8359 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
8360 c->closes |= CLOSES_RCVD_CLOSE;
8361 ssh2_channel_check_close(c);
8365 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
8367 struct ssh_channel *c;
8369 c = ssh_channel_msg(ssh, pktin);
8372 assert(c->halfopen); /* ssh_channel_msg will have enforced this */
8373 c->remoteid = ssh_pkt_getuint32(pktin);
8374 c->halfopen = FALSE;
8375 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8376 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8378 if (c->type == CHAN_SOCKDATA) {
8379 assert(c->u.pfd.pf != NULL);
8380 pfd_confirm(c->u.pfd.pf);
8381 } else if (c->type == CHAN_ZOMBIE) {
8383 * This case can occur if a local socket error occurred
8384 * between us sending out CHANNEL_OPEN and receiving
8385 * OPEN_CONFIRMATION. In this case, all we can do is
8386 * immediately initiate close proceedings now that we know the
8387 * server's id to put in the close message.
8389 ssh2_channel_check_close(c);
8392 * We never expect to receive OPEN_CONFIRMATION for any
8393 * *other* channel type (since only local-to-remote port
8394 * forwardings cause us to send CHANNEL_OPEN after the main
8395 * channel is live - all other auxiliary channel types are
8396 * initiated from the server end). It's safe to enforce this
8397 * by assertion rather than by ssh_disconnect, because the
8398 * real point is that we never constructed a half-open channel
8399 * structure in the first place with any type other than the
8402 assert(!"Funny channel type in ssh2_msg_channel_open_confirmation");
8406 ssh_channel_try_eof(c); /* in case we had a pending EOF */
8409 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
8411 static const char *const reasons[] = {
8412 "<unknown reason code>",
8413 "Administratively prohibited",
8415 "Unknown channel type",
8416 "Resource shortage",
8418 unsigned reason_code;
8419 char *reason_string;
8421 struct ssh_channel *c;
8423 c = ssh_channel_msg(ssh, pktin);
8426 assert(c->halfopen); /* ssh_channel_msg will have enforced this */
8428 if (c->type == CHAN_SOCKDATA) {
8429 reason_code = ssh_pkt_getuint32(pktin);
8430 if (reason_code >= lenof(reasons))
8431 reason_code = 0; /* ensure reasons[reason_code] in range */
8432 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
8433 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
8434 reasons[reason_code], reason_length,
8435 NULLTOEMPTY(reason_string));
8437 pfd_close(c->u.pfd.pf);
8438 } else if (c->type == CHAN_ZOMBIE) {
8440 * This case can occur if a local socket error occurred
8441 * between us sending out CHANNEL_OPEN and receiving
8442 * OPEN_FAILURE. In this case, we need do nothing except allow
8443 * the code below to throw the half-open channel away.
8447 * We never expect to receive OPEN_FAILURE for any *other*
8448 * channel type (since only local-to-remote port forwardings
8449 * cause us to send CHANNEL_OPEN after the main channel is
8450 * live - all other auxiliary channel types are initiated from
8451 * the server end). It's safe to enforce this by assertion
8452 * rather than by ssh_disconnect, because the real point is
8453 * that we never constructed a half-open channel structure in
8454 * the first place with any type other than the above.
8456 assert(!"Funny channel type in ssh2_msg_channel_open_failure");
8459 del234(ssh->channels, c);
8463 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
8466 int typelen, want_reply;
8467 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
8468 struct ssh_channel *c;
8469 struct Packet *pktout;
8471 c = ssh_channel_msg(ssh, pktin);
8474 ssh_pkt_getstring(pktin, &type, &typelen);
8475 want_reply = ssh2_pkt_getbool(pktin);
8477 if (c->closes & CLOSES_SENT_CLOSE) {
8479 * We don't reply to channel requests after we've sent
8480 * CHANNEL_CLOSE for the channel, because our reply might
8481 * cross in the network with the other side's CHANNEL_CLOSE
8482 * and arrive after they have wound the channel up completely.
8488 * Having got the channel number, we now look at
8489 * the request type string to see if it's something
8492 if (c == ssh->mainchan) {
8494 * We recognise "exit-status" and "exit-signal" on
8495 * the primary channel.
8497 if (typelen == 11 &&
8498 !memcmp(type, "exit-status", 11)) {
8500 ssh->exitcode = ssh_pkt_getuint32(pktin);
8501 logeventf(ssh, "Server sent command exit status %d",
8503 reply = SSH2_MSG_CHANNEL_SUCCESS;
8505 } else if (typelen == 11 &&
8506 !memcmp(type, "exit-signal", 11)) {
8508 int is_plausible = TRUE, is_int = FALSE;
8509 char *fmt_sig = NULL, *fmt_msg = NULL;
8511 int msglen = 0, core = FALSE;
8512 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
8513 * provide an `int' for the signal, despite its
8514 * having been a `string' in the drafts of RFC 4254 since at
8515 * least 2001. (Fixed in session.c 1.147.) Try to
8516 * infer which we can safely parse it as. */
8518 unsigned char *p = pktin->body +
8520 long len = pktin->length - pktin->savedpos;
8521 unsigned long num = GET_32BIT(p); /* what is it? */
8522 /* If it's 0, it hardly matters; assume string */
8526 int maybe_int = FALSE, maybe_str = FALSE;
8527 #define CHECK_HYPOTHESIS(offset, result) \
8530 int q = toint(offset); \
8531 if (q >= 0 && q+4 <= len) { \
8532 q = toint(q + 4 + GET_32BIT(p+q)); \
8533 if (q >= 0 && q+4 <= len && \
8534 ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
8539 CHECK_HYPOTHESIS(4+1, maybe_int);
8540 CHECK_HYPOTHESIS(4+num+1, maybe_str);
8541 #undef CHECK_HYPOTHESIS
8542 if (maybe_int && !maybe_str)
8544 else if (!maybe_int && maybe_str)
8547 /* Crikey. Either or neither. Panic. */
8548 is_plausible = FALSE;
8551 ssh->exitcode = 128; /* means `unknown signal' */
8554 /* Old non-standard OpenSSH. */
8555 int signum = ssh_pkt_getuint32(pktin);
8556 fmt_sig = dupprintf(" %d", signum);
8557 ssh->exitcode = 128 + signum;
8559 /* As per RFC 4254. */
8562 ssh_pkt_getstring(pktin, &sig, &siglen);
8563 /* Signal name isn't supposed to be blank, but
8564 * let's cope gracefully if it is. */
8566 fmt_sig = dupprintf(" \"%.*s\"",
8571 * Really hideous method of translating the
8572 * signal description back into a locally
8573 * meaningful number.
8578 #define TRANSLATE_SIGNAL(s) \
8579 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
8580 ssh->exitcode = 128 + SIG ## s
8582 TRANSLATE_SIGNAL(ABRT);
8585 TRANSLATE_SIGNAL(ALRM);
8588 TRANSLATE_SIGNAL(FPE);
8591 TRANSLATE_SIGNAL(HUP);
8594 TRANSLATE_SIGNAL(ILL);
8597 TRANSLATE_SIGNAL(INT);
8600 TRANSLATE_SIGNAL(KILL);
8603 TRANSLATE_SIGNAL(PIPE);
8606 TRANSLATE_SIGNAL(QUIT);
8609 TRANSLATE_SIGNAL(SEGV);
8612 TRANSLATE_SIGNAL(TERM);
8615 TRANSLATE_SIGNAL(USR1);
8618 TRANSLATE_SIGNAL(USR2);
8620 #undef TRANSLATE_SIGNAL
8622 ssh->exitcode = 128;
8624 core = ssh2_pkt_getbool(pktin);
8625 ssh_pkt_getstring(pktin, &msg, &msglen);
8627 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
8629 /* ignore lang tag */
8630 } /* else don't attempt to parse */
8631 logeventf(ssh, "Server exited on signal%s%s%s",
8632 fmt_sig ? fmt_sig : "",
8633 core ? " (core dumped)" : "",
8634 fmt_msg ? fmt_msg : "");
8637 reply = SSH2_MSG_CHANNEL_SUCCESS;
8642 * This is a channel request we don't know
8643 * about, so we now either ignore the request
8644 * or respond with CHANNEL_FAILURE, depending
8647 reply = SSH2_MSG_CHANNEL_FAILURE;
8650 pktout = ssh2_pkt_init(reply);
8651 ssh2_pkt_adduint32(pktout, c->remoteid);
8652 ssh2_pkt_send(ssh, pktout);
8656 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
8659 int typelen, want_reply;
8660 struct Packet *pktout;
8662 ssh_pkt_getstring(pktin, &type, &typelen);
8663 want_reply = ssh2_pkt_getbool(pktin);
8666 * We currently don't support any global requests
8667 * at all, so we either ignore the request or
8668 * respond with REQUEST_FAILURE, depending on
8672 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
8673 ssh2_pkt_send(ssh, pktout);
8677 struct X11FakeAuth *ssh_sharing_add_x11_display(Ssh ssh, int authtype,
8681 struct X11FakeAuth *auth;
8684 * Make up a new set of fake X11 auth data, and add it to the tree
8685 * of currently valid ones with an indication of the sharing
8686 * context that it's relevant to.
8688 auth = x11_invent_fake_auth(ssh->x11authtree, authtype);
8689 auth->share_cs = share_cs;
8690 auth->share_chan = share_chan;
8695 void ssh_sharing_remove_x11_display(Ssh ssh, struct X11FakeAuth *auth)
8697 del234(ssh->x11authtree, auth);
8698 x11_free_fake_auth(auth);
8701 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
8708 const char *error = NULL;
8709 struct ssh_channel *c;
8710 unsigned remid, winsize, pktsize;
8711 unsigned our_winsize_override = 0;
8712 struct Packet *pktout;
8714 ssh_pkt_getstring(pktin, &type, &typelen);
8715 c = snew(struct ssh_channel);
8718 remid = ssh_pkt_getuint32(pktin);
8719 winsize = ssh_pkt_getuint32(pktin);
8720 pktsize = ssh_pkt_getuint32(pktin);
8722 if (typelen == 3 && !memcmp(type, "x11", 3)) {
8725 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8726 addrstr = dupprintf("%.*s", peeraddrlen, NULLTOEMPTY(peeraddr));
8727 peerport = ssh_pkt_getuint32(pktin);
8729 logeventf(ssh, "Received X11 connect request from %s:%d",
8732 if (!ssh->X11_fwd_enabled && !ssh->connshare)
8733 error = "X11 forwarding is not enabled";
8735 c->u.x11.xconn = x11_init(ssh->x11authtree, c,
8738 c->u.x11.initial = TRUE;
8741 * If we are a connection-sharing upstream, then we should
8742 * initially present a very small window, adequate to take
8743 * the X11 initial authorisation packet but not much more.
8744 * Downstream will then present us a larger window (by
8745 * fiat of the connection-sharing protocol) and we can
8746 * guarantee to send a positive-valued WINDOW_ADJUST.
8749 our_winsize_override = 128;
8751 logevent("Opened X11 forward channel");
8755 } else if (typelen == 15 &&
8756 !memcmp(type, "forwarded-tcpip", 15)) {
8757 struct ssh_rportfwd pf, *realpf;
8760 ssh_pkt_getstring(pktin, &shost, &shostlen);/* skip address */
8761 pf.shost = dupprintf("%.*s", shostlen, NULLTOEMPTY(shost));
8762 pf.sport = ssh_pkt_getuint32(pktin);
8763 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8764 peerport = ssh_pkt_getuint32(pktin);
8765 realpf = find234(ssh->rportfwds, &pf, NULL);
8766 logeventf(ssh, "Received remote port %s:%d open request "
8767 "from %.*s:%d", pf.shost, pf.sport,
8768 peeraddrlen, NULLTOEMPTY(peeraddr), peerport);
8771 if (realpf == NULL) {
8772 error = "Remote port is not recognised";
8776 if (realpf->share_ctx) {
8778 * This port forwarding is on behalf of a
8779 * connection-sharing downstream, so abandon our own
8780 * channel-open procedure and just pass the message on
8783 share_got_pkt_from_server(realpf->share_ctx, pktin->type,
8784 pktin->body, pktin->length);
8789 err = pfd_connect(&c->u.pfd.pf, realpf->dhost, realpf->dport,
8790 c, ssh->conf, realpf->pfrec->addressfamily);
8791 logeventf(ssh, "Attempting to forward remote port to "
8792 "%s:%d", realpf->dhost, realpf->dport);
8794 logeventf(ssh, "Port open failed: %s", err);
8796 error = "Port open failed";
8798 logevent("Forwarded port opened successfully");
8799 c->type = CHAN_SOCKDATA;
8802 } else if (typelen == 22 &&
8803 !memcmp(type, "auth-agent@openssh.com", 22)) {
8804 if (!ssh->agentfwd_enabled)
8805 error = "Agent forwarding is not enabled";
8807 c->type = CHAN_AGENT; /* identify channel type */
8808 c->u.a.lensofar = 0;
8809 c->u.a.message = NULL;
8810 c->u.a.pending = NULL;
8811 c->u.a.outstanding_requests = 0;
8814 error = "Unsupported channel type requested";
8817 c->remoteid = remid;
8818 c->halfopen = FALSE;
8820 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
8821 ssh2_pkt_adduint32(pktout, c->remoteid);
8822 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
8823 ssh2_pkt_addstring(pktout, error);
8824 ssh2_pkt_addstring(pktout, "en"); /* language tag */
8825 ssh2_pkt_send(ssh, pktout);
8826 logeventf(ssh, "Rejected channel open: %s", error);
8829 ssh_channel_init(c);
8830 c->v.v2.remwindow = winsize;
8831 c->v.v2.remmaxpkt = pktsize;
8832 if (our_winsize_override) {
8833 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
8834 our_winsize_override;
8836 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
8837 ssh2_pkt_adduint32(pktout, c->remoteid);
8838 ssh2_pkt_adduint32(pktout, c->localid);
8839 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
8840 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
8841 ssh2_pkt_send(ssh, pktout);
8845 void sshfwd_x11_sharing_handover(struct ssh_channel *c,
8846 void *share_cs, void *share_chan,
8847 const char *peer_addr, int peer_port,
8848 int endian, int protomajor, int protominor,
8849 const void *initial_data, int initial_len)
8852 * This function is called when we've just discovered that an X
8853 * forwarding channel on which we'd been handling the initial auth
8854 * ourselves turns out to be destined for a connection-sharing
8855 * downstream. So we turn the channel into a CHAN_SHARING, meaning
8856 * that we completely stop tracking windows and buffering data and
8857 * just pass more or less unmodified SSH messages back and forth.
8859 c->type = CHAN_SHARING;
8860 c->u.sharing.ctx = share_cs;
8861 share_setup_x11_channel(share_cs, share_chan,
8862 c->localid, c->remoteid, c->v.v2.remwindow,
8863 c->v.v2.remmaxpkt, c->v.v2.locwindow,
8864 peer_addr, peer_port, endian,
8865 protomajor, protominor,
8866 initial_data, initial_len);
8869 void sshfwd_x11_is_local(struct ssh_channel *c)
8872 * This function is called when we've just discovered that an X
8873 * forwarding channel is _not_ destined for a connection-sharing
8874 * downstream but we're going to handle it ourselves. We stop
8875 * presenting a cautiously small window and go into ordinary data
8878 c->u.x11.initial = FALSE;
8879 ssh2_set_window(c, ssh_is_simple(c->ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE);
8883 * Buffer banner messages for later display at some convenient point,
8884 * if we're going to display them.
8886 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
8888 /* Arbitrary limit to prevent unbounded inflation of buffer */
8889 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
8890 bufchain_size(&ssh->banner) <= 131072) {
8891 char *banner = NULL;
8893 ssh_pkt_getstring(pktin, &banner, &size);
8895 bufchain_add(&ssh->banner, banner, size);
8899 /* Helper function to deal with sending tty modes for "pty-req" */
8900 static void ssh2_send_ttymode(void *data,
8901 const struct ssh_ttymode *mode, char *val)
8903 struct Packet *pktout = (struct Packet *)data;
8904 unsigned int arg = 0;
8906 switch (mode->type) {
8908 arg = ssh_tty_parse_specchar(val);
8911 arg = ssh_tty_parse_boolean(val);
8914 ssh2_pkt_addbyte(pktout, mode->opcode);
8915 ssh2_pkt_adduint32(pktout, arg);
8918 static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
8921 struct ssh2_setup_x11_state {
8925 struct Packet *pktout;
8926 crStateP(ssh2_setup_x11_state, ctx);
8930 logevent("Requesting X11 forwarding");
8931 pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
8933 ssh2_pkt_addbool(pktout, 0); /* many connections */
8934 ssh2_pkt_addstring(pktout, ssh->x11auth->protoname);
8935 ssh2_pkt_addstring(pktout, ssh->x11auth->datastring);
8936 ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
8937 ssh2_pkt_send(ssh, pktout);
8939 /* Wait to be called back with either a response packet, or NULL
8940 * meaning clean up and free our data */
8944 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8945 logevent("X11 forwarding enabled");
8946 ssh->X11_fwd_enabled = TRUE;
8948 logevent("X11 forwarding refused");
8954 static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
8957 struct ssh2_setup_agent_state {
8961 struct Packet *pktout;
8962 crStateP(ssh2_setup_agent_state, ctx);
8966 logevent("Requesting OpenSSH-style agent forwarding");
8967 pktout = ssh2_chanreq_init(ssh->mainchan, "auth-agent-req@openssh.com",
8968 ssh2_setup_agent, s);
8969 ssh2_pkt_send(ssh, pktout);
8971 /* Wait to be called back with either a response packet, or NULL
8972 * meaning clean up and free our data */
8976 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8977 logevent("Agent forwarding enabled");
8978 ssh->agentfwd_enabled = TRUE;
8980 logevent("Agent forwarding refused");
8986 static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
8989 struct ssh2_setup_pty_state {
8993 struct Packet *pktout;
8994 crStateP(ssh2_setup_pty_state, ctx);
8998 /* Unpick the terminal-speed string. */
8999 /* XXX perhaps we should allow no speeds to be sent. */
9000 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
9001 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
9002 /* Build the pty request. */
9003 pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
9005 ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
9006 ssh2_pkt_adduint32(pktout, ssh->term_width);
9007 ssh2_pkt_adduint32(pktout, ssh->term_height);
9008 ssh2_pkt_adduint32(pktout, 0); /* pixel width */
9009 ssh2_pkt_adduint32(pktout, 0); /* pixel height */
9010 ssh2_pkt_addstring_start(pktout);
9011 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
9012 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
9013 ssh2_pkt_adduint32(pktout, ssh->ispeed);
9014 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
9015 ssh2_pkt_adduint32(pktout, ssh->ospeed);
9016 ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
9017 ssh2_pkt_send(ssh, pktout);
9018 ssh->state = SSH_STATE_INTERMED;
9020 /* Wait to be called back with either a response packet, or NULL
9021 * meaning clean up and free our data */
9025 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
9026 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
9027 ssh->ospeed, ssh->ispeed);
9028 ssh->got_pty = TRUE;
9030 c_write_str(ssh, "Server refused to allocate pty\r\n");
9031 ssh->editing = ssh->echoing = 1;
9038 static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
9041 struct ssh2_setup_env_state {
9043 int num_env, env_left, env_ok;
9046 struct Packet *pktout;
9047 crStateP(ssh2_setup_env_state, ctx);
9052 * Send environment variables.
9054 * Simplest thing here is to send all the requests at once, and
9055 * then wait for a whole bunch of successes or failures.
9061 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
9063 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
9064 pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
9065 ssh2_pkt_addstring(pktout, key);
9066 ssh2_pkt_addstring(pktout, val);
9067 ssh2_pkt_send(ssh, pktout);
9072 logeventf(ssh, "Sent %d environment variables", s->num_env);
9077 s->env_left = s->num_env;
9079 while (s->env_left > 0) {
9080 /* Wait to be called back with either a response packet,
9081 * or NULL meaning clean up and free our data */
9083 if (!pktin) goto out;
9084 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
9089 if (s->env_ok == s->num_env) {
9090 logevent("All environment variables successfully set");
9091 } else if (s->env_ok == 0) {
9092 logevent("All environment variables refused");
9093 c_write_str(ssh, "Server refused to set environment variables\r\n");
9095 logeventf(ssh, "%d environment variables refused",
9096 s->num_env - s->env_ok);
9097 c_write_str(ssh, "Server refused to set all environment variables\r\n");
9105 * Handle the SSH-2 userauth and connection layers.
9107 static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
9109 do_ssh2_authconn(ssh, NULL, 0, pktin);
9112 static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
9116 do_ssh2_authconn(c->ssh, NULL, 0, pktin);
9119 static void do_ssh2_authconn(Ssh ssh, const unsigned char *in, int inlen,
9120 struct Packet *pktin)
9122 struct do_ssh2_authconn_state {
9126 AUTH_TYPE_PUBLICKEY,
9127 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
9128 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
9130 AUTH_TYPE_GSSAPI, /* always QUIET */
9131 AUTH_TYPE_KEYBOARD_INTERACTIVE,
9132 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
9134 int done_service_req;
9135 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
9136 int tried_pubkey_config, done_agent;
9141 int kbd_inter_refused;
9142 int we_are_in, userauth_success;
9143 prompts_t *cur_prompt;
9148 void *publickey_blob;
9149 int publickey_bloblen;
9150 int privatekey_available, privatekey_encrypted;
9151 char *publickey_algorithm;
9152 char *publickey_comment;
9153 unsigned char agent_request[5], *agent_response, *agentp;
9154 int agent_responselen;
9155 unsigned char *pkblob_in_agent;
9157 char *pkblob, *alg, *commentp;
9158 int pklen, alglen, commentlen;
9159 int siglen, retlen, len;
9160 char *q, *agentreq, *ret;
9161 struct Packet *pktout;
9164 struct ssh_gss_library *gsslib;
9165 Ssh_gss_ctx gss_ctx;
9166 Ssh_gss_buf gss_buf;
9167 Ssh_gss_buf gss_rcvtok, gss_sndtok;
9168 Ssh_gss_name gss_srv_name;
9169 Ssh_gss_stat gss_stat;
9172 crState(do_ssh2_authconn_state);
9176 /* Register as a handler for all the messages this coroutine handles. */
9177 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
9178 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
9179 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
9180 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
9181 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
9182 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
9183 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
9184 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
9185 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
9186 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
9187 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
9188 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
9189 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
9190 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
9191 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
9192 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
9193 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
9194 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
9195 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
9196 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
9198 s->done_service_req = FALSE;
9199 s->we_are_in = s->userauth_success = FALSE;
9200 s->agent_response = NULL;
9202 s->tried_gssapi = FALSE;
9205 if (!ssh->bare_connection) {
9206 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
9208 * Request userauth protocol, and await a response to it.
9210 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
9211 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
9212 ssh2_pkt_send(ssh, s->pktout);
9213 crWaitUntilV(pktin);
9214 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
9215 s->done_service_req = TRUE;
9217 if (!s->done_service_req) {
9219 * Request connection protocol directly, without authentication.
9221 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
9222 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9223 ssh2_pkt_send(ssh, s->pktout);
9224 crWaitUntilV(pktin);
9225 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
9226 s->we_are_in = TRUE; /* no auth required */
9228 bombout(("Server refused service request"));
9233 s->we_are_in = TRUE;
9236 /* Arrange to be able to deal with any BANNERs that come in.
9237 * (We do this now as packets may come in during the next bit.) */
9238 bufchain_init(&ssh->banner);
9239 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
9240 ssh2_msg_userauth_banner;
9243 * Misc one-time setup for authentication.
9245 s->publickey_blob = NULL;
9246 if (!s->we_are_in) {
9249 * Load the public half of any configured public key file
9252 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9253 if (!filename_is_null(s->keyfile)) {
9255 logeventf(ssh, "Reading key file \"%.150s\"",
9256 filename_to_str(s->keyfile));
9257 keytype = key_type(s->keyfile);
9258 if (keytype == SSH_KEYTYPE_SSH2 ||
9259 keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 ||
9260 keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
9263 ssh2_userkey_loadpub(s->keyfile,
9264 &s->publickey_algorithm,
9265 &s->publickey_bloblen,
9266 &s->publickey_comment, &error);
9267 if (s->publickey_blob) {
9268 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH2);
9269 if (!s->privatekey_available)
9270 logeventf(ssh, "Key file contains public key only");
9271 s->privatekey_encrypted =
9272 ssh2_userkey_encrypted(s->keyfile, NULL);
9275 logeventf(ssh, "Unable to load key (%s)",
9277 msgbuf = dupprintf("Unable to load key file "
9278 "\"%.150s\" (%s)\r\n",
9279 filename_to_str(s->keyfile),
9281 c_write_str(ssh, msgbuf);
9286 logeventf(ssh, "Unable to use this key file (%s)",
9287 key_type_to_str(keytype));
9288 msgbuf = dupprintf("Unable to use key file \"%.150s\""
9290 filename_to_str(s->keyfile),
9291 key_type_to_str(keytype));
9292 c_write_str(ssh, msgbuf);
9294 s->publickey_blob = NULL;
9299 * Find out about any keys Pageant has (but if there's a
9300 * public key configured, filter out all others).
9303 s->agent_response = NULL;
9304 s->pkblob_in_agent = NULL;
9305 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
9309 logevent("Pageant is running. Requesting keys.");
9311 /* Request the keys held by the agent. */
9312 PUT_32BIT(s->agent_request, 1);
9313 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
9314 ssh->auth_agent_query = agent_query(
9315 s->agent_request, 5, &r, &s->agent_responselen,
9316 ssh_agent_callback, ssh);
9317 if (ssh->auth_agent_query) {
9321 bombout(("Unexpected data from server while"
9322 " waiting for agent response"));
9325 } while (pktin || inlen > 0);
9326 r = ssh->agent_response;
9327 s->agent_responselen = ssh->agent_response_len;
9329 s->agent_response = (unsigned char *) r;
9330 if (s->agent_response && s->agent_responselen >= 5 &&
9331 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
9334 p = s->agent_response + 5;
9335 s->nkeys = toint(GET_32BIT(p));
9338 * Vet the Pageant response to ensure that the key
9339 * count and blob lengths make sense.
9342 logeventf(ssh, "Pageant response contained a negative"
9343 " key count %d", s->nkeys);
9345 goto done_agent_query;
9347 unsigned char *q = p + 4;
9348 int lenleft = s->agent_responselen - 5 - 4;
9350 for (keyi = 0; keyi < s->nkeys; keyi++) {
9351 int bloblen, commentlen;
9353 logeventf(ssh, "Pageant response was truncated");
9355 goto done_agent_query;
9357 bloblen = toint(GET_32BIT(q));
9358 if (bloblen < 0 || bloblen > lenleft) {
9359 logeventf(ssh, "Pageant response was truncated");
9361 goto done_agent_query;
9363 lenleft -= 4 + bloblen;
9365 commentlen = toint(GET_32BIT(q));
9366 if (commentlen < 0 || commentlen > lenleft) {
9367 logeventf(ssh, "Pageant response was truncated");
9369 goto done_agent_query;
9371 lenleft -= 4 + commentlen;
9372 q += 4 + commentlen;
9377 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
9378 if (s->publickey_blob) {
9379 /* See if configured key is in agent. */
9380 for (keyi = 0; keyi < s->nkeys; keyi++) {
9381 s->pklen = toint(GET_32BIT(p));
9382 if (s->pklen == s->publickey_bloblen &&
9383 !memcmp(p+4, s->publickey_blob,
9384 s->publickey_bloblen)) {
9385 logeventf(ssh, "Pageant key #%d matches "
9386 "configured key file", keyi);
9388 s->pkblob_in_agent = p;
9392 p += toint(GET_32BIT(p)) + 4; /* comment */
9394 if (!s->pkblob_in_agent) {
9395 logevent("Configured key file not in Pageant");
9400 logevent("Failed to get reply from Pageant");
9408 * We repeat this whole loop, including the username prompt,
9409 * until we manage a successful authentication. If the user
9410 * types the wrong _password_, they can be sent back to the
9411 * beginning to try another username, if this is configured on.
9412 * (If they specify a username in the config, they are never
9413 * asked, even if they do give a wrong password.)
9415 * I think this best serves the needs of
9417 * - the people who have no configuration, no keys, and just
9418 * want to try repeated (username,password) pairs until they
9419 * type both correctly
9421 * - people who have keys and configuration but occasionally
9422 * need to fall back to passwords
9424 * - people with a key held in Pageant, who might not have
9425 * logged in to a particular machine before; so they want to
9426 * type a username, and then _either_ their key will be
9427 * accepted, _or_ they will type a password. If they mistype
9428 * the username they will want to be able to get back and
9431 s->got_username = FALSE;
9432 while (!s->we_are_in) {
9436 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
9438 * We got a username last time round this loop, and
9439 * with change_username turned off we don't try to get
9442 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
9443 int ret; /* need not be kept over crReturn */
9444 s->cur_prompt = new_prompts(ssh->frontend);
9445 s->cur_prompt->to_server = TRUE;
9446 s->cur_prompt->name = dupstr("SSH login name");
9447 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
9448 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9451 crWaitUntilV(!pktin);
9452 ret = get_userpass_input(s->cur_prompt, in, inlen);
9457 * get_userpass_input() failed to get a username.
9460 free_prompts(s->cur_prompt);
9461 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
9464 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
9465 free_prompts(s->cur_prompt);
9468 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
9469 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
9470 c_write_str(ssh, stuff);
9474 s->got_username = TRUE;
9477 * Send an authentication request using method "none": (a)
9478 * just in case it succeeds, and (b) so that we know what
9479 * authentication methods we can usefully try next.
9481 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9483 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9484 ssh2_pkt_addstring(s->pktout, ssh->username);
9485 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
9486 ssh2_pkt_addstring(s->pktout, "none"); /* method */
9487 ssh2_pkt_send(ssh, s->pktout);
9488 s->type = AUTH_TYPE_NONE;
9490 s->we_are_in = FALSE;
9492 s->tried_pubkey_config = FALSE;
9493 s->kbd_inter_refused = FALSE;
9495 /* Reset agent request state. */
9496 s->done_agent = FALSE;
9497 if (s->agent_response) {
9498 if (s->pkblob_in_agent) {
9499 s->agentp = s->pkblob_in_agent;
9501 s->agentp = s->agent_response + 5 + 4;
9507 char *methods = NULL;
9511 * Wait for the result of the last authentication request.
9514 crWaitUntilV(pktin);
9516 * Now is a convenient point to spew any banner material
9517 * that we've accumulated. (This should ensure that when
9518 * we exit the auth loop, we haven't any left to deal
9522 int size = bufchain_size(&ssh->banner);
9524 * Don't show the banner if we're operating in
9525 * non-verbose non-interactive mode. (It's probably
9526 * a script, which means nobody will read the
9527 * banner _anyway_, and moreover the printing of
9528 * the banner will screw up processing on the
9529 * output of (say) plink.)
9531 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
9532 char *banner = snewn(size, char);
9533 bufchain_fetch(&ssh->banner, banner, size);
9534 c_write_untrusted(ssh, banner, size);
9537 bufchain_clear(&ssh->banner);
9539 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
9540 logevent("Access granted");
9541 s->we_are_in = s->userauth_success = TRUE;
9545 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
9546 bombout(("Strange packet received during authentication: "
9547 "type %d", pktin->type));
9554 * OK, we're now sitting on a USERAUTH_FAILURE message, so
9555 * we can look at the string in it and know what we can
9556 * helpfully try next.
9558 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
9559 ssh_pkt_getstring(pktin, &methods, &methlen);
9560 if (!ssh2_pkt_getbool(pktin)) {
9562 * We have received an unequivocal Access
9563 * Denied. This can translate to a variety of
9564 * messages, or no message at all.
9566 * For forms of authentication which are attempted
9567 * implicitly, by which I mean without printing
9568 * anything in the window indicating that we're
9569 * trying them, we should never print 'Access
9572 * If we do print a message saying that we're
9573 * attempting some kind of authentication, it's OK
9574 * to print a followup message saying it failed -
9575 * but the message may sometimes be more specific
9576 * than simply 'Access denied'.
9578 * Additionally, if we'd just tried password
9579 * authentication, we should break out of this
9580 * whole loop so as to go back to the username
9581 * prompt (iff we're configured to allow
9582 * username change attempts).
9584 if (s->type == AUTH_TYPE_NONE) {
9586 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
9587 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
9588 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
9589 c_write_str(ssh, "Server refused our key\r\n");
9590 logevent("Server refused our key");
9591 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
9592 /* This _shouldn't_ happen except by a
9593 * protocol bug causing client and server to
9594 * disagree on what is a correct signature. */
9595 c_write_str(ssh, "Server refused public-key signature"
9596 " despite accepting key!\r\n");
9597 logevent("Server refused public-key signature"
9598 " despite accepting key!");
9599 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
9600 /* quiet, so no c_write */
9601 logevent("Server refused keyboard-interactive authentication");
9602 } else if (s->type==AUTH_TYPE_GSSAPI) {
9603 /* always quiet, so no c_write */
9604 /* also, the code down in the GSSAPI block has
9605 * already logged this in the Event Log */
9606 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
9607 logevent("Keyboard-interactive authentication failed");
9608 c_write_str(ssh, "Access denied\r\n");
9610 assert(s->type == AUTH_TYPE_PASSWORD);
9611 logevent("Password authentication failed");
9612 c_write_str(ssh, "Access denied\r\n");
9614 if (conf_get_int(ssh->conf, CONF_change_username)) {
9615 /* XXX perhaps we should allow
9616 * keyboard-interactive to do this too? */
9617 s->we_are_in = FALSE;
9622 c_write_str(ssh, "Further authentication required\r\n");
9623 logevent("Further authentication required");
9627 in_commasep_string("publickey", methods, methlen);
9629 in_commasep_string("password", methods, methlen);
9630 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
9631 in_commasep_string("keyboard-interactive", methods, methlen);
9633 if (conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
9634 in_commasep_string("gssapi-with-mic", methods, methlen)) {
9635 /* Try loading the GSS libraries and see if we
9638 ssh->gsslibs = ssh_gss_setup(ssh->conf);
9639 s->can_gssapi = (ssh->gsslibs->nlibraries > 0);
9641 /* No point in even bothering to try to load the
9642 * GSS libraries, if the user configuration and
9643 * server aren't both prepared to attempt GSSAPI
9644 * auth in the first place. */
9645 s->can_gssapi = FALSE;
9650 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9652 if (s->can_pubkey && !s->done_agent && s->nkeys) {
9655 * Attempt public-key authentication using a key from Pageant.
9658 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9660 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
9662 /* Unpack key from agent response */
9663 s->pklen = toint(GET_32BIT(s->agentp));
9665 s->pkblob = (char *)s->agentp;
9666 s->agentp += s->pklen;
9667 s->alglen = toint(GET_32BIT(s->pkblob));
9668 s->alg = s->pkblob + 4;
9669 s->commentlen = toint(GET_32BIT(s->agentp));
9671 s->commentp = (char *)s->agentp;
9672 s->agentp += s->commentlen;
9673 /* s->agentp now points at next key, if any */
9675 /* See if server will accept it */
9676 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9677 ssh2_pkt_addstring(s->pktout, ssh->username);
9678 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9679 /* service requested */
9680 ssh2_pkt_addstring(s->pktout, "publickey");
9682 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
9683 ssh2_pkt_addstring_start(s->pktout);
9684 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9685 ssh2_pkt_addstring_start(s->pktout);
9686 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9687 ssh2_pkt_send(ssh, s->pktout);
9688 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
9690 crWaitUntilV(pktin);
9691 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9693 /* Offer of key refused. */
9700 if (flags & FLAG_VERBOSE) {
9701 c_write_str(ssh, "Authenticating with "
9703 c_write(ssh, s->commentp, s->commentlen);
9704 c_write_str(ssh, "\" from agent\r\n");
9708 * Server is willing to accept the key.
9709 * Construct a SIGN_REQUEST.
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, TRUE); /* 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);
9723 /* Ask agent for signature. */
9724 s->siglen = s->pktout->length - 5 + 4 +
9725 ssh->v2_session_id_len;
9726 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9728 s->len = 1; /* message type */
9729 s->len += 4 + s->pklen; /* key blob */
9730 s->len += 4 + s->siglen; /* data to sign */
9731 s->len += 4; /* flags */
9732 s->agentreq = snewn(4 + s->len, char);
9733 PUT_32BIT(s->agentreq, s->len);
9734 s->q = s->agentreq + 4;
9735 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
9736 PUT_32BIT(s->q, s->pklen);
9738 memcpy(s->q, s->pkblob, s->pklen);
9740 PUT_32BIT(s->q, s->siglen);
9742 /* Now the data to be signed... */
9743 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9744 PUT_32BIT(s->q, ssh->v2_session_id_len);
9747 memcpy(s->q, ssh->v2_session_id,
9748 ssh->v2_session_id_len);
9749 s->q += ssh->v2_session_id_len;
9750 memcpy(s->q, s->pktout->data + 5,
9751 s->pktout->length - 5);
9752 s->q += s->pktout->length - 5;
9753 /* And finally the (zero) flags word. */
9755 ssh->auth_agent_query = agent_query(
9756 s->agentreq, s->len + 4, &vret, &s->retlen,
9757 ssh_agent_callback, ssh);
9758 if (ssh->auth_agent_query) {
9762 bombout(("Unexpected data from server"
9763 " while waiting for agent"
9767 } while (pktin || inlen > 0);
9768 vret = ssh->agent_response;
9769 s->retlen = ssh->agent_response_len;
9774 if (s->retlen >= 9 &&
9775 s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
9776 GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
9777 logevent("Sending Pageant's response");
9778 ssh2_add_sigblob(ssh, s->pktout,
9779 s->pkblob, s->pklen,
9781 GET_32BIT(s->ret + 5));
9782 ssh2_pkt_send(ssh, s->pktout);
9783 s->type = AUTH_TYPE_PUBLICKEY;
9785 /* FIXME: less drastic response */
9786 bombout(("Pageant failed to answer challenge"));
9792 /* Do we have any keys left to try? */
9793 if (s->pkblob_in_agent) {
9794 s->done_agent = TRUE;
9795 s->tried_pubkey_config = TRUE;
9798 if (s->keyi >= s->nkeys)
9799 s->done_agent = TRUE;
9802 } else if (s->can_pubkey && s->publickey_blob &&
9803 s->privatekey_available && !s->tried_pubkey_config) {
9805 struct ssh2_userkey *key; /* not live over crReturn */
9806 char *passphrase; /* not live over crReturn */
9808 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9810 s->tried_pubkey_config = TRUE;
9813 * Try the public key supplied in the configuration.
9815 * First, offer the public blob to see if the server is
9816 * willing to accept it.
9818 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9819 ssh2_pkt_addstring(s->pktout, ssh->username);
9820 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9821 /* service requested */
9822 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
9823 ssh2_pkt_addbool(s->pktout, FALSE);
9824 /* no signature included */
9825 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
9826 ssh2_pkt_addstring_start(s->pktout);
9827 ssh2_pkt_addstring_data(s->pktout,
9828 (char *)s->publickey_blob,
9829 s->publickey_bloblen);
9830 ssh2_pkt_send(ssh, s->pktout);
9831 logevent("Offered public key");
9833 crWaitUntilV(pktin);
9834 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9835 /* Key refused. Give up. */
9836 s->gotit = TRUE; /* reconsider message next loop */
9837 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
9838 continue; /* process this new message */
9840 logevent("Offer of public key accepted");
9843 * Actually attempt a serious authentication using
9846 if (flags & FLAG_VERBOSE) {
9847 c_write_str(ssh, "Authenticating with public key \"");
9848 c_write_str(ssh, s->publickey_comment);
9849 c_write_str(ssh, "\"\r\n");
9853 const char *error; /* not live over crReturn */
9854 if (s->privatekey_encrypted) {
9856 * Get a passphrase from the user.
9858 int ret; /* need not be kept over crReturn */
9859 s->cur_prompt = new_prompts(ssh->frontend);
9860 s->cur_prompt->to_server = FALSE;
9861 s->cur_prompt->name = dupstr("SSH key passphrase");
9862 add_prompt(s->cur_prompt,
9863 dupprintf("Passphrase for key \"%.100s\": ",
9864 s->publickey_comment),
9866 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9869 crWaitUntilV(!pktin);
9870 ret = get_userpass_input(s->cur_prompt,
9875 /* Failed to get a passphrase. Terminate. */
9876 free_prompts(s->cur_prompt);
9877 ssh_disconnect(ssh, NULL,
9878 "Unable to authenticate",
9879 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9884 dupstr(s->cur_prompt->prompts[0]->result);
9885 free_prompts(s->cur_prompt);
9887 passphrase = NULL; /* no passphrase needed */
9891 * Try decrypting the key.
9893 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9894 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
9896 /* burn the evidence */
9897 smemclr(passphrase, strlen(passphrase));
9900 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
9902 (key == SSH2_WRONG_PASSPHRASE)) {
9903 c_write_str(ssh, "Wrong passphrase\r\n");
9905 /* and loop again */
9907 c_write_str(ssh, "Unable to load private key (");
9908 c_write_str(ssh, error);
9909 c_write_str(ssh, ")\r\n");
9911 break; /* try something else */
9917 unsigned char *pkblob, *sigblob, *sigdata;
9918 int pkblob_len, sigblob_len, sigdata_len;
9922 * We have loaded the private key and the server
9923 * has announced that it's willing to accept it.
9924 * Hallelujah. Generate a signature and send it.
9926 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9927 ssh2_pkt_addstring(s->pktout, ssh->username);
9928 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9929 /* service requested */
9930 ssh2_pkt_addstring(s->pktout, "publickey");
9932 ssh2_pkt_addbool(s->pktout, TRUE);
9933 /* signature follows */
9934 ssh2_pkt_addstring(s->pktout, key->alg->name);
9935 pkblob = key->alg->public_blob(key->data,
9937 ssh2_pkt_addstring_start(s->pktout);
9938 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
9942 * The data to be signed is:
9946 * followed by everything so far placed in the
9949 sigdata_len = s->pktout->length - 5 + 4 +
9950 ssh->v2_session_id_len;
9951 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9953 sigdata = snewn(sigdata_len, unsigned char);
9955 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9956 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
9959 memcpy(sigdata+p, ssh->v2_session_id,
9960 ssh->v2_session_id_len);
9961 p += ssh->v2_session_id_len;
9962 memcpy(sigdata+p, s->pktout->data + 5,
9963 s->pktout->length - 5);
9964 p += s->pktout->length - 5;
9965 assert(p == sigdata_len);
9966 sigblob = key->alg->sign(key->data, (char *)sigdata,
9967 sigdata_len, &sigblob_len);
9968 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
9969 sigblob, sigblob_len);
9974 ssh2_pkt_send(ssh, s->pktout);
9975 logevent("Sent public key signature");
9976 s->type = AUTH_TYPE_PUBLICKEY;
9977 key->alg->freekey(key->data);
9978 sfree(key->comment);
9983 } else if (s->can_gssapi && !s->tried_gssapi) {
9985 /* GSSAPI Authentication */
9990 s->type = AUTH_TYPE_GSSAPI;
9991 s->tried_gssapi = TRUE;
9993 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
9996 * Pick the highest GSS library on the preference
10002 for (i = 0; i < ngsslibs; i++) {
10003 int want_id = conf_get_int_int(ssh->conf,
10004 CONF_ssh_gsslist, i);
10005 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
10006 if (ssh->gsslibs->libraries[j].id == want_id) {
10007 s->gsslib = &ssh->gsslibs->libraries[j];
10008 goto got_gsslib; /* double break */
10013 * We always expect to have found something in
10014 * the above loop: we only came here if there
10015 * was at least one viable GSS library, and the
10016 * preference list should always mention
10017 * everything and only change the order.
10022 if (s->gsslib->gsslogmsg)
10023 logevent(s->gsslib->gsslogmsg);
10025 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
10026 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10027 ssh2_pkt_addstring(s->pktout, ssh->username);
10028 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10029 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
10030 logevent("Attempting GSSAPI authentication");
10032 /* add mechanism info */
10033 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
10035 /* number of GSSAPI mechanisms */
10036 ssh2_pkt_adduint32(s->pktout,1);
10038 /* length of OID + 2 */
10039 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
10040 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
10042 /* length of OID */
10043 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
10045 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
10046 s->gss_buf.length);
10047 ssh2_pkt_send(ssh, s->pktout);
10048 crWaitUntilV(pktin);
10049 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
10050 logevent("GSSAPI authentication request refused");
10054 /* check returned packet ... */
10056 ssh_pkt_getstring(pktin, &data, &len);
10057 s->gss_rcvtok.value = data;
10058 s->gss_rcvtok.length = len;
10059 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
10060 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
10061 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
10062 memcmp((char *)s->gss_rcvtok.value + 2,
10063 s->gss_buf.value,s->gss_buf.length) ) {
10064 logevent("GSSAPI authentication - wrong response from server");
10068 /* now start running */
10069 s->gss_stat = s->gsslib->import_name(s->gsslib,
10072 if (s->gss_stat != SSH_GSS_OK) {
10073 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
10074 logevent("GSSAPI import name failed - Bad service name");
10076 logevent("GSSAPI import name failed");
10080 /* fetch TGT into GSS engine */
10081 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
10083 if (s->gss_stat != SSH_GSS_OK) {
10084 logevent("GSSAPI authentication failed to get credentials");
10085 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10089 /* initial tokens are empty */
10090 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
10091 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
10093 /* now enter the loop */
10095 s->gss_stat = s->gsslib->init_sec_context
10099 conf_get_int(ssh->conf, CONF_gssapifwd),
10103 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
10104 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
10105 logevent("GSSAPI authentication initialisation failed");
10107 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
10108 &s->gss_buf) == SSH_GSS_OK) {
10109 logevent(s->gss_buf.value);
10110 sfree(s->gss_buf.value);
10115 logevent("GSSAPI authentication initialised");
10117 /* Client and server now exchange tokens until GSSAPI
10118 * no longer says CONTINUE_NEEDED */
10120 if (s->gss_sndtok.length != 0) {
10121 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
10122 ssh_pkt_addstring_start(s->pktout);
10123 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
10124 ssh2_pkt_send(ssh, s->pktout);
10125 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
10128 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
10129 crWaitUntilV(pktin);
10130 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
10131 logevent("GSSAPI authentication - bad server response");
10132 s->gss_stat = SSH_GSS_FAILURE;
10135 ssh_pkt_getstring(pktin, &data, &len);
10136 s->gss_rcvtok.value = data;
10137 s->gss_rcvtok.length = len;
10139 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
10141 if (s->gss_stat != SSH_GSS_OK) {
10142 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10143 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
10146 logevent("GSSAPI authentication loop finished OK");
10148 /* Now send the MIC */
10150 s->pktout = ssh2_pkt_init(0);
10151 micoffset = s->pktout->length;
10152 ssh_pkt_addstring_start(s->pktout);
10153 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
10154 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
10155 ssh_pkt_addstring(s->pktout, ssh->username);
10156 ssh_pkt_addstring(s->pktout, "ssh-connection");
10157 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
10159 s->gss_buf.value = (char *)s->pktout->data + micoffset;
10160 s->gss_buf.length = s->pktout->length - micoffset;
10162 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
10163 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
10164 ssh_pkt_addstring_start(s->pktout);
10165 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
10166 ssh2_pkt_send(ssh, s->pktout);
10167 s->gsslib->free_mic(s->gsslib, &mic);
10171 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10172 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
10175 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
10178 * Keyboard-interactive authentication.
10181 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
10183 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
10185 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10186 ssh2_pkt_addstring(s->pktout, ssh->username);
10187 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10188 /* service requested */
10189 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
10191 ssh2_pkt_addstring(s->pktout, ""); /* lang */
10192 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
10193 ssh2_pkt_send(ssh, s->pktout);
10195 logevent("Attempting keyboard-interactive authentication");
10197 crWaitUntilV(pktin);
10198 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
10199 /* Server is not willing to do keyboard-interactive
10200 * at all (or, bizarrely but legally, accepts the
10201 * user without actually issuing any prompts).
10202 * Give up on it entirely. */
10204 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
10205 s->kbd_inter_refused = TRUE; /* don't try it again */
10210 * Loop while the server continues to send INFO_REQUESTs.
10212 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
10214 char *name, *inst, *lang;
10215 int name_len, inst_len, lang_len;
10219 * We've got a fresh USERAUTH_INFO_REQUEST.
10220 * Get the preamble and start building a prompt.
10222 ssh_pkt_getstring(pktin, &name, &name_len);
10223 ssh_pkt_getstring(pktin, &inst, &inst_len);
10224 ssh_pkt_getstring(pktin, &lang, &lang_len);
10225 s->cur_prompt = new_prompts(ssh->frontend);
10226 s->cur_prompt->to_server = TRUE;
10229 * Get any prompt(s) from the packet.
10231 s->num_prompts = ssh_pkt_getuint32(pktin);
10232 for (i = 0; i < s->num_prompts; i++) {
10236 static char noprompt[] =
10237 "<server failed to send prompt>: ";
10239 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10240 echo = ssh2_pkt_getbool(pktin);
10243 prompt_len = lenof(noprompt)-1;
10245 add_prompt(s->cur_prompt,
10246 dupprintf("%.*s", prompt_len, prompt),
10251 /* FIXME: better prefix to distinguish from
10252 * local prompts? */
10253 s->cur_prompt->name =
10254 dupprintf("SSH server: %.*s", name_len, name);
10255 s->cur_prompt->name_reqd = TRUE;
10257 s->cur_prompt->name =
10258 dupstr("SSH server authentication");
10259 s->cur_prompt->name_reqd = FALSE;
10261 /* We add a prefix to try to make it clear that a prompt
10262 * has come from the server.
10263 * FIXME: ugly to print "Using..." in prompt _every_
10264 * time round. Can this be done more subtly? */
10265 /* Special case: for reasons best known to themselves,
10266 * some servers send k-i requests with no prompts and
10267 * nothing to display. Keep quiet in this case. */
10268 if (s->num_prompts || name_len || inst_len) {
10269 s->cur_prompt->instruction =
10270 dupprintf("Using keyboard-interactive authentication.%s%.*s",
10271 inst_len ? "\n" : "", inst_len, inst);
10272 s->cur_prompt->instr_reqd = TRUE;
10274 s->cur_prompt->instr_reqd = FALSE;
10278 * Display any instructions, and get the user's
10282 int ret; /* not live over crReturn */
10283 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10286 crWaitUntilV(!pktin);
10287 ret = get_userpass_input(s->cur_prompt, in, inlen);
10292 * Failed to get responses. Terminate.
10294 free_prompts(s->cur_prompt);
10295 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10296 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10303 * Send the response(s) to the server.
10305 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
10306 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
10307 for (i=0; i < s->num_prompts; i++) {
10308 ssh2_pkt_addstring(s->pktout,
10309 s->cur_prompt->prompts[i]->result);
10311 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10314 * Free the prompts structure from this iteration.
10315 * If there's another, a new one will be allocated
10316 * when we return to the top of this while loop.
10318 free_prompts(s->cur_prompt);
10321 * Get the next packet in case it's another
10324 crWaitUntilV(pktin);
10329 * We should have SUCCESS or FAILURE now.
10333 } else if (s->can_passwd) {
10336 * Plain old password authentication.
10338 int ret; /* not live over crReturn */
10339 int changereq_first_time; /* not live over crReturn */
10341 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
10343 s->cur_prompt = new_prompts(ssh->frontend);
10344 s->cur_prompt->to_server = TRUE;
10345 s->cur_prompt->name = dupstr("SSH password");
10346 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
10351 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10354 crWaitUntilV(!pktin);
10355 ret = get_userpass_input(s->cur_prompt, in, inlen);
10360 * Failed to get responses. Terminate.
10362 free_prompts(s->cur_prompt);
10363 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10364 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10369 * Squirrel away the password. (We may need it later if
10370 * asked to change it.)
10372 s->password = dupstr(s->cur_prompt->prompts[0]->result);
10373 free_prompts(s->cur_prompt);
10376 * Send the password packet.
10378 * We pad out the password packet to 256 bytes to make
10379 * it harder for an attacker to find the length of the
10382 * Anyone using a password longer than 256 bytes
10383 * probably doesn't have much to worry about from
10384 * people who find out how long their password is!
10386 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10387 ssh2_pkt_addstring(s->pktout, ssh->username);
10388 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10389 /* service requested */
10390 ssh2_pkt_addstring(s->pktout, "password");
10391 ssh2_pkt_addbool(s->pktout, FALSE);
10392 ssh2_pkt_addstring(s->pktout, s->password);
10393 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10394 logevent("Sent password");
10395 s->type = AUTH_TYPE_PASSWORD;
10398 * Wait for next packet, in case it's a password change
10401 crWaitUntilV(pktin);
10402 changereq_first_time = TRUE;
10404 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
10407 * We're being asked for a new password
10408 * (perhaps not for the first time).
10409 * Loop until the server accepts it.
10412 int got_new = FALSE; /* not live over crReturn */
10413 char *prompt; /* not live over crReturn */
10414 int prompt_len; /* not live over crReturn */
10418 if (changereq_first_time)
10419 msg = "Server requested password change";
10421 msg = "Server rejected new password";
10423 c_write_str(ssh, msg);
10424 c_write_str(ssh, "\r\n");
10427 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10429 s->cur_prompt = new_prompts(ssh->frontend);
10430 s->cur_prompt->to_server = TRUE;
10431 s->cur_prompt->name = dupstr("New SSH password");
10432 s->cur_prompt->instruction =
10433 dupprintf("%.*s", prompt_len, NULLTOEMPTY(prompt));
10434 s->cur_prompt->instr_reqd = TRUE;
10436 * There's no explicit requirement in the protocol
10437 * for the "old" passwords in the original and
10438 * password-change messages to be the same, and
10439 * apparently some Cisco kit supports password change
10440 * by the user entering a blank password originally
10441 * and the real password subsequently, so,
10442 * reluctantly, we prompt for the old password again.
10444 * (On the other hand, some servers don't even bother
10445 * to check this field.)
10447 add_prompt(s->cur_prompt,
10448 dupstr("Current password (blank for previously entered password): "),
10450 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
10452 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
10456 * Loop until the user manages to enter the same
10461 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10464 crWaitUntilV(!pktin);
10465 ret = get_userpass_input(s->cur_prompt, in, inlen);
10470 * Failed to get responses. Terminate.
10472 /* burn the evidence */
10473 free_prompts(s->cur_prompt);
10474 smemclr(s->password, strlen(s->password));
10475 sfree(s->password);
10476 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10477 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10483 * If the user specified a new original password
10484 * (IYSWIM), overwrite any previously specified
10486 * (A side effect is that the user doesn't have to
10487 * re-enter it if they louse up the new password.)
10489 if (s->cur_prompt->prompts[0]->result[0]) {
10490 smemclr(s->password, strlen(s->password));
10491 /* burn the evidence */
10492 sfree(s->password);
10494 dupstr(s->cur_prompt->prompts[0]->result);
10498 * Check the two new passwords match.
10500 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
10501 s->cur_prompt->prompts[2]->result)
10504 /* They don't. Silly user. */
10505 c_write_str(ssh, "Passwords do not match\r\n");
10510 * Send the new password (along with the old one).
10511 * (see above for padding rationale)
10513 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10514 ssh2_pkt_addstring(s->pktout, ssh->username);
10515 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10516 /* service requested */
10517 ssh2_pkt_addstring(s->pktout, "password");
10518 ssh2_pkt_addbool(s->pktout, TRUE);
10519 ssh2_pkt_addstring(s->pktout, s->password);
10520 ssh2_pkt_addstring(s->pktout,
10521 s->cur_prompt->prompts[1]->result);
10522 free_prompts(s->cur_prompt);
10523 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10524 logevent("Sent new password");
10527 * Now see what the server has to say about it.
10528 * (If it's CHANGEREQ again, it's not happy with the
10531 crWaitUntilV(pktin);
10532 changereq_first_time = FALSE;
10537 * We need to reexamine the current pktin at the top
10538 * of the loop. Either:
10539 * - we weren't asked to change password at all, in
10540 * which case it's a SUCCESS or FAILURE with the
10542 * - we sent a new password, and the server was
10543 * either OK with it (SUCCESS or FAILURE w/partial
10544 * success) or unhappy with the _old_ password
10545 * (FAILURE w/o partial success)
10546 * In any of these cases, we go back to the top of
10547 * the loop and start again.
10552 * We don't need the old password any more, in any
10553 * case. Burn the evidence.
10555 smemclr(s->password, strlen(s->password));
10556 sfree(s->password);
10559 char *str = dupprintf("No supported authentication methods available"
10560 " (server sent: %.*s)",
10563 ssh_disconnect(ssh, str,
10564 "No supported authentication methods available",
10565 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
10575 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
10577 /* Clear up various bits and pieces from authentication. */
10578 if (s->publickey_blob) {
10579 sfree(s->publickey_algorithm);
10580 sfree(s->publickey_blob);
10581 sfree(s->publickey_comment);
10583 if (s->agent_response)
10584 sfree(s->agent_response);
10586 if (s->userauth_success && !ssh->bare_connection) {
10588 * We've just received USERAUTH_SUCCESS, and we haven't sent any
10589 * packets since. Signal the transport layer to consider enacting
10590 * delayed compression.
10592 * (Relying on we_are_in is not sufficient, as
10593 * draft-miller-secsh-compression-delayed is quite clear that it
10594 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
10595 * become set for other reasons.)
10597 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
10600 ssh->channels = newtree234(ssh_channelcmp);
10603 * Set up handlers for some connection protocol messages, so we
10604 * don't have to handle them repeatedly in this coroutine.
10606 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
10607 ssh2_msg_channel_window_adjust;
10608 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
10609 ssh2_msg_global_request;
10612 * Create the main session channel.
10614 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
10615 ssh->mainchan = NULL;
10617 ssh->mainchan = snew(struct ssh_channel);
10618 ssh->mainchan->ssh = ssh;
10619 ssh_channel_init(ssh->mainchan);
10621 if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
10623 * Just start a direct-tcpip channel and use it as the main
10626 ssh_send_port_open(ssh->mainchan,
10627 conf_get_str(ssh->conf, CONF_ssh_nc_host),
10628 conf_get_int(ssh->conf, CONF_ssh_nc_port),
10630 ssh->ncmode = TRUE;
10632 s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
10633 logevent("Opening session as main channel");
10634 ssh2_pkt_send(ssh, s->pktout);
10635 ssh->ncmode = FALSE;
10637 crWaitUntilV(pktin);
10638 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
10639 bombout(("Server refused to open channel"));
10641 /* FIXME: error data comes back in FAILURE packet */
10643 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
10644 bombout(("Server's channel confirmation cited wrong channel"));
10647 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
10648 ssh->mainchan->halfopen = FALSE;
10649 ssh->mainchan->type = CHAN_MAINSESSION;
10650 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
10651 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
10652 update_specials_menu(ssh->frontend);
10653 logevent("Opened main channel");
10657 * Now we have a channel, make dispatch table entries for
10658 * general channel-based messages.
10660 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
10661 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
10662 ssh2_msg_channel_data;
10663 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
10664 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
10665 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
10666 ssh2_msg_channel_open_confirmation;
10667 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
10668 ssh2_msg_channel_open_failure;
10669 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
10670 ssh2_msg_channel_request;
10671 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
10672 ssh2_msg_channel_open;
10673 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
10674 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
10677 * Now the connection protocol is properly up and running, with
10678 * all those dispatch table entries, so it's safe to let
10679 * downstreams start trying to open extra channels through us.
10681 if (ssh->connshare)
10682 share_activate(ssh->connshare, ssh->v_s);
10684 if (ssh->mainchan && ssh_is_simple(ssh)) {
10686 * This message indicates to the server that we promise
10687 * not to try to run any other channel in parallel with
10688 * this one, so it's safe for it to advertise a very large
10689 * window and leave the flow control to TCP.
10691 s->pktout = ssh2_chanreq_init(ssh->mainchan,
10692 "simple@putty.projects.tartarus.org",
10694 ssh2_pkt_send(ssh, s->pktout);
10698 * Enable port forwardings.
10700 ssh_setup_portfwd(ssh, ssh->conf);
10702 if (ssh->mainchan && !ssh->ncmode) {
10704 * Send the CHANNEL_REQUESTS for the main session channel.
10705 * Each one is handled by its own little asynchronous
10709 /* Potentially enable X11 forwarding. */
10710 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
10712 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
10714 if (!ssh->x11disp) {
10715 /* FIXME: return an error message from x11_setup_display */
10716 logevent("X11 forwarding not enabled: unable to"
10717 " initialise X display");
10719 ssh->x11auth = x11_invent_fake_auth
10720 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
10721 ssh->x11auth->disp = ssh->x11disp;
10723 ssh2_setup_x11(ssh->mainchan, NULL, NULL);
10727 /* Potentially enable agent forwarding. */
10728 if (ssh_agent_forwarding_permitted(ssh))
10729 ssh2_setup_agent(ssh->mainchan, NULL, NULL);
10731 /* Now allocate a pty for the session. */
10732 if (!conf_get_int(ssh->conf, CONF_nopty))
10733 ssh2_setup_pty(ssh->mainchan, NULL, NULL);
10735 /* Send environment variables. */
10736 ssh2_setup_env(ssh->mainchan, NULL, NULL);
10739 * Start a shell or a remote command. We may have to attempt
10740 * this twice if the config data has provided a second choice
10747 if (ssh->fallback_cmd) {
10748 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
10749 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
10751 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
10752 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
10756 s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
10757 ssh2_response_authconn, NULL);
10758 ssh2_pkt_addstring(s->pktout, cmd);
10760 s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
10761 ssh2_response_authconn, NULL);
10762 ssh2_pkt_addstring(s->pktout, cmd);
10764 s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
10765 ssh2_response_authconn, NULL);
10767 ssh2_pkt_send(ssh, s->pktout);
10769 crWaitUntilV(pktin);
10771 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
10772 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
10773 bombout(("Unexpected response to shell/command request:"
10774 " packet type %d", pktin->type));
10778 * We failed to start the command. If this is the
10779 * fallback command, we really are finished; if it's
10780 * not, and if the fallback command exists, try falling
10781 * back to it before complaining.
10783 if (!ssh->fallback_cmd &&
10784 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
10785 logevent("Primary command failed; attempting fallback");
10786 ssh->fallback_cmd = TRUE;
10789 bombout(("Server refused to start a shell/command"));
10792 logevent("Started a shell/command");
10797 ssh->editing = ssh->echoing = TRUE;
10800 ssh->state = SSH_STATE_SESSION;
10801 if (ssh->size_needed)
10802 ssh_size(ssh, ssh->term_width, ssh->term_height);
10803 if (ssh->eof_needed)
10804 ssh_special(ssh, TS_EOF);
10810 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
10818 * _All_ the connection-layer packets we expect to
10819 * receive are now handled by the dispatch table.
10820 * Anything that reaches here must be bogus.
10823 bombout(("Strange packet received: type %d", pktin->type));
10825 } else if (ssh->mainchan) {
10827 * We have spare data. Add it to the channel buffer.
10829 ssh_send_channel_data(ssh->mainchan, (char *)in, inlen);
10837 * Handlers for SSH-2 messages that might arrive at any moment.
10839 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
10841 /* log reason code in disconnect message */
10843 int reason, msglen;
10845 reason = ssh_pkt_getuint32(pktin);
10846 ssh_pkt_getstring(pktin, &msg, &msglen);
10848 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
10849 buf = dupprintf("Received disconnect message (%s)",
10850 ssh2_disconnect_reasons[reason]);
10852 buf = dupprintf("Received disconnect message (unknown"
10853 " type %d)", reason);
10857 buf = dupprintf("Disconnection message text: %.*s",
10858 msglen, NULLTOEMPTY(msg));
10860 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
10862 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
10863 ssh2_disconnect_reasons[reason] : "unknown",
10864 msglen, NULLTOEMPTY(msg)));
10868 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
10870 /* log the debug message */
10874 /* XXX maybe we should actually take notice of the return value */
10875 ssh2_pkt_getbool(pktin);
10876 ssh_pkt_getstring(pktin, &msg, &msglen);
10878 logeventf(ssh, "Remote debug message: %.*s", msglen, NULLTOEMPTY(msg));
10881 static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
10883 do_ssh2_transport(ssh, NULL, 0, pktin);
10887 * Called if we receive a packet that isn't allowed by the protocol.
10888 * This only applies to packets whose meaning PuTTY understands.
10889 * Entirely unknown packets are handled below.
10891 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
10893 char *buf = dupprintf("Server protocol violation: unexpected %s packet",
10894 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
10896 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
10900 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
10902 struct Packet *pktout;
10903 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
10904 ssh2_pkt_adduint32(pktout, pktin->sequence);
10906 * UNIMPLEMENTED messages MUST appear in the same order as the
10907 * messages they respond to. Hence, never queue them.
10909 ssh2_pkt_send_noqueue(ssh, pktout);
10913 * Handle the top-level SSH-2 protocol.
10915 static void ssh2_protocol_setup(Ssh ssh)
10920 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10922 for (i = 0; i < 256; i++)
10923 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10926 * Initially, we only accept transport messages (and a few generic
10927 * ones). do_ssh2_authconn will add more when it starts.
10928 * Messages that are understood but not currently acceptable go to
10929 * ssh2_msg_unexpected.
10931 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10932 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
10933 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
10934 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
10935 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
10936 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
10937 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
10938 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
10939 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
10940 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
10941 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
10942 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
10943 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
10944 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
10945 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
10946 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
10947 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
10948 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
10949 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
10950 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10951 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10952 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10953 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10954 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10955 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10956 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10957 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10958 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10959 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10960 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10961 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10962 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10963 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10966 * These messages have a special handler from the start.
10968 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
10969 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
10970 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
10973 static void ssh2_bare_connection_protocol_setup(Ssh ssh)
10978 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10980 for (i = 0; i < 256; i++)
10981 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10984 * Initially, we set all ssh-connection messages to 'unexpected';
10985 * do_ssh2_authconn will fill things in properly. We also handle a
10986 * couple of messages from the transport protocol which aren't
10987 * related to key exchange (UNIMPLEMENTED, IGNORE, DEBUG,
10990 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10991 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10992 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10993 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10994 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10995 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10996 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10997 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10998 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10999 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
11000 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
11001 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
11002 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
11003 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
11005 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
11008 * These messages have a special handler from the start.
11010 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
11011 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore;
11012 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
11015 static void ssh2_timer(void *ctx, unsigned long now)
11017 Ssh ssh = (Ssh)ctx;
11019 if (ssh->state == SSH_STATE_CLOSED)
11022 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11023 conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
11024 now == ssh->next_rekey) {
11025 do_ssh2_transport(ssh, "timeout", -1, NULL);
11029 static void ssh2_protocol(Ssh ssh, const void *vin, int inlen,
11030 struct Packet *pktin)
11032 const unsigned char *in = (const unsigned char *)vin;
11033 if (ssh->state == SSH_STATE_CLOSED)
11037 ssh->incoming_data_size += pktin->encrypted_len;
11038 if (!ssh->kex_in_progress &&
11039 ssh->max_data_size != 0 &&
11040 ssh->incoming_data_size > ssh->max_data_size)
11041 do_ssh2_transport(ssh, "too much data received", -1, NULL);
11045 ssh->packet_dispatch[pktin->type](ssh, pktin);
11046 else if (!ssh->protocol_initial_phase_done)
11047 do_ssh2_transport(ssh, in, inlen, pktin);
11049 do_ssh2_authconn(ssh, in, inlen, pktin);
11052 static void ssh2_bare_connection_protocol(Ssh ssh, const void *vin, int inlen,
11053 struct Packet *pktin)
11055 const unsigned char *in = (const unsigned char *)vin;
11056 if (ssh->state == SSH_STATE_CLOSED)
11060 ssh->packet_dispatch[pktin->type](ssh, pktin);
11062 do_ssh2_authconn(ssh, in, inlen, pktin);
11065 static void ssh_cache_conf_values(Ssh ssh)
11067 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
11071 * Called to set up the connection.
11073 * Returns an error message, or NULL on success.
11075 static const char *ssh_init(void *frontend_handle, void **backend_handle,
11077 const char *host, int port, char **realhost,
11078 int nodelay, int keepalive)
11083 ssh = snew(struct ssh_tag);
11084 ssh->conf = conf_copy(conf);
11085 ssh_cache_conf_values(ssh);
11086 ssh->version = 0; /* when not ready yet */
11088 ssh->cipher = NULL;
11089 ssh->v1_cipher_ctx = NULL;
11090 ssh->crcda_ctx = NULL;
11091 ssh->cscipher = NULL;
11092 ssh->cs_cipher_ctx = NULL;
11093 ssh->sccipher = NULL;
11094 ssh->sc_cipher_ctx = NULL;
11096 ssh->cs_mac_ctx = NULL;
11098 ssh->sc_mac_ctx = NULL;
11099 ssh->cscomp = NULL;
11100 ssh->cs_comp_ctx = NULL;
11101 ssh->sccomp = NULL;
11102 ssh->sc_comp_ctx = NULL;
11104 ssh->kex_ctx = NULL;
11105 ssh->hostkey = NULL;
11106 ssh->hostkey_str = NULL;
11107 ssh->exitcode = -1;
11108 ssh->close_expected = FALSE;
11109 ssh->clean_exit = FALSE;
11110 ssh->state = SSH_STATE_PREPACKET;
11111 ssh->size_needed = FALSE;
11112 ssh->eof_needed = FALSE;
11114 ssh->logctx = NULL;
11115 ssh->deferred_send_data = NULL;
11116 ssh->deferred_len = 0;
11117 ssh->deferred_size = 0;
11118 ssh->fallback_cmd = 0;
11119 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
11120 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
11121 ssh->x11disp = NULL;
11122 ssh->x11auth = NULL;
11123 ssh->x11authtree = newtree234(x11_authcmp);
11124 ssh->v1_compressing = FALSE;
11125 ssh->v2_outgoing_sequence = 0;
11126 ssh->ssh1_rdpkt_crstate = 0;
11127 ssh->ssh2_rdpkt_crstate = 0;
11128 ssh->ssh2_bare_rdpkt_crstate = 0;
11129 ssh->ssh_gotdata_crstate = 0;
11130 ssh->do_ssh1_connection_crstate = 0;
11131 ssh->do_ssh_init_state = NULL;
11132 ssh->do_ssh_connection_init_state = NULL;
11133 ssh->do_ssh1_login_state = NULL;
11134 ssh->do_ssh2_transport_state = NULL;
11135 ssh->do_ssh2_authconn_state = NULL;
11138 ssh->mainchan = NULL;
11139 ssh->throttled_all = 0;
11140 ssh->v1_stdout_throttling = 0;
11142 ssh->queuelen = ssh->queuesize = 0;
11143 ssh->queueing = FALSE;
11144 ssh->qhead = ssh->qtail = NULL;
11145 ssh->deferred_rekey_reason = NULL;
11146 bufchain_init(&ssh->queued_incoming_data);
11147 ssh->frozen = FALSE;
11148 ssh->username = NULL;
11149 ssh->sent_console_eof = FALSE;
11150 ssh->got_pty = FALSE;
11151 ssh->bare_connection = FALSE;
11152 ssh->X11_fwd_enabled = FALSE;
11153 ssh->connshare = NULL;
11154 ssh->attempting_connshare = FALSE;
11155 ssh->session_started = FALSE;
11156 ssh->specials = NULL;
11157 ssh->n_uncert_hostkeys = 0;
11158 ssh->cross_certifying = FALSE;
11160 *backend_handle = ssh;
11163 if (crypto_startup() == 0)
11164 return "Microsoft high encryption pack not installed!";
11167 ssh->frontend = frontend_handle;
11168 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
11169 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
11171 ssh->channels = NULL;
11172 ssh->rportfwds = NULL;
11173 ssh->portfwds = NULL;
11178 ssh->conn_throttle_count = 0;
11179 ssh->overall_bufsize = 0;
11180 ssh->fallback_cmd = 0;
11182 ssh->protocol = NULL;
11184 ssh->protocol_initial_phase_done = FALSE;
11186 ssh->pinger = NULL;
11188 ssh->incoming_data_size = ssh->outgoing_data_size =
11189 ssh->deferred_data_size = 0L;
11190 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11191 CONF_ssh_rekey_data));
11192 ssh->kex_in_progress = FALSE;
11194 ssh->auth_agent_query = NULL;
11197 ssh->gsslibs = NULL;
11200 random_ref(); /* do this now - may be needed by sharing setup code */
11202 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
11211 static void ssh_free(void *handle)
11213 Ssh ssh = (Ssh) handle;
11214 struct ssh_channel *c;
11215 struct ssh_rportfwd *pf;
11216 struct X11FakeAuth *auth;
11218 if (ssh->v1_cipher_ctx)
11219 ssh->cipher->free_context(ssh->v1_cipher_ctx);
11220 if (ssh->cs_cipher_ctx)
11221 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
11222 if (ssh->sc_cipher_ctx)
11223 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
11224 if (ssh->cs_mac_ctx)
11225 ssh->csmac->free_context(ssh->cs_mac_ctx);
11226 if (ssh->sc_mac_ctx)
11227 ssh->scmac->free_context(ssh->sc_mac_ctx);
11228 if (ssh->cs_comp_ctx) {
11230 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
11232 zlib_compress_cleanup(ssh->cs_comp_ctx);
11234 if (ssh->sc_comp_ctx) {
11236 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
11238 zlib_decompress_cleanup(ssh->sc_comp_ctx);
11241 dh_cleanup(ssh->kex_ctx);
11242 sfree(ssh->savedhost);
11244 while (ssh->queuelen-- > 0)
11245 ssh_free_packet(ssh->queue[ssh->queuelen]);
11248 while (ssh->qhead) {
11249 struct queued_handler *qh = ssh->qhead;
11250 ssh->qhead = qh->next;
11253 ssh->qhead = ssh->qtail = NULL;
11255 if (ssh->channels) {
11256 while ((c = delpos234(ssh->channels, 0)) != NULL) {
11257 ssh_channel_close_local(c, NULL);
11258 if (ssh->version == 2) {
11259 struct outstanding_channel_request *ocr, *nocr;
11260 ocr = c->v.v2.chanreq_head;
11262 ocr->handler(c, NULL, ocr->ctx);
11267 bufchain_clear(&c->v.v2.outbuffer);
11271 freetree234(ssh->channels);
11272 ssh->channels = NULL;
11275 if (ssh->connshare)
11276 sharestate_free(ssh->connshare);
11278 if (ssh->rportfwds) {
11279 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
11281 freetree234(ssh->rportfwds);
11282 ssh->rportfwds = NULL;
11284 sfree(ssh->deferred_send_data);
11286 x11_free_display(ssh->x11disp);
11287 while ((auth = delpos234(ssh->x11authtree, 0)) != NULL)
11288 x11_free_fake_auth(auth);
11289 freetree234(ssh->x11authtree);
11290 sfree(ssh->do_ssh_init_state);
11291 sfree(ssh->do_ssh1_login_state);
11292 sfree(ssh->do_ssh2_transport_state);
11293 sfree(ssh->do_ssh2_authconn_state);
11296 sfree(ssh->fullhostname);
11297 sfree(ssh->hostkey_str);
11298 sfree(ssh->specials);
11299 if (ssh->crcda_ctx) {
11300 crcda_free_context(ssh->crcda_ctx);
11301 ssh->crcda_ctx = NULL;
11304 ssh_do_close(ssh, TRUE);
11305 expire_timer_context(ssh);
11307 pinger_free(ssh->pinger);
11308 bufchain_clear(&ssh->queued_incoming_data);
11309 sfree(ssh->username);
11310 conf_free(ssh->conf);
11312 if (ssh->auth_agent_query)
11313 agent_cancel_query(ssh->auth_agent_query);
11317 ssh_gss_cleanup(ssh->gsslibs);
11325 * Reconfigure the SSH backend.
11327 static void ssh_reconfig(void *handle, Conf *conf)
11329 Ssh ssh = (Ssh) handle;
11330 const char *rekeying = NULL;
11331 int rekey_mandatory = FALSE;
11332 unsigned long old_max_data_size;
11335 pinger_reconfig(ssh->pinger, ssh->conf, conf);
11337 ssh_setup_portfwd(ssh, conf);
11339 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
11340 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
11342 unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
11343 unsigned long now = GETTICKCOUNT();
11345 if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
11346 rekeying = "timeout shortened";
11348 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
11352 old_max_data_size = ssh->max_data_size;
11353 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11354 CONF_ssh_rekey_data));
11355 if (old_max_data_size != ssh->max_data_size &&
11356 ssh->max_data_size != 0) {
11357 if (ssh->outgoing_data_size > ssh->max_data_size ||
11358 ssh->incoming_data_size > ssh->max_data_size)
11359 rekeying = "data limit lowered";
11362 if (conf_get_int(ssh->conf, CONF_compression) !=
11363 conf_get_int(conf, CONF_compression)) {
11364 rekeying = "compression setting changed";
11365 rekey_mandatory = TRUE;
11368 for (i = 0; i < CIPHER_MAX; i++)
11369 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
11370 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
11371 rekeying = "cipher settings changed";
11372 rekey_mandatory = TRUE;
11374 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
11375 conf_get_int(conf, CONF_ssh2_des_cbc)) {
11376 rekeying = "cipher settings changed";
11377 rekey_mandatory = TRUE;
11380 conf_free(ssh->conf);
11381 ssh->conf = conf_copy(conf);
11382 ssh_cache_conf_values(ssh);
11384 if (!ssh->bare_connection && rekeying) {
11385 if (!ssh->kex_in_progress) {
11386 do_ssh2_transport(ssh, rekeying, -1, NULL);
11387 } else if (rekey_mandatory) {
11388 ssh->deferred_rekey_reason = rekeying;
11394 * Called to send data down the SSH connection.
11396 static int ssh_send(void *handle, const char *buf, int len)
11398 Ssh ssh = (Ssh) handle;
11400 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11403 ssh->protocol(ssh, (const unsigned char *)buf, len, 0);
11405 return ssh_sendbuffer(ssh);
11409 * Called to query the current amount of buffered stdin data.
11411 static int ssh_sendbuffer(void *handle)
11413 Ssh ssh = (Ssh) handle;
11414 int override_value;
11416 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11420 * If the SSH socket itself has backed up, add the total backup
11421 * size on that to any individual buffer on the stdin channel.
11423 override_value = 0;
11424 if (ssh->throttled_all)
11425 override_value = ssh->overall_bufsize;
11427 if (ssh->version == 1) {
11428 return override_value;
11429 } else if (ssh->version == 2) {
11430 if (!ssh->mainchan)
11431 return override_value;
11433 return (override_value +
11434 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
11441 * Called to set the size of the window from SSH's POV.
11443 static void ssh_size(void *handle, int width, int height)
11445 Ssh ssh = (Ssh) handle;
11446 struct Packet *pktout;
11448 ssh->term_width = width;
11449 ssh->term_height = height;
11451 switch (ssh->state) {
11452 case SSH_STATE_BEFORE_SIZE:
11453 case SSH_STATE_PREPACKET:
11454 case SSH_STATE_CLOSED:
11455 break; /* do nothing */
11456 case SSH_STATE_INTERMED:
11457 ssh->size_needed = TRUE; /* buffer for later */
11459 case SSH_STATE_SESSION:
11460 if (!conf_get_int(ssh->conf, CONF_nopty)) {
11461 if (ssh->version == 1) {
11462 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
11463 PKT_INT, ssh->term_height,
11464 PKT_INT, ssh->term_width,
11465 PKT_INT, 0, PKT_INT, 0, PKT_END);
11466 } else if (ssh->mainchan) {
11467 pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
11469 ssh2_pkt_adduint32(pktout, ssh->term_width);
11470 ssh2_pkt_adduint32(pktout, ssh->term_height);
11471 ssh2_pkt_adduint32(pktout, 0);
11472 ssh2_pkt_adduint32(pktout, 0);
11473 ssh2_pkt_send(ssh, pktout);
11481 * Return a list of the special codes that make sense in this
11484 static const struct telnet_special *ssh_get_specials(void *handle)
11486 static const struct telnet_special ssh1_ignore_special[] = {
11487 {"IGNORE message", TS_NOP}
11489 static const struct telnet_special ssh2_ignore_special[] = {
11490 {"IGNORE message", TS_NOP},
11492 static const struct telnet_special ssh2_rekey_special[] = {
11493 {"Repeat key exchange", TS_REKEY},
11495 static const struct telnet_special ssh2_session_specials[] = {
11498 /* These are the signal names defined by RFC 4254.
11499 * They include all the ISO C signals, but are a subset of the POSIX
11500 * required signals. */
11501 {"SIGINT (Interrupt)", TS_SIGINT},
11502 {"SIGTERM (Terminate)", TS_SIGTERM},
11503 {"SIGKILL (Kill)", TS_SIGKILL},
11504 {"SIGQUIT (Quit)", TS_SIGQUIT},
11505 {"SIGHUP (Hangup)", TS_SIGHUP},
11506 {"More signals", TS_SUBMENU},
11507 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
11508 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
11509 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
11510 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
11511 {NULL, TS_EXITMENU}
11513 static const struct telnet_special specials_end[] = {
11514 {NULL, TS_EXITMENU}
11517 struct telnet_special *specials = NULL;
11518 int nspecials = 0, specialsize = 0;
11520 Ssh ssh = (Ssh) handle;
11522 sfree(ssh->specials);
11524 #define ADD_SPECIALS(name) do \
11526 int len = lenof(name); \
11527 if (nspecials + len > specialsize) { \
11528 specialsize = (nspecials + len) * 5 / 4 + 32; \
11529 specials = sresize(specials, specialsize, struct telnet_special); \
11531 memcpy(specials+nspecials, name, len*sizeof(struct telnet_special)); \
11532 nspecials += len; \
11535 if (ssh->version == 1) {
11536 /* Don't bother offering IGNORE if we've decided the remote
11537 * won't cope with it, since we wouldn't bother sending it if
11539 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11540 ADD_SPECIALS(ssh1_ignore_special);
11541 } else if (ssh->version == 2) {
11542 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
11543 ADD_SPECIALS(ssh2_ignore_special);
11544 if (!(ssh->remote_bugs & BUG_SSH2_REKEY) && !ssh->bare_connection)
11545 ADD_SPECIALS(ssh2_rekey_special);
11547 ADD_SPECIALS(ssh2_session_specials);
11549 if (ssh->n_uncert_hostkeys) {
11550 static const struct telnet_special uncert_start[] = {
11552 {"Cache new host key type", TS_SUBMENU},
11554 static const struct telnet_special uncert_end[] = {
11555 {NULL, TS_EXITMENU},
11559 ADD_SPECIALS(uncert_start);
11560 for (i = 0; i < ssh->n_uncert_hostkeys; i++) {
11561 struct telnet_special uncert[1];
11562 const struct ssh_signkey *alg =
11563 hostkey_algs[ssh->uncert_hostkeys[i]].alg;
11564 uncert[0].name = alg->name;
11565 uncert[0].code = TS_LOCALSTART + ssh->uncert_hostkeys[i];
11566 ADD_SPECIALS(uncert);
11568 ADD_SPECIALS(uncert_end);
11570 } /* else we're not ready yet */
11573 ADD_SPECIALS(specials_end);
11575 ssh->specials = specials;
11582 #undef ADD_SPECIALS
11586 * Send special codes. TS_EOF is useful for `plink', so you
11587 * can send an EOF and collect resulting output (e.g. `plink
11590 static void ssh_special(void *handle, Telnet_Special code)
11592 Ssh ssh = (Ssh) handle;
11593 struct Packet *pktout;
11595 if (code == TS_EOF) {
11596 if (ssh->state != SSH_STATE_SESSION) {
11598 * Buffer the EOF in case we are pre-SESSION, so we can
11599 * send it as soon as we reach SESSION.
11601 if (code == TS_EOF)
11602 ssh->eof_needed = TRUE;
11605 if (ssh->version == 1) {
11606 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
11607 } else if (ssh->mainchan) {
11608 sshfwd_write_eof(ssh->mainchan);
11609 ssh->send_ok = 0; /* now stop trying to read from stdin */
11611 logevent("Sent EOF message");
11612 } else if (code == TS_PING || code == TS_NOP) {
11613 if (ssh->state == SSH_STATE_CLOSED
11614 || ssh->state == SSH_STATE_PREPACKET) return;
11615 if (ssh->version == 1) {
11616 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11617 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
11619 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
11620 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
11621 ssh2_pkt_addstring_start(pktout);
11622 ssh2_pkt_send_noqueue(ssh, pktout);
11625 } else if (code == TS_REKEY) {
11626 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11627 ssh->version == 2) {
11628 do_ssh2_transport(ssh, "at user request", -1, NULL);
11630 } else if (code >= TS_LOCALSTART) {
11631 ssh->hostkey = hostkey_algs[code - TS_LOCALSTART].alg;
11632 ssh->cross_certifying = TRUE;
11633 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11634 ssh->version == 2) {
11635 do_ssh2_transport(ssh, "cross-certifying new host key", -1, NULL);
11637 } else if (code == TS_BRK) {
11638 if (ssh->state == SSH_STATE_CLOSED
11639 || ssh->state == SSH_STATE_PREPACKET) return;
11640 if (ssh->version == 1) {
11641 logevent("Unable to send BREAK signal in SSH-1");
11642 } else if (ssh->mainchan) {
11643 pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
11644 ssh2_pkt_adduint32(pktout, 0); /* default break length */
11645 ssh2_pkt_send(ssh, pktout);
11648 /* Is is a POSIX signal? */
11649 const char *signame = NULL;
11650 if (code == TS_SIGABRT) signame = "ABRT";
11651 if (code == TS_SIGALRM) signame = "ALRM";
11652 if (code == TS_SIGFPE) signame = "FPE";
11653 if (code == TS_SIGHUP) signame = "HUP";
11654 if (code == TS_SIGILL) signame = "ILL";
11655 if (code == TS_SIGINT) signame = "INT";
11656 if (code == TS_SIGKILL) signame = "KILL";
11657 if (code == TS_SIGPIPE) signame = "PIPE";
11658 if (code == TS_SIGQUIT) signame = "QUIT";
11659 if (code == TS_SIGSEGV) signame = "SEGV";
11660 if (code == TS_SIGTERM) signame = "TERM";
11661 if (code == TS_SIGUSR1) signame = "USR1";
11662 if (code == TS_SIGUSR2) signame = "USR2";
11663 /* The SSH-2 protocol does in principle support arbitrary named
11664 * signals, including signame@domain, but we don't support those. */
11666 /* It's a signal. */
11667 if (ssh->version == 2 && ssh->mainchan) {
11668 pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
11669 ssh2_pkt_addstring(pktout, signame);
11670 ssh2_pkt_send(ssh, pktout);
11671 logeventf(ssh, "Sent signal SIG%s", signame);
11674 /* Never heard of it. Do nothing */
11679 void *new_sock_channel(void *handle, struct PortForwarding *pf)
11681 Ssh ssh = (Ssh) handle;
11682 struct ssh_channel *c;
11683 c = snew(struct ssh_channel);
11686 ssh_channel_init(c);
11687 c->halfopen = TRUE;
11688 c->type = CHAN_SOCKDATA;/* identify channel type */
11693 unsigned ssh_alloc_sharing_channel(Ssh ssh, void *sharing_ctx)
11695 struct ssh_channel *c;
11696 c = snew(struct ssh_channel);
11699 ssh_channel_init(c);
11700 c->type = CHAN_SHARING;
11701 c->u.sharing.ctx = sharing_ctx;
11705 void ssh_delete_sharing_channel(Ssh ssh, unsigned localid)
11707 struct ssh_channel *c;
11709 c = find234(ssh->channels, &localid, ssh_channelfind);
11711 ssh_channel_destroy(c);
11714 void ssh_send_packet_from_downstream(Ssh ssh, unsigned id, int type,
11715 const void *data, int datalen,
11716 const char *additional_log_text)
11718 struct Packet *pkt;
11720 pkt = ssh2_pkt_init(type);
11721 pkt->downstream_id = id;
11722 pkt->additional_log_text = additional_log_text;
11723 ssh2_pkt_adddata(pkt, data, datalen);
11724 ssh2_pkt_send(ssh, pkt);
11728 * This is called when stdout/stderr (the entity to which
11729 * from_backend sends data) manages to clear some backlog.
11731 static void ssh_unthrottle(void *handle, int bufsize)
11733 Ssh ssh = (Ssh) handle;
11735 if (ssh->version == 1) {
11736 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
11737 ssh->v1_stdout_throttling = 0;
11738 ssh_throttle_conn(ssh, -1);
11742 ssh_channel_unthrottle(ssh->mainchan, bufsize);
11746 * Now process any SSH connection data that was stashed in our
11747 * queue while we were frozen.
11749 ssh_process_queued_incoming_data(ssh);
11752 void ssh_send_port_open(void *channel, const char *hostname, int port,
11755 struct ssh_channel *c = (struct ssh_channel *)channel;
11757 struct Packet *pktout;
11759 logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
11761 if (ssh->version == 1) {
11762 send_packet(ssh, SSH1_MSG_PORT_OPEN,
11763 PKT_INT, c->localid,
11766 /* PKT_STR, <org:orgport>, */
11769 pktout = ssh2_chanopen_init(c, "direct-tcpip");
11771 char *trimmed_host = host_strduptrim(hostname);
11772 ssh2_pkt_addstring(pktout, trimmed_host);
11773 sfree(trimmed_host);
11775 ssh2_pkt_adduint32(pktout, port);
11777 * We make up values for the originator data; partly it's
11778 * too much hassle to keep track, and partly I'm not
11779 * convinced the server should be told details like that
11780 * about my local network configuration.
11781 * The "originator IP address" is syntactically a numeric
11782 * IP address, and some servers (e.g., Tectia) get upset
11783 * if it doesn't match this syntax.
11785 ssh2_pkt_addstring(pktout, "0.0.0.0");
11786 ssh2_pkt_adduint32(pktout, 0);
11787 ssh2_pkt_send(ssh, pktout);
11791 static int ssh_connected(void *handle)
11793 Ssh ssh = (Ssh) handle;
11794 return ssh->s != NULL;
11797 static int ssh_sendok(void *handle)
11799 Ssh ssh = (Ssh) handle;
11800 return ssh->send_ok;
11803 static int ssh_ldisc(void *handle, int option)
11805 Ssh ssh = (Ssh) handle;
11806 if (option == LD_ECHO)
11807 return ssh->echoing;
11808 if (option == LD_EDIT)
11809 return ssh->editing;
11813 static void ssh_provide_ldisc(void *handle, void *ldisc)
11815 Ssh ssh = (Ssh) handle;
11816 ssh->ldisc = ldisc;
11819 static void ssh_provide_logctx(void *handle, void *logctx)
11821 Ssh ssh = (Ssh) handle;
11822 ssh->logctx = logctx;
11825 static int ssh_return_exitcode(void *handle)
11827 Ssh ssh = (Ssh) handle;
11828 if (ssh->s != NULL)
11831 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
11835 * cfg_info for SSH is the protocol running in this session.
11836 * (1 or 2 for the full SSH-1 or SSH-2 protocol; -1 for the bare
11837 * SSH-2 connection protocol, i.e. a downstream; 0 for not-decided-yet.)
11839 static int ssh_cfg_info(void *handle)
11841 Ssh ssh = (Ssh) handle;
11842 if (ssh->version == 0)
11843 return 0; /* don't know yet */
11844 else if (ssh->bare_connection)
11847 return ssh->version;
11851 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
11852 * that fails. This variable is the means by which scp.c can reach
11853 * into the SSH code and find out which one it got.
11855 extern int ssh_fallback_cmd(void *handle)
11857 Ssh ssh = (Ssh) handle;
11858 return ssh->fallback_cmd;
11861 Backend ssh_backend = {
11871 ssh_return_exitcode,
11875 ssh_provide_logctx,
11878 ssh_test_for_upstream,