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 ssh2_channel_check_close(struct ssh_channel *c);
370 static void ssh_channel_destroy(struct ssh_channel *c);
371 static void ssh_channel_unthrottle(struct ssh_channel *c, int bufsize);
372 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin);
375 * Buffer management constants. There are several of these for
376 * various different purposes:
378 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
379 * on a local data stream before we throttle the whole SSH
380 * connection (in SSH-1 only). Throttling the whole connection is
381 * pretty drastic so we set this high in the hope it won't
384 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
385 * on the SSH connection itself before we defensively throttle
386 * _all_ local data streams. This is pretty drastic too (though
387 * thankfully unlikely in SSH-2 since the window mechanism should
388 * ensure that the server never has any need to throttle its end
389 * of the connection), so we set this high as well.
391 * - OUR_V2_WINSIZE is the default window size we present on SSH-2
394 * - OUR_V2_BIGWIN is the window size we advertise for the only
395 * channel in a simple connection. It must be <= INT_MAX.
397 * - OUR_V2_MAXPKT is the official "maximum packet size" we send
398 * to the remote side. This actually has nothing to do with the
399 * size of the _packet_, but is instead a limit on the amount
400 * of data we're willing to receive in a single SSH2 channel
403 * - OUR_V2_PACKETLIMIT is actually the maximum size of SSH
404 * _packet_ we're prepared to cope with. It must be a multiple
405 * of the cipher block size, and must be at least 35000.
408 #define SSH1_BUFFER_LIMIT 32768
409 #define SSH_MAX_BACKLOG 32768
410 #define OUR_V2_WINSIZE 16384
411 #define OUR_V2_BIGWIN 0x7fffffff
412 #define OUR_V2_MAXPKT 0x4000UL
413 #define OUR_V2_PACKETLIMIT 0x9000UL
415 struct ssh_signkey_with_user_pref_id {
416 const struct ssh_signkey *alg;
419 const static struct ssh_signkey_with_user_pref_id hostkey_algs[] = {
420 { &ssh_ecdsa_ed25519, HK_ED25519 },
421 { &ssh_ecdsa_nistp256, HK_ECDSA },
422 { &ssh_ecdsa_nistp384, HK_ECDSA },
423 { &ssh_ecdsa_nistp521, HK_ECDSA },
424 { &ssh_dss, HK_DSA },
425 { &ssh_rsa, HK_RSA },
428 const static struct ssh_mac *const macs[] = {
429 &ssh_hmac_sha256, &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
431 const static struct ssh_mac *const buggymacs[] = {
432 &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
435 static void *ssh_comp_none_init(void)
439 static void ssh_comp_none_cleanup(void *handle)
442 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
443 unsigned char **outblock, int *outlen)
447 static int ssh_comp_none_disable(void *handle)
451 const static struct ssh_compress ssh_comp_none = {
453 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
454 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
455 ssh_comp_none_disable, NULL
457 extern const struct ssh_compress ssh_zlib;
458 const static struct ssh_compress *const compressions[] = {
459 &ssh_zlib, &ssh_comp_none
462 enum { /* channel types */
467 CHAN_SOCKDATA_DORMANT, /* one the remote hasn't confirmed */
469 * CHAN_SHARING indicates a channel which is tracked here on
470 * behalf of a connection-sharing downstream. We do almost nothing
471 * with these channels ourselves: all messages relating to them
472 * get thrown straight to sshshare.c and passed on almost
473 * unmodified to downstream.
477 * CHAN_ZOMBIE is used to indicate a channel for which we've
478 * already destroyed the local data source: for instance, if a
479 * forwarded port experiences a socket error on the local side, we
480 * immediately destroy its local socket and turn the SSH channel
486 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
487 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
488 typedef void (*cchandler_fn_t)(struct ssh_channel *, struct Packet *, void *);
491 * Each channel has a queue of outstanding CHANNEL_REQUESTS and their
494 struct outstanding_channel_request {
495 cchandler_fn_t handler;
497 struct outstanding_channel_request *next;
501 * 2-3-4 tree storing channels.
504 Ssh ssh; /* pointer back to main context */
505 unsigned remoteid, localid;
507 /* True if we opened this channel but server hasn't confirmed. */
510 * In SSH-1, this value contains four bits:
512 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
513 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
514 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
515 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
517 * A channel is completely finished with when all four bits are set.
519 * In SSH-2, the four bits mean:
521 * 1 We have sent SSH2_MSG_CHANNEL_EOF.
522 * 2 We have sent SSH2_MSG_CHANNEL_CLOSE.
523 * 4 We have received SSH2_MSG_CHANNEL_EOF.
524 * 8 We have received SSH2_MSG_CHANNEL_CLOSE.
526 * A channel is completely finished with when we have both sent
527 * and received CLOSE.
529 * The symbolic constants below use the SSH-2 terminology, which
530 * is a bit confusing in SSH-1, but we have to use _something_.
532 #define CLOSES_SENT_EOF 1
533 #define CLOSES_SENT_CLOSE 2
534 #define CLOSES_RCVD_EOF 4
535 #define CLOSES_RCVD_CLOSE 8
539 * This flag indicates that an EOF is pending on the outgoing side
540 * of the channel: that is, wherever we're getting the data for
541 * this channel has sent us some data followed by EOF. We can't
542 * actually send the EOF until we've finished sending the data, so
543 * we set this flag instead to remind us to do so once our buffer
549 * True if this channel is causing the underlying connection to be
554 struct ssh2_data_channel {
556 unsigned remwindow, remmaxpkt;
557 /* locwindow is signed so we can cope with excess data. */
558 int locwindow, locmaxwin;
560 * remlocwin is the amount of local window that we think
561 * the remote end had available to it after it sent the
562 * last data packet or window adjust ack.
566 * These store the list of channel requests that haven't
569 struct outstanding_channel_request *chanreq_head, *chanreq_tail;
570 enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
574 struct ssh_agent_channel {
575 unsigned char *message;
576 unsigned char msglen[4];
577 unsigned lensofar, totallen;
578 int outstanding_requests;
580 struct ssh_x11_channel {
581 struct X11Connection *xconn;
584 struct ssh_pfd_channel {
585 struct PortForwarding *pf;
587 struct ssh_sharing_channel {
594 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
595 * use this structure in different ways, reflecting SSH-2's
596 * altogether saner approach to port forwarding.
598 * In SSH-1, you arrange a remote forwarding by sending the server
599 * the remote port number, and the local destination host:port.
600 * When a connection comes in, the server sends you back that
601 * host:port pair, and you connect to it. This is a ready-made
602 * security hole if you're not on the ball: a malicious server
603 * could send you back _any_ host:port pair, so if you trustingly
604 * connect to the address it gives you then you've just opened the
605 * entire inside of your corporate network just by connecting
606 * through it to a dodgy SSH server. Hence, we must store a list of
607 * host:port pairs we _are_ trying to forward to, and reject a
608 * connection request from the server if it's not in the list.
610 * In SSH-2, each side of the connection minds its own business and
611 * doesn't send unnecessary information to the other. You arrange a
612 * remote forwarding by sending the server just the remote port
613 * number. When a connection comes in, the server tells you which
614 * of its ports was connected to; and _you_ have to remember what
615 * local host:port pair went with that port number.
617 * Hence, in SSH-1 this structure is indexed by destination
618 * host:port pair, whereas in SSH-2 it is indexed by source port.
620 struct ssh_portfwd; /* forward declaration */
622 struct ssh_rportfwd {
623 unsigned sport, dport;
627 struct ssh_portfwd *pfrec;
630 static void free_rportfwd(struct ssh_rportfwd *pf)
633 sfree(pf->sportdesc);
641 * Separately to the rportfwd tree (which is for looking up port
642 * open requests from the server), a tree of _these_ structures is
643 * used to keep track of all the currently open port forwardings,
644 * so that we can reconfigure in mid-session if the user requests
648 enum { DESTROY, KEEP, CREATE } status;
650 unsigned sport, dport;
653 struct ssh_rportfwd *remote;
655 struct PortListener *local;
657 #define free_portfwd(pf) ( \
658 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
659 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
662 long length; /* length of packet: see below */
663 long forcepad; /* SSH-2: force padding to at least this length */
664 int type; /* only used for incoming packets */
665 unsigned long sequence; /* SSH-2 incoming sequence number */
666 unsigned char *data; /* allocated storage */
667 unsigned char *body; /* offset of payload within `data' */
668 long savedpos; /* dual-purpose saved packet position: see below */
669 long maxlen; /* amount of storage allocated for `data' */
670 long encrypted_len; /* for SSH-2 total-size counting */
673 * A note on the 'length' and 'savedpos' fields above.
675 * Incoming packets are set up so that pkt->length is measured
676 * relative to pkt->body, which itself points to a few bytes after
677 * pkt->data (skipping some uninteresting header fields including
678 * the packet type code). The ssh_pkt_get* functions all expect
679 * this setup, and they also use pkt->savedpos to indicate how far
680 * through the packet being decoded they've got - and that, too,
681 * is an offset from pkt->body rather than pkt->data.
683 * During construction of an outgoing packet, however, pkt->length
684 * is measured relative to the base pointer pkt->data, and
685 * pkt->body is not really used for anything until the packet is
686 * ready for sending. In this mode, pkt->savedpos is reused as a
687 * temporary variable by the addstring functions, which write out
688 * a string length field and then keep going back and updating it
689 * as more data is appended to the subsequent string data field;
690 * pkt->savedpos stores the offset (again relative to pkt->data)
691 * of the start of the string data field.
694 /* Extra metadata used in SSH packet logging mode, allowing us to
695 * log in the packet header line that the packet came from a
696 * connection-sharing downstream and what if anything unusual was
697 * done to it. The additional_log_text field is expected to be a
698 * static string - it will not be freed. */
699 unsigned downstream_id;
700 const char *additional_log_text;
703 static void ssh1_protocol(Ssh ssh, const void *vin, int inlen,
704 struct Packet *pktin);
705 static void ssh2_protocol(Ssh ssh, const void *vin, int inlen,
706 struct Packet *pktin);
707 static void ssh2_bare_connection_protocol(Ssh ssh, const void *vin, int inlen,
708 struct Packet *pktin);
709 static void ssh1_protocol_setup(Ssh ssh);
710 static void ssh2_protocol_setup(Ssh ssh);
711 static void ssh2_bare_connection_protocol_setup(Ssh ssh);
712 static void ssh_size(void *handle, int width, int height);
713 static void ssh_special(void *handle, Telnet_Special);
714 static int ssh2_try_send(struct ssh_channel *c);
715 static int ssh_send_channel_data(struct ssh_channel *c,
716 const char *buf, int len);
717 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
718 static void ssh2_set_window(struct ssh_channel *c, int newwin);
719 static int ssh_sendbuffer(void *handle);
720 static int ssh_do_close(Ssh ssh, int notify_exit);
721 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
722 static int ssh2_pkt_getbool(struct Packet *pkt);
723 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
724 static void ssh2_timer(void *ctx, unsigned long now);
725 static void do_ssh2_transport(Ssh ssh, const void *vin, int inlen,
726 struct Packet *pktin);
727 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin);
729 struct rdpkt1_state_tag {
730 long len, pad, biglen, to_read;
731 unsigned long realcrc, gotcrc;
735 struct Packet *pktin;
738 struct rdpkt2_state_tag {
739 long len, pad, payload, packetlen, maclen;
742 unsigned long incoming_sequence;
743 struct Packet *pktin;
746 struct rdpkt2_bare_state_tag {
750 unsigned long incoming_sequence;
751 struct Packet *pktin;
754 struct queued_handler;
755 struct queued_handler {
757 chandler_fn_t handler;
759 struct queued_handler *next;
763 const struct plug_function_table *fn;
764 /* the above field _must_ be first in the structure */
774 unsigned char session_key[32];
776 int v1_remote_protoflags;
777 int v1_local_protoflags;
778 int agentfwd_enabled;
781 const struct ssh_cipher *cipher;
784 const struct ssh2_cipher *cscipher, *sccipher;
785 void *cs_cipher_ctx, *sc_cipher_ctx;
786 const struct ssh_mac *csmac, *scmac;
787 int csmac_etm, scmac_etm;
788 void *cs_mac_ctx, *sc_mac_ctx;
789 const struct ssh_compress *cscomp, *sccomp;
790 void *cs_comp_ctx, *sc_comp_ctx;
791 const struct ssh_kex *kex;
792 const struct ssh_signkey *hostkey;
793 char *hostkey_str; /* string representation, for easy checking in rekeys */
794 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
795 int v2_session_id_len;
799 int attempting_connshare;
805 int echoing, editing;
810 int ospeed, ispeed; /* temporaries */
811 int term_width, term_height;
813 tree234 *channels; /* indexed by local id */
814 struct ssh_channel *mainchan; /* primary session channel */
815 int ncmode; /* is primary channel direct-tcpip? */
820 tree234 *rportfwds, *portfwds;
824 SSH_STATE_BEFORE_SIZE,
830 int size_needed, eof_needed;
831 int sent_console_eof;
832 int got_pty; /* affects EOF behaviour on main channel */
834 struct Packet **queue;
835 int queuelen, queuesize;
837 unsigned char *deferred_send_data;
838 int deferred_len, deferred_size;
841 * Gross hack: pscp will try to start SFTP but fall back to
842 * scp1 if that fails. This variable is the means by which
843 * scp.c can reach into the SSH code and find out which one it
848 bufchain banner; /* accumulates banners during do_ssh2_authconn */
853 struct X11Display *x11disp;
854 struct X11FakeAuth *x11auth;
855 tree234 *x11authtree;
858 int conn_throttle_count;
861 int v1_stdout_throttling;
862 unsigned long v2_outgoing_sequence;
864 int ssh1_rdpkt_crstate;
865 int ssh2_rdpkt_crstate;
866 int ssh2_bare_rdpkt_crstate;
867 int ssh_gotdata_crstate;
868 int do_ssh1_connection_crstate;
870 void *do_ssh_init_state;
871 void *do_ssh1_login_state;
872 void *do_ssh2_transport_state;
873 void *do_ssh2_authconn_state;
874 void *do_ssh_connection_init_state;
876 struct rdpkt1_state_tag rdpkt1_state;
877 struct rdpkt2_state_tag rdpkt2_state;
878 struct rdpkt2_bare_state_tag rdpkt2_bare_state;
880 /* SSH-1 and SSH-2 use this for different things, but both use it */
881 int protocol_initial_phase_done;
883 void (*protocol) (Ssh ssh, const void *vin, int inlen,
885 struct Packet *(*s_rdpkt) (Ssh ssh, const unsigned char **data,
887 int (*do_ssh_init)(Ssh ssh, unsigned char c);
890 * We maintain our own copy of a Conf structure here. That way,
891 * when we're passed a new one for reconfiguration, we can check
892 * the differences and potentially reconfigure port forwardings
893 * etc in mid-session.
898 * Values cached out of conf so as to avoid the tree234 lookup
899 * cost every time they're used.
904 * Dynamically allocated username string created during SSH
905 * login. Stored in here rather than in the coroutine state so
906 * that it'll be reliably freed if we shut down the SSH session
907 * at some unexpected moment.
912 * Used to transfer data back from async callbacks.
914 void *agent_response;
915 int agent_response_len;
919 * The SSH connection can be set as `frozen', meaning we are
920 * not currently accepting incoming data from the network. This
921 * is slightly more serious than setting the _socket_ as
922 * frozen, because we may already have had data passed to us
923 * from the network which we need to delay processing until
924 * after the freeze is lifted, so we also need a bufchain to
928 bufchain queued_incoming_data;
931 * Dispatch table for packet types that we may have to deal
934 handler_fn_t packet_dispatch[256];
937 * Queues of one-off handler functions for success/failure
938 * indications from a request.
940 struct queued_handler *qhead, *qtail;
941 handler_fn_t q_saved_handler1, q_saved_handler2;
944 * This module deals with sending keepalives.
949 * Track incoming and outgoing data sizes and time, for
952 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
953 unsigned long max_data_size;
955 unsigned long next_rekey, last_rekey;
956 const char *deferred_rekey_reason;
959 * Fully qualified host name, which we need if doing GSSAPI.
965 * GSSAPI libraries for this session.
967 struct ssh_gss_liblist *gsslibs;
971 * The last list returned from get_specials.
973 struct telnet_special *specials;
976 * List of host key algorithms for which we _don't_ have a stored
977 * host key. These are indices into the main hostkey_algs[] array
979 int uncert_hostkeys[lenof(hostkey_algs)];
980 int n_uncert_hostkeys;
983 * Flag indicating that the current rekey is intended to finish
984 * with a newly cross-certified host key.
986 int cross_certifying;
989 static const char *ssh_pkt_type(Ssh ssh, int type)
991 if (ssh->version == 1)
992 return ssh1_pkt_type(type);
994 return ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, type);
997 #define logevent(s) logevent(ssh->frontend, s)
999 /* logevent, only printf-formatted. */
1000 static void logeventf(Ssh ssh, const char *fmt, ...)
1006 buf = dupvprintf(fmt, ap);
1012 static void bomb_out(Ssh ssh, char *text)
1014 ssh_do_close(ssh, FALSE);
1016 connection_fatal(ssh->frontend, "%s", text);
1020 #define bombout(msg) bomb_out(ssh, dupprintf msg)
1022 /* Helper function for common bits of parsing ttymodes. */
1023 static void parse_ttymodes(Ssh ssh,
1024 void (*do_mode)(void *data,
1025 const struct ssh_ttymode *mode,
1030 const struct ssh_ttymode *mode;
1032 char default_val[2];
1034 strcpy(default_val, "A");
1036 for (i = 0; i < lenof(ssh_ttymodes); i++) {
1037 mode = ssh_ttymodes + i;
1038 val = conf_get_str_str_opt(ssh->conf, CONF_ttymodes, mode->mode);
1043 * val[0] is either 'V', indicating that an explicit value
1044 * follows it, or 'A' indicating that we should pass the
1045 * value through from the local environment via get_ttymode.
1047 if (val[0] == 'A') {
1048 val = get_ttymode(ssh->frontend, mode->mode);
1050 do_mode(data, mode, val);
1054 do_mode(data, mode, val + 1); /* skip the 'V' */
1058 static int ssh_channelcmp(void *av, void *bv)
1060 struct ssh_channel *a = (struct ssh_channel *) av;
1061 struct ssh_channel *b = (struct ssh_channel *) bv;
1062 if (a->localid < b->localid)
1064 if (a->localid > b->localid)
1068 static int ssh_channelfind(void *av, void *bv)
1070 unsigned *a = (unsigned *) av;
1071 struct ssh_channel *b = (struct ssh_channel *) bv;
1072 if (*a < b->localid)
1074 if (*a > b->localid)
1079 static int ssh_rportcmp_ssh1(void *av, void *bv)
1081 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1082 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1084 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
1085 return i < 0 ? -1 : +1;
1086 if (a->dport > b->dport)
1088 if (a->dport < b->dport)
1093 static int ssh_rportcmp_ssh2(void *av, void *bv)
1095 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1096 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1098 if ( (i = strcmp(a->shost, b->shost)) != 0)
1099 return i < 0 ? -1 : +1;
1100 if (a->sport > b->sport)
1102 if (a->sport < b->sport)
1108 * Special form of strcmp which can cope with NULL inputs. NULL is
1109 * defined to sort before even the empty string.
1111 static int nullstrcmp(const char *a, const char *b)
1113 if (a == NULL && b == NULL)
1119 return strcmp(a, b);
1122 static int ssh_portcmp(void *av, void *bv)
1124 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1125 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1127 if (a->type > b->type)
1129 if (a->type < b->type)
1131 if (a->addressfamily > b->addressfamily)
1133 if (a->addressfamily < b->addressfamily)
1135 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1136 return i < 0 ? -1 : +1;
1137 if (a->sport > b->sport)
1139 if (a->sport < b->sport)
1141 if (a->type != 'D') {
1142 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1143 return i < 0 ? -1 : +1;
1144 if (a->dport > b->dport)
1146 if (a->dport < b->dport)
1152 static int alloc_channel_id(Ssh ssh)
1154 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1155 unsigned low, high, mid;
1157 struct ssh_channel *c;
1160 * First-fit allocation of channel numbers: always pick the
1161 * lowest unused one. To do this, binary-search using the
1162 * counted B-tree to find the largest channel ID which is in a
1163 * contiguous sequence from the beginning. (Precisely
1164 * everything in that sequence must have ID equal to its tree
1165 * index plus CHANNEL_NUMBER_OFFSET.)
1167 tsize = count234(ssh->channels);
1171 while (high - low > 1) {
1172 mid = (high + low) / 2;
1173 c = index234(ssh->channels, mid);
1174 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1175 low = mid; /* this one is fine */
1177 high = mid; /* this one is past it */
1180 * Now low points to either -1, or the tree index of the
1181 * largest ID in the initial sequence.
1184 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1185 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1187 return low + 1 + CHANNEL_NUMBER_OFFSET;
1190 static void c_write_stderr(int trusted, const char *buf, int len)
1193 for (i = 0; i < len; i++)
1194 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1195 fputc(buf[i], stderr);
1198 static void c_write(Ssh ssh, const char *buf, int len)
1200 if (flags & FLAG_STDERR)
1201 c_write_stderr(1, buf, len);
1203 from_backend(ssh->frontend, 1, buf, len);
1206 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1208 if (flags & FLAG_STDERR)
1209 c_write_stderr(0, buf, len);
1211 from_backend_untrusted(ssh->frontend, buf, len);
1214 static void c_write_str(Ssh ssh, const char *buf)
1216 c_write(ssh, buf, strlen(buf));
1219 static void ssh_free_packet(struct Packet *pkt)
1224 static struct Packet *ssh_new_packet(void)
1226 struct Packet *pkt = snew(struct Packet);
1228 pkt->body = pkt->data = NULL;
1234 static void ssh1_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1237 struct logblank_t blanks[4];
1243 if (ssh->logomitdata &&
1244 (pkt->type == SSH1_SMSG_STDOUT_DATA ||
1245 pkt->type == SSH1_SMSG_STDERR_DATA ||
1246 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1247 /* "Session data" packets - omit the data string. */
1248 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1249 ssh_pkt_getuint32(pkt); /* skip channel id */
1250 blanks[nblanks].offset = pkt->savedpos + 4;
1251 blanks[nblanks].type = PKTLOG_OMIT;
1252 ssh_pkt_getstring(pkt, &str, &slen);
1254 blanks[nblanks].len = slen;
1258 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1259 ssh1_pkt_type(pkt->type),
1260 pkt->body, pkt->length, nblanks, blanks, NULL,
1264 static void ssh1_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1267 struct logblank_t blanks[4];
1272 * For outgoing packets, pkt->length represents the length of the
1273 * whole packet starting at pkt->data (including some header), and
1274 * pkt->body refers to the point within that where the log-worthy
1275 * payload begins. However, incoming packets expect pkt->length to
1276 * represent only the payload length (that is, it's measured from
1277 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1278 * packet to conform to the incoming-packet semantics, so that we
1279 * can analyse it with the ssh_pkt_get functions.
1281 pkt->length -= (pkt->body - pkt->data);
1284 if (ssh->logomitdata &&
1285 (pkt->type == SSH1_CMSG_STDIN_DATA ||
1286 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1287 /* "Session data" packets - omit the data string. */
1288 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1289 ssh_pkt_getuint32(pkt); /* skip channel id */
1290 blanks[nblanks].offset = pkt->savedpos + 4;
1291 blanks[nblanks].type = PKTLOG_OMIT;
1292 ssh_pkt_getstring(pkt, &str, &slen);
1294 blanks[nblanks].len = slen;
1299 if ((pkt->type == SSH1_CMSG_AUTH_PASSWORD ||
1300 pkt->type == SSH1_CMSG_AUTH_TIS_RESPONSE ||
1301 pkt->type == SSH1_CMSG_AUTH_CCARD_RESPONSE) &&
1302 conf_get_int(ssh->conf, CONF_logomitpass)) {
1303 /* If this is a password or similar packet, blank the password(s). */
1304 blanks[nblanks].offset = 0;
1305 blanks[nblanks].len = pkt->length;
1306 blanks[nblanks].type = PKTLOG_BLANK;
1308 } else if (pkt->type == SSH1_CMSG_X11_REQUEST_FORWARDING &&
1309 conf_get_int(ssh->conf, CONF_logomitpass)) {
1311 * If this is an X forwarding request packet, blank the fake
1314 * Note that while we blank the X authentication data here, we
1315 * don't take any special action to blank the start of an X11
1316 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1317 * an X connection without having session blanking enabled is
1318 * likely to leak your cookie into the log.
1321 ssh_pkt_getstring(pkt, &str, &slen);
1322 blanks[nblanks].offset = pkt->savedpos;
1323 blanks[nblanks].type = PKTLOG_BLANK;
1324 ssh_pkt_getstring(pkt, &str, &slen);
1326 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1331 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1332 ssh1_pkt_type(pkt->data[12]),
1333 pkt->body, pkt->length,
1334 nblanks, blanks, NULL, 0, NULL);
1337 * Undo the above adjustment of pkt->length, to put the packet
1338 * back in the state we found it.
1340 pkt->length += (pkt->body - pkt->data);
1344 * Collect incoming data in the incoming packet buffer.
1345 * Decipher and verify the packet when it is completely read.
1346 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1347 * Update the *data and *datalen variables.
1348 * Return a Packet structure when a packet is completed.
1350 static struct Packet *ssh1_rdpkt(Ssh ssh, const unsigned char **data,
1353 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1355 crBegin(ssh->ssh1_rdpkt_crstate);
1357 st->pktin = ssh_new_packet();
1359 st->pktin->type = 0;
1360 st->pktin->length = 0;
1362 for (st->i = st->len = 0; st->i < 4; st->i++) {
1363 while ((*datalen) == 0)
1365 st->len = (st->len << 8) + **data;
1366 (*data)++, (*datalen)--;
1369 st->pad = 8 - (st->len % 8);
1370 st->biglen = st->len + st->pad;
1371 st->pktin->length = st->len - 5;
1373 if (st->biglen < 0) {
1374 bombout(("Extremely large packet length from server suggests"
1375 " data stream corruption"));
1376 ssh_free_packet(st->pktin);
1380 st->pktin->maxlen = st->biglen;
1381 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1383 st->to_read = st->biglen;
1384 st->p = st->pktin->data;
1385 while (st->to_read > 0) {
1386 st->chunk = st->to_read;
1387 while ((*datalen) == 0)
1389 if (st->chunk > (*datalen))
1390 st->chunk = (*datalen);
1391 memcpy(st->p, *data, st->chunk);
1393 *datalen -= st->chunk;
1395 st->to_read -= st->chunk;
1398 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1399 st->biglen, NULL)) {
1400 bombout(("Network attack (CRC compensation) detected!"));
1401 ssh_free_packet(st->pktin);
1406 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1408 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1409 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1410 if (st->gotcrc != st->realcrc) {
1411 bombout(("Incorrect CRC received on packet"));
1412 ssh_free_packet(st->pktin);
1416 st->pktin->body = st->pktin->data + st->pad + 1;
1418 if (ssh->v1_compressing) {
1419 unsigned char *decompblk;
1421 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1422 st->pktin->body - 1, st->pktin->length + 1,
1423 &decompblk, &decomplen)) {
1424 bombout(("Zlib decompression encountered invalid data"));
1425 ssh_free_packet(st->pktin);
1429 if (st->pktin->maxlen < st->pad + decomplen) {
1430 st->pktin->maxlen = st->pad + decomplen;
1431 st->pktin->data = sresize(st->pktin->data,
1432 st->pktin->maxlen + APIEXTRA,
1434 st->pktin->body = st->pktin->data + st->pad + 1;
1437 memcpy(st->pktin->body - 1, decompblk, decomplen);
1439 st->pktin->length = decomplen - 1;
1442 st->pktin->type = st->pktin->body[-1];
1445 * Now pktin->body and pktin->length identify the semantic content
1446 * of the packet, excluding the initial type byte.
1450 ssh1_log_incoming_packet(ssh, st->pktin);
1452 st->pktin->savedpos = 0;
1454 crFinish(st->pktin);
1457 static void ssh2_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1460 struct logblank_t blanks[4];
1466 if (ssh->logomitdata &&
1467 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1468 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1469 /* "Session data" packets - omit the data string. */
1470 ssh_pkt_getuint32(pkt); /* skip channel id */
1471 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1472 ssh_pkt_getuint32(pkt); /* skip extended data type */
1473 blanks[nblanks].offset = pkt->savedpos + 4;
1474 blanks[nblanks].type = PKTLOG_OMIT;
1475 ssh_pkt_getstring(pkt, &str, &slen);
1477 blanks[nblanks].len = slen;
1482 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1483 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->type),
1484 pkt->body, pkt->length, nblanks, blanks, &pkt->sequence,
1488 static void ssh2_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1491 struct logblank_t blanks[4];
1496 * For outgoing packets, pkt->length represents the length of the
1497 * whole packet starting at pkt->data (including some header), and
1498 * pkt->body refers to the point within that where the log-worthy
1499 * payload begins. However, incoming packets expect pkt->length to
1500 * represent only the payload length (that is, it's measured from
1501 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1502 * packet to conform to the incoming-packet semantics, so that we
1503 * can analyse it with the ssh_pkt_get functions.
1505 pkt->length -= (pkt->body - pkt->data);
1508 if (ssh->logomitdata &&
1509 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1510 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1511 /* "Session data" packets - omit the data string. */
1512 ssh_pkt_getuint32(pkt); /* skip channel id */
1513 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1514 ssh_pkt_getuint32(pkt); /* skip extended data type */
1515 blanks[nblanks].offset = pkt->savedpos + 4;
1516 blanks[nblanks].type = PKTLOG_OMIT;
1517 ssh_pkt_getstring(pkt, &str, &slen);
1519 blanks[nblanks].len = slen;
1524 if (pkt->type == SSH2_MSG_USERAUTH_REQUEST &&
1525 conf_get_int(ssh->conf, CONF_logomitpass)) {
1526 /* If this is a password packet, blank the password(s). */
1528 ssh_pkt_getstring(pkt, &str, &slen);
1529 ssh_pkt_getstring(pkt, &str, &slen);
1530 ssh_pkt_getstring(pkt, &str, &slen);
1531 if (slen == 8 && !memcmp(str, "password", 8)) {
1532 ssh2_pkt_getbool(pkt);
1533 /* Blank the password field. */
1534 blanks[nblanks].offset = pkt->savedpos;
1535 blanks[nblanks].type = PKTLOG_BLANK;
1536 ssh_pkt_getstring(pkt, &str, &slen);
1538 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1540 /* If there's another password field beyond it (change of
1541 * password), blank that too. */
1542 ssh_pkt_getstring(pkt, &str, &slen);
1544 blanks[nblanks-1].len =
1545 pkt->savedpos - blanks[nblanks].offset;
1548 } else if (ssh->pkt_actx == SSH2_PKTCTX_KBDINTER &&
1549 pkt->type == SSH2_MSG_USERAUTH_INFO_RESPONSE &&
1550 conf_get_int(ssh->conf, CONF_logomitpass)) {
1551 /* If this is a keyboard-interactive response packet, blank
1554 ssh_pkt_getuint32(pkt);
1555 blanks[nblanks].offset = pkt->savedpos;
1556 blanks[nblanks].type = PKTLOG_BLANK;
1558 ssh_pkt_getstring(pkt, &str, &slen);
1562 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1564 } else if (pkt->type == SSH2_MSG_CHANNEL_REQUEST &&
1565 conf_get_int(ssh->conf, CONF_logomitpass)) {
1567 * If this is an X forwarding request packet, blank the fake
1570 * Note that while we blank the X authentication data here, we
1571 * don't take any special action to blank the start of an X11
1572 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1573 * an X connection without having session blanking enabled is
1574 * likely to leak your cookie into the log.
1577 ssh_pkt_getuint32(pkt);
1578 ssh_pkt_getstring(pkt, &str, &slen);
1579 if (slen == 7 && !memcmp(str, "x11-req", 0)) {
1580 ssh2_pkt_getbool(pkt);
1581 ssh2_pkt_getbool(pkt);
1582 ssh_pkt_getstring(pkt, &str, &slen);
1583 blanks[nblanks].offset = pkt->savedpos;
1584 blanks[nblanks].type = PKTLOG_BLANK;
1585 ssh_pkt_getstring(pkt, &str, &slen);
1587 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1593 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1594 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1595 pkt->body, pkt->length, nblanks, blanks,
1596 &ssh->v2_outgoing_sequence,
1597 pkt->downstream_id, pkt->additional_log_text);
1600 * Undo the above adjustment of pkt->length, to put the packet
1601 * back in the state we found it.
1603 pkt->length += (pkt->body - pkt->data);
1606 static struct Packet *ssh2_rdpkt(Ssh ssh, const unsigned char **data,
1609 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1611 crBegin(ssh->ssh2_rdpkt_crstate);
1613 st->pktin = ssh_new_packet();
1615 st->pktin->type = 0;
1616 st->pktin->length = 0;
1618 st->cipherblk = ssh->sccipher->blksize;
1621 if (st->cipherblk < 8)
1623 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1625 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1626 ssh->scmac && !ssh->scmac_etm) {
1628 * When dealing with a CBC-mode cipher, we want to avoid the
1629 * possibility of an attacker's tweaking the ciphertext stream
1630 * so as to cause us to feed the same block to the block
1631 * cipher more than once and thus leak information
1632 * (VU#958563). The way we do this is not to take any
1633 * decisions on the basis of anything we've decrypted until
1634 * we've verified it with a MAC. That includes the packet
1635 * length, so we just read data and check the MAC repeatedly,
1636 * and when the MAC passes, see if the length we've got is
1639 * This defence is unnecessary in OpenSSH ETM mode, because
1640 * the whole point of ETM mode is that the attacker can't
1641 * tweak the ciphertext stream at all without the MAC
1642 * detecting it before we decrypt anything.
1645 /* May as well allocate the whole lot now. */
1646 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1649 /* Read an amount corresponding to the MAC. */
1650 for (st->i = 0; st->i < st->maclen; st->i++) {
1651 while ((*datalen) == 0)
1653 st->pktin->data[st->i] = *(*data)++;
1659 unsigned char seq[4];
1660 ssh->scmac->start(ssh->sc_mac_ctx);
1661 PUT_32BIT(seq, st->incoming_sequence);
1662 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1665 for (;;) { /* Once around this loop per cipher block. */
1666 /* Read another cipher-block's worth, and tack it onto the end. */
1667 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1668 while ((*datalen) == 0)
1670 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1673 /* Decrypt one more block (a little further back in the stream). */
1674 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1675 st->pktin->data + st->packetlen,
1677 /* Feed that block to the MAC. */
1678 ssh->scmac->bytes(ssh->sc_mac_ctx,
1679 st->pktin->data + st->packetlen, st->cipherblk);
1680 st->packetlen += st->cipherblk;
1681 /* See if that gives us a valid packet. */
1682 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1683 st->pktin->data + st->packetlen) &&
1684 ((st->len = toint(GET_32BIT(st->pktin->data))) ==
1687 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1688 bombout(("No valid incoming packet found"));
1689 ssh_free_packet(st->pktin);
1693 st->pktin->maxlen = st->packetlen + st->maclen;
1694 st->pktin->data = sresize(st->pktin->data,
1695 st->pktin->maxlen + APIEXTRA,
1697 } else if (ssh->scmac && ssh->scmac_etm) {
1698 st->pktin->data = snewn(4 + APIEXTRA, unsigned char);
1701 * OpenSSH encrypt-then-MAC mode: the packet length is
1702 * unencrypted, unless the cipher supports length encryption.
1704 for (st->i = st->len = 0; st->i < 4; st->i++) {
1705 while ((*datalen) == 0)
1707 st->pktin->data[st->i] = *(*data)++;
1710 /* Cipher supports length decryption, so do it */
1711 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_SEPARATE_LENGTH)) {
1712 /* Keep the packet the same though, so the MAC passes */
1713 unsigned char len[4];
1714 memcpy(len, st->pktin->data, 4);
1715 ssh->sccipher->decrypt_length(ssh->sc_cipher_ctx, len, 4, st->incoming_sequence);
1716 st->len = toint(GET_32BIT(len));
1718 st->len = toint(GET_32BIT(st->pktin->data));
1722 * _Completely_ silly lengths should be stomped on before they
1723 * do us any more damage.
1725 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1726 st->len % st->cipherblk != 0) {
1727 bombout(("Incoming packet length field was garbled"));
1728 ssh_free_packet(st->pktin);
1733 * So now we can work out the total packet length.
1735 st->packetlen = st->len + 4;
1738 * Allocate memory for the rest of the packet.
1740 st->pktin->maxlen = st->packetlen + st->maclen;
1741 st->pktin->data = sresize(st->pktin->data,
1742 st->pktin->maxlen + APIEXTRA,
1746 * Read the remainder of the packet.
1748 for (st->i = 4; st->i < st->packetlen + st->maclen; st->i++) {
1749 while ((*datalen) == 0)
1751 st->pktin->data[st->i] = *(*data)++;
1759 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1760 st->len + 4, st->incoming_sequence)) {
1761 bombout(("Incorrect MAC received on packet"));
1762 ssh_free_packet(st->pktin);
1766 /* Decrypt everything between the length field and the MAC. */
1768 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1769 st->pktin->data + 4,
1772 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1775 * Acquire and decrypt the first block of the packet. This will
1776 * contain the length and padding details.
1778 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1779 while ((*datalen) == 0)
1781 st->pktin->data[st->i] = *(*data)++;
1786 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1787 st->pktin->data, st->cipherblk);
1790 * Now get the length figure.
1792 st->len = toint(GET_32BIT(st->pktin->data));
1795 * _Completely_ silly lengths should be stomped on before they
1796 * do us any more damage.
1798 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1799 (st->len + 4) % st->cipherblk != 0) {
1800 bombout(("Incoming packet was garbled on decryption"));
1801 ssh_free_packet(st->pktin);
1806 * So now we can work out the total packet length.
1808 st->packetlen = st->len + 4;
1811 * Allocate memory for the rest of the packet.
1813 st->pktin->maxlen = st->packetlen + st->maclen;
1814 st->pktin->data = sresize(st->pktin->data,
1815 st->pktin->maxlen + APIEXTRA,
1819 * Read and decrypt the remainder of the packet.
1821 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1823 while ((*datalen) == 0)
1825 st->pktin->data[st->i] = *(*data)++;
1828 /* Decrypt everything _except_ the MAC. */
1830 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1831 st->pktin->data + st->cipherblk,
1832 st->packetlen - st->cipherblk);
1838 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1839 st->len + 4, st->incoming_sequence)) {
1840 bombout(("Incorrect MAC received on packet"));
1841 ssh_free_packet(st->pktin);
1845 /* Get and sanity-check the amount of random padding. */
1846 st->pad = st->pktin->data[4];
1847 if (st->pad < 4 || st->len - st->pad < 1) {
1848 bombout(("Invalid padding length on received packet"));
1849 ssh_free_packet(st->pktin);
1853 * This enables us to deduce the payload length.
1855 st->payload = st->len - st->pad - 1;
1857 st->pktin->length = st->payload + 5;
1858 st->pktin->encrypted_len = st->packetlen;
1860 st->pktin->sequence = st->incoming_sequence++;
1862 st->pktin->length = st->packetlen - st->pad;
1863 assert(st->pktin->length >= 0);
1866 * Decompress packet payload.
1869 unsigned char *newpayload;
1872 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1873 st->pktin->data + 5, st->pktin->length - 5,
1874 &newpayload, &newlen)) {
1875 if (st->pktin->maxlen < newlen + 5) {
1876 st->pktin->maxlen = newlen + 5;
1877 st->pktin->data = sresize(st->pktin->data,
1878 st->pktin->maxlen + APIEXTRA,
1881 st->pktin->length = 5 + newlen;
1882 memcpy(st->pktin->data + 5, newpayload, newlen);
1888 * RFC 4253 doesn't explicitly say that completely empty packets
1889 * with no type byte are forbidden, so treat them as deserving
1890 * an SSH_MSG_UNIMPLEMENTED.
1892 if (st->pktin->length <= 5) { /* == 5 we hope, but robustness */
1893 ssh2_msg_something_unimplemented(ssh, st->pktin);
1897 * pktin->body and pktin->length should identify the semantic
1898 * content of the packet, excluding the initial type byte.
1900 st->pktin->type = st->pktin->data[5];
1901 st->pktin->body = st->pktin->data + 6;
1902 st->pktin->length -= 6;
1903 assert(st->pktin->length >= 0); /* one last double-check */
1906 ssh2_log_incoming_packet(ssh, st->pktin);
1908 st->pktin->savedpos = 0;
1910 crFinish(st->pktin);
1913 static struct Packet *ssh2_bare_connection_rdpkt(Ssh ssh,
1914 const unsigned char **data,
1917 struct rdpkt2_bare_state_tag *st = &ssh->rdpkt2_bare_state;
1919 crBegin(ssh->ssh2_bare_rdpkt_crstate);
1922 * Read the packet length field.
1924 for (st->i = 0; st->i < 4; st->i++) {
1925 while ((*datalen) == 0)
1927 st->length[st->i] = *(*data)++;
1931 st->packetlen = toint(GET_32BIT_MSB_FIRST(st->length));
1932 if (st->packetlen <= 0 || st->packetlen >= OUR_V2_PACKETLIMIT) {
1933 bombout(("Invalid packet length received"));
1937 st->pktin = ssh_new_packet();
1938 st->pktin->data = snewn(st->packetlen, unsigned char);
1940 st->pktin->encrypted_len = st->packetlen;
1942 st->pktin->sequence = st->incoming_sequence++;
1945 * Read the remainder of the packet.
1947 for (st->i = 0; st->i < st->packetlen; st->i++) {
1948 while ((*datalen) == 0)
1950 st->pktin->data[st->i] = *(*data)++;
1955 * pktin->body and pktin->length should identify the semantic
1956 * content of the packet, excluding the initial type byte.
1958 st->pktin->type = st->pktin->data[0];
1959 st->pktin->body = st->pktin->data + 1;
1960 st->pktin->length = st->packetlen - 1;
1963 * Log incoming packet, possibly omitting sensitive fields.
1966 ssh2_log_incoming_packet(ssh, st->pktin);
1968 st->pktin->savedpos = 0;
1970 crFinish(st->pktin);
1973 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1975 int pad, biglen, i, pktoffs;
1979 * XXX various versions of SC (including 8.8.4) screw up the
1980 * register allocation in this function and use the same register
1981 * (D6) for len and as a temporary, with predictable results. The
1982 * following sledgehammer prevents this.
1989 ssh1_log_outgoing_packet(ssh, pkt);
1991 if (ssh->v1_compressing) {
1992 unsigned char *compblk;
1994 zlib_compress_block(ssh->cs_comp_ctx,
1995 pkt->data + 12, pkt->length - 12,
1996 &compblk, &complen);
1997 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1998 memcpy(pkt->data + 12, compblk, complen);
2000 pkt->length = complen + 12;
2003 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
2005 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
2006 pad = 8 - (len % 8);
2008 biglen = len + pad; /* len(padding+type+data+CRC) */
2010 for (i = pktoffs; i < 4+8; i++)
2011 pkt->data[i] = random_byte();
2012 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
2013 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
2014 PUT_32BIT(pkt->data + pktoffs, len);
2017 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
2018 pkt->data + pktoffs + 4, biglen);
2020 if (offset_p) *offset_p = pktoffs;
2021 return biglen + 4; /* len(length+padding+type+data+CRC) */
2024 static int s_write(Ssh ssh, void *data, int len)
2027 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
2028 0, NULL, NULL, 0, NULL);
2031 return sk_write(ssh->s, (char *)data, len);
2034 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
2036 int len, backlog, offset;
2037 len = s_wrpkt_prepare(ssh, pkt, &offset);
2038 backlog = s_write(ssh, pkt->data + offset, len);
2039 if (backlog > SSH_MAX_BACKLOG)
2040 ssh_throttle_all(ssh, 1, backlog);
2041 ssh_free_packet(pkt);
2044 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
2047 len = s_wrpkt_prepare(ssh, pkt, &offset);
2048 if (ssh->deferred_len + len > ssh->deferred_size) {
2049 ssh->deferred_size = ssh->deferred_len + len + 128;
2050 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2054 memcpy(ssh->deferred_send_data + ssh->deferred_len,
2055 pkt->data + offset, len);
2056 ssh->deferred_len += len;
2057 ssh_free_packet(pkt);
2061 * Construct a SSH-1 packet with the specified contents.
2062 * (This all-at-once interface used to be the only one, but now SSH-1
2063 * packets can also be constructed incrementally.)
2065 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
2071 pkt = ssh1_pkt_init(pkttype);
2073 while ((argtype = va_arg(ap, int)) != PKT_END) {
2074 unsigned char *argp, argchar;
2076 unsigned long argint;
2079 /* Actual fields in the packet */
2081 argint = va_arg(ap, int);
2082 ssh_pkt_adduint32(pkt, argint);
2085 argchar = (unsigned char) va_arg(ap, int);
2086 ssh_pkt_addbyte(pkt, argchar);
2089 argp = va_arg(ap, unsigned char *);
2090 arglen = va_arg(ap, int);
2091 ssh_pkt_adddata(pkt, argp, arglen);
2094 sargp = va_arg(ap, char *);
2095 ssh_pkt_addstring(pkt, sargp);
2098 bn = va_arg(ap, Bignum);
2099 ssh1_pkt_addmp(pkt, bn);
2107 static void send_packet(Ssh ssh, int pkttype, ...)
2111 va_start(ap, pkttype);
2112 pkt = construct_packet(ssh, pkttype, ap);
2117 static void defer_packet(Ssh ssh, int pkttype, ...)
2121 va_start(ap, pkttype);
2122 pkt = construct_packet(ssh, pkttype, ap);
2124 s_wrpkt_defer(ssh, pkt);
2127 static int ssh_versioncmp(const char *a, const char *b)
2130 unsigned long av, bv;
2132 av = strtoul(a, &ae, 10);
2133 bv = strtoul(b, &be, 10);
2135 return (av < bv ? -1 : +1);
2140 av = strtoul(ae, &ae, 10);
2141 bv = strtoul(be, &be, 10);
2143 return (av < bv ? -1 : +1);
2148 * Utility routines for putting an SSH-protocol `string' and
2149 * `uint32' into a hash state.
2151 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
2153 unsigned char lenblk[4];
2154 PUT_32BIT(lenblk, len);
2155 h->bytes(s, lenblk, 4);
2156 h->bytes(s, str, len);
2159 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
2161 unsigned char intblk[4];
2162 PUT_32BIT(intblk, i);
2163 h->bytes(s, intblk, 4);
2167 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
2169 static void ssh_pkt_ensure(struct Packet *pkt, int length)
2171 if (pkt->maxlen < length) {
2172 unsigned char *body = pkt->body;
2173 int offset = body ? body - pkt->data : 0;
2174 pkt->maxlen = length + 256;
2175 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
2176 if (body) pkt->body = pkt->data + offset;
2179 static void ssh_pkt_adddata(struct Packet *pkt, const void *data, int len)
2182 ssh_pkt_ensure(pkt, pkt->length);
2183 memcpy(pkt->data + pkt->length - len, data, len);
2185 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
2187 ssh_pkt_adddata(pkt, &byte, 1);
2189 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
2191 ssh_pkt_adddata(pkt, &value, 1);
2193 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
2196 PUT_32BIT(x, value);
2197 ssh_pkt_adddata(pkt, x, 4);
2199 static void ssh_pkt_addstring_start(struct Packet *pkt)
2201 ssh_pkt_adduint32(pkt, 0);
2202 pkt->savedpos = pkt->length;
2204 static void ssh_pkt_addstring_data(struct Packet *pkt, const char *data,
2207 ssh_pkt_adddata(pkt, data, len);
2208 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
2210 static void ssh_pkt_addstring_str(struct Packet *pkt, const char *data)
2212 ssh_pkt_addstring_data(pkt, data, strlen(data));
2214 static void ssh_pkt_addstring(struct Packet *pkt, const char *data)
2216 ssh_pkt_addstring_start(pkt);
2217 ssh_pkt_addstring_str(pkt, data);
2219 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
2221 int len = ssh1_bignum_length(b);
2222 unsigned char *data = snewn(len, unsigned char);
2223 (void) ssh1_write_bignum(data, b);
2224 ssh_pkt_adddata(pkt, data, len);
2227 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
2230 int i, n = (bignum_bitcount(b) + 7) / 8;
2231 p = snewn(n + 1, unsigned char);
2233 for (i = 1; i <= n; i++)
2234 p[i] = bignum_byte(b, n - i);
2236 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
2238 memmove(p, p + i, n + 1 - i);
2242 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
2246 p = ssh2_mpint_fmt(b, &len);
2247 ssh_pkt_addstring_start(pkt);
2248 ssh_pkt_addstring_data(pkt, (char *)p, len);
2252 static struct Packet *ssh1_pkt_init(int pkt_type)
2254 struct Packet *pkt = ssh_new_packet();
2255 pkt->length = 4 + 8; /* space for length + max padding */
2256 ssh_pkt_addbyte(pkt, pkt_type);
2257 pkt->body = pkt->data + pkt->length;
2258 pkt->type = pkt_type;
2259 pkt->downstream_id = 0;
2260 pkt->additional_log_text = NULL;
2264 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
2265 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
2266 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
2267 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
2268 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
2269 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
2270 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
2271 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
2272 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
2274 static struct Packet *ssh2_pkt_init(int pkt_type)
2276 struct Packet *pkt = ssh_new_packet();
2277 pkt->length = 5; /* space for packet length + padding length */
2279 pkt->type = pkt_type;
2280 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
2281 pkt->body = pkt->data + pkt->length; /* after packet type */
2282 pkt->downstream_id = 0;
2283 pkt->additional_log_text = NULL;
2288 * Construct an SSH-2 final-form packet: compress it, encrypt it,
2289 * put the MAC on it. Final packet, ready to be sent, is stored in
2290 * pkt->data. Total length is returned.
2292 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
2294 int cipherblk, maclen, padding, unencrypted_prefix, i;
2297 ssh2_log_outgoing_packet(ssh, pkt);
2299 if (ssh->bare_connection) {
2301 * Trivial packet construction for the bare connection
2304 PUT_32BIT(pkt->data + 1, pkt->length - 5);
2305 pkt->body = pkt->data + 1;
2306 ssh->v2_outgoing_sequence++; /* only for diagnostics, really */
2307 return pkt->length - 1;
2311 * Compress packet payload.
2314 unsigned char *newpayload;
2317 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
2319 &newpayload, &newlen)) {
2321 ssh2_pkt_adddata(pkt, newpayload, newlen);
2327 * Add padding. At least four bytes, and must also bring total
2328 * length (minus MAC) up to a multiple of the block size.
2329 * If pkt->forcepad is set, make sure the packet is at least that size
2332 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
2333 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
2335 unencrypted_prefix = (ssh->csmac && ssh->csmac_etm) ? 4 : 0;
2336 if (pkt->length + padding < pkt->forcepad)
2337 padding = pkt->forcepad - pkt->length;
2339 (cipherblk - (pkt->length - unencrypted_prefix + padding) % cipherblk)
2341 assert(padding <= 255);
2342 maclen = ssh->csmac ? ssh->csmac->len : 0;
2343 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
2344 pkt->data[4] = padding;
2345 for (i = 0; i < padding; i++)
2346 pkt->data[pkt->length + i] = random_byte();
2347 PUT_32BIT(pkt->data, pkt->length + padding - 4);
2349 /* Encrypt length if the scheme requires it */
2350 if (ssh->cscipher && (ssh->cscipher->flags & SSH_CIPHER_SEPARATE_LENGTH)) {
2351 ssh->cscipher->encrypt_length(ssh->cs_cipher_ctx, pkt->data, 4,
2352 ssh->v2_outgoing_sequence);
2355 if (ssh->csmac && ssh->csmac_etm) {
2357 * OpenSSH-defined encrypt-then-MAC protocol.
2360 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2361 pkt->data + 4, pkt->length + padding - 4);
2362 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2363 pkt->length + padding,
2364 ssh->v2_outgoing_sequence);
2367 * SSH-2 standard protocol.
2370 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2371 pkt->length + padding,
2372 ssh->v2_outgoing_sequence);
2374 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2375 pkt->data, pkt->length + padding);
2378 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
2379 pkt->encrypted_len = pkt->length + padding;
2381 /* Ready-to-send packet starts at pkt->data. We return length. */
2382 pkt->body = pkt->data;
2383 return pkt->length + padding + maclen;
2387 * Routines called from the main SSH code to send packets. There
2388 * are quite a few of these, because we have two separate
2389 * mechanisms for delaying the sending of packets:
2391 * - In order to send an IGNORE message and a password message in
2392 * a single fixed-length blob, we require the ability to
2393 * concatenate the encrypted forms of those two packets _into_ a
2394 * single blob and then pass it to our <network.h> transport
2395 * layer in one go. Hence, there's a deferment mechanism which
2396 * works after packet encryption.
2398 * - In order to avoid sending any connection-layer messages
2399 * during repeat key exchange, we have to queue up any such
2400 * outgoing messages _before_ they are encrypted (and in
2401 * particular before they're allocated sequence numbers), and
2402 * then send them once we've finished.
2404 * I call these mechanisms `defer' and `queue' respectively, so as
2405 * to distinguish them reasonably easily.
2407 * The functions send_noqueue() and defer_noqueue() free the packet
2408 * structure they are passed. Every outgoing packet goes through
2409 * precisely one of these functions in its life; packets passed to
2410 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
2411 * these or get queued, and then when the queue is later emptied
2412 * the packets are all passed to defer_noqueue().
2414 * When using a CBC-mode cipher, it's necessary to ensure that an
2415 * attacker can't provide data to be encrypted using an IV that they
2416 * know. We ensure this by prefixing each packet that might contain
2417 * user data with an SSH_MSG_IGNORE. This is done using the deferral
2418 * mechanism, so in this case send_noqueue() ends up redirecting to
2419 * defer_noqueue(). If you don't like this inefficiency, don't use
2423 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
2424 static void ssh_pkt_defersend(Ssh);
2427 * Send an SSH-2 packet immediately, without queuing or deferring.
2429 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
2433 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
2434 /* We need to send two packets, so use the deferral mechanism. */
2435 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2436 ssh_pkt_defersend(ssh);
2439 len = ssh2_pkt_construct(ssh, pkt);
2440 backlog = s_write(ssh, pkt->body, len);
2441 if (backlog > SSH_MAX_BACKLOG)
2442 ssh_throttle_all(ssh, 1, backlog);
2444 ssh->outgoing_data_size += pkt->encrypted_len;
2445 if (!ssh->kex_in_progress &&
2446 !ssh->bare_connection &&
2447 ssh->max_data_size != 0 &&
2448 ssh->outgoing_data_size > ssh->max_data_size)
2449 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2451 ssh_free_packet(pkt);
2455 * Defer an SSH-2 packet.
2457 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2460 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2461 ssh->deferred_len == 0 && !noignore &&
2462 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2464 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2465 * get encrypted with a known IV.
2467 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2468 ssh2_pkt_addstring_start(ipkt);
2469 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2471 len = ssh2_pkt_construct(ssh, pkt);
2472 if (ssh->deferred_len + len > ssh->deferred_size) {
2473 ssh->deferred_size = ssh->deferred_len + len + 128;
2474 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2478 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->body, len);
2479 ssh->deferred_len += len;
2480 ssh->deferred_data_size += pkt->encrypted_len;
2481 ssh_free_packet(pkt);
2485 * Queue an SSH-2 packet.
2487 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2489 assert(ssh->queueing);
2491 if (ssh->queuelen >= ssh->queuesize) {
2492 ssh->queuesize = ssh->queuelen + 32;
2493 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2496 ssh->queue[ssh->queuelen++] = pkt;
2500 * Either queue or send a packet, depending on whether queueing is
2503 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2506 ssh2_pkt_queue(ssh, pkt);
2508 ssh2_pkt_send_noqueue(ssh, pkt);
2512 * Either queue or defer a packet, depending on whether queueing is
2515 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2518 ssh2_pkt_queue(ssh, pkt);
2520 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2524 * Send the whole deferred data block constructed by
2525 * ssh2_pkt_defer() or SSH-1's defer_packet().
2527 * The expected use of the defer mechanism is that you call
2528 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2529 * not currently queueing, this simply sets up deferred_send_data
2530 * and then sends it. If we _are_ currently queueing, the calls to
2531 * ssh2_pkt_defer() put the deferred packets on to the queue
2532 * instead, and therefore ssh_pkt_defersend() has no deferred data
2533 * to send. Hence, there's no need to make it conditional on
2536 static void ssh_pkt_defersend(Ssh ssh)
2539 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2540 ssh->deferred_len = ssh->deferred_size = 0;
2541 sfree(ssh->deferred_send_data);
2542 ssh->deferred_send_data = NULL;
2543 if (backlog > SSH_MAX_BACKLOG)
2544 ssh_throttle_all(ssh, 1, backlog);
2546 if (ssh->version == 2) {
2547 ssh->outgoing_data_size += ssh->deferred_data_size;
2548 ssh->deferred_data_size = 0;
2549 if (!ssh->kex_in_progress &&
2550 !ssh->bare_connection &&
2551 ssh->max_data_size != 0 &&
2552 ssh->outgoing_data_size > ssh->max_data_size)
2553 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2558 * Send a packet whose length needs to be disguised (typically
2559 * passwords or keyboard-interactive responses).
2561 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2567 * The simplest way to do this is to adjust the
2568 * variable-length padding field in the outgoing packet.
2570 * Currently compiled out, because some Cisco SSH servers
2571 * don't like excessively padded packets (bah, why's it
2574 pkt->forcepad = padsize;
2575 ssh2_pkt_send(ssh, pkt);
2580 * If we can't do that, however, an alternative approach is
2581 * to use the pkt_defer mechanism to bundle the packet
2582 * tightly together with an SSH_MSG_IGNORE such that their
2583 * combined length is a constant. So first we construct the
2584 * final form of this packet and defer its sending.
2586 ssh2_pkt_defer(ssh, pkt);
2589 * Now construct an SSH_MSG_IGNORE which includes a string
2590 * that's an exact multiple of the cipher block size. (If
2591 * the cipher is NULL so that the block size is
2592 * unavailable, we don't do this trick at all, because we
2593 * gain nothing by it.)
2595 if (ssh->cscipher &&
2596 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2599 stringlen = (256 - ssh->deferred_len);
2600 stringlen += ssh->cscipher->blksize - 1;
2601 stringlen -= (stringlen % ssh->cscipher->blksize);
2604 * Temporarily disable actual compression, so we
2605 * can guarantee to get this string exactly the
2606 * length we want it. The compression-disabling
2607 * routine should return an integer indicating how
2608 * many bytes we should adjust our string length
2612 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2614 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2615 ssh2_pkt_addstring_start(pkt);
2616 for (i = 0; i < stringlen; i++) {
2617 char c = (char) random_byte();
2618 ssh2_pkt_addstring_data(pkt, &c, 1);
2620 ssh2_pkt_defer(ssh, pkt);
2622 ssh_pkt_defersend(ssh);
2627 * Send all queued SSH-2 packets. We send them by means of
2628 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2629 * packets that needed to be lumped together.
2631 static void ssh2_pkt_queuesend(Ssh ssh)
2635 assert(!ssh->queueing);
2637 for (i = 0; i < ssh->queuelen; i++)
2638 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2641 ssh_pkt_defersend(ssh);
2645 void bndebug(char *string, Bignum b)
2649 p = ssh2_mpint_fmt(b, &len);
2650 debug(("%s", string));
2651 for (i = 0; i < len; i++)
2652 debug((" %02x", p[i]));
2658 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2662 p = ssh2_mpint_fmt(b, &len);
2663 hash_string(h, s, p, len);
2668 * Packet decode functions for both SSH-1 and SSH-2.
2670 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2672 unsigned long value;
2673 if (pkt->length - pkt->savedpos < 4)
2674 return 0; /* arrgh, no way to decline (FIXME?) */
2675 value = GET_32BIT(pkt->body + pkt->savedpos);
2679 static int ssh2_pkt_getbool(struct Packet *pkt)
2681 unsigned long value;
2682 if (pkt->length - pkt->savedpos < 1)
2683 return 0; /* arrgh, no way to decline (FIXME?) */
2684 value = pkt->body[pkt->savedpos] != 0;
2688 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2693 if (pkt->length - pkt->savedpos < 4)
2695 len = toint(GET_32BIT(pkt->body + pkt->savedpos));
2700 if (pkt->length - pkt->savedpos < *length)
2702 *p = (char *)(pkt->body + pkt->savedpos);
2703 pkt->savedpos += *length;
2705 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2707 if (pkt->length - pkt->savedpos < length)
2709 pkt->savedpos += length;
2710 return pkt->body + (pkt->savedpos - length);
2712 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2713 const unsigned char **keystr)
2717 j = makekey(pkt->body + pkt->savedpos,
2718 pkt->length - pkt->savedpos,
2725 assert(pkt->savedpos < pkt->length);
2729 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2734 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2735 pkt->length - pkt->savedpos, &b);
2743 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2749 ssh_pkt_getstring(pkt, &p, &length);
2754 b = bignum_from_bytes((unsigned char *)p, length);
2759 * Helper function to add an SSH-2 signature blob to a packet.
2760 * Expects to be shown the public key blob as well as the signature
2761 * blob. Normally works just like ssh2_pkt_addstring, but will
2762 * fiddle with the signature packet if necessary for
2763 * BUG_SSH2_RSA_PADDING.
2765 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2766 void *pkblob_v, int pkblob_len,
2767 void *sigblob_v, int sigblob_len)
2769 unsigned char *pkblob = (unsigned char *)pkblob_v;
2770 unsigned char *sigblob = (unsigned char *)sigblob_v;
2772 /* dmemdump(pkblob, pkblob_len); */
2773 /* dmemdump(sigblob, sigblob_len); */
2776 * See if this is in fact an ssh-rsa signature and a buggy
2777 * server; otherwise we can just do this the easy way.
2779 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) && pkblob_len > 4+7+4 &&
2780 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2781 int pos, len, siglen;
2784 * Find the byte length of the modulus.
2787 pos = 4+7; /* skip over "ssh-rsa" */
2788 len = toint(GET_32BIT(pkblob+pos)); /* get length of exponent */
2789 if (len < 0 || len > pkblob_len - pos - 4)
2791 pos += 4 + len; /* skip over exponent */
2792 if (pkblob_len - pos < 4)
2794 len = toint(GET_32BIT(pkblob+pos)); /* find length of modulus */
2795 if (len < 0 || len > pkblob_len - pos - 4)
2797 pos += 4; /* find modulus itself */
2798 while (len > 0 && pkblob[pos] == 0)
2800 /* debug(("modulus length is %d\n", len)); */
2803 * Now find the signature integer.
2805 pos = 4+7; /* skip over "ssh-rsa" */
2806 if (sigblob_len < pos+4)
2808 siglen = toint(GET_32BIT(sigblob+pos));
2809 if (siglen != sigblob_len - pos - 4)
2811 /* debug(("signature length is %d\n", siglen)); */
2813 if (len != siglen) {
2814 unsigned char newlen[4];
2815 ssh2_pkt_addstring_start(pkt);
2816 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2817 /* dmemdump(sigblob, pos); */
2818 pos += 4; /* point to start of actual sig */
2819 PUT_32BIT(newlen, len);
2820 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2821 /* dmemdump(newlen, 4); */
2823 while (len-- > siglen) {
2824 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2825 /* dmemdump(newlen, 1); */
2827 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2828 /* dmemdump(sigblob+pos, siglen); */
2832 /* Otherwise fall through and do it the easy way. We also come
2833 * here as a fallback if we discover above that the key blob
2834 * is misformatted in some way. */
2838 ssh2_pkt_addstring_start(pkt);
2839 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2843 * Examine the remote side's version string and compare it against
2844 * a list of known buggy implementations.
2846 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2848 char *imp; /* pointer to implementation part */
2850 imp += strcspn(imp, "-");
2852 imp += strcspn(imp, "-");
2855 ssh->remote_bugs = 0;
2858 * General notes on server version strings:
2859 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2860 * here -- in particular, we've heard of one that's perfectly happy
2861 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2862 * so we can't distinguish them.
2864 if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
2865 (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
2866 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2867 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2868 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2869 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2871 * These versions don't support SSH1_MSG_IGNORE, so we have
2872 * to use a different defence against password length
2875 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2876 logevent("We believe remote version has SSH-1 ignore bug");
2879 if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
2880 (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
2881 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2883 * These versions need a plain password sent; they can't
2884 * handle having a null and a random length of data after
2887 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2888 logevent("We believe remote version needs a plain SSH-1 password");
2891 if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
2892 (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
2893 (!strcmp(imp, "Cisco-1.25")))) {
2895 * These versions apparently have no clue whatever about
2896 * RSA authentication and will panic and die if they see
2897 * an AUTH_RSA message.
2899 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2900 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2903 if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
2904 (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
2905 !wc_match("* VShell", imp) &&
2906 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2907 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2908 wc_match("2.1 *", imp)))) {
2910 * These versions have the HMAC bug.
2912 ssh->remote_bugs |= BUG_SSH2_HMAC;
2913 logevent("We believe remote version has SSH-2 HMAC bug");
2916 if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
2917 (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
2918 !wc_match("* VShell", imp) &&
2919 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2921 * These versions have the key-derivation bug (failing to
2922 * include the literal shared secret in the hashes that
2923 * generate the keys).
2925 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2926 logevent("We believe remote version has SSH-2 key-derivation bug");
2929 if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
2930 (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
2931 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2932 wc_match("OpenSSH_3.[0-2]*", imp) ||
2933 wc_match("mod_sftp/0.[0-8]*", imp) ||
2934 wc_match("mod_sftp/0.9.[0-8]", imp)))) {
2936 * These versions have the SSH-2 RSA padding bug.
2938 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2939 logevent("We believe remote version has SSH-2 RSA padding bug");
2942 if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
2943 (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
2944 wc_match("OpenSSH_2.[0-2]*", imp))) {
2946 * These versions have the SSH-2 session-ID bug in
2947 * public-key authentication.
2949 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2950 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2953 if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
2954 (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
2955 (wc_match("DigiSSH_2.0", imp) ||
2956 wc_match("OpenSSH_2.[0-4]*", imp) ||
2957 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2958 wc_match("Sun_SSH_1.0", imp) ||
2959 wc_match("Sun_SSH_1.0.1", imp) ||
2960 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2961 wc_match("WeOnlyDo-*", imp)))) {
2963 * These versions have the SSH-2 rekey bug.
2965 ssh->remote_bugs |= BUG_SSH2_REKEY;
2966 logevent("We believe remote version has SSH-2 rekey bug");
2969 if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
2970 (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
2971 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2972 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2974 * This version ignores our makpkt and needs to be throttled.
2976 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2977 logevent("We believe remote version ignores SSH-2 maximum packet size");
2980 if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
2982 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2983 * none detected automatically.
2985 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2986 logevent("We believe remote version has SSH-2 ignore bug");
2989 if (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == FORCE_ON ||
2990 (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == AUTO &&
2991 (wc_match("OpenSSH_2.[235]*", imp)))) {
2993 * These versions only support the original (pre-RFC4419)
2994 * SSH-2 GEX request, and disconnect with a protocol error if
2995 * we use the newer version.
2997 ssh->remote_bugs |= BUG_SSH2_OLDGEX;
2998 logevent("We believe remote version has outdated SSH-2 GEX");
3001 if (conf_get_int(ssh->conf, CONF_sshbug_winadj) == FORCE_ON) {
3003 * Servers that don't support our winadj request for one
3004 * reason or another. Currently, none detected automatically.
3006 ssh->remote_bugs |= BUG_CHOKES_ON_WINADJ;
3007 logevent("We believe remote version has winadj bug");
3010 if (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == FORCE_ON ||
3011 (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == AUTO &&
3012 (wc_match("OpenSSH_[2-5].*", imp) ||
3013 wc_match("OpenSSH_6.[0-6]*", imp) ||
3014 wc_match("dropbear_0.[2-4][0-9]*", imp) ||
3015 wc_match("dropbear_0.5[01]*", imp)))) {
3017 * These versions have the SSH-2 channel request bug.
3018 * OpenSSH 6.7 and above do not:
3019 * https://bugzilla.mindrot.org/show_bug.cgi?id=1818
3020 * dropbear_0.52 and above do not:
3021 * https://secure.ucc.asn.au/hg/dropbear/rev/cd02449b709c
3023 ssh->remote_bugs |= BUG_SENDS_LATE_REQUEST_REPLY;
3024 logevent("We believe remote version has SSH-2 channel request bug");
3029 * The `software version' part of an SSH version string is required
3030 * to contain no spaces or minus signs.
3032 static void ssh_fix_verstring(char *str)
3034 /* Eat "<protoversion>-". */
3035 while (*str && *str != '-') str++;
3036 assert(*str == '-'); str++;
3038 /* Convert minus signs and spaces in the remaining string into
3041 if (*str == '-' || *str == ' ')
3048 * Send an appropriate SSH version string.
3050 static void ssh_send_verstring(Ssh ssh, const char *protoname, char *svers)
3054 if (ssh->version == 2) {
3056 * Construct a v2 version string.
3058 verstring = dupprintf("%s2.0-%s\015\012", protoname, sshver);
3061 * Construct a v1 version string.
3063 assert(!strcmp(protoname, "SSH-")); /* no v1 bare connection protocol */
3064 verstring = dupprintf("SSH-%s-%s\012",
3065 (ssh_versioncmp(svers, "1.5") <= 0 ?
3070 ssh_fix_verstring(verstring + strlen(protoname));
3072 /* FUZZING make PuTTY insecure, so make live use difficult. */
3076 if (ssh->version == 2) {
3079 * Record our version string.
3081 len = strcspn(verstring, "\015\012");
3082 ssh->v_c = snewn(len + 1, char);
3083 memcpy(ssh->v_c, verstring, len);
3087 logeventf(ssh, "We claim version: %.*s",
3088 strcspn(verstring, "\015\012"), verstring);
3089 s_write(ssh, verstring, strlen(verstring));
3093 static int do_ssh_init(Ssh ssh, unsigned char c)
3095 static const char protoname[] = "SSH-";
3097 struct do_ssh_init_state {
3106 crState(do_ssh_init_state);
3110 /* Search for a line beginning with the protocol name prefix in
3113 for (s->i = 0; protoname[s->i]; s->i++) {
3114 if ((char)c != protoname[s->i]) goto no;
3124 ssh->session_started = TRUE;
3126 s->vstrsize = sizeof(protoname) + 16;
3127 s->vstring = snewn(s->vstrsize, char);
3128 strcpy(s->vstring, protoname);
3129 s->vslen = strlen(protoname);
3132 if (s->vslen >= s->vstrsize - 1) {
3134 s->vstring = sresize(s->vstring, s->vstrsize, char);
3136 s->vstring[s->vslen++] = c;
3139 s->version[s->i] = '\0';
3141 } else if (s->i < sizeof(s->version) - 1)
3142 s->version[s->i++] = c;
3143 } else if (c == '\012')
3145 crReturn(1); /* get another char */
3148 ssh->agentfwd_enabled = FALSE;
3149 ssh->rdpkt2_state.incoming_sequence = 0;
3151 s->vstring[s->vslen] = 0;
3152 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3153 logeventf(ssh, "Server version: %s", s->vstring);
3154 ssh_detect_bugs(ssh, s->vstring);
3157 * Decide which SSH protocol version to support.
3160 /* Anything strictly below "2.0" means protocol 1 is supported. */
3161 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
3162 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
3163 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
3165 if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
3167 bombout(("SSH protocol version 1 required by our configuration "
3168 "but not provided by server"));
3171 } else if (conf_get_int(ssh->conf, CONF_sshprot) == 3) {
3173 bombout(("SSH protocol version 2 required by our configuration "
3174 "but server only provides (old, insecure) SSH-1"));
3178 /* No longer support values 1 or 2 for CONF_sshprot */
3179 assert(!"Unexpected value for CONF_sshprot");
3182 if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
3187 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
3189 /* Send the version string, if we haven't already */
3190 if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
3191 ssh_send_verstring(ssh, protoname, s->version);
3193 if (ssh->version == 2) {
3196 * Record their version string.
3198 len = strcspn(s->vstring, "\015\012");
3199 ssh->v_s = snewn(len + 1, char);
3200 memcpy(ssh->v_s, s->vstring, len);
3204 * Initialise SSH-2 protocol.
3206 ssh->protocol = ssh2_protocol;
3207 ssh2_protocol_setup(ssh);
3208 ssh->s_rdpkt = ssh2_rdpkt;
3211 * Initialise SSH-1 protocol.
3213 ssh->protocol = ssh1_protocol;
3214 ssh1_protocol_setup(ssh);
3215 ssh->s_rdpkt = ssh1_rdpkt;
3217 if (ssh->version == 2)
3218 do_ssh2_transport(ssh, NULL, -1, NULL);
3220 update_specials_menu(ssh->frontend);
3221 ssh->state = SSH_STATE_BEFORE_SIZE;
3222 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3229 static int do_ssh_connection_init(Ssh ssh, unsigned char c)
3232 * Ordinary SSH begins with the banner "SSH-x.y-...". This is just
3233 * the ssh-connection part, extracted and given a trivial binary
3234 * packet protocol, so we replace 'SSH-' at the start with a new
3235 * name. In proper SSH style (though of course this part of the
3236 * proper SSH protocol _isn't_ subject to this kind of
3237 * DNS-domain-based extension), we define the new name in our
3240 static const char protoname[] =
3241 "SSHCONNECTION@putty.projects.tartarus.org-";
3243 struct do_ssh_connection_init_state {
3251 crState(do_ssh_connection_init_state);
3255 /* Search for a line beginning with the protocol name prefix in
3258 for (s->i = 0; protoname[s->i]; s->i++) {
3259 if ((char)c != protoname[s->i]) goto no;
3269 s->vstrsize = sizeof(protoname) + 16;
3270 s->vstring = snewn(s->vstrsize, char);
3271 strcpy(s->vstring, protoname);
3272 s->vslen = strlen(protoname);
3275 if (s->vslen >= s->vstrsize - 1) {
3277 s->vstring = sresize(s->vstring, s->vstrsize, char);
3279 s->vstring[s->vslen++] = c;
3282 s->version[s->i] = '\0';
3284 } else if (s->i < sizeof(s->version) - 1)
3285 s->version[s->i++] = c;
3286 } else if (c == '\012')
3288 crReturn(1); /* get another char */
3291 ssh->agentfwd_enabled = FALSE;
3292 ssh->rdpkt2_bare_state.incoming_sequence = 0;
3294 s->vstring[s->vslen] = 0;
3295 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3296 logeventf(ssh, "Server version: %s", s->vstring);
3297 ssh_detect_bugs(ssh, s->vstring);
3300 * Decide which SSH protocol version to support. This is easy in
3301 * bare ssh-connection mode: only 2.0 is legal.
3303 if (ssh_versioncmp(s->version, "2.0") < 0) {
3304 bombout(("Server announces compatibility with SSH-1 in bare ssh-connection protocol"));
3307 if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
3308 bombout(("Bare ssh-connection protocol cannot be run in SSH-1-only mode"));
3314 logeventf(ssh, "Using bare ssh-connection protocol");
3316 /* Send the version string, if we haven't already */
3317 ssh_send_verstring(ssh, protoname, s->version);
3320 * Initialise bare connection protocol.
3322 ssh->protocol = ssh2_bare_connection_protocol;
3323 ssh2_bare_connection_protocol_setup(ssh);
3324 ssh->s_rdpkt = ssh2_bare_connection_rdpkt;
3326 update_specials_menu(ssh->frontend);
3327 ssh->state = SSH_STATE_BEFORE_SIZE;
3328 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3331 * Get authconn (really just conn) under way.
3333 do_ssh2_authconn(ssh, NULL, 0, NULL);
3340 static void ssh_process_incoming_data(Ssh ssh,
3341 const unsigned char **data, int *datalen)
3343 struct Packet *pktin;
3345 pktin = ssh->s_rdpkt(ssh, data, datalen);
3347 ssh->protocol(ssh, NULL, 0, pktin);
3348 ssh_free_packet(pktin);
3352 static void ssh_queue_incoming_data(Ssh ssh,
3353 const unsigned char **data, int *datalen)
3355 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
3360 static void ssh_process_queued_incoming_data(Ssh ssh)
3363 const unsigned char *data;
3366 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
3367 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
3371 while (!ssh->frozen && len > 0)
3372 ssh_process_incoming_data(ssh, &data, &len);
3375 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
3379 static void ssh_set_frozen(Ssh ssh, int frozen)
3382 sk_set_frozen(ssh->s, frozen);
3383 ssh->frozen = frozen;
3386 static void ssh_gotdata(Ssh ssh, const unsigned char *data, int datalen)
3388 /* Log raw data, if we're in that mode. */
3390 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
3391 0, NULL, NULL, 0, NULL);
3393 crBegin(ssh->ssh_gotdata_crstate);
3396 * To begin with, feed the characters one by one to the
3397 * protocol initialisation / selection function do_ssh_init().
3398 * When that returns 0, we're done with the initial greeting
3399 * exchange and can move on to packet discipline.
3402 int ret; /* need not be kept across crReturn */
3404 crReturnV; /* more data please */
3405 ret = ssh->do_ssh_init(ssh, *data);
3413 * We emerge from that loop when the initial negotiation is
3414 * over and we have selected an s_rdpkt function. Now pass
3415 * everything to s_rdpkt, and then pass the resulting packets
3416 * to the proper protocol handler.
3420 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
3422 ssh_queue_incoming_data(ssh, &data, &datalen);
3423 /* This uses up all data and cannot cause anything interesting
3424 * to happen; indeed, for anything to happen at all, we must
3425 * return, so break out. */
3427 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
3428 /* This uses up some or all data, and may freeze the
3430 ssh_process_queued_incoming_data(ssh);
3432 /* This uses up some or all data, and may freeze the
3434 ssh_process_incoming_data(ssh, &data, &datalen);
3436 /* FIXME this is probably EBW. */
3437 if (ssh->state == SSH_STATE_CLOSED)
3440 /* We're out of data. Go and get some more. */
3446 static int ssh_do_close(Ssh ssh, int notify_exit)
3449 struct ssh_channel *c;
3451 ssh->state = SSH_STATE_CLOSED;
3452 expire_timer_context(ssh);
3457 notify_remote_exit(ssh->frontend);
3462 * Now we must shut down any port- and X-forwarded channels going
3463 * through this connection.
3465 if (ssh->channels) {
3466 while (NULL != (c = index234(ssh->channels, 0))) {
3469 x11_close(c->u.x11.xconn);
3472 case CHAN_SOCKDATA_DORMANT:
3473 pfd_close(c->u.pfd.pf);
3476 del234(ssh->channels, c); /* moving next one to index 0 */
3477 if (ssh->version == 2)
3478 bufchain_clear(&c->v.v2.outbuffer);
3483 * Go through port-forwardings, and close any associated
3484 * listening sockets.
3486 if (ssh->portfwds) {
3487 struct ssh_portfwd *pf;
3488 while (NULL != (pf = index234(ssh->portfwds, 0))) {
3489 /* Dispose of any listening socket. */
3491 pfl_terminate(pf->local);
3492 del234(ssh->portfwds, pf); /* moving next one to index 0 */
3495 freetree234(ssh->portfwds);
3496 ssh->portfwds = NULL;
3500 * Also stop attempting to connection-share.
3502 if (ssh->connshare) {
3503 sharestate_free(ssh->connshare);
3504 ssh->connshare = NULL;
3510 static void ssh_socket_log(Plug plug, int type, SockAddr addr, int port,
3511 const char *error_msg, int error_code)
3513 Ssh ssh = (Ssh) plug;
3516 * While we're attempting connection sharing, don't loudly log
3517 * everything that happens. Real TCP connections need to be logged
3518 * when we _start_ trying to connect, because it might be ages
3519 * before they respond if something goes wrong; but connection
3520 * sharing is local and quick to respond, and it's sufficient to
3521 * simply wait and see whether it worked afterwards.
3524 if (!ssh->attempting_connshare)
3525 backend_socket_log(ssh->frontend, type, addr, port,
3526 error_msg, error_code, ssh->conf,
3527 ssh->session_started);
3530 void ssh_connshare_log(Ssh ssh, int event, const char *logtext,
3531 const char *ds_err, const char *us_err)
3533 if (event == SHARE_NONE) {
3534 /* In this case, 'logtext' is an error message indicating a
3535 * reason why connection sharing couldn't be set up _at all_.
3536 * Failing that, ds_err and us_err indicate why we couldn't be
3537 * a downstream and an upstream respectively. */
3539 logeventf(ssh, "Could not set up connection sharing: %s", logtext);
3542 logeventf(ssh, "Could not set up connection sharing"
3543 " as downstream: %s", ds_err);
3545 logeventf(ssh, "Could not set up connection sharing"
3546 " as upstream: %s", us_err);
3548 } else if (event == SHARE_DOWNSTREAM) {
3549 /* In this case, 'logtext' is a local endpoint address */
3550 logeventf(ssh, "Using existing shared connection at %s", logtext);
3551 /* Also we should mention this in the console window to avoid
3552 * confusing users as to why this window doesn't behave the
3554 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
3555 c_write_str(ssh,"Reusing a shared connection to this server.\r\n");
3557 } else if (event == SHARE_UPSTREAM) {
3558 /* In this case, 'logtext' is a local endpoint address too */
3559 logeventf(ssh, "Sharing this connection at %s", logtext);
3563 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
3566 Ssh ssh = (Ssh) plug;
3567 int need_notify = ssh_do_close(ssh, FALSE);
3570 if (!ssh->close_expected)
3571 error_msg = "Server unexpectedly closed network connection";
3573 error_msg = "Server closed network connection";
3576 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
3580 notify_remote_exit(ssh->frontend);
3583 logevent(error_msg);
3584 if (!ssh->close_expected || !ssh->clean_exit)
3585 connection_fatal(ssh->frontend, "%s", error_msg);
3589 static int ssh_receive(Plug plug, int urgent, char *data, int len)
3591 Ssh ssh = (Ssh) plug;
3592 ssh_gotdata(ssh, (unsigned char *)data, len);
3593 if (ssh->state == SSH_STATE_CLOSED) {
3594 ssh_do_close(ssh, TRUE);
3600 static void ssh_sent(Plug plug, int bufsize)
3602 Ssh ssh = (Ssh) plug;
3604 * If the send backlog on the SSH socket itself clears, we
3605 * should unthrottle the whole world if it was throttled.
3607 if (bufsize < SSH_MAX_BACKLOG)
3608 ssh_throttle_all(ssh, 0, bufsize);
3611 static void ssh_hostport_setup(const char *host, int port, Conf *conf,
3612 char **savedhost, int *savedport,
3615 char *loghost = conf_get_str(conf, CONF_loghost);
3617 *loghost_ret = loghost;
3623 tmphost = dupstr(loghost);
3624 *savedport = 22; /* default ssh port */
3627 * A colon suffix on the hostname string also lets us affect
3628 * savedport. (Unless there are multiple colons, in which case
3629 * we assume this is an unbracketed IPv6 literal.)
3631 colon = host_strrchr(tmphost, ':');
3632 if (colon && colon == host_strchr(tmphost, ':')) {
3635 *savedport = atoi(colon);
3638 *savedhost = host_strduptrim(tmphost);
3641 *savedhost = host_strduptrim(host);
3643 port = 22; /* default ssh port */
3648 static int ssh_test_for_upstream(const char *host, int port, Conf *conf)
3654 random_ref(); /* platform may need this to determine share socket name */
3655 ssh_hostport_setup(host, port, conf, &savedhost, &savedport, NULL);
3656 ret = ssh_share_test_for_upstream(savedhost, savedport, conf);
3664 * Connect to specified host and port.
3665 * Returns an error message, or NULL on success.
3666 * Also places the canonical host name into `realhost'. It must be
3667 * freed by the caller.
3669 static const char *connect_to_host(Ssh ssh, const char *host, int port,
3670 char **realhost, int nodelay, int keepalive)
3672 static const struct plug_function_table fn_table = {
3683 int addressfamily, sshprot;
3685 ssh_hostport_setup(host, port, ssh->conf,
3686 &ssh->savedhost, &ssh->savedport, &loghost);
3688 ssh->fn = &fn_table; /* make 'ssh' usable as a Plug */
3691 * Try connection-sharing, in case that means we don't open a
3692 * socket after all. ssh_connection_sharing_init will connect to a
3693 * previously established upstream if it can, and failing that,
3694 * establish a listening socket for _us_ to be the upstream. In
3695 * the latter case it will return NULL just as if it had done
3696 * nothing, because here we only need to care if we're a
3697 * downstream and need to do our connection setup differently.
3699 ssh->connshare = NULL;
3700 ssh->attempting_connshare = TRUE; /* affects socket logging behaviour */
3701 ssh->s = ssh_connection_sharing_init(ssh->savedhost, ssh->savedport,
3702 ssh->conf, ssh, &ssh->connshare);
3703 ssh->attempting_connshare = FALSE;
3704 if (ssh->s != NULL) {
3706 * We are a downstream.
3708 ssh->bare_connection = TRUE;
3709 ssh->do_ssh_init = do_ssh_connection_init;
3710 ssh->fullhostname = NULL;
3711 *realhost = dupstr(host); /* best we can do */
3714 * We're not a downstream, so open a normal socket.
3716 ssh->do_ssh_init = do_ssh_init;
3721 addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
3722 addr = name_lookup(host, port, realhost, ssh->conf, addressfamily,
3723 ssh->frontend, "SSH connection");
3724 if ((err = sk_addr_error(addr)) != NULL) {
3728 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
3730 ssh->s = new_connection(addr, *realhost, port,
3731 0, 1, nodelay, keepalive,
3732 (Plug) ssh, ssh->conf);
3733 if ((err = sk_socket_error(ssh->s)) != NULL) {
3735 notify_remote_exit(ssh->frontend);
3741 * The SSH version number is always fixed (since we no longer support
3742 * fallback between versions), so set it now, and if it's SSH-2,
3743 * send the version string now too.
3745 sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3746 assert(sshprot == 0 || sshprot == 3);
3750 if (sshprot == 3 && !ssh->bare_connection) {
3753 ssh_send_verstring(ssh, "SSH-", NULL);
3757 * loghost, if configured, overrides realhost.
3761 *realhost = dupstr(loghost);
3768 * Throttle or unthrottle the SSH connection.
3770 static void ssh_throttle_conn(Ssh ssh, int adjust)
3772 int old_count = ssh->conn_throttle_count;
3773 ssh->conn_throttle_count += adjust;
3774 assert(ssh->conn_throttle_count >= 0);
3775 if (ssh->conn_throttle_count && !old_count) {
3776 ssh_set_frozen(ssh, 1);
3777 } else if (!ssh->conn_throttle_count && old_count) {
3778 ssh_set_frozen(ssh, 0);
3783 * Throttle or unthrottle _all_ local data streams (for when sends
3784 * on the SSH connection itself back up).
3786 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3789 struct ssh_channel *c;
3791 if (enable == ssh->throttled_all)
3793 ssh->throttled_all = enable;
3794 ssh->overall_bufsize = bufsize;
3797 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3799 case CHAN_MAINSESSION:
3801 * This is treated separately, outside the switch.
3805 x11_override_throttle(c->u.x11.xconn, enable);
3808 /* Agent channels require no buffer management. */
3811 pfd_override_throttle(c->u.pfd.pf, enable);
3817 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3819 Ssh ssh = (Ssh) sshv;
3821 ssh->agent_response = reply;
3822 ssh->agent_response_len = replylen;
3824 if (ssh->version == 1)
3825 do_ssh1_login(ssh, NULL, -1, NULL);
3827 do_ssh2_authconn(ssh, NULL, -1, NULL);
3830 static void ssh_dialog_callback(void *sshv, int ret)
3832 Ssh ssh = (Ssh) sshv;
3834 ssh->user_response = ret;
3836 if (ssh->version == 1)
3837 do_ssh1_login(ssh, NULL, -1, NULL);
3839 do_ssh2_transport(ssh, NULL, -1, NULL);
3842 * This may have unfrozen the SSH connection, so do a
3845 ssh_process_queued_incoming_data(ssh);
3848 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3850 struct ssh_channel *c = (struct ssh_channel *)cv;
3851 const void *sentreply = reply;
3853 c->u.a.outstanding_requests--;
3855 /* Fake SSH_AGENT_FAILURE. */
3856 sentreply = "\0\0\0\1\5";
3859 ssh_send_channel_data(c, sentreply, replylen);
3863 * If we've already seen an incoming EOF but haven't sent an
3864 * outgoing one, this may be the moment to send it.
3866 if (c->u.a.outstanding_requests == 0 && (c->closes & CLOSES_RCVD_EOF))
3867 sshfwd_write_eof(c);
3871 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3872 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3873 * => log `wire_reason'.
3875 static void ssh_disconnect(Ssh ssh, const char *client_reason,
3876 const char *wire_reason,
3877 int code, int clean_exit)
3881 client_reason = wire_reason;
3883 error = dupprintf("Disconnected: %s", client_reason);
3885 error = dupstr("Disconnected");
3887 if (ssh->version == 1) {
3888 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3890 } else if (ssh->version == 2) {
3891 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3892 ssh2_pkt_adduint32(pktout, code);
3893 ssh2_pkt_addstring(pktout, wire_reason);
3894 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3895 ssh2_pkt_send_noqueue(ssh, pktout);
3898 ssh->close_expected = TRUE;
3899 ssh->clean_exit = clean_exit;
3900 ssh_closing((Plug)ssh, error, 0, 0);
3904 int verify_ssh_manual_host_key(Ssh ssh, const char *fingerprint,
3905 const struct ssh_signkey *ssh2keytype,
3908 if (!conf_get_str_nthstrkey(ssh->conf, CONF_ssh_manual_hostkeys, 0)) {
3909 return -1; /* no manual keys configured */
3914 * The fingerprint string we've been given will have things
3915 * like 'ssh-rsa 2048' at the front of it. Strip those off and
3916 * narrow down to just the colon-separated hex block at the
3917 * end of the string.
3919 const char *p = strrchr(fingerprint, ' ');
3920 fingerprint = p ? p+1 : fingerprint;
3921 /* Quick sanity checks, including making sure it's in lowercase */
3922 assert(strlen(fingerprint) == 16*3 - 1);
3923 assert(fingerprint[2] == ':');
3924 assert(fingerprint[strspn(fingerprint, "0123456789abcdef:")] == 0);
3926 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3928 return 1; /* success */
3933 * Construct the base64-encoded public key blob and see if
3936 unsigned char *binblob;
3938 int binlen, atoms, i;
3939 binblob = ssh2keytype->public_blob(ssh2keydata, &binlen);
3940 atoms = (binlen + 2) / 3;
3941 base64blob = snewn(atoms * 4 + 1, char);
3942 for (i = 0; i < atoms; i++)
3943 base64_encode_atom(binblob + 3*i, binlen - 3*i, base64blob + 4*i);
3944 base64blob[atoms * 4] = '\0';
3946 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3949 return 1; /* success */
3958 * Handle the key exchange and user authentication phases.
3960 static int do_ssh1_login(Ssh ssh, const unsigned char *in, int inlen,
3961 struct Packet *pktin)
3964 unsigned char cookie[8], *ptr;
3965 struct MD5Context md5c;
3966 struct do_ssh1_login_state {
3969 unsigned char *rsabuf;
3970 const unsigned char *keystr1, *keystr2;
3971 unsigned long supported_ciphers_mask, supported_auths_mask;
3972 int tried_publickey, tried_agent;
3973 int tis_auth_refused, ccard_auth_refused;
3974 unsigned char session_id[16];
3976 void *publickey_blob;
3977 int publickey_bloblen;
3978 char *publickey_comment;
3979 int privatekey_available, privatekey_encrypted;
3980 prompts_t *cur_prompt;
3983 unsigned char request[5], *response, *p;
3993 struct RSAKey servkey, hostkey;
3995 crState(do_ssh1_login_state);
4002 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
4003 bombout(("Public key packet not received"));
4007 logevent("Received public keys");
4009 ptr = ssh_pkt_getdata(pktin, 8);
4011 bombout(("SSH-1 public key packet stopped before random cookie"));
4014 memcpy(cookie, ptr, 8);
4016 if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
4017 !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) {
4018 bombout(("Failed to read SSH-1 public keys from public key packet"));
4023 * Log the host key fingerprint.
4027 logevent("Host key fingerprint is:");
4028 strcpy(logmsg, " ");
4029 s->hostkey.comment = NULL;
4030 rsa_fingerprint(logmsg + strlen(logmsg),
4031 sizeof(logmsg) - strlen(logmsg), &s->hostkey);
4035 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
4036 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
4037 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
4038 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
4039 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
4041 ssh->v1_local_protoflags =
4042 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
4043 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
4046 MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
4047 MD5Update(&md5c, s->keystr1, s->servkey.bytes);
4048 MD5Update(&md5c, cookie, 8);
4049 MD5Final(s->session_id, &md5c);
4051 for (i = 0; i < 32; i++)
4052 ssh->session_key[i] = random_byte();
4055 * Verify that the `bits' and `bytes' parameters match.
4057 if (s->hostkey.bits > s->hostkey.bytes * 8 ||
4058 s->servkey.bits > s->servkey.bytes * 8) {
4059 bombout(("SSH-1 public keys were badly formatted"));
4063 s->len = (s->hostkey.bytes > s->servkey.bytes ?
4064 s->hostkey.bytes : s->servkey.bytes);
4066 s->rsabuf = snewn(s->len, unsigned char);
4069 * Verify the host key.
4073 * First format the key into a string.
4075 int len = rsastr_len(&s->hostkey);
4076 char fingerprint[100];
4077 char *keystr = snewn(len, char);
4078 rsastr_fmt(keystr, &s->hostkey);
4079 rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
4081 /* First check against manually configured host keys. */
4082 s->dlgret = verify_ssh_manual_host_key(ssh, fingerprint, NULL, NULL);
4083 if (s->dlgret == 0) { /* did not match */
4084 bombout(("Host key did not appear in manually configured list"));
4087 } else if (s->dlgret < 0) { /* none configured; use standard handling */
4088 ssh_set_frozen(ssh, 1);
4089 s->dlgret = verify_ssh_host_key(ssh->frontend,
4090 ssh->savedhost, ssh->savedport,
4091 "rsa", keystr, fingerprint,
4092 ssh_dialog_callback, ssh);
4097 if (s->dlgret < 0) {
4101 bombout(("Unexpected data from server while waiting"
4102 " for user host key response"));
4105 } while (pktin || inlen > 0);
4106 s->dlgret = ssh->user_response;
4108 ssh_set_frozen(ssh, 0);
4110 if (s->dlgret == 0) {
4111 ssh_disconnect(ssh, "User aborted at host key verification",
4120 for (i = 0; i < 32; i++) {
4121 s->rsabuf[i] = ssh->session_key[i];
4123 s->rsabuf[i] ^= s->session_id[i];
4126 if (s->hostkey.bytes > s->servkey.bytes) {
4127 ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
4129 ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
4131 ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
4133 ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
4136 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
4140 logevent("Encrypted session key");
4143 int cipher_chosen = 0, warn = 0;
4144 const char *cipher_string = NULL;
4146 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
4147 int next_cipher = conf_get_int_int(ssh->conf,
4148 CONF_ssh_cipherlist, i);
4149 if (next_cipher == CIPHER_WARN) {
4150 /* If/when we choose a cipher, warn about it */
4152 } else if (next_cipher == CIPHER_AES) {
4153 /* XXX Probably don't need to mention this. */
4154 logevent("AES not supported in SSH-1, skipping");
4156 switch (next_cipher) {
4157 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
4158 cipher_string = "3DES"; break;
4159 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
4160 cipher_string = "Blowfish"; break;
4161 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
4162 cipher_string = "single-DES"; break;
4164 if (s->supported_ciphers_mask & (1 << s->cipher_type))
4168 if (!cipher_chosen) {
4169 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
4170 bombout(("Server violates SSH-1 protocol by not "
4171 "supporting 3DES encryption"));
4173 /* shouldn't happen */
4174 bombout(("No supported ciphers found"));
4178 /* Warn about chosen cipher if necessary. */
4180 ssh_set_frozen(ssh, 1);
4181 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
4182 ssh_dialog_callback, ssh);
4183 if (s->dlgret < 0) {
4187 bombout(("Unexpected data from server while waiting"
4188 " for user response"));
4191 } while (pktin || inlen > 0);
4192 s->dlgret = ssh->user_response;
4194 ssh_set_frozen(ssh, 0);
4195 if (s->dlgret == 0) {
4196 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
4203 switch (s->cipher_type) {
4204 case SSH_CIPHER_3DES:
4205 logevent("Using 3DES encryption");
4207 case SSH_CIPHER_DES:
4208 logevent("Using single-DES encryption");
4210 case SSH_CIPHER_BLOWFISH:
4211 logevent("Using Blowfish encryption");
4215 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
4216 PKT_CHAR, s->cipher_type,
4217 PKT_DATA, cookie, 8,
4218 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
4219 PKT_DATA, s->rsabuf, s->len,
4220 PKT_INT, ssh->v1_local_protoflags, PKT_END);
4222 logevent("Trying to enable encryption...");
4226 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
4227 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
4229 ssh->v1_cipher_ctx = ssh->cipher->make_context();
4230 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
4231 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
4233 ssh->crcda_ctx = crcda_make_context();
4234 logevent("Installing CRC compensation attack detector");
4236 if (s->servkey.modulus) {
4237 sfree(s->servkey.modulus);
4238 s->servkey.modulus = NULL;
4240 if (s->servkey.exponent) {
4241 sfree(s->servkey.exponent);
4242 s->servkey.exponent = NULL;
4244 if (s->hostkey.modulus) {
4245 sfree(s->hostkey.modulus);
4246 s->hostkey.modulus = NULL;
4248 if (s->hostkey.exponent) {
4249 sfree(s->hostkey.exponent);
4250 s->hostkey.exponent = NULL;
4254 if (pktin->type != SSH1_SMSG_SUCCESS) {
4255 bombout(("Encryption not successfully enabled"));
4259 logevent("Successfully started encryption");
4261 fflush(stdout); /* FIXME eh? */
4263 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
4264 int ret; /* need not be kept over crReturn */
4265 s->cur_prompt = new_prompts(ssh->frontend);
4266 s->cur_prompt->to_server = TRUE;
4267 s->cur_prompt->name = dupstr("SSH login name");
4268 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
4269 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4272 crWaitUntil(!pktin);
4273 ret = get_userpass_input(s->cur_prompt, in, inlen);
4278 * Failed to get a username. Terminate.
4280 free_prompts(s->cur_prompt);
4281 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
4284 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
4285 free_prompts(s->cur_prompt);
4288 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
4290 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
4292 if (flags & FLAG_INTERACTIVE &&
4293 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
4294 c_write_str(ssh, userlog);
4295 c_write_str(ssh, "\r\n");
4303 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
4304 /* We must not attempt PK auth. Pretend we've already tried it. */
4305 s->tried_publickey = s->tried_agent = 1;
4307 s->tried_publickey = s->tried_agent = 0;
4309 s->tis_auth_refused = s->ccard_auth_refused = 0;
4311 * Load the public half of any configured keyfile for later use.
4313 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4314 if (!filename_is_null(s->keyfile)) {
4316 logeventf(ssh, "Reading key file \"%.150s\"",
4317 filename_to_str(s->keyfile));
4318 keytype = key_type(s->keyfile);
4319 if (keytype == SSH_KEYTYPE_SSH1 ||
4320 keytype == SSH_KEYTYPE_SSH1_PUBLIC) {
4322 if (rsakey_pubblob(s->keyfile,
4323 &s->publickey_blob, &s->publickey_bloblen,
4324 &s->publickey_comment, &error)) {
4325 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH1);
4326 if (!s->privatekey_available)
4327 logeventf(ssh, "Key file contains public key only");
4328 s->privatekey_encrypted = rsakey_encrypted(s->keyfile,
4332 logeventf(ssh, "Unable to load key (%s)", error);
4333 msgbuf = dupprintf("Unable to load key file "
4334 "\"%.150s\" (%s)\r\n",
4335 filename_to_str(s->keyfile),
4337 c_write_str(ssh, msgbuf);
4339 s->publickey_blob = NULL;
4343 logeventf(ssh, "Unable to use this key file (%s)",
4344 key_type_to_str(keytype));
4345 msgbuf = dupprintf("Unable to use key file \"%.150s\""
4347 filename_to_str(s->keyfile),
4348 key_type_to_str(keytype));
4349 c_write_str(ssh, msgbuf);
4351 s->publickey_blob = NULL;
4354 s->publickey_blob = NULL;
4356 while (pktin->type == SSH1_SMSG_FAILURE) {
4357 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
4359 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
4361 * Attempt RSA authentication using Pageant.
4367 logevent("Pageant is running. Requesting keys.");
4369 /* Request the keys held by the agent. */
4370 PUT_32BIT(s->request, 1);
4371 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
4372 if (!agent_query(s->request, 5, &r, &s->responselen,
4373 ssh_agent_callback, ssh)) {
4377 bombout(("Unexpected data from server while waiting"
4378 " for agent response"));
4381 } while (pktin || inlen > 0);
4382 r = ssh->agent_response;
4383 s->responselen = ssh->agent_response_len;
4385 s->response = (unsigned char *) r;
4386 if (s->response && s->responselen >= 5 &&
4387 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
4388 s->p = s->response + 5;
4389 s->nkeys = toint(GET_32BIT(s->p));
4391 logeventf(ssh, "Pageant reported negative key count %d",
4396 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
4397 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
4398 unsigned char *pkblob = s->p;
4402 do { /* do while (0) to make breaking easy */
4403 n = ssh1_read_bignum
4404 (s->p, toint(s->responselen-(s->p-s->response)),
4409 n = ssh1_read_bignum
4410 (s->p, toint(s->responselen-(s->p-s->response)),
4415 if (s->responselen - (s->p-s->response) < 4)
4417 s->commentlen = toint(GET_32BIT(s->p));
4419 if (s->commentlen < 0 ||
4420 toint(s->responselen - (s->p-s->response)) <
4423 s->commentp = (char *)s->p;
4424 s->p += s->commentlen;
4428 logevent("Pageant key list packet was truncated");
4432 if (s->publickey_blob) {
4433 if (!memcmp(pkblob, s->publickey_blob,
4434 s->publickey_bloblen)) {
4435 logeventf(ssh, "Pageant key #%d matches "
4436 "configured key file", s->keyi);
4437 s->tried_publickey = 1;
4439 /* Skip non-configured key */
4442 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
4443 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4444 PKT_BIGNUM, s->key.modulus, PKT_END);
4446 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4447 logevent("Key refused");
4450 logevent("Received RSA challenge");
4451 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4452 bombout(("Server's RSA challenge was badly formatted"));
4457 char *agentreq, *q, *ret;
4460 len = 1 + 4; /* message type, bit count */
4461 len += ssh1_bignum_length(s->key.exponent);
4462 len += ssh1_bignum_length(s->key.modulus);
4463 len += ssh1_bignum_length(s->challenge);
4464 len += 16; /* session id */
4465 len += 4; /* response format */
4466 agentreq = snewn(4 + len, char);
4467 PUT_32BIT(agentreq, len);
4469 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
4470 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
4472 q += ssh1_write_bignum(q, s->key.exponent);
4473 q += ssh1_write_bignum(q, s->key.modulus);
4474 q += ssh1_write_bignum(q, s->challenge);
4475 memcpy(q, s->session_id, 16);
4477 PUT_32BIT(q, 1); /* response format */
4478 if (!agent_query(agentreq, len + 4, &vret, &retlen,
4479 ssh_agent_callback, ssh)) {
4484 bombout(("Unexpected data from server"
4485 " while waiting for agent"
4489 } while (pktin || inlen > 0);
4490 vret = ssh->agent_response;
4491 retlen = ssh->agent_response_len;
4496 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
4497 logevent("Sending Pageant's response");
4498 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4499 PKT_DATA, ret + 5, 16,
4503 if (pktin->type == SSH1_SMSG_SUCCESS) {
4505 ("Pageant's response accepted");
4506 if (flags & FLAG_VERBOSE) {
4507 c_write_str(ssh, "Authenticated using"
4509 c_write(ssh, s->commentp,
4511 c_write_str(ssh, "\" from agent\r\n");
4516 ("Pageant's response not accepted");
4519 ("Pageant failed to answer challenge");
4523 logevent("No reply received from Pageant");
4526 freebn(s->key.exponent);
4527 freebn(s->key.modulus);
4528 freebn(s->challenge);
4533 if (s->publickey_blob && !s->tried_publickey)
4534 logevent("Configured key file not in Pageant");
4536 logevent("Failed to get reply from Pageant");
4541 if (s->publickey_blob && s->privatekey_available &&
4542 !s->tried_publickey) {
4544 * Try public key authentication with the specified
4547 int got_passphrase; /* need not be kept over crReturn */
4548 if (flags & FLAG_VERBOSE)
4549 c_write_str(ssh, "Trying public key authentication.\r\n");
4550 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4551 logeventf(ssh, "Trying public key \"%s\"",
4552 filename_to_str(s->keyfile));
4553 s->tried_publickey = 1;
4554 got_passphrase = FALSE;
4555 while (!got_passphrase) {
4557 * Get a passphrase, if necessary.
4559 char *passphrase = NULL; /* only written after crReturn */
4561 if (!s->privatekey_encrypted) {
4562 if (flags & FLAG_VERBOSE)
4563 c_write_str(ssh, "No passphrase required.\r\n");
4566 int ret; /* need not be kept over crReturn */
4567 s->cur_prompt = new_prompts(ssh->frontend);
4568 s->cur_prompt->to_server = FALSE;
4569 s->cur_prompt->name = dupstr("SSH key passphrase");
4570 add_prompt(s->cur_prompt,
4571 dupprintf("Passphrase for key \"%.100s\": ",
4572 s->publickey_comment), FALSE);
4573 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4576 crWaitUntil(!pktin);
4577 ret = get_userpass_input(s->cur_prompt, in, inlen);
4581 /* Failed to get a passphrase. Terminate. */
4582 free_prompts(s->cur_prompt);
4583 ssh_disconnect(ssh, NULL, "Unable to authenticate",
4587 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
4588 free_prompts(s->cur_prompt);
4591 * Try decrypting key with passphrase.
4593 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4594 ret = loadrsakey(s->keyfile, &s->key, passphrase,
4597 smemclr(passphrase, strlen(passphrase));
4601 /* Correct passphrase. */
4602 got_passphrase = TRUE;
4603 } else if (ret == 0) {
4604 c_write_str(ssh, "Couldn't load private key from ");
4605 c_write_str(ssh, filename_to_str(s->keyfile));
4606 c_write_str(ssh, " (");
4607 c_write_str(ssh, error);
4608 c_write_str(ssh, ").\r\n");
4609 got_passphrase = FALSE;
4610 break; /* go and try something else */
4611 } else if (ret == -1) {
4612 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
4613 got_passphrase = FALSE;
4616 assert(0 && "unexpected return from loadrsakey()");
4617 got_passphrase = FALSE; /* placate optimisers */
4621 if (got_passphrase) {
4624 * Send a public key attempt.
4626 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4627 PKT_BIGNUM, s->key.modulus, PKT_END);
4630 if (pktin->type == SSH1_SMSG_FAILURE) {
4631 c_write_str(ssh, "Server refused our public key.\r\n");
4632 continue; /* go and try something else */
4634 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4635 bombout(("Bizarre response to offer of public key"));
4641 unsigned char buffer[32];
4642 Bignum challenge, response;
4644 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4645 bombout(("Server's RSA challenge was badly formatted"));
4648 response = rsadecrypt(challenge, &s->key);
4649 freebn(s->key.private_exponent);/* burn the evidence */
4651 for (i = 0; i < 32; i++) {
4652 buffer[i] = bignum_byte(response, 31 - i);
4656 MD5Update(&md5c, buffer, 32);
4657 MD5Update(&md5c, s->session_id, 16);
4658 MD5Final(buffer, &md5c);
4660 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4661 PKT_DATA, buffer, 16, PKT_END);
4668 if (pktin->type == SSH1_SMSG_FAILURE) {
4669 if (flags & FLAG_VERBOSE)
4670 c_write_str(ssh, "Failed to authenticate with"
4671 " our public key.\r\n");
4672 continue; /* go and try something else */
4673 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4674 bombout(("Bizarre response to RSA authentication response"));
4678 break; /* we're through! */
4684 * Otherwise, try various forms of password-like authentication.
4686 s->cur_prompt = new_prompts(ssh->frontend);
4688 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4689 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
4690 !s->tis_auth_refused) {
4691 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
4692 logevent("Requested TIS authentication");
4693 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
4695 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
4696 logevent("TIS authentication declined");
4697 if (flags & FLAG_INTERACTIVE)
4698 c_write_str(ssh, "TIS authentication refused.\r\n");
4699 s->tis_auth_refused = 1;
4704 char *instr_suf, *prompt;
4706 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4708 bombout(("TIS challenge packet was badly formed"));
4711 logevent("Received TIS challenge");
4712 s->cur_prompt->to_server = TRUE;
4713 s->cur_prompt->name = dupstr("SSH TIS authentication");
4714 /* Prompt heuristic comes from OpenSSH */
4715 if (memchr(challenge, '\n', challengelen)) {
4716 instr_suf = dupstr("");
4717 prompt = dupprintf("%.*s", challengelen, challenge);
4719 instr_suf = dupprintf("%.*s", challengelen, challenge);
4720 prompt = dupstr("Response: ");
4722 s->cur_prompt->instruction =
4723 dupprintf("Using TIS authentication.%s%s",
4724 (*instr_suf) ? "\n" : "",
4726 s->cur_prompt->instr_reqd = TRUE;
4727 add_prompt(s->cur_prompt, prompt, FALSE);
4731 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4732 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
4733 !s->ccard_auth_refused) {
4734 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
4735 logevent("Requested CryptoCard authentication");
4736 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
4738 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
4739 logevent("CryptoCard authentication declined");
4740 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
4741 s->ccard_auth_refused = 1;
4746 char *instr_suf, *prompt;
4748 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4750 bombout(("CryptoCard challenge packet was badly formed"));
4753 logevent("Received CryptoCard challenge");
4754 s->cur_prompt->to_server = TRUE;
4755 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4756 s->cur_prompt->name_reqd = FALSE;
4757 /* Prompt heuristic comes from OpenSSH */
4758 if (memchr(challenge, '\n', challengelen)) {
4759 instr_suf = dupstr("");
4760 prompt = dupprintf("%.*s", challengelen, challenge);
4762 instr_suf = dupprintf("%.*s", challengelen, challenge);
4763 prompt = dupstr("Response: ");
4765 s->cur_prompt->instruction =
4766 dupprintf("Using CryptoCard authentication.%s%s",
4767 (*instr_suf) ? "\n" : "",
4769 s->cur_prompt->instr_reqd = TRUE;
4770 add_prompt(s->cur_prompt, prompt, FALSE);
4774 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4775 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4776 bombout(("No supported authentication methods available"));
4779 s->cur_prompt->to_server = TRUE;
4780 s->cur_prompt->name = dupstr("SSH password");
4781 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4782 ssh->username, ssh->savedhost),
4787 * Show password prompt, having first obtained it via a TIS
4788 * or CryptoCard exchange if we're doing TIS or CryptoCard
4792 int ret; /* need not be kept over crReturn */
4793 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4796 crWaitUntil(!pktin);
4797 ret = get_userpass_input(s->cur_prompt, in, inlen);
4802 * Failed to get a password (for example
4803 * because one was supplied on the command line
4804 * which has already failed to work). Terminate.
4806 free_prompts(s->cur_prompt);
4807 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4812 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4814 * Defence against traffic analysis: we send a
4815 * whole bunch of packets containing strings of
4816 * different lengths. One of these strings is the
4817 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4818 * The others are all random data in
4819 * SSH1_MSG_IGNORE packets. This way a passive
4820 * listener can't tell which is the password, and
4821 * hence can't deduce the password length.
4823 * Anybody with a password length greater than 16
4824 * bytes is going to have enough entropy in their
4825 * password that a listener won't find it _that_
4826 * much help to know how long it is. So what we'll
4829 * - if password length < 16, we send 15 packets
4830 * containing string lengths 1 through 15
4832 * - otherwise, we let N be the nearest multiple
4833 * of 8 below the password length, and send 8
4834 * packets containing string lengths N through
4835 * N+7. This won't obscure the order of
4836 * magnitude of the password length, but it will
4837 * introduce a bit of extra uncertainty.
4839 * A few servers can't deal with SSH1_MSG_IGNORE, at
4840 * least in this context. For these servers, we need
4841 * an alternative defence. We make use of the fact
4842 * that the password is interpreted as a C string:
4843 * so we can append a NUL, then some random data.
4845 * A few servers can deal with neither SSH1_MSG_IGNORE
4846 * here _nor_ a padded password string.
4847 * For these servers we are left with no defences
4848 * against password length sniffing.
4850 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4851 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4853 * The server can deal with SSH1_MSG_IGNORE, so
4854 * we can use the primary defence.
4856 int bottom, top, pwlen, i;
4859 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4861 bottom = 0; /* zero length passwords are OK! :-) */
4864 bottom = pwlen & ~7;
4868 assert(pwlen >= bottom && pwlen <= top);
4870 randomstr = snewn(top + 1, char);
4872 for (i = bottom; i <= top; i++) {
4874 defer_packet(ssh, s->pwpkt_type,
4875 PKT_STR,s->cur_prompt->prompts[0]->result,
4878 for (j = 0; j < i; j++) {
4880 randomstr[j] = random_byte();
4881 } while (randomstr[j] == '\0');
4883 randomstr[i] = '\0';
4884 defer_packet(ssh, SSH1_MSG_IGNORE,
4885 PKT_STR, randomstr, PKT_END);
4888 logevent("Sending password with camouflage packets");
4889 ssh_pkt_defersend(ssh);
4892 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4894 * The server can't deal with SSH1_MSG_IGNORE
4895 * but can deal with padded passwords, so we
4896 * can use the secondary defence.
4902 len = strlen(s->cur_prompt->prompts[0]->result);
4903 if (len < sizeof(string)) {
4905 strcpy(string, s->cur_prompt->prompts[0]->result);
4906 len++; /* cover the zero byte */
4907 while (len < sizeof(string)) {
4908 string[len++] = (char) random_byte();
4911 ss = s->cur_prompt->prompts[0]->result;
4913 logevent("Sending length-padded password");
4914 send_packet(ssh, s->pwpkt_type,
4915 PKT_INT, len, PKT_DATA, ss, len,
4919 * The server is believed unable to cope with
4920 * any of our password camouflage methods.
4923 len = strlen(s->cur_prompt->prompts[0]->result);
4924 logevent("Sending unpadded password");
4925 send_packet(ssh, s->pwpkt_type,
4927 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4931 send_packet(ssh, s->pwpkt_type,
4932 PKT_STR, s->cur_prompt->prompts[0]->result,
4935 logevent("Sent password");
4936 free_prompts(s->cur_prompt);
4938 if (pktin->type == SSH1_SMSG_FAILURE) {
4939 if (flags & FLAG_VERBOSE)
4940 c_write_str(ssh, "Access denied\r\n");
4941 logevent("Authentication refused");
4942 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4943 bombout(("Strange packet received, type %d", pktin->type));
4949 if (s->publickey_blob) {
4950 sfree(s->publickey_blob);
4951 sfree(s->publickey_comment);
4954 logevent("Authentication successful");
4959 static void ssh_channel_try_eof(struct ssh_channel *c)
4962 assert(c->pending_eof); /* precondition for calling us */
4964 return; /* can't close: not even opened yet */
4965 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4966 return; /* can't send EOF: pending outgoing data */
4968 c->pending_eof = FALSE; /* we're about to send it */
4969 if (ssh->version == 1) {
4970 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4972 c->closes |= CLOSES_SENT_EOF;
4974 struct Packet *pktout;
4975 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4976 ssh2_pkt_adduint32(pktout, c->remoteid);
4977 ssh2_pkt_send(ssh, pktout);
4978 c->closes |= CLOSES_SENT_EOF;
4979 ssh2_channel_check_close(c);
4983 Conf *sshfwd_get_conf(struct ssh_channel *c)
4989 void sshfwd_write_eof(struct ssh_channel *c)
4993 if (ssh->state == SSH_STATE_CLOSED)
4996 if (c->closes & CLOSES_SENT_EOF)
4999 c->pending_eof = TRUE;
5000 ssh_channel_try_eof(c);
5003 void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
5007 if (ssh->state == SSH_STATE_CLOSED)
5012 x11_close(c->u.x11.xconn);
5013 logeventf(ssh, "Forwarded X11 connection terminated due to local "
5017 case CHAN_SOCKDATA_DORMANT:
5018 pfd_close(c->u.pfd.pf);
5019 logeventf(ssh, "Forwarded port closed due to local error: %s", err);
5022 c->type = CHAN_ZOMBIE;
5023 c->pending_eof = FALSE; /* this will confuse a zombie channel */
5025 ssh2_channel_check_close(c);
5028 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
5032 if (ssh->state == SSH_STATE_CLOSED)
5035 return ssh_send_channel_data(c, buf, len);
5038 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
5042 if (ssh->state == SSH_STATE_CLOSED)
5045 ssh_channel_unthrottle(c, bufsize);
5048 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
5050 struct queued_handler *qh = ssh->qhead;
5054 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
5057 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
5058 ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
5061 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
5062 ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
5066 ssh->qhead = qh->next;
5068 if (ssh->qhead->msg1 > 0) {
5069 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5070 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
5072 if (ssh->qhead->msg2 > 0) {
5073 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5074 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
5077 ssh->qhead = ssh->qtail = NULL;
5080 qh->handler(ssh, pktin, qh->ctx);
5085 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
5086 chandler_fn_t handler, void *ctx)
5088 struct queued_handler *qh;
5090 qh = snew(struct queued_handler);
5093 qh->handler = handler;
5097 if (ssh->qtail == NULL) {
5101 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5102 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
5105 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5106 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
5109 ssh->qtail->next = qh;
5114 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
5116 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
5118 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
5119 SSH2_MSG_REQUEST_SUCCESS)) {
5120 logeventf(ssh, "Remote port forwarding from %s enabled",
5123 logeventf(ssh, "Remote port forwarding from %s refused",
5126 rpf = del234(ssh->rportfwds, pf);
5128 pf->pfrec->remote = NULL;
5133 int ssh_alloc_sharing_rportfwd(Ssh ssh, const char *shost, int sport,
5136 struct ssh_rportfwd *pf = snew(struct ssh_rportfwd);
5139 pf->share_ctx = share_ctx;
5140 pf->shost = dupstr(shost);
5142 pf->sportdesc = NULL;
5143 if (!ssh->rportfwds) {
5144 assert(ssh->version == 2);
5145 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5147 if (add234(ssh->rportfwds, pf) != pf) {
5155 static void ssh_sharing_global_request_response(Ssh ssh, struct Packet *pktin,
5158 share_got_pkt_from_server(ctx, pktin->type,
5159 pktin->body, pktin->length);
5162 void ssh_sharing_queue_global_request(Ssh ssh, void *share_ctx)
5164 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE,
5165 ssh_sharing_global_request_response, share_ctx);
5168 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
5170 struct ssh_portfwd *epf;
5174 if (!ssh->portfwds) {
5175 ssh->portfwds = newtree234(ssh_portcmp);
5178 * Go through the existing port forwardings and tag them
5179 * with status==DESTROY. Any that we want to keep will be
5180 * re-enabled (status==KEEP) as we go through the
5181 * configuration and find out which bits are the same as
5184 struct ssh_portfwd *epf;
5186 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5187 epf->status = DESTROY;
5190 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
5192 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
5193 char *kp, *kp2, *vp, *vp2;
5194 char address_family, type;
5195 int sport,dport,sserv,dserv;
5196 char *sports, *dports, *saddr, *host;
5200 address_family = 'A';
5202 if (*kp == 'A' || *kp == '4' || *kp == '6')
5203 address_family = *kp++;
5204 if (*kp == 'L' || *kp == 'R')
5207 if ((kp2 = host_strchr(kp, ':')) != NULL) {
5209 * There's a colon in the middle of the source port
5210 * string, which means that the part before it is
5211 * actually a source address.
5213 char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp);
5214 saddr = host_strduptrim(saddr_tmp);
5221 sport = atoi(sports);
5225 sport = net_service_lookup(sports);
5227 logeventf(ssh, "Service lookup failed for source"
5228 " port \"%s\"", sports);
5232 if (type == 'L' && !strcmp(val, "D")) {
5233 /* dynamic forwarding */
5240 /* ordinary forwarding */
5242 vp2 = vp + host_strcspn(vp, ":");
5243 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
5247 dport = atoi(dports);
5251 dport = net_service_lookup(dports);
5253 logeventf(ssh, "Service lookup failed for destination"
5254 " port \"%s\"", dports);
5259 if (sport && dport) {
5260 /* Set up a description of the source port. */
5261 struct ssh_portfwd *pfrec, *epfrec;
5263 pfrec = snew(struct ssh_portfwd);
5265 pfrec->saddr = saddr;
5266 pfrec->sserv = sserv ? dupstr(sports) : NULL;
5267 pfrec->sport = sport;
5268 pfrec->daddr = host;
5269 pfrec->dserv = dserv ? dupstr(dports) : NULL;
5270 pfrec->dport = dport;
5271 pfrec->local = NULL;
5272 pfrec->remote = NULL;
5273 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
5274 address_family == '6' ? ADDRTYPE_IPV6 :
5277 epfrec = add234(ssh->portfwds, pfrec);
5278 if (epfrec != pfrec) {
5279 if (epfrec->status == DESTROY) {
5281 * We already have a port forwarding up and running
5282 * with precisely these parameters. Hence, no need
5283 * to do anything; simply re-tag the existing one
5286 epfrec->status = KEEP;
5289 * Anything else indicates that there was a duplicate
5290 * in our input, which we'll silently ignore.
5292 free_portfwd(pfrec);
5294 pfrec->status = CREATE;
5303 * Now go through and destroy any port forwardings which were
5306 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5307 if (epf->status == DESTROY) {
5310 message = dupprintf("%s port forwarding from %s%s%d",
5311 epf->type == 'L' ? "local" :
5312 epf->type == 'R' ? "remote" : "dynamic",
5313 epf->saddr ? epf->saddr : "",
5314 epf->saddr ? ":" : "",
5317 if (epf->type != 'D') {
5318 char *msg2 = dupprintf("%s to %s:%d", message,
5319 epf->daddr, epf->dport);
5324 logeventf(ssh, "Cancelling %s", message);
5327 /* epf->remote or epf->local may be NULL if setting up a
5328 * forwarding failed. */
5330 struct ssh_rportfwd *rpf = epf->remote;
5331 struct Packet *pktout;
5334 * Cancel the port forwarding at the server
5337 if (ssh->version == 1) {
5339 * We cannot cancel listening ports on the
5340 * server side in SSH-1! There's no message
5341 * to support it. Instead, we simply remove
5342 * the rportfwd record from the local end
5343 * so that any connections the server tries
5344 * to make on it are rejected.
5347 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5348 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
5349 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
5351 ssh2_pkt_addstring(pktout, epf->saddr);
5352 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5353 /* XXX: rport_acceptall may not represent
5354 * what was used to open the original connection,
5355 * since it's reconfigurable. */
5356 ssh2_pkt_addstring(pktout, "");
5358 ssh2_pkt_addstring(pktout, "localhost");
5360 ssh2_pkt_adduint32(pktout, epf->sport);
5361 ssh2_pkt_send(ssh, pktout);
5364 del234(ssh->rportfwds, rpf);
5366 } else if (epf->local) {
5367 pfl_terminate(epf->local);
5370 delpos234(ssh->portfwds, i);
5372 i--; /* so we don't skip one in the list */
5376 * And finally, set up any new port forwardings (status==CREATE).
5378 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5379 if (epf->status == CREATE) {
5380 char *sportdesc, *dportdesc;
5381 sportdesc = dupprintf("%s%s%s%s%d%s",
5382 epf->saddr ? epf->saddr : "",
5383 epf->saddr ? ":" : "",
5384 epf->sserv ? epf->sserv : "",
5385 epf->sserv ? "(" : "",
5387 epf->sserv ? ")" : "");
5388 if (epf->type == 'D') {
5391 dportdesc = dupprintf("%s:%s%s%d%s",
5393 epf->dserv ? epf->dserv : "",
5394 epf->dserv ? "(" : "",
5396 epf->dserv ? ")" : "");
5399 if (epf->type == 'L') {
5400 char *err = pfl_listen(epf->daddr, epf->dport,
5401 epf->saddr, epf->sport,
5402 ssh, conf, &epf->local,
5403 epf->addressfamily);
5405 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
5406 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5407 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5408 sportdesc, dportdesc,
5409 err ? " failed: " : "", err ? err : "");
5412 } else if (epf->type == 'D') {
5413 char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport,
5414 ssh, conf, &epf->local,
5415 epf->addressfamily);
5417 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
5418 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5419 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5421 err ? " failed: " : "", err ? err : "");
5426 struct ssh_rportfwd *pf;
5429 * Ensure the remote port forwardings tree exists.
5431 if (!ssh->rportfwds) {
5432 if (ssh->version == 1)
5433 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
5435 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5438 pf = snew(struct ssh_rportfwd);
5439 pf->share_ctx = NULL;
5440 pf->dhost = dupstr(epf->daddr);
5441 pf->dport = epf->dport;
5443 pf->shost = dupstr(epf->saddr);
5444 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5445 pf->shost = dupstr("");
5447 pf->shost = dupstr("localhost");
5449 pf->sport = epf->sport;
5450 if (add234(ssh->rportfwds, pf) != pf) {
5451 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
5452 epf->daddr, epf->dport);
5455 logeventf(ssh, "Requesting remote port %s"
5456 " forward to %s", sportdesc, dportdesc);
5458 pf->sportdesc = sportdesc;
5463 if (ssh->version == 1) {
5464 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
5465 PKT_INT, epf->sport,
5466 PKT_STR, epf->daddr,
5467 PKT_INT, epf->dport,
5469 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
5471 ssh_rportfwd_succfail, pf);
5473 struct Packet *pktout;
5474 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5475 ssh2_pkt_addstring(pktout, "tcpip-forward");
5476 ssh2_pkt_addbool(pktout, 1);/* want reply */
5477 ssh2_pkt_addstring(pktout, pf->shost);
5478 ssh2_pkt_adduint32(pktout, pf->sport);
5479 ssh2_pkt_send(ssh, pktout);
5481 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
5482 SSH2_MSG_REQUEST_FAILURE,
5483 ssh_rportfwd_succfail, pf);
5492 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
5495 int stringlen, bufsize;
5497 ssh_pkt_getstring(pktin, &string, &stringlen);
5498 if (string == NULL) {
5499 bombout(("Incoming terminal data packet was badly formed"));
5503 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
5505 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
5506 ssh->v1_stdout_throttling = 1;
5507 ssh_throttle_conn(ssh, +1);
5511 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
5513 /* Remote side is trying to open a channel to talk to our
5514 * X-Server. Give them back a local channel number. */
5515 struct ssh_channel *c;
5516 int remoteid = ssh_pkt_getuint32(pktin);
5518 logevent("Received X11 connect request");
5519 /* Refuse if X11 forwarding is disabled. */
5520 if (!ssh->X11_fwd_enabled) {
5521 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5522 PKT_INT, remoteid, PKT_END);
5523 logevent("Rejected X11 connect request");
5525 c = snew(struct ssh_channel);
5528 ssh_channel_init(c);
5529 c->u.x11.xconn = x11_init(ssh->x11authtree, c, NULL, -1);
5530 c->remoteid = remoteid;
5531 c->halfopen = FALSE;
5532 c->type = CHAN_X11; /* identify channel type */
5533 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5534 PKT_INT, c->remoteid, PKT_INT,
5535 c->localid, PKT_END);
5536 logevent("Opened X11 forward channel");
5540 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
5542 /* Remote side is trying to open a channel to talk to our
5543 * agent. Give them back a local channel number. */
5544 struct ssh_channel *c;
5545 int remoteid = ssh_pkt_getuint32(pktin);
5547 /* Refuse if agent forwarding is disabled. */
5548 if (!ssh->agentfwd_enabled) {
5549 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5550 PKT_INT, remoteid, PKT_END);
5552 c = snew(struct ssh_channel);
5554 ssh_channel_init(c);
5555 c->remoteid = remoteid;
5556 c->halfopen = FALSE;
5557 c->type = CHAN_AGENT; /* identify channel type */
5558 c->u.a.lensofar = 0;
5559 c->u.a.message = NULL;
5560 c->u.a.outstanding_requests = 0;
5561 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5562 PKT_INT, c->remoteid, PKT_INT, c->localid,
5567 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
5569 /* Remote side is trying to open a channel to talk to a
5570 * forwarded port. Give them back a local channel number. */
5571 struct ssh_rportfwd pf, *pfp;
5577 remoteid = ssh_pkt_getuint32(pktin);
5578 ssh_pkt_getstring(pktin, &host, &hostsize);
5579 port = ssh_pkt_getuint32(pktin);
5581 pf.dhost = dupprintf("%.*s", hostsize, NULLTOEMPTY(host));
5583 pfp = find234(ssh->rportfwds, &pf, NULL);
5586 logeventf(ssh, "Rejected remote port open request for %s:%d",
5588 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5589 PKT_INT, remoteid, PKT_END);
5591 struct ssh_channel *c = snew(struct ssh_channel);
5594 logeventf(ssh, "Received remote port open request for %s:%d",
5596 err = pfd_connect(&c->u.pfd.pf, pf.dhost, port,
5597 c, ssh->conf, pfp->pfrec->addressfamily);
5599 logeventf(ssh, "Port open failed: %s", err);
5602 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5603 PKT_INT, remoteid, PKT_END);
5605 ssh_channel_init(c);
5606 c->remoteid = remoteid;
5607 c->halfopen = FALSE;
5608 c->type = CHAN_SOCKDATA; /* identify channel type */
5609 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5610 PKT_INT, c->remoteid, PKT_INT,
5611 c->localid, PKT_END);
5612 logevent("Forwarded port opened successfully");
5619 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
5621 struct ssh_channel *c;
5623 c = ssh_channel_msg(ssh, pktin);
5624 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5625 c->remoteid = ssh_pkt_getuint32(pktin);
5626 c->halfopen = FALSE;
5627 c->type = CHAN_SOCKDATA;
5628 c->throttling_conn = 0;
5629 pfd_confirm(c->u.pfd.pf);
5632 if (c && c->pending_eof) {
5634 * We have a pending close on this channel,
5635 * which we decided on before the server acked
5636 * the channel open. So now we know the
5637 * remoteid, we can close it again.
5639 ssh_channel_try_eof(c);
5643 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
5645 struct ssh_channel *c;
5647 c = ssh_channel_msg(ssh, pktin);
5648 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5649 logevent("Forwarded connection refused by server");
5650 pfd_close(c->u.pfd.pf);
5651 del234(ssh->channels, c);
5656 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
5658 /* Remote side closes a channel. */
5659 struct ssh_channel *c;
5661 c = ssh_channel_msg(ssh, pktin);
5664 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
5665 !(c->closes & CLOSES_RCVD_EOF)) {
5667 * Received CHANNEL_CLOSE, which we translate into
5670 int send_close = FALSE;
5672 c->closes |= CLOSES_RCVD_EOF;
5677 x11_send_eof(c->u.x11.xconn);
5683 pfd_send_eof(c->u.pfd.pf);
5692 if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
5693 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
5695 c->closes |= CLOSES_SENT_EOF;
5699 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
5700 !(c->closes & CLOSES_RCVD_CLOSE)) {
5702 if (!(c->closes & CLOSES_SENT_EOF)) {
5703 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %u"
5704 " for which we never sent CHANNEL_CLOSE\n",
5708 c->closes |= CLOSES_RCVD_CLOSE;
5711 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
5712 !(c->closes & CLOSES_SENT_CLOSE)) {
5713 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
5714 PKT_INT, c->remoteid, PKT_END);
5715 c->closes |= CLOSES_SENT_CLOSE;
5718 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
5719 ssh_channel_destroy(c);
5724 * Handle incoming data on an SSH-1 or SSH-2 agent-forwarding channel.
5726 static int ssh_agent_channel_data(struct ssh_channel *c, char *data,
5729 while (length > 0) {
5730 if (c->u.a.lensofar < 4) {
5731 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)length);
5732 memcpy(c->u.a.msglen + c->u.a.lensofar, data, l);
5735 c->u.a.lensofar += l;
5737 if (c->u.a.lensofar == 4) {
5738 c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
5739 c->u.a.message = snewn(c->u.a.totallen, unsigned char);
5740 memcpy(c->u.a.message, c->u.a.msglen, 4);
5742 if (c->u.a.lensofar >= 4 && length > 0) {
5743 unsigned int l = min(c->u.a.totallen - c->u.a.lensofar,
5745 memcpy(c->u.a.message + c->u.a.lensofar, data, l);
5748 c->u.a.lensofar += l;
5750 if (c->u.a.lensofar == c->u.a.totallen) {
5753 c->u.a.outstanding_requests++;
5754 if (agent_query(c->u.a.message, c->u.a.totallen, &reply, &replylen,
5755 ssh_agentf_callback, c))
5756 ssh_agentf_callback(c, reply, replylen);
5757 sfree(c->u.a.message);
5758 c->u.a.message = NULL;
5759 c->u.a.lensofar = 0;
5762 return 0; /* agent channels never back up */
5765 static int ssh_channel_data(struct ssh_channel *c, int is_stderr,
5766 char *data, int length)
5769 case CHAN_MAINSESSION:
5770 return from_backend(c->ssh->frontend, is_stderr, data, length);
5772 return x11_send(c->u.x11.xconn, data, length);
5774 return pfd_send(c->u.pfd.pf, data, length);
5776 return ssh_agent_channel_data(c, data, length);
5781 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
5783 /* Data sent down one of our channels. */
5786 struct ssh_channel *c;
5788 c = ssh_channel_msg(ssh, pktin);
5789 ssh_pkt_getstring(pktin, &p, &len);
5792 int bufsize = ssh_channel_data(c, FALSE, p, len);
5793 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5794 c->throttling_conn = 1;
5795 ssh_throttle_conn(ssh, +1);
5800 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5802 ssh->exitcode = ssh_pkt_getuint32(pktin);
5803 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5804 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5806 * In case `helpful' firewalls or proxies tack
5807 * extra human-readable text on the end of the
5808 * session which we might mistake for another
5809 * encrypted packet, we close the session once
5810 * we've sent EXIT_CONFIRMATION.
5812 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5815 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5816 static void ssh1_send_ttymode(void *data,
5817 const struct ssh_ttymode *mode, char *val)
5819 struct Packet *pktout = (struct Packet *)data;
5820 unsigned int arg = 0;
5822 switch (mode->type) {
5824 arg = ssh_tty_parse_specchar(val);
5827 arg = ssh_tty_parse_boolean(val);
5830 ssh2_pkt_addbyte(pktout, mode->opcode);
5831 ssh2_pkt_addbyte(pktout, arg);
5834 int ssh_agent_forwarding_permitted(Ssh ssh)
5836 return conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists();
5839 static void do_ssh1_connection(Ssh ssh, const unsigned char *in, int inlen,
5840 struct Packet *pktin)
5842 crBegin(ssh->do_ssh1_connection_crstate);
5844 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5845 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5846 ssh1_smsg_stdout_stderr_data;
5848 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5849 ssh1_msg_channel_open_confirmation;
5850 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5851 ssh1_msg_channel_open_failure;
5852 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5853 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5854 ssh1_msg_channel_close;
5855 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5856 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5858 if (ssh_agent_forwarding_permitted(ssh)) {
5859 logevent("Requesting agent forwarding");
5860 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5864 if (pktin->type != SSH1_SMSG_SUCCESS
5865 && pktin->type != SSH1_SMSG_FAILURE) {
5866 bombout(("Protocol confusion"));
5868 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5869 logevent("Agent forwarding refused");
5871 logevent("Agent forwarding enabled");
5872 ssh->agentfwd_enabled = TRUE;
5873 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5877 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
5879 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5881 if (!ssh->x11disp) {
5882 /* FIXME: return an error message from x11_setup_display */
5883 logevent("X11 forwarding not enabled: unable to"
5884 " initialise X display");
5886 ssh->x11auth = x11_invent_fake_auth
5887 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
5888 ssh->x11auth->disp = ssh->x11disp;
5890 logevent("Requesting X11 forwarding");
5891 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5892 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5893 PKT_STR, ssh->x11auth->protoname,
5894 PKT_STR, ssh->x11auth->datastring,
5895 PKT_INT, ssh->x11disp->screennum,
5898 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5899 PKT_STR, ssh->x11auth->protoname,
5900 PKT_STR, ssh->x11auth->datastring,
5906 if (pktin->type != SSH1_SMSG_SUCCESS
5907 && pktin->type != SSH1_SMSG_FAILURE) {
5908 bombout(("Protocol confusion"));
5910 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5911 logevent("X11 forwarding refused");
5913 logevent("X11 forwarding enabled");
5914 ssh->X11_fwd_enabled = TRUE;
5915 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5920 ssh_setup_portfwd(ssh, ssh->conf);
5921 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5923 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5925 /* Unpick the terminal-speed string. */
5926 /* XXX perhaps we should allow no speeds to be sent. */
5927 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5928 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5929 /* Send the pty request. */
5930 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5931 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5932 ssh_pkt_adduint32(pkt, ssh->term_height);
5933 ssh_pkt_adduint32(pkt, ssh->term_width);
5934 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5935 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5936 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5937 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5938 ssh_pkt_adduint32(pkt, ssh->ispeed);
5939 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5940 ssh_pkt_adduint32(pkt, ssh->ospeed);
5941 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5943 ssh->state = SSH_STATE_INTERMED;
5947 if (pktin->type != SSH1_SMSG_SUCCESS
5948 && pktin->type != SSH1_SMSG_FAILURE) {
5949 bombout(("Protocol confusion"));
5951 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5952 c_write_str(ssh, "Server refused to allocate pty\r\n");
5953 ssh->editing = ssh->echoing = 1;
5955 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5956 ssh->ospeed, ssh->ispeed);
5957 ssh->got_pty = TRUE;
5960 ssh->editing = ssh->echoing = 1;
5963 if (conf_get_int(ssh->conf, CONF_compression)) {
5964 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5968 if (pktin->type != SSH1_SMSG_SUCCESS
5969 && pktin->type != SSH1_SMSG_FAILURE) {
5970 bombout(("Protocol confusion"));
5972 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5973 c_write_str(ssh, "Server refused to compress\r\n");
5975 logevent("Started compression");
5976 ssh->v1_compressing = TRUE;
5977 ssh->cs_comp_ctx = zlib_compress_init();
5978 logevent("Initialised zlib (RFC1950) compression");
5979 ssh->sc_comp_ctx = zlib_decompress_init();
5980 logevent("Initialised zlib (RFC1950) decompression");
5984 * Start the shell or command.
5986 * Special case: if the first-choice command is an SSH-2
5987 * subsystem (hence not usable here) and the second choice
5988 * exists, we fall straight back to that.
5991 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
5993 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
5994 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
5995 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
5996 ssh->fallback_cmd = TRUE;
5999 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
6001 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
6002 logevent("Started session");
6005 ssh->state = SSH_STATE_SESSION;
6006 if (ssh->size_needed)
6007 ssh_size(ssh, ssh->term_width, ssh->term_height);
6008 if (ssh->eof_needed)
6009 ssh_special(ssh, TS_EOF);
6012 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
6014 ssh->channels = newtree234(ssh_channelcmp);
6018 * By this point, most incoming packets are already being
6019 * handled by the dispatch table, and we need only pay
6020 * attention to the unusual ones.
6025 if (pktin->type == SSH1_SMSG_SUCCESS) {
6026 /* may be from EXEC_SHELL on some servers */
6027 } else if (pktin->type == SSH1_SMSG_FAILURE) {
6028 /* may be from EXEC_SHELL on some servers
6029 * if no pty is available or in other odd cases. Ignore */
6031 bombout(("Strange packet received: type %d", pktin->type));
6036 int len = min(inlen, 512);
6037 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
6038 PKT_INT, len, PKT_DATA, in, len,
6050 * Handle the top-level SSH-2 protocol.
6052 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
6057 ssh_pkt_getstring(pktin, &msg, &msglen);
6058 logeventf(ssh, "Remote debug message: %.*s", msglen, NULLTOEMPTY(msg));
6061 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
6063 /* log reason code in disconnect message */
6067 ssh_pkt_getstring(pktin, &msg, &msglen);
6068 bombout(("Server sent disconnect message:\n\"%.*s\"",
6069 msglen, NULLTOEMPTY(msg)));
6072 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
6074 /* Do nothing, because we're ignoring it! Duhh. */
6077 static void ssh1_protocol_setup(Ssh ssh)
6082 * Most messages are handled by the coroutines.
6084 for (i = 0; i < 256; i++)
6085 ssh->packet_dispatch[i] = NULL;
6088 * These special message types we install handlers for.
6090 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
6091 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
6092 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
6095 static void ssh1_protocol(Ssh ssh, const void *vin, int inlen,
6096 struct Packet *pktin)
6098 const unsigned char *in = (const unsigned char *)vin;
6099 if (ssh->state == SSH_STATE_CLOSED)
6102 if (pktin && ssh->packet_dispatch[pktin->type]) {
6103 ssh->packet_dispatch[pktin->type](ssh, pktin);
6107 if (!ssh->protocol_initial_phase_done) {
6108 if (do_ssh1_login(ssh, in, inlen, pktin))
6109 ssh->protocol_initial_phase_done = TRUE;
6114 do_ssh1_connection(ssh, in, inlen, pktin);
6118 * Utility routines for decoding comma-separated strings in KEXINIT.
6120 static int first_in_commasep_string(char const *needle, char const *haystack,
6124 if (!needle || !haystack) /* protect against null pointers */
6126 needlen = strlen(needle);
6128 if (haylen >= needlen && /* haystack is long enough */
6129 !memcmp(needle, haystack, needlen) && /* initial match */
6130 (haylen == needlen || haystack[needlen] == ',')
6131 /* either , or EOS follows */
6137 static int in_commasep_string(char const *needle, char const *haystack,
6142 if (!needle || !haystack) /* protect against null pointers */
6145 * Is it at the start of the string?
6147 if (first_in_commasep_string(needle, haystack, haylen))
6150 * If not, search for the next comma and resume after that.
6151 * If no comma found, terminate.
6153 p = memchr(haystack, ',', haylen);
6155 /* + 1 to skip over comma */
6156 return in_commasep_string(needle, p + 1, haylen - (p + 1 - haystack));
6160 * Add a value to the comma-separated string at the end of the packet.
6162 static void ssh2_pkt_addstring_commasep(struct Packet *pkt, const char *data)
6164 if (pkt->length - pkt->savedpos > 0)
6165 ssh_pkt_addstring_str(pkt, ",");
6166 ssh_pkt_addstring_str(pkt, data);
6171 * SSH-2 key derivation (RFC 4253 section 7.2).
6173 static unsigned char *ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H,
6174 char chr, int keylen)
6176 const struct ssh_hash *h = ssh->kex->hash;
6184 /* Round up to the next multiple of hash length. */
6185 keylen_padded = ((keylen + h->hlen - 1) / h->hlen) * h->hlen;
6187 key = snewn(keylen_padded, unsigned char);
6189 /* First hlen bytes. */
6191 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6192 hash_mpint(h, s, K);
6193 h->bytes(s, H, h->hlen);
6194 h->bytes(s, &chr, 1);
6195 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
6198 /* Subsequent blocks of hlen bytes. */
6199 if (keylen_padded > h->hlen) {
6203 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6204 hash_mpint(h, s, K);
6205 h->bytes(s, H, h->hlen);
6207 for (offset = h->hlen; offset < keylen_padded; offset += h->hlen) {
6208 h->bytes(s, key + offset - h->hlen, h->hlen);
6210 h->final(s2, key + offset);
6216 /* Now clear any extra bytes of key material beyond the length
6217 * we're officially returning, because the caller won't know to
6219 if (keylen_padded > keylen)
6220 smemclr(key + keylen, keylen_padded - keylen);
6226 * Structure for constructing KEXINIT algorithm lists.
6228 #define MAXKEXLIST 16
6229 struct kexinit_algorithm {
6233 const struct ssh_kex *kex;
6237 const struct ssh_signkey *hostkey;
6241 const struct ssh2_cipher *cipher;
6245 const struct ssh_mac *mac;
6248 const struct ssh_compress *comp;
6253 * Find a slot in a KEXINIT algorithm list to use for a new algorithm.
6254 * If the algorithm is already in the list, return a pointer to its
6255 * entry, otherwise return an entry from the end of the list.
6256 * This assumes that every time a particular name is passed in, it
6257 * comes from the same string constant. If this isn't true, this
6258 * function may need to be rewritten to use strcmp() instead.
6260 static struct kexinit_algorithm *ssh2_kexinit_addalg(struct kexinit_algorithm
6261 *list, const char *name)
6265 for (i = 0; i < MAXKEXLIST; i++)
6266 if (list[i].name == NULL || list[i].name == name) {
6267 list[i].name = name;
6270 assert(!"No space in KEXINIT list");
6275 * Handle the SSH-2 transport layer.
6277 static void do_ssh2_transport(Ssh ssh, const void *vin, int inlen,
6278 struct Packet *pktin)
6280 const unsigned char *in = (const unsigned char *)vin;
6282 KEXLIST_KEX, KEXLIST_HOSTKEY, KEXLIST_CSCIPHER, KEXLIST_SCCIPHER,
6283 KEXLIST_CSMAC, KEXLIST_SCMAC, KEXLIST_CSCOMP, KEXLIST_SCCOMP,
6286 const char * kexlist_descr[NKEXLIST] = {
6287 "key exchange algorithm", "host key algorithm",
6288 "client-to-server cipher", "server-to-client cipher",
6289 "client-to-server MAC", "server-to-client MAC",
6290 "client-to-server compression method",
6291 "server-to-client compression method" };
6292 struct do_ssh2_transport_state {
6294 int nbits, pbits, warn_kex, warn_hk, warn_cscipher, warn_sccipher;
6295 Bignum p, g, e, f, K;
6298 int kex_init_value, kex_reply_value;
6299 const struct ssh_mac *const *maclist;
6301 const struct ssh2_cipher *cscipher_tobe;
6302 const struct ssh2_cipher *sccipher_tobe;
6303 const struct ssh_mac *csmac_tobe;
6304 const struct ssh_mac *scmac_tobe;
6305 int csmac_etm_tobe, scmac_etm_tobe;
6306 const struct ssh_compress *cscomp_tobe;
6307 const struct ssh_compress *sccomp_tobe;
6308 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
6309 int hostkeylen, siglen, rsakeylen;
6310 void *hkey; /* actual host key */
6311 void *rsakey; /* for RSA kex */
6312 void *eckey; /* for ECDH kex */
6313 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
6314 int n_preferred_kex;
6315 const struct ssh_kexes *preferred_kex[KEX_MAX];
6317 int preferred_hk[HK_MAX];
6318 int n_preferred_ciphers;
6319 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
6320 const struct ssh_compress *preferred_comp;
6321 int userauth_succeeded; /* for delayed compression */
6322 int pending_compression;
6323 int got_session_id, activated_authconn;
6324 struct Packet *pktout;
6328 struct kexinit_algorithm kexlists[NKEXLIST][MAXKEXLIST];
6330 crState(do_ssh2_transport_state);
6332 assert(!ssh->bare_connection);
6333 assert(ssh->version == 2);
6337 s->cscipher_tobe = s->sccipher_tobe = NULL;
6338 s->csmac_tobe = s->scmac_tobe = NULL;
6339 s->cscomp_tobe = s->sccomp_tobe = NULL;
6341 s->got_session_id = s->activated_authconn = FALSE;
6342 s->userauth_succeeded = FALSE;
6343 s->pending_compression = FALSE;
6346 * Be prepared to work around the buggy MAC problem.
6348 if (ssh->remote_bugs & BUG_SSH2_HMAC)
6349 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
6351 s->maclist = macs, s->nmacs = lenof(macs);
6354 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
6357 struct kexinit_algorithm *alg;
6360 * Set up the preferred key exchange. (NULL => warn below here)
6362 s->n_preferred_kex = 0;
6363 for (i = 0; i < KEX_MAX; i++) {
6364 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
6366 s->preferred_kex[s->n_preferred_kex++] =
6367 &ssh_diffiehellman_gex;
6370 s->preferred_kex[s->n_preferred_kex++] =
6371 &ssh_diffiehellman_group14;
6374 s->preferred_kex[s->n_preferred_kex++] =
6375 &ssh_diffiehellman_group1;
6378 s->preferred_kex[s->n_preferred_kex++] =
6382 s->preferred_kex[s->n_preferred_kex++] =
6386 /* Flag for later. Don't bother if it's the last in
6388 if (i < KEX_MAX - 1) {
6389 s->preferred_kex[s->n_preferred_kex++] = NULL;
6396 * Set up the preferred host key types. These are just the ids
6397 * in the enum in putty.h, so 'warn below here' is indicated
6400 s->n_preferred_hk = 0;
6401 for (i = 0; i < HK_MAX; i++) {
6402 int id = conf_get_int_int(ssh->conf, CONF_ssh_hklist, i);
6403 /* As above, don't bother with HK_WARN if it's last in the
6405 if (id != HK_WARN || i < HK_MAX - 1)
6406 s->preferred_hk[s->n_preferred_hk++] = id;
6410 * Set up the preferred ciphers. (NULL => warn below here)
6412 s->n_preferred_ciphers = 0;
6413 for (i = 0; i < CIPHER_MAX; i++) {
6414 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
6415 case CIPHER_BLOWFISH:
6416 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
6419 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
6420 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
6424 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
6427 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
6429 case CIPHER_ARCFOUR:
6430 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
6432 case CIPHER_CHACHA20:
6433 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_ccp;
6436 /* Flag for later. Don't bother if it's the last in
6438 if (i < CIPHER_MAX - 1) {
6439 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
6446 * Set up preferred compression.
6448 if (conf_get_int(ssh->conf, CONF_compression))
6449 s->preferred_comp = &ssh_zlib;
6451 s->preferred_comp = &ssh_comp_none;
6454 * Enable queueing of outgoing auth- or connection-layer
6455 * packets while we are in the middle of a key exchange.
6457 ssh->queueing = TRUE;
6460 * Flag that KEX is in progress.
6462 ssh->kex_in_progress = TRUE;
6464 for (i = 0; i < NKEXLIST; i++)
6465 for (j = 0; j < MAXKEXLIST; j++)
6466 s->kexlists[i][j].name = NULL;
6467 /* List key exchange algorithms. */
6469 for (i = 0; i < s->n_preferred_kex; i++) {
6470 const struct ssh_kexes *k = s->preferred_kex[i];
6471 if (!k) warn = TRUE;
6472 else for (j = 0; j < k->nkexes; j++) {
6473 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_KEX],
6475 alg->u.kex.kex = k->list[j];
6476 alg->u.kex.warn = warn;
6479 /* List server host key algorithms. */
6480 if (!s->got_session_id) {
6482 * In the first key exchange, we list all the algorithms
6483 * we're prepared to cope with, but prefer those algorithms
6484 * for which we have a host key for this host.
6486 * If the host key algorithm is below the warning
6487 * threshold, we warn even if we did already have a key
6488 * for it, on the basis that if the user has just
6489 * reconfigured that host key type to be warned about,
6490 * they surely _do_ want to be alerted that a server
6491 * they're actually connecting to is using it.
6494 for (i = 0; i < s->n_preferred_hk; i++) {
6495 if (s->preferred_hk[i] == HK_WARN)
6497 for (j = 0; j < lenof(hostkey_algs); j++) {
6498 if (hostkey_algs[j].id != s->preferred_hk[i])
6500 if (have_ssh_host_key(ssh->savedhost, ssh->savedport,
6501 hostkey_algs[j].alg->keytype)) {
6502 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6503 hostkey_algs[j].alg->name);
6504 alg->u.hk.hostkey = hostkey_algs[j].alg;
6505 alg->u.hk.warn = warn;
6510 for (i = 0; i < s->n_preferred_hk; i++) {
6511 if (s->preferred_hk[i] == HK_WARN)
6513 for (j = 0; j < lenof(hostkey_algs); j++) {
6514 if (hostkey_algs[j].id != s->preferred_hk[i])
6516 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6517 hostkey_algs[j].alg->name);
6518 alg->u.hk.hostkey = hostkey_algs[j].alg;
6519 alg->u.hk.warn = warn;
6524 * In subsequent key exchanges, we list only the kex
6525 * algorithm that was selected in the first key exchange,
6526 * so that we keep getting the same host key and hence
6527 * don't have to interrupt the user's session to ask for
6531 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6532 ssh->hostkey->name);
6533 alg->u.hk.hostkey = ssh->hostkey;
6534 alg->u.hk.warn = FALSE;
6536 /* List encryption algorithms (client->server then server->client). */
6537 for (k = KEXLIST_CSCIPHER; k <= KEXLIST_SCCIPHER; k++) {
6540 alg = ssh2_kexinit_addalg(s->kexlists[k], "none");
6541 alg->u.cipher.cipher = NULL;
6542 alg->u.cipher.warn = warn;
6543 #endif /* FUZZING */
6544 for (i = 0; i < s->n_preferred_ciphers; i++) {
6545 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6546 if (!c) warn = TRUE;
6547 else for (j = 0; j < c->nciphers; j++) {
6548 alg = ssh2_kexinit_addalg(s->kexlists[k],
6550 alg->u.cipher.cipher = c->list[j];
6551 alg->u.cipher.warn = warn;
6555 /* List MAC algorithms (client->server then server->client). */
6556 for (j = KEXLIST_CSMAC; j <= KEXLIST_SCMAC; j++) {
6558 alg = ssh2_kexinit_addalg(s->kexlists[j], "none");
6559 alg->u.mac.mac = NULL;
6560 alg->u.mac.etm = FALSE;
6561 #endif /* FUZZING */
6562 for (i = 0; i < s->nmacs; i++) {
6563 alg = ssh2_kexinit_addalg(s->kexlists[j], s->maclist[i]->name);
6564 alg->u.mac.mac = s->maclist[i];
6565 alg->u.mac.etm = FALSE;
6567 for (i = 0; i < s->nmacs; i++)
6568 /* For each MAC, there may also be an ETM version,
6569 * which we list second. */
6570 if (s->maclist[i]->etm_name) {
6571 alg = ssh2_kexinit_addalg(s->kexlists[j],
6572 s->maclist[i]->etm_name);
6573 alg->u.mac.mac = s->maclist[i];
6574 alg->u.mac.etm = TRUE;
6577 /* List client->server compression algorithms,
6578 * then server->client compression algorithms. (We use the
6579 * same set twice.) */
6580 for (j = KEXLIST_CSCOMP; j <= KEXLIST_SCCOMP; j++) {
6581 assert(lenof(compressions) > 1);
6582 /* Prefer non-delayed versions */
6583 alg = ssh2_kexinit_addalg(s->kexlists[j], s->preferred_comp->name);
6584 alg->u.comp = s->preferred_comp;
6585 /* We don't even list delayed versions of algorithms until
6586 * they're allowed to be used, to avoid a race. See the end of
6588 if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
6589 alg = ssh2_kexinit_addalg(s->kexlists[j],
6590 s->preferred_comp->delayed_name);
6591 alg->u.comp = s->preferred_comp;
6593 for (i = 0; i < lenof(compressions); i++) {
6594 const struct ssh_compress *c = compressions[i];
6595 alg = ssh2_kexinit_addalg(s->kexlists[j], c->name);
6597 if (s->userauth_succeeded && c->delayed_name) {
6598 alg = ssh2_kexinit_addalg(s->kexlists[j], c->delayed_name);
6604 * Construct and send our key exchange packet.
6606 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
6607 for (i = 0; i < 16; i++)
6608 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
6609 for (i = 0; i < NKEXLIST; i++) {
6610 ssh2_pkt_addstring_start(s->pktout);
6611 for (j = 0; j < MAXKEXLIST; j++) {
6612 if (s->kexlists[i][j].name == NULL) break;
6613 ssh2_pkt_addstring_commasep(s->pktout, s->kexlists[i][j].name);
6616 /* List client->server languages. Empty list. */
6617 ssh2_pkt_addstring_start(s->pktout);
6618 /* List server->client languages. Empty list. */
6619 ssh2_pkt_addstring_start(s->pktout);
6620 /* First KEX packet does _not_ follow, because we're not that brave. */
6621 ssh2_pkt_addbool(s->pktout, FALSE);
6623 ssh2_pkt_adduint32(s->pktout, 0);
6626 s->our_kexinitlen = s->pktout->length - 5;
6627 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
6628 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
6630 ssh2_pkt_send_noqueue(ssh, s->pktout);
6633 crWaitUntilV(pktin);
6636 * Now examine the other side's KEXINIT to see what we're up
6643 if (pktin->type != SSH2_MSG_KEXINIT) {
6644 bombout(("expected key exchange packet from server"));
6648 ssh->hostkey = NULL;
6649 s->cscipher_tobe = NULL;
6650 s->sccipher_tobe = NULL;
6651 s->csmac_tobe = NULL;
6652 s->scmac_tobe = NULL;
6653 s->cscomp_tobe = NULL;
6654 s->sccomp_tobe = NULL;
6655 s->warn_kex = s->warn_hk = FALSE;
6656 s->warn_cscipher = s->warn_sccipher = FALSE;
6658 pktin->savedpos += 16; /* skip garbage cookie */
6661 for (i = 0; i < NKEXLIST; i++) {
6662 ssh_pkt_getstring(pktin, &str, &len);
6664 bombout(("KEXINIT packet was incomplete"));
6668 /* If we've already selected a cipher which requires a
6669 * particular MAC, then just select that, and don't even
6670 * bother looking through the server's KEXINIT string for
6672 if (i == KEXLIST_CSMAC && s->cscipher_tobe &&
6673 s->cscipher_tobe->required_mac) {
6674 s->csmac_tobe = s->cscipher_tobe->required_mac;
6675 s->csmac_etm_tobe = !!(s->csmac_tobe->etm_name);
6678 if (i == KEXLIST_SCMAC && s->sccipher_tobe &&
6679 s->sccipher_tobe->required_mac) {
6680 s->scmac_tobe = s->sccipher_tobe->required_mac;
6681 s->scmac_etm_tobe = !!(s->scmac_tobe->etm_name);
6685 for (j = 0; j < MAXKEXLIST; j++) {
6686 struct kexinit_algorithm *alg = &s->kexlists[i][j];
6687 if (alg->name == NULL) break;
6688 if (in_commasep_string(alg->name, str, len)) {
6689 /* We've found a matching algorithm. */
6690 if (i == KEXLIST_KEX || i == KEXLIST_HOSTKEY) {
6691 /* Check if we might need to ignore first kex pkt */
6693 !first_in_commasep_string(alg->name, str, len))
6696 if (i == KEXLIST_KEX) {
6697 ssh->kex = alg->u.kex.kex;
6698 s->warn_kex = alg->u.kex.warn;
6699 } else if (i == KEXLIST_HOSTKEY) {
6700 ssh->hostkey = alg->u.hk.hostkey;
6701 s->warn_hk = alg->u.hk.warn;
6702 } else if (i == KEXLIST_CSCIPHER) {
6703 s->cscipher_tobe = alg->u.cipher.cipher;
6704 s->warn_cscipher = alg->u.cipher.warn;
6705 } else if (i == KEXLIST_SCCIPHER) {
6706 s->sccipher_tobe = alg->u.cipher.cipher;
6707 s->warn_sccipher = alg->u.cipher.warn;
6708 } else if (i == KEXLIST_CSMAC) {
6709 s->csmac_tobe = alg->u.mac.mac;
6710 s->csmac_etm_tobe = alg->u.mac.etm;
6711 } else if (i == KEXLIST_SCMAC) {
6712 s->scmac_tobe = alg->u.mac.mac;
6713 s->scmac_etm_tobe = alg->u.mac.etm;
6714 } else if (i == KEXLIST_CSCOMP) {
6715 s->cscomp_tobe = alg->u.comp;
6716 } else if (i == KEXLIST_SCCOMP) {
6717 s->sccomp_tobe = alg->u.comp;
6721 if ((i == KEXLIST_CSCOMP || i == KEXLIST_SCCOMP) &&
6722 in_commasep_string(alg->u.comp->delayed_name, str, len))
6723 s->pending_compression = TRUE; /* try this later */
6725 bombout(("Couldn't agree a %s (available: %.*s)",
6726 kexlist_descr[i], len, str));
6730 if (i == KEXLIST_HOSTKEY) {
6734 * In addition to deciding which host key we're
6735 * actually going to use, we should make a list of the
6736 * host keys offered by the server which we _don't_
6737 * have cached. These will be offered as cross-
6738 * certification options by ssh_get_specials.
6740 * We also count the key we're currently using for KEX
6741 * as one we've already got, because by the time this
6742 * menu becomes visible, it will be.
6744 ssh->n_uncert_hostkeys = 0;
6746 for (j = 0; j < lenof(hostkey_algs); j++) {
6747 if (hostkey_algs[j].alg != ssh->hostkey &&
6748 in_commasep_string(hostkey_algs[j].alg->name,
6750 !have_ssh_host_key(ssh->savedhost, ssh->savedport,
6751 hostkey_algs[j].alg->keytype)) {
6752 ssh->uncert_hostkeys[ssh->n_uncert_hostkeys++] = j;
6758 if (s->pending_compression) {
6759 logevent("Server supports delayed compression; "
6760 "will try this later");
6762 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
6763 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
6764 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
6766 ssh->exhash = ssh->kex->hash->init();
6767 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
6768 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
6769 hash_string(ssh->kex->hash, ssh->exhash,
6770 s->our_kexinit, s->our_kexinitlen);
6771 sfree(s->our_kexinit);
6772 /* Include the type byte in the hash of server's KEXINIT */
6773 hash_string(ssh->kex->hash, ssh->exhash,
6774 pktin->body - 1, pktin->length + 1);
6777 ssh_set_frozen(ssh, 1);
6778 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
6780 ssh_dialog_callback, ssh);
6781 if (s->dlgret < 0) {
6785 bombout(("Unexpected data from server while"
6786 " waiting for user response"));
6789 } while (pktin || inlen > 0);
6790 s->dlgret = ssh->user_response;
6792 ssh_set_frozen(ssh, 0);
6793 if (s->dlgret == 0) {
6794 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
6804 ssh_set_frozen(ssh, 1);
6807 * Change warning box wording depending on why we chose a
6808 * warning-level host key algorithm. If it's because
6809 * that's all we have *cached*, use the askhk mechanism,
6810 * and list the host keys we could usefully cross-certify.
6811 * Otherwise, use askalg for the standard wording.
6814 for (j = 0; j < ssh->n_uncert_hostkeys; j++) {
6815 const struct ssh_signkey_with_user_pref_id *hktype =
6816 &hostkey_algs[ssh->uncert_hostkeys[j]];
6818 for (k = 0; k < HK_MAX; k++) {
6819 int id = conf_get_int_int(ssh->conf, CONF_ssh_hklist, k);
6820 if (id == HK_WARN) {
6822 } else if (id == hktype->id) {
6829 char *old_ba = betteralgs;
6830 betteralgs = dupcat(betteralgs, ",",
6832 (const char *)NULL);
6835 betteralgs = dupstr(hktype->alg->name);
6840 s->dlgret = askhk(ssh->frontend, ssh->hostkey->name,
6841 betteralgs, ssh_dialog_callback, ssh);
6844 s->dlgret = askalg(ssh->frontend, "host key type",
6846 ssh_dialog_callback, ssh);
6848 if (s->dlgret < 0) {
6852 bombout(("Unexpected data from server while"
6853 " waiting for user response"));
6856 } while (pktin || inlen > 0);
6857 s->dlgret = ssh->user_response;
6859 ssh_set_frozen(ssh, 0);
6860 if (s->dlgret == 0) {
6861 ssh_disconnect(ssh, "User aborted at host key warning", NULL,
6867 if (s->warn_cscipher) {
6868 ssh_set_frozen(ssh, 1);
6869 s->dlgret = askalg(ssh->frontend,
6870 "client-to-server cipher",
6871 s->cscipher_tobe->name,
6872 ssh_dialog_callback, ssh);
6873 if (s->dlgret < 0) {
6877 bombout(("Unexpected data from server while"
6878 " waiting for user response"));
6881 } while (pktin || inlen > 0);
6882 s->dlgret = ssh->user_response;
6884 ssh_set_frozen(ssh, 0);
6885 if (s->dlgret == 0) {
6886 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6892 if (s->warn_sccipher) {
6893 ssh_set_frozen(ssh, 1);
6894 s->dlgret = askalg(ssh->frontend,
6895 "server-to-client cipher",
6896 s->sccipher_tobe->name,
6897 ssh_dialog_callback, ssh);
6898 if (s->dlgret < 0) {
6902 bombout(("Unexpected data from server while"
6903 " waiting for user response"));
6906 } while (pktin || inlen > 0);
6907 s->dlgret = ssh->user_response;
6909 ssh_set_frozen(ssh, 0);
6910 if (s->dlgret == 0) {
6911 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6917 if (s->ignorepkt) /* first_kex_packet_follows */
6918 crWaitUntilV(pktin); /* Ignore packet */
6921 if (ssh->kex->main_type == KEXTYPE_DH) {
6923 * Work out the number of bits of key we will need from the
6924 * key exchange. We start with the maximum key length of
6930 csbits = s->cscipher_tobe ? s->cscipher_tobe->real_keybits : 0;
6931 scbits = s->sccipher_tobe ? s->sccipher_tobe->real_keybits : 0;
6932 s->nbits = (csbits > scbits ? csbits : scbits);
6934 /* The keys only have hlen-bit entropy, since they're based on
6935 * a hash. So cap the key size at hlen bits. */
6936 if (s->nbits > ssh->kex->hash->hlen * 8)
6937 s->nbits = ssh->kex->hash->hlen * 8;
6940 * If we're doing Diffie-Hellman group exchange, start by
6941 * requesting a group.
6943 if (dh_is_gex(ssh->kex)) {
6944 logevent("Doing Diffie-Hellman group exchange");
6945 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
6947 * Work out how big a DH group we will need to allow that
6950 s->pbits = 512 << ((s->nbits - 1) / 64);
6951 if (s->pbits < DH_MIN_SIZE)
6952 s->pbits = DH_MIN_SIZE;
6953 if (s->pbits > DH_MAX_SIZE)
6954 s->pbits = DH_MAX_SIZE;
6955 if ((ssh->remote_bugs & BUG_SSH2_OLDGEX)) {
6956 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD);
6957 ssh2_pkt_adduint32(s->pktout, s->pbits);
6959 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
6960 ssh2_pkt_adduint32(s->pktout, DH_MIN_SIZE);
6961 ssh2_pkt_adduint32(s->pktout, s->pbits);
6962 ssh2_pkt_adduint32(s->pktout, DH_MAX_SIZE);
6964 ssh2_pkt_send_noqueue(ssh, s->pktout);
6966 crWaitUntilV(pktin);
6967 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
6968 bombout(("expected key exchange group packet from server"));
6971 s->p = ssh2_pkt_getmp(pktin);
6972 s->g = ssh2_pkt_getmp(pktin);
6973 if (!s->p || !s->g) {
6974 bombout(("unable to read mp-ints from incoming group packet"));
6977 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
6978 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
6979 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
6981 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
6982 ssh->kex_ctx = dh_setup_group(ssh->kex);
6983 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
6984 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
6985 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
6986 ssh->kex->groupname);
6989 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
6990 ssh->kex->hash->text_name);
6992 * Now generate and send e for Diffie-Hellman.
6994 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
6995 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
6996 s->pktout = ssh2_pkt_init(s->kex_init_value);
6997 ssh2_pkt_addmp(s->pktout, s->e);
6998 ssh2_pkt_send_noqueue(ssh, s->pktout);
7000 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
7001 crWaitUntilV(pktin);
7002 if (pktin->type != s->kex_reply_value) {
7003 bombout(("expected key exchange reply packet from server"));
7006 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
7007 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7008 if (!s->hostkeydata) {
7009 bombout(("unable to parse key exchange reply packet"));
7012 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7013 s->hostkeydata, s->hostkeylen);
7014 s->f = ssh2_pkt_getmp(pktin);
7016 bombout(("unable to parse key exchange reply packet"));
7019 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7021 bombout(("unable to parse key exchange reply packet"));
7026 const char *err = dh_validate_f(ssh->kex_ctx, s->f);
7028 bombout(("key exchange reply failed validation: %s", err));
7032 s->K = dh_find_K(ssh->kex_ctx, s->f);
7034 /* We assume everything from now on will be quick, and it might
7035 * involve user interaction. */
7036 set_busy_status(ssh->frontend, BUSY_NOT);
7038 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
7039 if (dh_is_gex(ssh->kex)) {
7040 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
7041 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MIN_SIZE);
7042 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
7043 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
7044 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MAX_SIZE);
7045 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
7046 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
7048 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
7049 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
7051 dh_cleanup(ssh->kex_ctx);
7053 if (dh_is_gex(ssh->kex)) {
7057 } else if (ssh->kex->main_type == KEXTYPE_ECDH) {
7059 logeventf(ssh, "Doing ECDH key exchange with curve %s and hash %s",
7060 ssh_ecdhkex_curve_textname(ssh->kex),
7061 ssh->kex->hash->text_name);
7062 ssh->pkt_kctx = SSH2_PKTCTX_ECDHKEX;
7064 s->eckey = ssh_ecdhkex_newkey(ssh->kex);
7066 bombout(("Unable to generate key for ECDH"));
7072 int publicPointLength;
7073 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
7075 ssh_ecdhkex_freekey(s->eckey);
7076 bombout(("Unable to encode public key for ECDH"));
7079 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_ECDH_INIT);
7080 ssh2_pkt_addstring_start(s->pktout);
7081 ssh2_pkt_addstring_data(s->pktout, publicPoint, publicPointLength);
7085 ssh2_pkt_send_noqueue(ssh, s->pktout);
7087 crWaitUntilV(pktin);
7088 if (pktin->type != SSH2_MSG_KEX_ECDH_REPLY) {
7089 ssh_ecdhkex_freekey(s->eckey);
7090 bombout(("expected ECDH reply packet from server"));
7094 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7095 if (!s->hostkeydata) {
7096 bombout(("unable to parse ECDH reply packet"));
7099 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
7100 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7101 s->hostkeydata, s->hostkeylen);
7105 int publicPointLength;
7106 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
7108 ssh_ecdhkex_freekey(s->eckey);
7109 bombout(("Unable to encode public key for ECDH hash"));
7112 hash_string(ssh->kex->hash, ssh->exhash,
7113 publicPoint, publicPointLength);
7120 ssh_pkt_getstring(pktin, &keydata, &keylen);
7122 bombout(("unable to parse ECDH reply packet"));
7125 hash_string(ssh->kex->hash, ssh->exhash, keydata, keylen);
7126 s->K = ssh_ecdhkex_getkey(s->eckey, keydata, keylen);
7128 ssh_ecdhkex_freekey(s->eckey);
7129 bombout(("point received in ECDH was not valid"));
7134 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7136 bombout(("unable to parse key exchange reply packet"));
7140 ssh_ecdhkex_freekey(s->eckey);
7142 logeventf(ssh, "Doing RSA key exchange with hash %s",
7143 ssh->kex->hash->text_name);
7144 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
7146 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
7149 crWaitUntilV(pktin);
7150 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
7151 bombout(("expected RSA public key packet from server"));
7155 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7156 if (!s->hostkeydata) {
7157 bombout(("unable to parse RSA public key packet"));
7160 hash_string(ssh->kex->hash, ssh->exhash,
7161 s->hostkeydata, s->hostkeylen);
7162 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7163 s->hostkeydata, s->hostkeylen);
7167 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
7169 bombout(("unable to parse RSA public key packet"));
7172 s->rsakeydata = snewn(s->rsakeylen, char);
7173 memcpy(s->rsakeydata, keydata, s->rsakeylen);
7176 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
7178 sfree(s->rsakeydata);
7179 bombout(("unable to parse RSA public key from server"));
7183 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
7186 * Next, set up a shared secret K, of precisely KLEN -
7187 * 2*HLEN - 49 bits, where KLEN is the bit length of the
7188 * RSA key modulus and HLEN is the bit length of the hash
7192 int klen = ssh_rsakex_klen(s->rsakey);
7193 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
7195 unsigned char *kstr1, *kstr2, *outstr;
7196 int kstr1len, kstr2len, outstrlen;
7198 s->K = bn_power_2(nbits - 1);
7200 for (i = 0; i < nbits; i++) {
7202 byte = random_byte();
7204 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
7208 * Encode this as an mpint.
7210 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
7211 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
7212 PUT_32BIT(kstr2, kstr1len);
7213 memcpy(kstr2 + 4, kstr1, kstr1len);
7216 * Encrypt it with the given RSA key.
7218 outstrlen = (klen + 7) / 8;
7219 outstr = snewn(outstrlen, unsigned char);
7220 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
7221 outstr, outstrlen, s->rsakey);
7224 * And send it off in a return packet.
7226 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
7227 ssh2_pkt_addstring_start(s->pktout);
7228 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
7229 ssh2_pkt_send_noqueue(ssh, s->pktout);
7231 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
7238 ssh_rsakex_freekey(s->rsakey);
7240 crWaitUntilV(pktin);
7241 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
7242 sfree(s->rsakeydata);
7243 bombout(("expected signature packet from server"));
7247 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7249 bombout(("unable to parse signature packet"));
7253 sfree(s->rsakeydata);
7256 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
7257 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
7258 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
7260 ssh->kex_ctx = NULL;
7263 debug(("Exchange hash is:\n"));
7264 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
7268 bombout(("Server's host key is invalid"));
7272 if (!ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
7273 (char *)s->exchange_hash,
7274 ssh->kex->hash->hlen)) {
7276 bombout(("Server's host key did not match the signature supplied"));
7281 s->keystr = ssh->hostkey->fmtkey(s->hkey);
7282 if (!s->got_session_id) {
7284 * Make a note of any other host key formats that are available.
7287 int i, j, nkeys = 0;
7289 for (i = 0; i < lenof(hostkey_algs); i++) {
7290 if (hostkey_algs[i].alg == ssh->hostkey)
7293 for (j = 0; j < ssh->n_uncert_hostkeys; j++)
7294 if (ssh->uncert_hostkeys[j] == i)
7297 if (j < ssh->n_uncert_hostkeys) {
7300 newlist = dupprintf("%s/%s", list,
7301 hostkey_algs[i].alg->name);
7303 newlist = dupprintf("%s", hostkey_algs[i].alg->name);
7311 "Server also has %s host key%s, but we "
7312 "don't know %s", list,
7313 nkeys > 1 ? "s" : "",
7314 nkeys > 1 ? "any of them" : "it");
7320 * Authenticate remote host: verify host key. (We've already
7321 * checked the signature of the exchange hash.)
7323 s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
7324 logevent("Host key fingerprint is:");
7325 logevent(s->fingerprint);
7326 /* First check against manually configured host keys. */
7327 s->dlgret = verify_ssh_manual_host_key(ssh, s->fingerprint,
7328 ssh->hostkey, s->hkey);
7329 if (s->dlgret == 0) { /* did not match */
7330 bombout(("Host key did not appear in manually configured list"));
7332 } else if (s->dlgret < 0) { /* none configured; use standard handling */
7333 ssh_set_frozen(ssh, 1);
7334 s->dlgret = verify_ssh_host_key(ssh->frontend,
7335 ssh->savedhost, ssh->savedport,
7336 ssh->hostkey->keytype, s->keystr,
7338 ssh_dialog_callback, ssh);
7342 if (s->dlgret < 0) {
7346 bombout(("Unexpected data from server while waiting"
7347 " for user host key response"));
7350 } while (pktin || inlen > 0);
7351 s->dlgret = ssh->user_response;
7353 ssh_set_frozen(ssh, 0);
7354 if (s->dlgret == 0) {
7355 ssh_disconnect(ssh, "Aborted at host key verification", NULL,
7360 sfree(s->fingerprint);
7362 * Save this host key, to check against the one presented in
7363 * subsequent rekeys.
7365 ssh->hostkey_str = s->keystr;
7366 } else if (ssh->cross_certifying) {
7367 s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
7368 logevent("Storing additional host key for this host:");
7369 logevent(s->fingerprint);
7370 store_host_key(ssh->savedhost, ssh->savedport,
7371 ssh->hostkey->keytype, s->keystr);
7372 ssh->cross_certifying = FALSE;
7374 * Don't forget to store the new key as the one we'll be
7375 * re-checking in future normal rekeys.
7377 ssh->hostkey_str = s->keystr;
7380 * In a rekey, we never present an interactive host key
7381 * verification request to the user. Instead, we simply
7382 * enforce that the key we're seeing this time is identical to
7383 * the one we saw before.
7385 if (strcmp(ssh->hostkey_str, s->keystr)) {
7387 bombout(("Host key was different in repeat key exchange"));
7393 ssh->hostkey->freekey(s->hkey);
7396 * The exchange hash from the very first key exchange is also
7397 * the session id, used in session key construction and
7400 if (!s->got_session_id) {
7401 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
7402 memcpy(ssh->v2_session_id, s->exchange_hash,
7403 sizeof(s->exchange_hash));
7404 ssh->v2_session_id_len = ssh->kex->hash->hlen;
7405 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
7406 s->got_session_id = TRUE;
7410 * Send SSH2_MSG_NEWKEYS.
7412 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
7413 ssh2_pkt_send_noqueue(ssh, s->pktout);
7414 ssh->outgoing_data_size = 0; /* start counting from here */
7417 * We've sent client NEWKEYS, so create and initialise
7418 * client-to-server session keys.
7420 if (ssh->cs_cipher_ctx)
7421 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
7422 ssh->cscipher = s->cscipher_tobe;
7423 if (ssh->cscipher) ssh->cs_cipher_ctx = ssh->cscipher->make_context();
7425 if (ssh->cs_mac_ctx)
7426 ssh->csmac->free_context(ssh->cs_mac_ctx);
7427 ssh->csmac = s->csmac_tobe;
7428 ssh->csmac_etm = s->csmac_etm_tobe;
7430 ssh->cs_mac_ctx = ssh->csmac->make_context(ssh->cs_cipher_ctx);
7432 if (ssh->cs_comp_ctx)
7433 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
7434 ssh->cscomp = s->cscomp_tobe;
7435 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
7438 * Set IVs on client-to-server keys. Here we use the exchange
7439 * hash from the _first_ key exchange.
7441 if (ssh->cscipher) {
7444 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'C',
7445 ssh->cscipher->padded_keybytes);
7446 ssh->cscipher->setkey(ssh->cs_cipher_ctx, key);
7447 smemclr(key, ssh->cscipher->padded_keybytes);
7450 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'A',
7451 ssh->cscipher->blksize);
7452 ssh->cscipher->setiv(ssh->cs_cipher_ctx, key);
7453 smemclr(key, ssh->cscipher->blksize);
7459 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'E',
7460 ssh->csmac->keylen);
7461 ssh->csmac->setkey(ssh->cs_mac_ctx, key);
7462 smemclr(key, ssh->csmac->keylen);
7467 logeventf(ssh, "Initialised %.200s client->server encryption",
7468 ssh->cscipher->text_name);
7470 logeventf(ssh, "Initialised %.200s client->server MAC algorithm%s%s",
7471 ssh->csmac->text_name,
7472 ssh->csmac_etm ? " (in ETM mode)" : "",
7473 ssh->cscipher->required_mac ? " (required by cipher)" : "");
7474 if (ssh->cscomp->text_name)
7475 logeventf(ssh, "Initialised %s compression",
7476 ssh->cscomp->text_name);
7479 * Now our end of the key exchange is complete, we can send all
7480 * our queued higher-layer packets.
7482 ssh->queueing = FALSE;
7483 ssh2_pkt_queuesend(ssh);
7486 * Expect SSH2_MSG_NEWKEYS from server.
7488 crWaitUntilV(pktin);
7489 if (pktin->type != SSH2_MSG_NEWKEYS) {
7490 bombout(("expected new-keys packet from server"));
7493 ssh->incoming_data_size = 0; /* start counting from here */
7496 * We've seen server NEWKEYS, so create and initialise
7497 * server-to-client session keys.
7499 if (ssh->sc_cipher_ctx)
7500 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
7501 if (s->sccipher_tobe) {
7502 ssh->sccipher = s->sccipher_tobe;
7503 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
7506 if (ssh->sc_mac_ctx)
7507 ssh->scmac->free_context(ssh->sc_mac_ctx);
7508 if (s->scmac_tobe) {
7509 ssh->scmac = s->scmac_tobe;
7510 ssh->scmac_etm = s->scmac_etm_tobe;
7511 ssh->sc_mac_ctx = ssh->scmac->make_context(ssh->sc_cipher_ctx);
7514 if (ssh->sc_comp_ctx)
7515 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
7516 ssh->sccomp = s->sccomp_tobe;
7517 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
7520 * Set IVs on server-to-client keys. Here we use the exchange
7521 * hash from the _first_ key exchange.
7523 if (ssh->sccipher) {
7526 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'D',
7527 ssh->sccipher->padded_keybytes);
7528 ssh->sccipher->setkey(ssh->sc_cipher_ctx, key);
7529 smemclr(key, ssh->sccipher->padded_keybytes);
7532 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'B',
7533 ssh->sccipher->blksize);
7534 ssh->sccipher->setiv(ssh->sc_cipher_ctx, key);
7535 smemclr(key, ssh->sccipher->blksize);
7541 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'F',
7542 ssh->scmac->keylen);
7543 ssh->scmac->setkey(ssh->sc_mac_ctx, key);
7544 smemclr(key, ssh->scmac->keylen);
7548 logeventf(ssh, "Initialised %.200s server->client encryption",
7549 ssh->sccipher->text_name);
7551 logeventf(ssh, "Initialised %.200s server->client MAC algorithm%s%s",
7552 ssh->scmac->text_name,
7553 ssh->scmac_etm ? " (in ETM mode)" : "",
7554 ssh->sccipher->required_mac ? " (required by cipher)" : "");
7555 if (ssh->sccomp->text_name)
7556 logeventf(ssh, "Initialised %s decompression",
7557 ssh->sccomp->text_name);
7560 * Free shared secret.
7565 * Update the specials menu to list the remaining uncertified host
7568 update_specials_menu(ssh->frontend);
7571 * Key exchange is over. Loop straight back round if we have a
7572 * deferred rekey reason.
7574 if (ssh->deferred_rekey_reason) {
7575 logevent(ssh->deferred_rekey_reason);
7577 ssh->deferred_rekey_reason = NULL;
7578 goto begin_key_exchange;
7582 * Otherwise, schedule a timer for our next rekey.
7584 ssh->kex_in_progress = FALSE;
7585 ssh->last_rekey = GETTICKCOUNT();
7586 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
7587 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7591 * Now we're encrypting. Begin returning 1 to the protocol main
7592 * function so that other things can run on top of the
7593 * transport. If we ever see a KEXINIT, we must go back to the
7596 * We _also_ go back to the start if we see pktin==NULL and
7597 * inlen negative, because this is a special signal meaning
7598 * `initiate client-driven rekey', and `in' contains a message
7599 * giving the reason for the rekey.
7601 * inlen==-1 means always initiate a rekey;
7602 * inlen==-2 means that userauth has completed successfully and
7603 * we should consider rekeying (for delayed compression).
7605 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
7606 (!pktin && inlen < 0))) {
7608 if (!ssh->protocol_initial_phase_done) {
7609 ssh->protocol_initial_phase_done = TRUE;
7611 * Allow authconn to initialise itself.
7613 do_ssh2_authconn(ssh, NULL, 0, NULL);
7618 logevent("Server initiated key re-exchange");
7622 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
7623 * delayed compression, if it's available.
7625 * draft-miller-secsh-compression-delayed-00 says that you
7626 * negotiate delayed compression in the first key exchange, and
7627 * both sides start compressing when the server has sent
7628 * USERAUTH_SUCCESS. This has a race condition -- the server
7629 * can't know when the client has seen it, and thus which incoming
7630 * packets it should treat as compressed.
7632 * Instead, we do the initial key exchange without offering the
7633 * delayed methods, but note if the server offers them; when we
7634 * get here, if a delayed method was available that was higher
7635 * on our list than what we got, we initiate a rekey in which we
7636 * _do_ list the delayed methods (and hopefully get it as a
7637 * result). Subsequent rekeys will do the same.
7639 assert(!s->userauth_succeeded); /* should only happen once */
7640 s->userauth_succeeded = TRUE;
7641 if (!s->pending_compression)
7642 /* Can't see any point rekeying. */
7643 goto wait_for_rekey; /* this is utterly horrid */
7644 /* else fall through to rekey... */
7645 s->pending_compression = FALSE;
7648 * Now we've decided to rekey.
7650 * Special case: if the server bug is set that doesn't
7651 * allow rekeying, we give a different log message and
7652 * continue waiting. (If such a server _initiates_ a rekey,
7653 * we process it anyway!)
7655 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
7656 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
7658 /* Reset the counters, so that at least this message doesn't
7659 * hit the event log _too_ often. */
7660 ssh->outgoing_data_size = 0;
7661 ssh->incoming_data_size = 0;
7662 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
7664 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7667 goto wait_for_rekey; /* this is still utterly horrid */
7669 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
7672 goto begin_key_exchange;
7678 * Send data on an SSH channel. In SSH-2, this involves buffering it
7681 static int ssh_send_channel_data(struct ssh_channel *c, const char *buf,
7684 if (c->ssh->version == 2) {
7685 bufchain_add(&c->v.v2.outbuffer, buf, len);
7686 return ssh2_try_send(c);
7688 send_packet(c->ssh, SSH1_MSG_CHANNEL_DATA,
7689 PKT_INT, c->remoteid,
7694 * In SSH-1 we can return 0 here - implying that channels are
7695 * never individually throttled - because the only
7696 * circumstance that can cause throttling will be the whole
7697 * SSH connection backing up, in which case _everything_ will
7698 * be throttled as a whole.
7705 * Attempt to send data on an SSH-2 channel.
7707 static int ssh2_try_send(struct ssh_channel *c)
7710 struct Packet *pktout;
7713 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
7716 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
7717 if ((unsigned)len > c->v.v2.remwindow)
7718 len = c->v.v2.remwindow;
7719 if ((unsigned)len > c->v.v2.remmaxpkt)
7720 len = c->v.v2.remmaxpkt;
7721 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
7722 ssh2_pkt_adduint32(pktout, c->remoteid);
7723 ssh2_pkt_addstring_start(pktout);
7724 ssh2_pkt_addstring_data(pktout, data, len);
7725 ssh2_pkt_send(ssh, pktout);
7726 bufchain_consume(&c->v.v2.outbuffer, len);
7727 c->v.v2.remwindow -= len;
7731 * After having sent as much data as we can, return the amount
7734 ret = bufchain_size(&c->v.v2.outbuffer);
7737 * And if there's no data pending but we need to send an EOF, send
7740 if (!ret && c->pending_eof)
7741 ssh_channel_try_eof(c);
7746 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
7749 if (c->closes & CLOSES_SENT_EOF)
7750 return; /* don't send on channels we've EOFed */
7751 bufsize = ssh2_try_send(c);
7754 case CHAN_MAINSESSION:
7755 /* stdin need not receive an unthrottle
7756 * notification since it will be polled */
7759 x11_unthrottle(c->u.x11.xconn);
7762 /* agent sockets are request/response and need no
7763 * buffer management */
7766 pfd_unthrottle(c->u.pfd.pf);
7772 static int ssh_is_simple(Ssh ssh)
7775 * We use the 'simple' variant of the SSH protocol if we're asked
7776 * to, except not if we're also doing connection-sharing (either
7777 * tunnelling our packets over an upstream or expecting to be
7778 * tunnelled over ourselves), since then the assumption that we
7779 * have only one channel to worry about is not true after all.
7781 return (conf_get_int(ssh->conf, CONF_ssh_simple) &&
7782 !ssh->bare_connection && !ssh->connshare);
7786 * Set up most of a new ssh_channel.
7788 static void ssh_channel_init(struct ssh_channel *c)
7791 c->localid = alloc_channel_id(ssh);
7793 c->pending_eof = FALSE;
7794 c->throttling_conn = FALSE;
7795 if (ssh->version == 2) {
7796 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
7797 ssh_is_simple(ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
7798 c->v.v2.chanreq_head = NULL;
7799 c->v.v2.throttle_state = UNTHROTTLED;
7800 bufchain_init(&c->v.v2.outbuffer);
7802 add234(ssh->channels, c);
7806 * Construct the common parts of a CHANNEL_OPEN.
7808 static struct Packet *ssh2_chanopen_init(struct ssh_channel *c,
7811 struct Packet *pktout;
7813 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7814 ssh2_pkt_addstring(pktout, type);
7815 ssh2_pkt_adduint32(pktout, c->localid);
7816 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
7817 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7822 * CHANNEL_FAILURE doesn't come with any indication of what message
7823 * caused it, so we have to keep track of the outstanding
7824 * CHANNEL_REQUESTs ourselves.
7826 static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
7827 cchandler_fn_t handler, void *ctx)
7829 struct outstanding_channel_request *ocr =
7830 snew(struct outstanding_channel_request);
7832 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7833 ocr->handler = handler;
7836 if (!c->v.v2.chanreq_head)
7837 c->v.v2.chanreq_head = ocr;
7839 c->v.v2.chanreq_tail->next = ocr;
7840 c->v.v2.chanreq_tail = ocr;
7844 * Construct the common parts of a CHANNEL_REQUEST. If handler is not
7845 * NULL then a reply will be requested and the handler will be called
7846 * when it arrives. The returned packet is ready to have any
7847 * request-specific data added and be sent. Note that if a handler is
7848 * provided, it's essential that the request actually be sent.
7850 * The handler will usually be passed the response packet in pktin. If
7851 * pktin is NULL, this means that no reply will ever be forthcoming
7852 * (e.g. because the entire connection is being destroyed, or because
7853 * the server initiated channel closure before we saw the response)
7854 * and the handler should free any storage it's holding.
7856 static struct Packet *ssh2_chanreq_init(struct ssh_channel *c,
7858 cchandler_fn_t handler, void *ctx)
7860 struct Packet *pktout;
7862 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7863 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7864 ssh2_pkt_adduint32(pktout, c->remoteid);
7865 ssh2_pkt_addstring(pktout, type);
7866 ssh2_pkt_addbool(pktout, handler != NULL);
7867 if (handler != NULL)
7868 ssh2_queue_chanreq_handler(c, handler, ctx);
7872 static void ssh_channel_unthrottle(struct ssh_channel *c, int bufsize)
7877 if (ssh->version == 1) {
7878 buflimit = SSH1_BUFFER_LIMIT;
7880 if (ssh_is_simple(ssh))
7883 buflimit = c->v.v2.locmaxwin;
7884 if (bufsize < buflimit)
7885 ssh2_set_window(c, buflimit - bufsize);
7887 if (c->throttling_conn && bufsize <= buflimit) {
7888 c->throttling_conn = 0;
7889 ssh_throttle_conn(ssh, -1);
7894 * Potentially enlarge the window on an SSH-2 channel.
7896 static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
7898 static void ssh2_set_window(struct ssh_channel *c, int newwin)
7903 * Never send WINDOW_ADJUST for a channel that the remote side has
7904 * already sent EOF on; there's no point, since it won't be
7905 * sending any more data anyway. Ditto if _we've_ already sent
7908 if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
7912 * Also, never widen the window for an X11 channel when we're
7913 * still waiting to see its initial auth and may yet hand it off
7916 if (c->type == CHAN_X11 && c->u.x11.initial)
7920 * If the remote end has a habit of ignoring maxpkt, limit the
7921 * window so that it has no choice (assuming it doesn't ignore the
7924 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
7925 newwin = OUR_V2_MAXPKT;
7928 * Only send a WINDOW_ADJUST if there's significantly more window
7929 * available than the other end thinks there is. This saves us
7930 * sending a WINDOW_ADJUST for every character in a shell session.
7932 * "Significant" is arbitrarily defined as half the window size.
7934 if (newwin / 2 >= c->v.v2.locwindow) {
7935 struct Packet *pktout;
7939 * In order to keep track of how much window the client
7940 * actually has available, we'd like it to acknowledge each
7941 * WINDOW_ADJUST. We can't do that directly, so we accompany
7942 * it with a CHANNEL_REQUEST that has to be acknowledged.
7944 * This is only necessary if we're opening the window wide.
7945 * If we're not, then throughput is being constrained by
7946 * something other than the maximum window size anyway.
7948 if (newwin == c->v.v2.locmaxwin &&
7949 !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
7950 up = snew(unsigned);
7951 *up = newwin - c->v.v2.locwindow;
7952 pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org",
7953 ssh2_handle_winadj_response, up);
7954 ssh2_pkt_send(ssh, pktout);
7956 if (c->v.v2.throttle_state != UNTHROTTLED)
7957 c->v.v2.throttle_state = UNTHROTTLING;
7959 /* Pretend the WINDOW_ADJUST was acked immediately. */
7960 c->v.v2.remlocwin = newwin;
7961 c->v.v2.throttle_state = THROTTLED;
7963 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
7964 ssh2_pkt_adduint32(pktout, c->remoteid);
7965 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
7966 ssh2_pkt_send(ssh, pktout);
7967 c->v.v2.locwindow = newwin;
7972 * Find the channel associated with a message. If there's no channel,
7973 * or it's not properly open, make a noise about it and return NULL.
7975 static struct ssh_channel *ssh_channel_msg(Ssh ssh, struct Packet *pktin)
7977 unsigned localid = ssh_pkt_getuint32(pktin);
7978 struct ssh_channel *c;
7981 /* Is this message OK on a half-open connection? */
7982 if (ssh->version == 1)
7983 halfopen_ok = (pktin->type == SSH1_MSG_CHANNEL_OPEN_CONFIRMATION ||
7984 pktin->type == SSH1_MSG_CHANNEL_OPEN_FAILURE);
7986 halfopen_ok = (pktin->type == SSH2_MSG_CHANNEL_OPEN_CONFIRMATION ||
7987 pktin->type == SSH2_MSG_CHANNEL_OPEN_FAILURE);
7988 c = find234(ssh->channels, &localid, ssh_channelfind);
7989 if (!c || (c->type != CHAN_SHARING && c->halfopen && !halfopen_ok)) {
7990 char *buf = dupprintf("Received %s for %s channel %u",
7991 ssh_pkt_type(ssh, pktin->type),
7992 c ? "half-open" : "nonexistent", localid);
7993 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
8000 static void ssh2_handle_winadj_response(struct ssh_channel *c,
8001 struct Packet *pktin, void *ctx)
8003 unsigned *sizep = ctx;
8006 * Winadj responses should always be failures. However, at least
8007 * one server ("boks_sshd") is known to return SUCCESS for channel
8008 * requests it's never heard of, such as "winadj@putty". Raised
8009 * with foxt.com as bug 090916-090424, but for the sake of a quiet
8010 * life, we don't worry about what kind of response we got.
8013 c->v.v2.remlocwin += *sizep;
8016 * winadj messages are only sent when the window is fully open, so
8017 * if we get an ack of one, we know any pending unthrottle is
8020 if (c->v.v2.throttle_state == UNTHROTTLING)
8021 c->v.v2.throttle_state = UNTHROTTLED;
8024 static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
8026 struct ssh_channel *c = ssh_channel_msg(ssh, pktin);
8027 struct outstanding_channel_request *ocr;
8030 if (c->type == CHAN_SHARING) {
8031 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8032 pktin->body, pktin->length);
8035 ocr = c->v.v2.chanreq_head;
8037 ssh2_msg_unexpected(ssh, pktin);
8040 ocr->handler(c, pktin, ocr->ctx);
8041 c->v.v2.chanreq_head = ocr->next;
8044 * We may now initiate channel-closing procedures, if that
8045 * CHANNEL_REQUEST was the last thing outstanding before we send
8048 ssh2_channel_check_close(c);
8051 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
8053 struct ssh_channel *c;
8054 c = ssh_channel_msg(ssh, pktin);
8057 if (c->type == CHAN_SHARING) {
8058 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8059 pktin->body, pktin->length);
8062 if (!(c->closes & CLOSES_SENT_EOF)) {
8063 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
8064 ssh2_try_send_and_unthrottle(ssh, c);
8068 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
8072 struct ssh_channel *c;
8073 c = ssh_channel_msg(ssh, pktin);
8076 if (c->type == CHAN_SHARING) {
8077 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8078 pktin->body, pktin->length);
8081 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
8082 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
8083 return; /* extended but not stderr */
8084 ssh_pkt_getstring(pktin, &data, &length);
8087 c->v.v2.locwindow -= length;
8088 c->v.v2.remlocwin -= length;
8089 bufsize = ssh_channel_data(c, pktin->type ==
8090 SSH2_MSG_CHANNEL_EXTENDED_DATA,
8093 * If it looks like the remote end hit the end of its window,
8094 * and we didn't want it to do that, think about using a
8097 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
8098 c->v.v2.locmaxwin < 0x40000000)
8099 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
8101 * If we are not buffering too much data,
8102 * enlarge the window again at the remote side.
8103 * If we are buffering too much, we may still
8104 * need to adjust the window if the server's
8107 if (bufsize < c->v.v2.locmaxwin)
8108 ssh2_set_window(c, c->v.v2.locmaxwin - bufsize);
8110 * If we're either buffering way too much data, or if we're
8111 * buffering anything at all and we're in "simple" mode,
8112 * throttle the whole channel.
8114 if ((bufsize > c->v.v2.locmaxwin || (ssh_is_simple(ssh) && bufsize>0))
8115 && !c->throttling_conn) {
8116 c->throttling_conn = 1;
8117 ssh_throttle_conn(ssh, +1);
8122 static void ssh_check_termination(Ssh ssh)
8124 if (ssh->version == 2 &&
8125 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
8126 (ssh->channels && count234(ssh->channels) == 0) &&
8127 !(ssh->connshare && share_ndownstreams(ssh->connshare) > 0)) {
8129 * We used to send SSH_MSG_DISCONNECT here, because I'd
8130 * believed that _every_ conforming SSH-2 connection had to
8131 * end with a disconnect being sent by at least one side;
8132 * apparently I was wrong and it's perfectly OK to
8133 * unceremoniously slam the connection shut when you're done,
8134 * and indeed OpenSSH feels this is more polite than sending a
8135 * DISCONNECT. So now we don't.
8137 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
8141 void ssh_sharing_downstream_connected(Ssh ssh, unsigned id,
8142 const char *peerinfo)
8145 logeventf(ssh, "Connection sharing downstream #%u connected from %s",
8148 logeventf(ssh, "Connection sharing downstream #%u connected", id);
8151 void ssh_sharing_downstream_disconnected(Ssh ssh, unsigned id)
8153 logeventf(ssh, "Connection sharing downstream #%u disconnected", id);
8154 ssh_check_termination(ssh);
8157 void ssh_sharing_logf(Ssh ssh, unsigned id, const char *logfmt, ...)
8162 va_start(ap, logfmt);
8163 buf = dupvprintf(logfmt, ap);
8166 logeventf(ssh, "Connection sharing downstream #%u: %s", id, buf);
8168 logeventf(ssh, "Connection sharing: %s", buf);
8172 static void ssh_channel_destroy(struct ssh_channel *c)
8177 case CHAN_MAINSESSION:
8178 ssh->mainchan = NULL;
8179 update_specials_menu(ssh->frontend);
8182 if (c->u.x11.xconn != NULL)
8183 x11_close(c->u.x11.xconn);
8184 logevent("Forwarded X11 connection terminated");
8187 sfree(c->u.a.message);
8190 if (c->u.pfd.pf != NULL)
8191 pfd_close(c->u.pfd.pf);
8192 logevent("Forwarded port closed");
8196 del234(ssh->channels, c);
8197 if (ssh->version == 2) {
8198 bufchain_clear(&c->v.v2.outbuffer);
8199 assert(c->v.v2.chanreq_head == NULL);
8204 * If that was the last channel left open, we might need to
8207 ssh_check_termination(ssh);
8210 static void ssh2_channel_check_close(struct ssh_channel *c)
8213 struct Packet *pktout;
8215 assert(ssh->version == 2);
8218 * If we've sent out our own CHANNEL_OPEN but not yet seen
8219 * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
8220 * it's too early to be sending close messages of any kind.
8225 if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
8226 c->type == CHAN_ZOMBIE) &&
8227 !c->v.v2.chanreq_head &&
8228 !(c->closes & CLOSES_SENT_CLOSE)) {
8230 * We have both sent and received EOF (or the channel is a
8231 * zombie), and we have no outstanding channel requests, which
8232 * means the channel is in final wind-up. But we haven't sent
8233 * CLOSE, so let's do so now.
8235 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
8236 ssh2_pkt_adduint32(pktout, c->remoteid);
8237 ssh2_pkt_send(ssh, pktout);
8238 c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
8241 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
8242 assert(c->v.v2.chanreq_head == NULL);
8244 * We have both sent and received CLOSE, which means we're
8245 * completely done with the channel.
8247 ssh_channel_destroy(c);
8251 static void ssh2_channel_got_eof(struct ssh_channel *c)
8253 if (c->closes & CLOSES_RCVD_EOF)
8254 return; /* already seen EOF */
8255 c->closes |= CLOSES_RCVD_EOF;
8257 if (c->type == CHAN_X11) {
8258 x11_send_eof(c->u.x11.xconn);
8259 } else if (c->type == CHAN_AGENT) {
8260 if (c->u.a.outstanding_requests == 0) {
8261 /* Manufacture an outgoing EOF in response to the incoming one. */
8262 sshfwd_write_eof(c);
8264 } else if (c->type == CHAN_SOCKDATA) {
8265 pfd_send_eof(c->u.pfd.pf);
8266 } else if (c->type == CHAN_MAINSESSION) {
8269 if (!ssh->sent_console_eof &&
8270 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
8272 * Either from_backend_eof told us that the front end
8273 * wants us to close the outgoing side of the connection
8274 * as soon as we see EOF from the far end, or else we've
8275 * unilaterally decided to do that because we've allocated
8276 * a remote pty and hence EOF isn't a particularly
8277 * meaningful concept.
8279 sshfwd_write_eof(c);
8281 ssh->sent_console_eof = TRUE;
8284 ssh2_channel_check_close(c);
8287 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
8289 struct ssh_channel *c;
8291 c = ssh_channel_msg(ssh, pktin);
8294 if (c->type == CHAN_SHARING) {
8295 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8296 pktin->body, pktin->length);
8299 ssh2_channel_got_eof(c);
8302 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
8304 struct ssh_channel *c;
8306 c = ssh_channel_msg(ssh, pktin);
8309 if (c->type == CHAN_SHARING) {
8310 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8311 pktin->body, pktin->length);
8316 * When we receive CLOSE on a channel, we assume it comes with an
8317 * implied EOF if we haven't seen EOF yet.
8319 ssh2_channel_got_eof(c);
8321 if (!(ssh->remote_bugs & BUG_SENDS_LATE_REQUEST_REPLY)) {
8323 * It also means we stop expecting to see replies to any
8324 * outstanding channel requests, so clean those up too.
8325 * (ssh_chanreq_init will enforce by assertion that we don't
8326 * subsequently put anything back on this list.)
8328 while (c->v.v2.chanreq_head) {
8329 struct outstanding_channel_request *ocr = c->v.v2.chanreq_head;
8330 ocr->handler(c, NULL, ocr->ctx);
8331 c->v.v2.chanreq_head = ocr->next;
8337 * And we also send an outgoing EOF, if we haven't already, on the
8338 * assumption that CLOSE is a pretty forceful announcement that
8339 * the remote side is doing away with the entire channel. (If it
8340 * had wanted to send us EOF and continue receiving data from us,
8341 * it would have just sent CHANNEL_EOF.)
8343 if (!(c->closes & CLOSES_SENT_EOF)) {
8345 * Make sure we don't read any more from whatever our local
8346 * data source is for this channel.
8349 case CHAN_MAINSESSION:
8350 ssh->send_ok = 0; /* stop trying to read from stdin */
8353 x11_override_throttle(c->u.x11.xconn, 1);
8356 pfd_override_throttle(c->u.pfd.pf, 1);
8361 * Abandon any buffered data we still wanted to send to this
8362 * channel. Receiving a CHANNEL_CLOSE is an indication that
8363 * the server really wants to get on and _destroy_ this
8364 * channel, and it isn't going to send us any further
8365 * WINDOW_ADJUSTs to permit us to send pending stuff.
8367 bufchain_clear(&c->v.v2.outbuffer);
8370 * Send outgoing EOF.
8372 sshfwd_write_eof(c);
8376 * Now process the actual close.
8378 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
8379 c->closes |= CLOSES_RCVD_CLOSE;
8380 ssh2_channel_check_close(c);
8384 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
8386 struct ssh_channel *c;
8388 c = ssh_channel_msg(ssh, pktin);
8391 if (c->type == CHAN_SHARING) {
8392 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8393 pktin->body, pktin->length);
8396 assert(c->halfopen); /* ssh_channel_msg will have enforced this */
8397 c->remoteid = ssh_pkt_getuint32(pktin);
8398 c->halfopen = FALSE;
8399 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8400 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8402 if (c->type == CHAN_SOCKDATA_DORMANT) {
8403 c->type = CHAN_SOCKDATA;
8405 pfd_confirm(c->u.pfd.pf);
8406 } else if (c->type == CHAN_ZOMBIE) {
8408 * This case can occur if a local socket error occurred
8409 * between us sending out CHANNEL_OPEN and receiving
8410 * OPEN_CONFIRMATION. In this case, all we can do is
8411 * immediately initiate close proceedings now that we know the
8412 * server's id to put in the close message.
8414 ssh2_channel_check_close(c);
8417 * We never expect to receive OPEN_CONFIRMATION for any
8418 * *other* channel type (since only local-to-remote port
8419 * forwardings cause us to send CHANNEL_OPEN after the main
8420 * channel is live - all other auxiliary channel types are
8421 * initiated from the server end). It's safe to enforce this
8422 * by assertion rather than by ssh_disconnect, because the
8423 * real point is that we never constructed a half-open channel
8424 * structure in the first place with any type other than the
8427 assert(!"Funny channel type in ssh2_msg_channel_open_confirmation");
8431 ssh_channel_try_eof(c); /* in case we had a pending EOF */
8434 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
8436 static const char *const reasons[] = {
8437 "<unknown reason code>",
8438 "Administratively prohibited",
8440 "Unknown channel type",
8441 "Resource shortage",
8443 unsigned reason_code;
8444 char *reason_string;
8446 struct ssh_channel *c;
8448 c = ssh_channel_msg(ssh, pktin);
8451 if (c->type == CHAN_SHARING) {
8452 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8453 pktin->body, pktin->length);
8456 assert(c->halfopen); /* ssh_channel_msg will have enforced this */
8458 if (c->type == CHAN_SOCKDATA_DORMANT) {
8459 reason_code = ssh_pkt_getuint32(pktin);
8460 if (reason_code >= lenof(reasons))
8461 reason_code = 0; /* ensure reasons[reason_code] in range */
8462 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
8463 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
8464 reasons[reason_code], reason_length,
8465 NULLTOEMPTY(reason_string));
8467 pfd_close(c->u.pfd.pf);
8468 } else if (c->type == CHAN_ZOMBIE) {
8470 * This case can occur if a local socket error occurred
8471 * between us sending out CHANNEL_OPEN and receiving
8472 * OPEN_FAILURE. In this case, we need do nothing except allow
8473 * the code below to throw the half-open channel away.
8477 * We never expect to receive OPEN_FAILURE for any *other*
8478 * channel type (since only local-to-remote port forwardings
8479 * cause us to send CHANNEL_OPEN after the main channel is
8480 * live - all other auxiliary channel types are initiated from
8481 * the server end). It's safe to enforce this by assertion
8482 * rather than by ssh_disconnect, because the real point is
8483 * that we never constructed a half-open channel structure in
8484 * the first place with any type other than the above.
8486 assert(!"Funny channel type in ssh2_msg_channel_open_failure");
8489 del234(ssh->channels, c);
8493 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
8496 int typelen, want_reply;
8497 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
8498 struct ssh_channel *c;
8499 struct Packet *pktout;
8501 c = ssh_channel_msg(ssh, pktin);
8504 if (c->type == CHAN_SHARING) {
8505 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8506 pktin->body, pktin->length);
8509 ssh_pkt_getstring(pktin, &type, &typelen);
8510 want_reply = ssh2_pkt_getbool(pktin);
8512 if (c->closes & CLOSES_SENT_CLOSE) {
8514 * We don't reply to channel requests after we've sent
8515 * CHANNEL_CLOSE for the channel, because our reply might
8516 * cross in the network with the other side's CHANNEL_CLOSE
8517 * and arrive after they have wound the channel up completely.
8523 * Having got the channel number, we now look at
8524 * the request type string to see if it's something
8527 if (c == ssh->mainchan) {
8529 * We recognise "exit-status" and "exit-signal" on
8530 * the primary channel.
8532 if (typelen == 11 &&
8533 !memcmp(type, "exit-status", 11)) {
8535 ssh->exitcode = ssh_pkt_getuint32(pktin);
8536 logeventf(ssh, "Server sent command exit status %d",
8538 reply = SSH2_MSG_CHANNEL_SUCCESS;
8540 } else if (typelen == 11 &&
8541 !memcmp(type, "exit-signal", 11)) {
8543 int is_plausible = TRUE, is_int = FALSE;
8544 char *fmt_sig = NULL, *fmt_msg = NULL;
8546 int msglen = 0, core = FALSE;
8547 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
8548 * provide an `int' for the signal, despite its
8549 * having been a `string' in the drafts of RFC 4254 since at
8550 * least 2001. (Fixed in session.c 1.147.) Try to
8551 * infer which we can safely parse it as. */
8553 unsigned char *p = pktin->body +
8555 long len = pktin->length - pktin->savedpos;
8556 unsigned long num = GET_32BIT(p); /* what is it? */
8557 /* If it's 0, it hardly matters; assume string */
8561 int maybe_int = FALSE, maybe_str = FALSE;
8562 #define CHECK_HYPOTHESIS(offset, result) \
8565 int q = toint(offset); \
8566 if (q >= 0 && q+4 <= len) { \
8567 q = toint(q + 4 + GET_32BIT(p+q)); \
8568 if (q >= 0 && q+4 <= len && \
8569 ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
8574 CHECK_HYPOTHESIS(4+1, maybe_int);
8575 CHECK_HYPOTHESIS(4+num+1, maybe_str);
8576 #undef CHECK_HYPOTHESIS
8577 if (maybe_int && !maybe_str)
8579 else if (!maybe_int && maybe_str)
8582 /* Crikey. Either or neither. Panic. */
8583 is_plausible = FALSE;
8586 ssh->exitcode = 128; /* means `unknown signal' */
8589 /* Old non-standard OpenSSH. */
8590 int signum = ssh_pkt_getuint32(pktin);
8591 fmt_sig = dupprintf(" %d", signum);
8592 ssh->exitcode = 128 + signum;
8594 /* As per RFC 4254. */
8597 ssh_pkt_getstring(pktin, &sig, &siglen);
8598 /* Signal name isn't supposed to be blank, but
8599 * let's cope gracefully if it is. */
8601 fmt_sig = dupprintf(" \"%.*s\"",
8606 * Really hideous method of translating the
8607 * signal description back into a locally
8608 * meaningful number.
8613 #define TRANSLATE_SIGNAL(s) \
8614 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
8615 ssh->exitcode = 128 + SIG ## s
8617 TRANSLATE_SIGNAL(ABRT);
8620 TRANSLATE_SIGNAL(ALRM);
8623 TRANSLATE_SIGNAL(FPE);
8626 TRANSLATE_SIGNAL(HUP);
8629 TRANSLATE_SIGNAL(ILL);
8632 TRANSLATE_SIGNAL(INT);
8635 TRANSLATE_SIGNAL(KILL);
8638 TRANSLATE_SIGNAL(PIPE);
8641 TRANSLATE_SIGNAL(QUIT);
8644 TRANSLATE_SIGNAL(SEGV);
8647 TRANSLATE_SIGNAL(TERM);
8650 TRANSLATE_SIGNAL(USR1);
8653 TRANSLATE_SIGNAL(USR2);
8655 #undef TRANSLATE_SIGNAL
8657 ssh->exitcode = 128;
8659 core = ssh2_pkt_getbool(pktin);
8660 ssh_pkt_getstring(pktin, &msg, &msglen);
8662 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
8664 /* ignore lang tag */
8665 } /* else don't attempt to parse */
8666 logeventf(ssh, "Server exited on signal%s%s%s",
8667 fmt_sig ? fmt_sig : "",
8668 core ? " (core dumped)" : "",
8669 fmt_msg ? fmt_msg : "");
8672 reply = SSH2_MSG_CHANNEL_SUCCESS;
8677 * This is a channel request we don't know
8678 * about, so we now either ignore the request
8679 * or respond with CHANNEL_FAILURE, depending
8682 reply = SSH2_MSG_CHANNEL_FAILURE;
8685 pktout = ssh2_pkt_init(reply);
8686 ssh2_pkt_adduint32(pktout, c->remoteid);
8687 ssh2_pkt_send(ssh, pktout);
8691 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
8694 int typelen, want_reply;
8695 struct Packet *pktout;
8697 ssh_pkt_getstring(pktin, &type, &typelen);
8698 want_reply = ssh2_pkt_getbool(pktin);
8701 * We currently don't support any global requests
8702 * at all, so we either ignore the request or
8703 * respond with REQUEST_FAILURE, depending on
8707 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
8708 ssh2_pkt_send(ssh, pktout);
8712 struct X11FakeAuth *ssh_sharing_add_x11_display(Ssh ssh, int authtype,
8716 struct X11FakeAuth *auth;
8719 * Make up a new set of fake X11 auth data, and add it to the tree
8720 * of currently valid ones with an indication of the sharing
8721 * context that it's relevant to.
8723 auth = x11_invent_fake_auth(ssh->x11authtree, authtype);
8724 auth->share_cs = share_cs;
8725 auth->share_chan = share_chan;
8730 void ssh_sharing_remove_x11_display(Ssh ssh, struct X11FakeAuth *auth)
8732 del234(ssh->x11authtree, auth);
8733 x11_free_fake_auth(auth);
8736 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
8743 const char *error = NULL;
8744 struct ssh_channel *c;
8745 unsigned remid, winsize, pktsize;
8746 unsigned our_winsize_override = 0;
8747 struct Packet *pktout;
8749 ssh_pkt_getstring(pktin, &type, &typelen);
8750 c = snew(struct ssh_channel);
8753 remid = ssh_pkt_getuint32(pktin);
8754 winsize = ssh_pkt_getuint32(pktin);
8755 pktsize = ssh_pkt_getuint32(pktin);
8757 if (typelen == 3 && !memcmp(type, "x11", 3)) {
8760 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8761 addrstr = dupprintf("%.*s", peeraddrlen, NULLTOEMPTY(peeraddr));
8762 peerport = ssh_pkt_getuint32(pktin);
8764 logeventf(ssh, "Received X11 connect request from %s:%d",
8767 if (!ssh->X11_fwd_enabled && !ssh->connshare)
8768 error = "X11 forwarding is not enabled";
8770 c->u.x11.xconn = x11_init(ssh->x11authtree, c,
8773 c->u.x11.initial = TRUE;
8776 * If we are a connection-sharing upstream, then we should
8777 * initially present a very small window, adequate to take
8778 * the X11 initial authorisation packet but not much more.
8779 * Downstream will then present us a larger window (by
8780 * fiat of the connection-sharing protocol) and we can
8781 * guarantee to send a positive-valued WINDOW_ADJUST.
8784 our_winsize_override = 128;
8786 logevent("Opened X11 forward channel");
8790 } else if (typelen == 15 &&
8791 !memcmp(type, "forwarded-tcpip", 15)) {
8792 struct ssh_rportfwd pf, *realpf;
8795 ssh_pkt_getstring(pktin, &shost, &shostlen);/* skip address */
8796 pf.shost = dupprintf("%.*s", shostlen, NULLTOEMPTY(shost));
8797 pf.sport = ssh_pkt_getuint32(pktin);
8798 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8799 peerport = ssh_pkt_getuint32(pktin);
8800 realpf = find234(ssh->rportfwds, &pf, NULL);
8801 logeventf(ssh, "Received remote port %s:%d open request "
8802 "from %.*s:%d", pf.shost, pf.sport,
8803 peeraddrlen, NULLTOEMPTY(peeraddr), peerport);
8806 if (realpf == NULL) {
8807 error = "Remote port is not recognised";
8811 if (realpf->share_ctx) {
8813 * This port forwarding is on behalf of a
8814 * connection-sharing downstream, so abandon our own
8815 * channel-open procedure and just pass the message on
8818 share_got_pkt_from_server(realpf->share_ctx, pktin->type,
8819 pktin->body, pktin->length);
8824 err = pfd_connect(&c->u.pfd.pf, realpf->dhost, realpf->dport,
8825 c, ssh->conf, realpf->pfrec->addressfamily);
8826 logeventf(ssh, "Attempting to forward remote port to "
8827 "%s:%d", realpf->dhost, realpf->dport);
8829 logeventf(ssh, "Port open failed: %s", err);
8831 error = "Port open failed";
8833 logevent("Forwarded port opened successfully");
8834 c->type = CHAN_SOCKDATA;
8837 } else if (typelen == 22 &&
8838 !memcmp(type, "auth-agent@openssh.com", 22)) {
8839 if (!ssh->agentfwd_enabled)
8840 error = "Agent forwarding is not enabled";
8842 c->type = CHAN_AGENT; /* identify channel type */
8843 c->u.a.lensofar = 0;
8844 c->u.a.message = NULL;
8845 c->u.a.outstanding_requests = 0;
8848 error = "Unsupported channel type requested";
8851 c->remoteid = remid;
8852 c->halfopen = FALSE;
8854 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
8855 ssh2_pkt_adduint32(pktout, c->remoteid);
8856 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
8857 ssh2_pkt_addstring(pktout, error);
8858 ssh2_pkt_addstring(pktout, "en"); /* language tag */
8859 ssh2_pkt_send(ssh, pktout);
8860 logeventf(ssh, "Rejected channel open: %s", error);
8863 ssh_channel_init(c);
8864 c->v.v2.remwindow = winsize;
8865 c->v.v2.remmaxpkt = pktsize;
8866 if (our_winsize_override) {
8867 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
8868 our_winsize_override;
8870 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
8871 ssh2_pkt_adduint32(pktout, c->remoteid);
8872 ssh2_pkt_adduint32(pktout, c->localid);
8873 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
8874 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
8875 ssh2_pkt_send(ssh, pktout);
8879 void sshfwd_x11_sharing_handover(struct ssh_channel *c,
8880 void *share_cs, void *share_chan,
8881 const char *peer_addr, int peer_port,
8882 int endian, int protomajor, int protominor,
8883 const void *initial_data, int initial_len)
8886 * This function is called when we've just discovered that an X
8887 * forwarding channel on which we'd been handling the initial auth
8888 * ourselves turns out to be destined for a connection-sharing
8889 * downstream. So we turn the channel into a CHAN_SHARING, meaning
8890 * that we completely stop tracking windows and buffering data and
8891 * just pass more or less unmodified SSH messages back and forth.
8893 c->type = CHAN_SHARING;
8894 c->u.sharing.ctx = share_cs;
8895 share_setup_x11_channel(share_cs, share_chan,
8896 c->localid, c->remoteid, c->v.v2.remwindow,
8897 c->v.v2.remmaxpkt, c->v.v2.locwindow,
8898 peer_addr, peer_port, endian,
8899 protomajor, protominor,
8900 initial_data, initial_len);
8903 void sshfwd_x11_is_local(struct ssh_channel *c)
8906 * This function is called when we've just discovered that an X
8907 * forwarding channel is _not_ destined for a connection-sharing
8908 * downstream but we're going to handle it ourselves. We stop
8909 * presenting a cautiously small window and go into ordinary data
8912 c->u.x11.initial = FALSE;
8913 ssh2_set_window(c, ssh_is_simple(c->ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE);
8917 * Buffer banner messages for later display at some convenient point,
8918 * if we're going to display them.
8920 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
8922 /* Arbitrary limit to prevent unbounded inflation of buffer */
8923 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
8924 bufchain_size(&ssh->banner) <= 131072) {
8925 char *banner = NULL;
8927 ssh_pkt_getstring(pktin, &banner, &size);
8929 bufchain_add(&ssh->banner, banner, size);
8933 /* Helper function to deal with sending tty modes for "pty-req" */
8934 static void ssh2_send_ttymode(void *data,
8935 const struct ssh_ttymode *mode, char *val)
8937 struct Packet *pktout = (struct Packet *)data;
8938 unsigned int arg = 0;
8940 switch (mode->type) {
8942 arg = ssh_tty_parse_specchar(val);
8945 arg = ssh_tty_parse_boolean(val);
8948 ssh2_pkt_addbyte(pktout, mode->opcode);
8949 ssh2_pkt_adduint32(pktout, arg);
8952 static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
8955 struct ssh2_setup_x11_state {
8959 struct Packet *pktout;
8960 crStateP(ssh2_setup_x11_state, ctx);
8964 logevent("Requesting X11 forwarding");
8965 pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
8967 ssh2_pkt_addbool(pktout, 0); /* many connections */
8968 ssh2_pkt_addstring(pktout, ssh->x11auth->protoname);
8969 ssh2_pkt_addstring(pktout, ssh->x11auth->datastring);
8970 ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
8971 ssh2_pkt_send(ssh, pktout);
8973 /* Wait to be called back with either a response packet, or NULL
8974 * meaning clean up and free our data */
8978 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8979 logevent("X11 forwarding enabled");
8980 ssh->X11_fwd_enabled = TRUE;
8982 logevent("X11 forwarding refused");
8988 static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
8991 struct ssh2_setup_agent_state {
8995 struct Packet *pktout;
8996 crStateP(ssh2_setup_agent_state, ctx);
9000 logevent("Requesting OpenSSH-style agent forwarding");
9001 pktout = ssh2_chanreq_init(ssh->mainchan, "auth-agent-req@openssh.com",
9002 ssh2_setup_agent, s);
9003 ssh2_pkt_send(ssh, pktout);
9005 /* Wait to be called back with either a response packet, or NULL
9006 * meaning clean up and free our data */
9010 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
9011 logevent("Agent forwarding enabled");
9012 ssh->agentfwd_enabled = TRUE;
9014 logevent("Agent forwarding refused");
9020 static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
9023 struct ssh2_setup_pty_state {
9027 struct Packet *pktout;
9028 crStateP(ssh2_setup_pty_state, ctx);
9032 /* Unpick the terminal-speed string. */
9033 /* XXX perhaps we should allow no speeds to be sent. */
9034 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
9035 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
9036 /* Build the pty request. */
9037 pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
9039 ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
9040 ssh2_pkt_adduint32(pktout, ssh->term_width);
9041 ssh2_pkt_adduint32(pktout, ssh->term_height);
9042 ssh2_pkt_adduint32(pktout, 0); /* pixel width */
9043 ssh2_pkt_adduint32(pktout, 0); /* pixel height */
9044 ssh2_pkt_addstring_start(pktout);
9045 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
9046 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
9047 ssh2_pkt_adduint32(pktout, ssh->ispeed);
9048 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
9049 ssh2_pkt_adduint32(pktout, ssh->ospeed);
9050 ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
9051 ssh2_pkt_send(ssh, pktout);
9052 ssh->state = SSH_STATE_INTERMED;
9054 /* Wait to be called back with either a response packet, or NULL
9055 * meaning clean up and free our data */
9059 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
9060 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
9061 ssh->ospeed, ssh->ispeed);
9062 ssh->got_pty = TRUE;
9064 c_write_str(ssh, "Server refused to allocate pty\r\n");
9065 ssh->editing = ssh->echoing = 1;
9072 static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
9075 struct ssh2_setup_env_state {
9077 int num_env, env_left, env_ok;
9080 struct Packet *pktout;
9081 crStateP(ssh2_setup_env_state, ctx);
9086 * Send environment variables.
9088 * Simplest thing here is to send all the requests at once, and
9089 * then wait for a whole bunch of successes or failures.
9095 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
9097 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
9098 pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
9099 ssh2_pkt_addstring(pktout, key);
9100 ssh2_pkt_addstring(pktout, val);
9101 ssh2_pkt_send(ssh, pktout);
9106 logeventf(ssh, "Sent %d environment variables", s->num_env);
9111 s->env_left = s->num_env;
9113 while (s->env_left > 0) {
9114 /* Wait to be called back with either a response packet,
9115 * or NULL meaning clean up and free our data */
9117 if (!pktin) goto out;
9118 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
9123 if (s->env_ok == s->num_env) {
9124 logevent("All environment variables successfully set");
9125 } else if (s->env_ok == 0) {
9126 logevent("All environment variables refused");
9127 c_write_str(ssh, "Server refused to set environment variables\r\n");
9129 logeventf(ssh, "%d environment variables refused",
9130 s->num_env - s->env_ok);
9131 c_write_str(ssh, "Server refused to set all environment variables\r\n");
9139 * Handle the SSH-2 userauth and connection layers.
9141 static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
9143 do_ssh2_authconn(ssh, NULL, 0, pktin);
9146 static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
9150 do_ssh2_authconn(c->ssh, NULL, 0, pktin);
9153 static void do_ssh2_authconn(Ssh ssh, const unsigned char *in, int inlen,
9154 struct Packet *pktin)
9156 struct do_ssh2_authconn_state {
9160 AUTH_TYPE_PUBLICKEY,
9161 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
9162 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
9164 AUTH_TYPE_GSSAPI, /* always QUIET */
9165 AUTH_TYPE_KEYBOARD_INTERACTIVE,
9166 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
9168 int done_service_req;
9169 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
9170 int tried_pubkey_config, done_agent;
9175 int kbd_inter_refused;
9176 int we_are_in, userauth_success;
9177 prompts_t *cur_prompt;
9182 void *publickey_blob;
9183 int publickey_bloblen;
9184 int privatekey_available, privatekey_encrypted;
9185 char *publickey_algorithm;
9186 char *publickey_comment;
9187 unsigned char agent_request[5], *agent_response, *agentp;
9188 int agent_responselen;
9189 unsigned char *pkblob_in_agent;
9191 char *pkblob, *alg, *commentp;
9192 int pklen, alglen, commentlen;
9193 int siglen, retlen, len;
9194 char *q, *agentreq, *ret;
9195 struct Packet *pktout;
9198 struct ssh_gss_library *gsslib;
9199 Ssh_gss_ctx gss_ctx;
9200 Ssh_gss_buf gss_buf;
9201 Ssh_gss_buf gss_rcvtok, gss_sndtok;
9202 Ssh_gss_name gss_srv_name;
9203 Ssh_gss_stat gss_stat;
9206 crState(do_ssh2_authconn_state);
9210 /* Register as a handler for all the messages this coroutine handles. */
9211 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
9212 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
9213 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
9214 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
9215 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
9216 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
9217 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
9218 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
9219 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
9220 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
9221 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
9222 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
9223 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
9224 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
9225 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
9226 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
9227 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
9228 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
9229 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
9230 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
9232 s->done_service_req = FALSE;
9233 s->we_are_in = s->userauth_success = FALSE;
9234 s->agent_response = NULL;
9236 s->tried_gssapi = FALSE;
9239 if (!ssh->bare_connection) {
9240 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
9242 * Request userauth protocol, and await a response to it.
9244 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
9245 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
9246 ssh2_pkt_send(ssh, s->pktout);
9247 crWaitUntilV(pktin);
9248 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
9249 s->done_service_req = TRUE;
9251 if (!s->done_service_req) {
9253 * Request connection protocol directly, without authentication.
9255 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
9256 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9257 ssh2_pkt_send(ssh, s->pktout);
9258 crWaitUntilV(pktin);
9259 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
9260 s->we_are_in = TRUE; /* no auth required */
9262 bombout(("Server refused service request"));
9267 s->we_are_in = TRUE;
9270 /* Arrange to be able to deal with any BANNERs that come in.
9271 * (We do this now as packets may come in during the next bit.) */
9272 bufchain_init(&ssh->banner);
9273 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
9274 ssh2_msg_userauth_banner;
9277 * Misc one-time setup for authentication.
9279 s->publickey_blob = NULL;
9280 if (!s->we_are_in) {
9283 * Load the public half of any configured public key file
9286 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9287 if (!filename_is_null(s->keyfile)) {
9289 logeventf(ssh, "Reading key file \"%.150s\"",
9290 filename_to_str(s->keyfile));
9291 keytype = key_type(s->keyfile);
9292 if (keytype == SSH_KEYTYPE_SSH2 ||
9293 keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 ||
9294 keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
9297 ssh2_userkey_loadpub(s->keyfile,
9298 &s->publickey_algorithm,
9299 &s->publickey_bloblen,
9300 &s->publickey_comment, &error);
9301 if (s->publickey_blob) {
9302 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH2);
9303 if (!s->privatekey_available)
9304 logeventf(ssh, "Key file contains public key only");
9305 s->privatekey_encrypted =
9306 ssh2_userkey_encrypted(s->keyfile, NULL);
9309 logeventf(ssh, "Unable to load key (%s)",
9311 msgbuf = dupprintf("Unable to load key file "
9312 "\"%.150s\" (%s)\r\n",
9313 filename_to_str(s->keyfile),
9315 c_write_str(ssh, msgbuf);
9320 logeventf(ssh, "Unable to use this key file (%s)",
9321 key_type_to_str(keytype));
9322 msgbuf = dupprintf("Unable to use key file \"%.150s\""
9324 filename_to_str(s->keyfile),
9325 key_type_to_str(keytype));
9326 c_write_str(ssh, msgbuf);
9328 s->publickey_blob = NULL;
9333 * Find out about any keys Pageant has (but if there's a
9334 * public key configured, filter out all others).
9337 s->agent_response = NULL;
9338 s->pkblob_in_agent = NULL;
9339 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
9343 logevent("Pageant is running. Requesting keys.");
9345 /* Request the keys held by the agent. */
9346 PUT_32BIT(s->agent_request, 1);
9347 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
9348 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
9349 ssh_agent_callback, ssh)) {
9353 bombout(("Unexpected data from server while"
9354 " waiting for agent response"));
9357 } while (pktin || inlen > 0);
9358 r = ssh->agent_response;
9359 s->agent_responselen = ssh->agent_response_len;
9361 s->agent_response = (unsigned char *) r;
9362 if (s->agent_response && s->agent_responselen >= 5 &&
9363 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
9366 p = s->agent_response + 5;
9367 s->nkeys = toint(GET_32BIT(p));
9370 * Vet the Pageant response to ensure that the key
9371 * count and blob lengths make sense.
9374 logeventf(ssh, "Pageant response contained a negative"
9375 " key count %d", s->nkeys);
9377 goto done_agent_query;
9379 unsigned char *q = p + 4;
9380 int lenleft = s->agent_responselen - 5 - 4;
9382 for (keyi = 0; keyi < s->nkeys; keyi++) {
9383 int bloblen, commentlen;
9385 logeventf(ssh, "Pageant response was truncated");
9387 goto done_agent_query;
9389 bloblen = toint(GET_32BIT(q));
9390 if (bloblen < 0 || bloblen > lenleft) {
9391 logeventf(ssh, "Pageant response was truncated");
9393 goto done_agent_query;
9395 lenleft -= 4 + bloblen;
9397 commentlen = toint(GET_32BIT(q));
9398 if (commentlen < 0 || commentlen > lenleft) {
9399 logeventf(ssh, "Pageant response was truncated");
9401 goto done_agent_query;
9403 lenleft -= 4 + commentlen;
9404 q += 4 + commentlen;
9409 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
9410 if (s->publickey_blob) {
9411 /* See if configured key is in agent. */
9412 for (keyi = 0; keyi < s->nkeys; keyi++) {
9413 s->pklen = toint(GET_32BIT(p));
9414 if (s->pklen == s->publickey_bloblen &&
9415 !memcmp(p+4, s->publickey_blob,
9416 s->publickey_bloblen)) {
9417 logeventf(ssh, "Pageant key #%d matches "
9418 "configured key file", keyi);
9420 s->pkblob_in_agent = p;
9424 p += toint(GET_32BIT(p)) + 4; /* comment */
9426 if (!s->pkblob_in_agent) {
9427 logevent("Configured key file not in Pageant");
9432 logevent("Failed to get reply from Pageant");
9440 * We repeat this whole loop, including the username prompt,
9441 * until we manage a successful authentication. If the user
9442 * types the wrong _password_, they can be sent back to the
9443 * beginning to try another username, if this is configured on.
9444 * (If they specify a username in the config, they are never
9445 * asked, even if they do give a wrong password.)
9447 * I think this best serves the needs of
9449 * - the people who have no configuration, no keys, and just
9450 * want to try repeated (username,password) pairs until they
9451 * type both correctly
9453 * - people who have keys and configuration but occasionally
9454 * need to fall back to passwords
9456 * - people with a key held in Pageant, who might not have
9457 * logged in to a particular machine before; so they want to
9458 * type a username, and then _either_ their key will be
9459 * accepted, _or_ they will type a password. If they mistype
9460 * the username they will want to be able to get back and
9463 s->got_username = FALSE;
9464 while (!s->we_are_in) {
9468 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
9470 * We got a username last time round this loop, and
9471 * with change_username turned off we don't try to get
9474 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
9475 int ret; /* need not be kept over crReturn */
9476 s->cur_prompt = new_prompts(ssh->frontend);
9477 s->cur_prompt->to_server = TRUE;
9478 s->cur_prompt->name = dupstr("SSH login name");
9479 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
9480 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9483 crWaitUntilV(!pktin);
9484 ret = get_userpass_input(s->cur_prompt, in, inlen);
9489 * get_userpass_input() failed to get a username.
9492 free_prompts(s->cur_prompt);
9493 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
9496 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
9497 free_prompts(s->cur_prompt);
9500 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
9501 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
9502 c_write_str(ssh, stuff);
9506 s->got_username = TRUE;
9509 * Send an authentication request using method "none": (a)
9510 * just in case it succeeds, and (b) so that we know what
9511 * authentication methods we can usefully try next.
9513 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9515 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9516 ssh2_pkt_addstring(s->pktout, ssh->username);
9517 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
9518 ssh2_pkt_addstring(s->pktout, "none"); /* method */
9519 ssh2_pkt_send(ssh, s->pktout);
9520 s->type = AUTH_TYPE_NONE;
9522 s->we_are_in = FALSE;
9524 s->tried_pubkey_config = FALSE;
9525 s->kbd_inter_refused = FALSE;
9527 /* Reset agent request state. */
9528 s->done_agent = FALSE;
9529 if (s->agent_response) {
9530 if (s->pkblob_in_agent) {
9531 s->agentp = s->pkblob_in_agent;
9533 s->agentp = s->agent_response + 5 + 4;
9539 char *methods = NULL;
9543 * Wait for the result of the last authentication request.
9546 crWaitUntilV(pktin);
9548 * Now is a convenient point to spew any banner material
9549 * that we've accumulated. (This should ensure that when
9550 * we exit the auth loop, we haven't any left to deal
9554 int size = bufchain_size(&ssh->banner);
9556 * Don't show the banner if we're operating in
9557 * non-verbose non-interactive mode. (It's probably
9558 * a script, which means nobody will read the
9559 * banner _anyway_, and moreover the printing of
9560 * the banner will screw up processing on the
9561 * output of (say) plink.)
9563 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
9564 char *banner = snewn(size, char);
9565 bufchain_fetch(&ssh->banner, banner, size);
9566 c_write_untrusted(ssh, banner, size);
9569 bufchain_clear(&ssh->banner);
9571 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
9572 logevent("Access granted");
9573 s->we_are_in = s->userauth_success = TRUE;
9577 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
9578 bombout(("Strange packet received during authentication: "
9579 "type %d", pktin->type));
9586 * OK, we're now sitting on a USERAUTH_FAILURE message, so
9587 * we can look at the string in it and know what we can
9588 * helpfully try next.
9590 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
9591 ssh_pkt_getstring(pktin, &methods, &methlen);
9592 if (!ssh2_pkt_getbool(pktin)) {
9594 * We have received an unequivocal Access
9595 * Denied. This can translate to a variety of
9596 * messages, or no message at all.
9598 * For forms of authentication which are attempted
9599 * implicitly, by which I mean without printing
9600 * anything in the window indicating that we're
9601 * trying them, we should never print 'Access
9604 * If we do print a message saying that we're
9605 * attempting some kind of authentication, it's OK
9606 * to print a followup message saying it failed -
9607 * but the message may sometimes be more specific
9608 * than simply 'Access denied'.
9610 * Additionally, if we'd just tried password
9611 * authentication, we should break out of this
9612 * whole loop so as to go back to the username
9613 * prompt (iff we're configured to allow
9614 * username change attempts).
9616 if (s->type == AUTH_TYPE_NONE) {
9618 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
9619 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
9620 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
9621 c_write_str(ssh, "Server refused our key\r\n");
9622 logevent("Server refused our key");
9623 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
9624 /* This _shouldn't_ happen except by a
9625 * protocol bug causing client and server to
9626 * disagree on what is a correct signature. */
9627 c_write_str(ssh, "Server refused public-key signature"
9628 " despite accepting key!\r\n");
9629 logevent("Server refused public-key signature"
9630 " despite accepting key!");
9631 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
9632 /* quiet, so no c_write */
9633 logevent("Server refused keyboard-interactive authentication");
9634 } else if (s->type==AUTH_TYPE_GSSAPI) {
9635 /* always quiet, so no c_write */
9636 /* also, the code down in the GSSAPI block has
9637 * already logged this in the Event Log */
9638 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
9639 logevent("Keyboard-interactive authentication failed");
9640 c_write_str(ssh, "Access denied\r\n");
9642 assert(s->type == AUTH_TYPE_PASSWORD);
9643 logevent("Password authentication failed");
9644 c_write_str(ssh, "Access denied\r\n");
9646 if (conf_get_int(ssh->conf, CONF_change_username)) {
9647 /* XXX perhaps we should allow
9648 * keyboard-interactive to do this too? */
9649 s->we_are_in = FALSE;
9654 c_write_str(ssh, "Further authentication required\r\n");
9655 logevent("Further authentication required");
9659 in_commasep_string("publickey", methods, methlen);
9661 in_commasep_string("password", methods, methlen);
9662 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
9663 in_commasep_string("keyboard-interactive", methods, methlen);
9665 if (conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
9666 in_commasep_string("gssapi-with-mic", methods, methlen)) {
9667 /* Try loading the GSS libraries and see if we
9670 ssh->gsslibs = ssh_gss_setup(ssh->conf);
9671 s->can_gssapi = (ssh->gsslibs->nlibraries > 0);
9673 /* No point in even bothering to try to load the
9674 * GSS libraries, if the user configuration and
9675 * server aren't both prepared to attempt GSSAPI
9676 * auth in the first place. */
9677 s->can_gssapi = FALSE;
9682 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9684 if (s->can_pubkey && !s->done_agent && s->nkeys) {
9687 * Attempt public-key authentication using a key from Pageant.
9690 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9692 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
9694 /* Unpack key from agent response */
9695 s->pklen = toint(GET_32BIT(s->agentp));
9697 s->pkblob = (char *)s->agentp;
9698 s->agentp += s->pklen;
9699 s->alglen = toint(GET_32BIT(s->pkblob));
9700 s->alg = s->pkblob + 4;
9701 s->commentlen = toint(GET_32BIT(s->agentp));
9703 s->commentp = (char *)s->agentp;
9704 s->agentp += s->commentlen;
9705 /* s->agentp now points at next key, if any */
9707 /* See if server will accept it */
9708 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9709 ssh2_pkt_addstring(s->pktout, ssh->username);
9710 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9711 /* service requested */
9712 ssh2_pkt_addstring(s->pktout, "publickey");
9714 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
9715 ssh2_pkt_addstring_start(s->pktout);
9716 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9717 ssh2_pkt_addstring_start(s->pktout);
9718 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9719 ssh2_pkt_send(ssh, s->pktout);
9720 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
9722 crWaitUntilV(pktin);
9723 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9725 /* Offer of key refused. */
9732 if (flags & FLAG_VERBOSE) {
9733 c_write_str(ssh, "Authenticating with "
9735 c_write(ssh, s->commentp, s->commentlen);
9736 c_write_str(ssh, "\" from agent\r\n");
9740 * Server is willing to accept the key.
9741 * Construct a SIGN_REQUEST.
9743 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9744 ssh2_pkt_addstring(s->pktout, ssh->username);
9745 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9746 /* service requested */
9747 ssh2_pkt_addstring(s->pktout, "publickey");
9749 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
9750 ssh2_pkt_addstring_start(s->pktout);
9751 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9752 ssh2_pkt_addstring_start(s->pktout);
9753 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9755 /* Ask agent for signature. */
9756 s->siglen = s->pktout->length - 5 + 4 +
9757 ssh->v2_session_id_len;
9758 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9760 s->len = 1; /* message type */
9761 s->len += 4 + s->pklen; /* key blob */
9762 s->len += 4 + s->siglen; /* data to sign */
9763 s->len += 4; /* flags */
9764 s->agentreq = snewn(4 + s->len, char);
9765 PUT_32BIT(s->agentreq, s->len);
9766 s->q = s->agentreq + 4;
9767 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
9768 PUT_32BIT(s->q, s->pklen);
9770 memcpy(s->q, s->pkblob, s->pklen);
9772 PUT_32BIT(s->q, s->siglen);
9774 /* Now the data to be signed... */
9775 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9776 PUT_32BIT(s->q, ssh->v2_session_id_len);
9779 memcpy(s->q, ssh->v2_session_id,
9780 ssh->v2_session_id_len);
9781 s->q += ssh->v2_session_id_len;
9782 memcpy(s->q, s->pktout->data + 5,
9783 s->pktout->length - 5);
9784 s->q += s->pktout->length - 5;
9785 /* And finally the (zero) flags word. */
9787 if (!agent_query(s->agentreq, s->len + 4,
9789 ssh_agent_callback, ssh)) {
9793 bombout(("Unexpected data from server"
9794 " while waiting for agent"
9798 } while (pktin || inlen > 0);
9799 vret = ssh->agent_response;
9800 s->retlen = ssh->agent_response_len;
9805 if (s->retlen >= 9 &&
9806 s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
9807 GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
9808 logevent("Sending Pageant's response");
9809 ssh2_add_sigblob(ssh, s->pktout,
9810 s->pkblob, s->pklen,
9812 GET_32BIT(s->ret + 5));
9813 ssh2_pkt_send(ssh, s->pktout);
9814 s->type = AUTH_TYPE_PUBLICKEY;
9816 /* FIXME: less drastic response */
9817 bombout(("Pageant failed to answer challenge"));
9823 /* Do we have any keys left to try? */
9824 if (s->pkblob_in_agent) {
9825 s->done_agent = TRUE;
9826 s->tried_pubkey_config = TRUE;
9829 if (s->keyi >= s->nkeys)
9830 s->done_agent = TRUE;
9833 } else if (s->can_pubkey && s->publickey_blob &&
9834 s->privatekey_available && !s->tried_pubkey_config) {
9836 struct ssh2_userkey *key; /* not live over crReturn */
9837 char *passphrase; /* not live over crReturn */
9839 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9841 s->tried_pubkey_config = TRUE;
9844 * Try the public key supplied in the configuration.
9846 * First, offer the public blob to see if the server is
9847 * willing to accept it.
9849 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9850 ssh2_pkt_addstring(s->pktout, ssh->username);
9851 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9852 /* service requested */
9853 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
9854 ssh2_pkt_addbool(s->pktout, FALSE);
9855 /* no signature included */
9856 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
9857 ssh2_pkt_addstring_start(s->pktout);
9858 ssh2_pkt_addstring_data(s->pktout,
9859 (char *)s->publickey_blob,
9860 s->publickey_bloblen);
9861 ssh2_pkt_send(ssh, s->pktout);
9862 logevent("Offered public key");
9864 crWaitUntilV(pktin);
9865 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9866 /* Key refused. Give up. */
9867 s->gotit = TRUE; /* reconsider message next loop */
9868 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
9869 continue; /* process this new message */
9871 logevent("Offer of public key accepted");
9874 * Actually attempt a serious authentication using
9877 if (flags & FLAG_VERBOSE) {
9878 c_write_str(ssh, "Authenticating with public key \"");
9879 c_write_str(ssh, s->publickey_comment);
9880 c_write_str(ssh, "\"\r\n");
9884 const char *error; /* not live over crReturn */
9885 if (s->privatekey_encrypted) {
9887 * Get a passphrase from the user.
9889 int ret; /* need not be kept over crReturn */
9890 s->cur_prompt = new_prompts(ssh->frontend);
9891 s->cur_prompt->to_server = FALSE;
9892 s->cur_prompt->name = dupstr("SSH key passphrase");
9893 add_prompt(s->cur_prompt,
9894 dupprintf("Passphrase for key \"%.100s\": ",
9895 s->publickey_comment),
9897 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9900 crWaitUntilV(!pktin);
9901 ret = get_userpass_input(s->cur_prompt,
9906 /* Failed to get a passphrase. Terminate. */
9907 free_prompts(s->cur_prompt);
9908 ssh_disconnect(ssh, NULL,
9909 "Unable to authenticate",
9910 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9915 dupstr(s->cur_prompt->prompts[0]->result);
9916 free_prompts(s->cur_prompt);
9918 passphrase = NULL; /* no passphrase needed */
9922 * Try decrypting the key.
9924 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9925 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
9927 /* burn the evidence */
9928 smemclr(passphrase, strlen(passphrase));
9931 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
9933 (key == SSH2_WRONG_PASSPHRASE)) {
9934 c_write_str(ssh, "Wrong passphrase\r\n");
9936 /* and loop again */
9938 c_write_str(ssh, "Unable to load private key (");
9939 c_write_str(ssh, error);
9940 c_write_str(ssh, ")\r\n");
9942 break; /* try something else */
9948 unsigned char *pkblob, *sigblob, *sigdata;
9949 int pkblob_len, sigblob_len, sigdata_len;
9953 * We have loaded the private key and the server
9954 * has announced that it's willing to accept it.
9955 * Hallelujah. Generate a signature and send it.
9957 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9958 ssh2_pkt_addstring(s->pktout, ssh->username);
9959 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9960 /* service requested */
9961 ssh2_pkt_addstring(s->pktout, "publickey");
9963 ssh2_pkt_addbool(s->pktout, TRUE);
9964 /* signature follows */
9965 ssh2_pkt_addstring(s->pktout, key->alg->name);
9966 pkblob = key->alg->public_blob(key->data,
9968 ssh2_pkt_addstring_start(s->pktout);
9969 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
9973 * The data to be signed is:
9977 * followed by everything so far placed in the
9980 sigdata_len = s->pktout->length - 5 + 4 +
9981 ssh->v2_session_id_len;
9982 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9984 sigdata = snewn(sigdata_len, unsigned char);
9986 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9987 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
9990 memcpy(sigdata+p, ssh->v2_session_id,
9991 ssh->v2_session_id_len);
9992 p += ssh->v2_session_id_len;
9993 memcpy(sigdata+p, s->pktout->data + 5,
9994 s->pktout->length - 5);
9995 p += s->pktout->length - 5;
9996 assert(p == sigdata_len);
9997 sigblob = key->alg->sign(key->data, (char *)sigdata,
9998 sigdata_len, &sigblob_len);
9999 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
10000 sigblob, sigblob_len);
10005 ssh2_pkt_send(ssh, s->pktout);
10006 logevent("Sent public key signature");
10007 s->type = AUTH_TYPE_PUBLICKEY;
10008 key->alg->freekey(key->data);
10009 sfree(key->comment);
10014 } else if (s->can_gssapi && !s->tried_gssapi) {
10016 /* GSSAPI Authentication */
10018 int micoffset, len;
10021 s->type = AUTH_TYPE_GSSAPI;
10022 s->tried_gssapi = TRUE;
10024 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
10027 * Pick the highest GSS library on the preference
10033 for (i = 0; i < ngsslibs; i++) {
10034 int want_id = conf_get_int_int(ssh->conf,
10035 CONF_ssh_gsslist, i);
10036 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
10037 if (ssh->gsslibs->libraries[j].id == want_id) {
10038 s->gsslib = &ssh->gsslibs->libraries[j];
10039 goto got_gsslib; /* double break */
10044 * We always expect to have found something in
10045 * the above loop: we only came here if there
10046 * was at least one viable GSS library, and the
10047 * preference list should always mention
10048 * everything and only change the order.
10053 if (s->gsslib->gsslogmsg)
10054 logevent(s->gsslib->gsslogmsg);
10056 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
10057 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10058 ssh2_pkt_addstring(s->pktout, ssh->username);
10059 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10060 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
10061 logevent("Attempting GSSAPI authentication");
10063 /* add mechanism info */
10064 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
10066 /* number of GSSAPI mechanisms */
10067 ssh2_pkt_adduint32(s->pktout,1);
10069 /* length of OID + 2 */
10070 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
10071 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
10073 /* length of OID */
10074 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
10076 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
10077 s->gss_buf.length);
10078 ssh2_pkt_send(ssh, s->pktout);
10079 crWaitUntilV(pktin);
10080 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
10081 logevent("GSSAPI authentication request refused");
10085 /* check returned packet ... */
10087 ssh_pkt_getstring(pktin, &data, &len);
10088 s->gss_rcvtok.value = data;
10089 s->gss_rcvtok.length = len;
10090 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
10091 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
10092 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
10093 memcmp((char *)s->gss_rcvtok.value + 2,
10094 s->gss_buf.value,s->gss_buf.length) ) {
10095 logevent("GSSAPI authentication - wrong response from server");
10099 /* now start running */
10100 s->gss_stat = s->gsslib->import_name(s->gsslib,
10103 if (s->gss_stat != SSH_GSS_OK) {
10104 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
10105 logevent("GSSAPI import name failed - Bad service name");
10107 logevent("GSSAPI import name failed");
10111 /* fetch TGT into GSS engine */
10112 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
10114 if (s->gss_stat != SSH_GSS_OK) {
10115 logevent("GSSAPI authentication failed to get credentials");
10116 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10120 /* initial tokens are empty */
10121 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
10122 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
10124 /* now enter the loop */
10126 s->gss_stat = s->gsslib->init_sec_context
10130 conf_get_int(ssh->conf, CONF_gssapifwd),
10134 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
10135 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
10136 logevent("GSSAPI authentication initialisation failed");
10138 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
10139 &s->gss_buf) == SSH_GSS_OK) {
10140 logevent(s->gss_buf.value);
10141 sfree(s->gss_buf.value);
10146 logevent("GSSAPI authentication initialised");
10148 /* Client and server now exchange tokens until GSSAPI
10149 * no longer says CONTINUE_NEEDED */
10151 if (s->gss_sndtok.length != 0) {
10152 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
10153 ssh_pkt_addstring_start(s->pktout);
10154 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
10155 ssh2_pkt_send(ssh, s->pktout);
10156 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
10159 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
10160 crWaitUntilV(pktin);
10161 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
10162 logevent("GSSAPI authentication - bad server response");
10163 s->gss_stat = SSH_GSS_FAILURE;
10166 ssh_pkt_getstring(pktin, &data, &len);
10167 s->gss_rcvtok.value = data;
10168 s->gss_rcvtok.length = len;
10170 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
10172 if (s->gss_stat != SSH_GSS_OK) {
10173 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10174 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
10177 logevent("GSSAPI authentication loop finished OK");
10179 /* Now send the MIC */
10181 s->pktout = ssh2_pkt_init(0);
10182 micoffset = s->pktout->length;
10183 ssh_pkt_addstring_start(s->pktout);
10184 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
10185 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
10186 ssh_pkt_addstring(s->pktout, ssh->username);
10187 ssh_pkt_addstring(s->pktout, "ssh-connection");
10188 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
10190 s->gss_buf.value = (char *)s->pktout->data + micoffset;
10191 s->gss_buf.length = s->pktout->length - micoffset;
10193 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
10194 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
10195 ssh_pkt_addstring_start(s->pktout);
10196 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
10197 ssh2_pkt_send(ssh, s->pktout);
10198 s->gsslib->free_mic(s->gsslib, &mic);
10202 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10203 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
10206 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
10209 * Keyboard-interactive authentication.
10212 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
10214 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
10216 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10217 ssh2_pkt_addstring(s->pktout, ssh->username);
10218 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10219 /* service requested */
10220 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
10222 ssh2_pkt_addstring(s->pktout, ""); /* lang */
10223 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
10224 ssh2_pkt_send(ssh, s->pktout);
10226 logevent("Attempting keyboard-interactive authentication");
10228 crWaitUntilV(pktin);
10229 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
10230 /* Server is not willing to do keyboard-interactive
10231 * at all (or, bizarrely but legally, accepts the
10232 * user without actually issuing any prompts).
10233 * Give up on it entirely. */
10235 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
10236 s->kbd_inter_refused = TRUE; /* don't try it again */
10241 * Loop while the server continues to send INFO_REQUESTs.
10243 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
10245 char *name, *inst, *lang;
10246 int name_len, inst_len, lang_len;
10250 * We've got a fresh USERAUTH_INFO_REQUEST.
10251 * Get the preamble and start building a prompt.
10253 ssh_pkt_getstring(pktin, &name, &name_len);
10254 ssh_pkt_getstring(pktin, &inst, &inst_len);
10255 ssh_pkt_getstring(pktin, &lang, &lang_len);
10256 s->cur_prompt = new_prompts(ssh->frontend);
10257 s->cur_prompt->to_server = TRUE;
10260 * Get any prompt(s) from the packet.
10262 s->num_prompts = ssh_pkt_getuint32(pktin);
10263 for (i = 0; i < s->num_prompts; i++) {
10267 static char noprompt[] =
10268 "<server failed to send prompt>: ";
10270 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10271 echo = ssh2_pkt_getbool(pktin);
10274 prompt_len = lenof(noprompt)-1;
10276 add_prompt(s->cur_prompt,
10277 dupprintf("%.*s", prompt_len, prompt),
10282 /* FIXME: better prefix to distinguish from
10283 * local prompts? */
10284 s->cur_prompt->name =
10285 dupprintf("SSH server: %.*s", name_len, name);
10286 s->cur_prompt->name_reqd = TRUE;
10288 s->cur_prompt->name =
10289 dupstr("SSH server authentication");
10290 s->cur_prompt->name_reqd = FALSE;
10292 /* We add a prefix to try to make it clear that a prompt
10293 * has come from the server.
10294 * FIXME: ugly to print "Using..." in prompt _every_
10295 * time round. Can this be done more subtly? */
10296 /* Special case: for reasons best known to themselves,
10297 * some servers send k-i requests with no prompts and
10298 * nothing to display. Keep quiet in this case. */
10299 if (s->num_prompts || name_len || inst_len) {
10300 s->cur_prompt->instruction =
10301 dupprintf("Using keyboard-interactive authentication.%s%.*s",
10302 inst_len ? "\n" : "", inst_len, inst);
10303 s->cur_prompt->instr_reqd = TRUE;
10305 s->cur_prompt->instr_reqd = FALSE;
10309 * Display any instructions, and get the user's
10313 int ret; /* not live over crReturn */
10314 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10317 crWaitUntilV(!pktin);
10318 ret = get_userpass_input(s->cur_prompt, in, inlen);
10323 * Failed to get responses. Terminate.
10325 free_prompts(s->cur_prompt);
10326 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10327 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10334 * Send the response(s) to the server.
10336 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
10337 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
10338 for (i=0; i < s->num_prompts; i++) {
10339 ssh2_pkt_addstring(s->pktout,
10340 s->cur_prompt->prompts[i]->result);
10342 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10345 * Free the prompts structure from this iteration.
10346 * If there's another, a new one will be allocated
10347 * when we return to the top of this while loop.
10349 free_prompts(s->cur_prompt);
10352 * Get the next packet in case it's another
10355 crWaitUntilV(pktin);
10360 * We should have SUCCESS or FAILURE now.
10364 } else if (s->can_passwd) {
10367 * Plain old password authentication.
10369 int ret; /* not live over crReturn */
10370 int changereq_first_time; /* not live over crReturn */
10372 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
10374 s->cur_prompt = new_prompts(ssh->frontend);
10375 s->cur_prompt->to_server = TRUE;
10376 s->cur_prompt->name = dupstr("SSH password");
10377 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
10382 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10385 crWaitUntilV(!pktin);
10386 ret = get_userpass_input(s->cur_prompt, in, inlen);
10391 * Failed to get responses. Terminate.
10393 free_prompts(s->cur_prompt);
10394 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10395 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10400 * Squirrel away the password. (We may need it later if
10401 * asked to change it.)
10403 s->password = dupstr(s->cur_prompt->prompts[0]->result);
10404 free_prompts(s->cur_prompt);
10407 * Send the password packet.
10409 * We pad out the password packet to 256 bytes to make
10410 * it harder for an attacker to find the length of the
10413 * Anyone using a password longer than 256 bytes
10414 * probably doesn't have much to worry about from
10415 * people who find out how long their password is!
10417 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10418 ssh2_pkt_addstring(s->pktout, ssh->username);
10419 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10420 /* service requested */
10421 ssh2_pkt_addstring(s->pktout, "password");
10422 ssh2_pkt_addbool(s->pktout, FALSE);
10423 ssh2_pkt_addstring(s->pktout, s->password);
10424 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10425 logevent("Sent password");
10426 s->type = AUTH_TYPE_PASSWORD;
10429 * Wait for next packet, in case it's a password change
10432 crWaitUntilV(pktin);
10433 changereq_first_time = TRUE;
10435 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
10438 * We're being asked for a new password
10439 * (perhaps not for the first time).
10440 * Loop until the server accepts it.
10443 int got_new = FALSE; /* not live over crReturn */
10444 char *prompt; /* not live over crReturn */
10445 int prompt_len; /* not live over crReturn */
10449 if (changereq_first_time)
10450 msg = "Server requested password change";
10452 msg = "Server rejected new password";
10454 c_write_str(ssh, msg);
10455 c_write_str(ssh, "\r\n");
10458 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10460 s->cur_prompt = new_prompts(ssh->frontend);
10461 s->cur_prompt->to_server = TRUE;
10462 s->cur_prompt->name = dupstr("New SSH password");
10463 s->cur_prompt->instruction =
10464 dupprintf("%.*s", prompt_len, NULLTOEMPTY(prompt));
10465 s->cur_prompt->instr_reqd = TRUE;
10467 * There's no explicit requirement in the protocol
10468 * for the "old" passwords in the original and
10469 * password-change messages to be the same, and
10470 * apparently some Cisco kit supports password change
10471 * by the user entering a blank password originally
10472 * and the real password subsequently, so,
10473 * reluctantly, we prompt for the old password again.
10475 * (On the other hand, some servers don't even bother
10476 * to check this field.)
10478 add_prompt(s->cur_prompt,
10479 dupstr("Current password (blank for previously entered password): "),
10481 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
10483 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
10487 * Loop until the user manages to enter the same
10492 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10495 crWaitUntilV(!pktin);
10496 ret = get_userpass_input(s->cur_prompt, in, inlen);
10501 * Failed to get responses. Terminate.
10503 /* burn the evidence */
10504 free_prompts(s->cur_prompt);
10505 smemclr(s->password, strlen(s->password));
10506 sfree(s->password);
10507 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10508 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10514 * If the user specified a new original password
10515 * (IYSWIM), overwrite any previously specified
10517 * (A side effect is that the user doesn't have to
10518 * re-enter it if they louse up the new password.)
10520 if (s->cur_prompt->prompts[0]->result[0]) {
10521 smemclr(s->password, strlen(s->password));
10522 /* burn the evidence */
10523 sfree(s->password);
10525 dupstr(s->cur_prompt->prompts[0]->result);
10529 * Check the two new passwords match.
10531 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
10532 s->cur_prompt->prompts[2]->result)
10535 /* They don't. Silly user. */
10536 c_write_str(ssh, "Passwords do not match\r\n");
10541 * Send the new password (along with the old one).
10542 * (see above for padding rationale)
10544 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10545 ssh2_pkt_addstring(s->pktout, ssh->username);
10546 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10547 /* service requested */
10548 ssh2_pkt_addstring(s->pktout, "password");
10549 ssh2_pkt_addbool(s->pktout, TRUE);
10550 ssh2_pkt_addstring(s->pktout, s->password);
10551 ssh2_pkt_addstring(s->pktout,
10552 s->cur_prompt->prompts[1]->result);
10553 free_prompts(s->cur_prompt);
10554 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10555 logevent("Sent new password");
10558 * Now see what the server has to say about it.
10559 * (If it's CHANGEREQ again, it's not happy with the
10562 crWaitUntilV(pktin);
10563 changereq_first_time = FALSE;
10568 * We need to reexamine the current pktin at the top
10569 * of the loop. Either:
10570 * - we weren't asked to change password at all, in
10571 * which case it's a SUCCESS or FAILURE with the
10573 * - we sent a new password, and the server was
10574 * either OK with it (SUCCESS or FAILURE w/partial
10575 * success) or unhappy with the _old_ password
10576 * (FAILURE w/o partial success)
10577 * In any of these cases, we go back to the top of
10578 * the loop and start again.
10583 * We don't need the old password any more, in any
10584 * case. Burn the evidence.
10586 smemclr(s->password, strlen(s->password));
10587 sfree(s->password);
10590 char *str = dupprintf("No supported authentication methods available"
10591 " (server sent: %.*s)",
10594 ssh_disconnect(ssh, str,
10595 "No supported authentication methods available",
10596 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
10606 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
10608 /* Clear up various bits and pieces from authentication. */
10609 if (s->publickey_blob) {
10610 sfree(s->publickey_algorithm);
10611 sfree(s->publickey_blob);
10612 sfree(s->publickey_comment);
10614 if (s->agent_response)
10615 sfree(s->agent_response);
10617 if (s->userauth_success && !ssh->bare_connection) {
10619 * We've just received USERAUTH_SUCCESS, and we haven't sent any
10620 * packets since. Signal the transport layer to consider enacting
10621 * delayed compression.
10623 * (Relying on we_are_in is not sufficient, as
10624 * draft-miller-secsh-compression-delayed is quite clear that it
10625 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
10626 * become set for other reasons.)
10628 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
10631 ssh->channels = newtree234(ssh_channelcmp);
10634 * Set up handlers for some connection protocol messages, so we
10635 * don't have to handle them repeatedly in this coroutine.
10637 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
10638 ssh2_msg_channel_window_adjust;
10639 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
10640 ssh2_msg_global_request;
10643 * Create the main session channel.
10645 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
10646 ssh->mainchan = NULL;
10648 ssh->mainchan = snew(struct ssh_channel);
10649 ssh->mainchan->ssh = ssh;
10650 ssh_channel_init(ssh->mainchan);
10652 if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
10654 * Just start a direct-tcpip channel and use it as the main
10657 ssh_send_port_open(ssh->mainchan,
10658 conf_get_str(ssh->conf, CONF_ssh_nc_host),
10659 conf_get_int(ssh->conf, CONF_ssh_nc_port),
10661 ssh->ncmode = TRUE;
10663 s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
10664 logevent("Opening session as main channel");
10665 ssh2_pkt_send(ssh, s->pktout);
10666 ssh->ncmode = FALSE;
10668 crWaitUntilV(pktin);
10669 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
10670 bombout(("Server refused to open channel"));
10672 /* FIXME: error data comes back in FAILURE packet */
10674 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
10675 bombout(("Server's channel confirmation cited wrong channel"));
10678 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
10679 ssh->mainchan->halfopen = FALSE;
10680 ssh->mainchan->type = CHAN_MAINSESSION;
10681 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
10682 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
10683 update_specials_menu(ssh->frontend);
10684 logevent("Opened main channel");
10688 * Now we have a channel, make dispatch table entries for
10689 * general channel-based messages.
10691 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
10692 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
10693 ssh2_msg_channel_data;
10694 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
10695 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
10696 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
10697 ssh2_msg_channel_open_confirmation;
10698 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
10699 ssh2_msg_channel_open_failure;
10700 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
10701 ssh2_msg_channel_request;
10702 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
10703 ssh2_msg_channel_open;
10704 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
10705 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
10708 * Now the connection protocol is properly up and running, with
10709 * all those dispatch table entries, so it's safe to let
10710 * downstreams start trying to open extra channels through us.
10712 if (ssh->connshare)
10713 share_activate(ssh->connshare, ssh->v_s);
10715 if (ssh->mainchan && ssh_is_simple(ssh)) {
10717 * This message indicates to the server that we promise
10718 * not to try to run any other channel in parallel with
10719 * this one, so it's safe for it to advertise a very large
10720 * window and leave the flow control to TCP.
10722 s->pktout = ssh2_chanreq_init(ssh->mainchan,
10723 "simple@putty.projects.tartarus.org",
10725 ssh2_pkt_send(ssh, s->pktout);
10729 * Enable port forwardings.
10731 ssh_setup_portfwd(ssh, ssh->conf);
10733 if (ssh->mainchan && !ssh->ncmode) {
10735 * Send the CHANNEL_REQUESTS for the main session channel.
10736 * Each one is handled by its own little asynchronous
10740 /* Potentially enable X11 forwarding. */
10741 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
10743 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
10745 if (!ssh->x11disp) {
10746 /* FIXME: return an error message from x11_setup_display */
10747 logevent("X11 forwarding not enabled: unable to"
10748 " initialise X display");
10750 ssh->x11auth = x11_invent_fake_auth
10751 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
10752 ssh->x11auth->disp = ssh->x11disp;
10754 ssh2_setup_x11(ssh->mainchan, NULL, NULL);
10758 /* Potentially enable agent forwarding. */
10759 if (ssh_agent_forwarding_permitted(ssh))
10760 ssh2_setup_agent(ssh->mainchan, NULL, NULL);
10762 /* Now allocate a pty for the session. */
10763 if (!conf_get_int(ssh->conf, CONF_nopty))
10764 ssh2_setup_pty(ssh->mainchan, NULL, NULL);
10766 /* Send environment variables. */
10767 ssh2_setup_env(ssh->mainchan, NULL, NULL);
10770 * Start a shell or a remote command. We may have to attempt
10771 * this twice if the config data has provided a second choice
10778 if (ssh->fallback_cmd) {
10779 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
10780 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
10782 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
10783 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
10787 s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
10788 ssh2_response_authconn, NULL);
10789 ssh2_pkt_addstring(s->pktout, cmd);
10791 s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
10792 ssh2_response_authconn, NULL);
10793 ssh2_pkt_addstring(s->pktout, cmd);
10795 s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
10796 ssh2_response_authconn, NULL);
10798 ssh2_pkt_send(ssh, s->pktout);
10800 crWaitUntilV(pktin);
10802 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
10803 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
10804 bombout(("Unexpected response to shell/command request:"
10805 " packet type %d", pktin->type));
10809 * We failed to start the command. If this is the
10810 * fallback command, we really are finished; if it's
10811 * not, and if the fallback command exists, try falling
10812 * back to it before complaining.
10814 if (!ssh->fallback_cmd &&
10815 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
10816 logevent("Primary command failed; attempting fallback");
10817 ssh->fallback_cmd = TRUE;
10820 bombout(("Server refused to start a shell/command"));
10823 logevent("Started a shell/command");
10828 ssh->editing = ssh->echoing = TRUE;
10831 ssh->state = SSH_STATE_SESSION;
10832 if (ssh->size_needed)
10833 ssh_size(ssh, ssh->term_width, ssh->term_height);
10834 if (ssh->eof_needed)
10835 ssh_special(ssh, TS_EOF);
10841 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
10849 * _All_ the connection-layer packets we expect to
10850 * receive are now handled by the dispatch table.
10851 * Anything that reaches here must be bogus.
10854 bombout(("Strange packet received: type %d", pktin->type));
10856 } else if (ssh->mainchan) {
10858 * We have spare data. Add it to the channel buffer.
10860 ssh_send_channel_data(ssh->mainchan, (char *)in, inlen);
10868 * Handlers for SSH-2 messages that might arrive at any moment.
10870 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
10872 /* log reason code in disconnect message */
10874 int reason, msglen;
10876 reason = ssh_pkt_getuint32(pktin);
10877 ssh_pkt_getstring(pktin, &msg, &msglen);
10879 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
10880 buf = dupprintf("Received disconnect message (%s)",
10881 ssh2_disconnect_reasons[reason]);
10883 buf = dupprintf("Received disconnect message (unknown"
10884 " type %d)", reason);
10888 buf = dupprintf("Disconnection message text: %.*s",
10889 msglen, NULLTOEMPTY(msg));
10891 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
10893 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
10894 ssh2_disconnect_reasons[reason] : "unknown",
10895 msglen, NULLTOEMPTY(msg)));
10899 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
10901 /* log the debug message */
10905 /* XXX maybe we should actually take notice of the return value */
10906 ssh2_pkt_getbool(pktin);
10907 ssh_pkt_getstring(pktin, &msg, &msglen);
10909 logeventf(ssh, "Remote debug message: %.*s", msglen, NULLTOEMPTY(msg));
10912 static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
10914 do_ssh2_transport(ssh, NULL, 0, pktin);
10918 * Called if we receive a packet that isn't allowed by the protocol.
10919 * This only applies to packets whose meaning PuTTY understands.
10920 * Entirely unknown packets are handled below.
10922 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
10924 char *buf = dupprintf("Server protocol violation: unexpected %s packet",
10925 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
10927 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
10931 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
10933 struct Packet *pktout;
10934 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
10935 ssh2_pkt_adduint32(pktout, pktin->sequence);
10937 * UNIMPLEMENTED messages MUST appear in the same order as the
10938 * messages they respond to. Hence, never queue them.
10940 ssh2_pkt_send_noqueue(ssh, pktout);
10944 * Handle the top-level SSH-2 protocol.
10946 static void ssh2_protocol_setup(Ssh ssh)
10951 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10953 for (i = 0; i < 256; i++)
10954 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10957 * Initially, we only accept transport messages (and a few generic
10958 * ones). do_ssh2_authconn will add more when it starts.
10959 * Messages that are understood but not currently acceptable go to
10960 * ssh2_msg_unexpected.
10962 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10963 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
10964 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
10965 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
10966 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
10967 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
10968 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
10969 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
10970 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
10971 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
10972 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
10973 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
10974 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
10975 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
10976 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
10977 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
10978 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
10979 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
10980 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
10981 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10982 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10983 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10984 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10985 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10986 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10987 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10988 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10989 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10990 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10991 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10992 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10993 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10994 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10997 * These messages have a special handler from the start.
10999 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
11000 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
11001 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
11004 static void ssh2_bare_connection_protocol_setup(Ssh ssh)
11009 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
11011 for (i = 0; i < 256; i++)
11012 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
11015 * Initially, we set all ssh-connection messages to 'unexpected';
11016 * do_ssh2_authconn will fill things in properly. We also handle a
11017 * couple of messages from the transport protocol which aren't
11018 * related to key exchange (UNIMPLEMENTED, IGNORE, DEBUG,
11021 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
11022 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
11023 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
11024 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
11025 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
11026 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
11027 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
11028 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
11029 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
11030 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
11031 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
11032 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
11033 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
11034 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
11036 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
11039 * These messages have a special handler from the start.
11041 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
11042 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore;
11043 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
11046 static void ssh2_timer(void *ctx, unsigned long now)
11048 Ssh ssh = (Ssh)ctx;
11050 if (ssh->state == SSH_STATE_CLOSED)
11053 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11054 conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
11055 now == ssh->next_rekey) {
11056 do_ssh2_transport(ssh, "timeout", -1, NULL);
11060 static void ssh2_protocol(Ssh ssh, const void *vin, int inlen,
11061 struct Packet *pktin)
11063 const unsigned char *in = (const unsigned char *)vin;
11064 if (ssh->state == SSH_STATE_CLOSED)
11068 ssh->incoming_data_size += pktin->encrypted_len;
11069 if (!ssh->kex_in_progress &&
11070 ssh->max_data_size != 0 &&
11071 ssh->incoming_data_size > ssh->max_data_size)
11072 do_ssh2_transport(ssh, "too much data received", -1, NULL);
11076 ssh->packet_dispatch[pktin->type](ssh, pktin);
11077 else if (!ssh->protocol_initial_phase_done)
11078 do_ssh2_transport(ssh, in, inlen, pktin);
11080 do_ssh2_authconn(ssh, in, inlen, pktin);
11083 static void ssh2_bare_connection_protocol(Ssh ssh, const void *vin, int inlen,
11084 struct Packet *pktin)
11086 const unsigned char *in = (const unsigned char *)vin;
11087 if (ssh->state == SSH_STATE_CLOSED)
11091 ssh->packet_dispatch[pktin->type](ssh, pktin);
11093 do_ssh2_authconn(ssh, in, inlen, pktin);
11096 static void ssh_cache_conf_values(Ssh ssh)
11098 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
11102 * Called to set up the connection.
11104 * Returns an error message, or NULL on success.
11106 static const char *ssh_init(void *frontend_handle, void **backend_handle,
11108 const char *host, int port, char **realhost,
11109 int nodelay, int keepalive)
11114 ssh = snew(struct ssh_tag);
11115 ssh->conf = conf_copy(conf);
11116 ssh_cache_conf_values(ssh);
11117 ssh->version = 0; /* when not ready yet */
11119 ssh->cipher = NULL;
11120 ssh->v1_cipher_ctx = NULL;
11121 ssh->crcda_ctx = NULL;
11122 ssh->cscipher = NULL;
11123 ssh->cs_cipher_ctx = NULL;
11124 ssh->sccipher = NULL;
11125 ssh->sc_cipher_ctx = NULL;
11127 ssh->cs_mac_ctx = NULL;
11129 ssh->sc_mac_ctx = NULL;
11130 ssh->cscomp = NULL;
11131 ssh->cs_comp_ctx = NULL;
11132 ssh->sccomp = NULL;
11133 ssh->sc_comp_ctx = NULL;
11135 ssh->kex_ctx = NULL;
11136 ssh->hostkey = NULL;
11137 ssh->hostkey_str = NULL;
11138 ssh->exitcode = -1;
11139 ssh->close_expected = FALSE;
11140 ssh->clean_exit = FALSE;
11141 ssh->state = SSH_STATE_PREPACKET;
11142 ssh->size_needed = FALSE;
11143 ssh->eof_needed = FALSE;
11145 ssh->logctx = NULL;
11146 ssh->deferred_send_data = NULL;
11147 ssh->deferred_len = 0;
11148 ssh->deferred_size = 0;
11149 ssh->fallback_cmd = 0;
11150 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
11151 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
11152 ssh->x11disp = NULL;
11153 ssh->x11auth = NULL;
11154 ssh->x11authtree = newtree234(x11_authcmp);
11155 ssh->v1_compressing = FALSE;
11156 ssh->v2_outgoing_sequence = 0;
11157 ssh->ssh1_rdpkt_crstate = 0;
11158 ssh->ssh2_rdpkt_crstate = 0;
11159 ssh->ssh2_bare_rdpkt_crstate = 0;
11160 ssh->ssh_gotdata_crstate = 0;
11161 ssh->do_ssh1_connection_crstate = 0;
11162 ssh->do_ssh_init_state = NULL;
11163 ssh->do_ssh_connection_init_state = NULL;
11164 ssh->do_ssh1_login_state = NULL;
11165 ssh->do_ssh2_transport_state = NULL;
11166 ssh->do_ssh2_authconn_state = NULL;
11169 ssh->mainchan = NULL;
11170 ssh->throttled_all = 0;
11171 ssh->v1_stdout_throttling = 0;
11173 ssh->queuelen = ssh->queuesize = 0;
11174 ssh->queueing = FALSE;
11175 ssh->qhead = ssh->qtail = NULL;
11176 ssh->deferred_rekey_reason = NULL;
11177 bufchain_init(&ssh->queued_incoming_data);
11178 ssh->frozen = FALSE;
11179 ssh->username = NULL;
11180 ssh->sent_console_eof = FALSE;
11181 ssh->got_pty = FALSE;
11182 ssh->bare_connection = FALSE;
11183 ssh->X11_fwd_enabled = FALSE;
11184 ssh->connshare = NULL;
11185 ssh->attempting_connshare = FALSE;
11186 ssh->session_started = FALSE;
11187 ssh->specials = NULL;
11188 ssh->n_uncert_hostkeys = 0;
11189 ssh->cross_certifying = FALSE;
11191 *backend_handle = ssh;
11194 if (crypto_startup() == 0)
11195 return "Microsoft high encryption pack not installed!";
11198 ssh->frontend = frontend_handle;
11199 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
11200 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
11202 ssh->channels = NULL;
11203 ssh->rportfwds = NULL;
11204 ssh->portfwds = NULL;
11209 ssh->conn_throttle_count = 0;
11210 ssh->overall_bufsize = 0;
11211 ssh->fallback_cmd = 0;
11213 ssh->protocol = NULL;
11215 ssh->protocol_initial_phase_done = FALSE;
11217 ssh->pinger = NULL;
11219 ssh->incoming_data_size = ssh->outgoing_data_size =
11220 ssh->deferred_data_size = 0L;
11221 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11222 CONF_ssh_rekey_data));
11223 ssh->kex_in_progress = FALSE;
11226 ssh->gsslibs = NULL;
11229 random_ref(); /* do this now - may be needed by sharing setup code */
11231 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
11240 static void ssh_free(void *handle)
11242 Ssh ssh = (Ssh) handle;
11243 struct ssh_channel *c;
11244 struct ssh_rportfwd *pf;
11245 struct X11FakeAuth *auth;
11247 if (ssh->v1_cipher_ctx)
11248 ssh->cipher->free_context(ssh->v1_cipher_ctx);
11249 if (ssh->cs_cipher_ctx)
11250 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
11251 if (ssh->sc_cipher_ctx)
11252 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
11253 if (ssh->cs_mac_ctx)
11254 ssh->csmac->free_context(ssh->cs_mac_ctx);
11255 if (ssh->sc_mac_ctx)
11256 ssh->scmac->free_context(ssh->sc_mac_ctx);
11257 if (ssh->cs_comp_ctx) {
11259 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
11261 zlib_compress_cleanup(ssh->cs_comp_ctx);
11263 if (ssh->sc_comp_ctx) {
11265 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
11267 zlib_decompress_cleanup(ssh->sc_comp_ctx);
11270 dh_cleanup(ssh->kex_ctx);
11271 sfree(ssh->savedhost);
11273 while (ssh->queuelen-- > 0)
11274 ssh_free_packet(ssh->queue[ssh->queuelen]);
11277 while (ssh->qhead) {
11278 struct queued_handler *qh = ssh->qhead;
11279 ssh->qhead = qh->next;
11282 ssh->qhead = ssh->qtail = NULL;
11284 if (ssh->channels) {
11285 while ((c = delpos234(ssh->channels, 0)) != NULL) {
11288 if (c->u.x11.xconn != NULL)
11289 x11_close(c->u.x11.xconn);
11291 case CHAN_SOCKDATA:
11292 case CHAN_SOCKDATA_DORMANT:
11293 if (c->u.pfd.pf != NULL)
11294 pfd_close(c->u.pfd.pf);
11297 if (ssh->version == 2) {
11298 struct outstanding_channel_request *ocr, *nocr;
11299 ocr = c->v.v2.chanreq_head;
11301 ocr->handler(c, NULL, ocr->ctx);
11306 bufchain_clear(&c->v.v2.outbuffer);
11310 freetree234(ssh->channels);
11311 ssh->channels = NULL;
11314 if (ssh->connshare)
11315 sharestate_free(ssh->connshare);
11317 if (ssh->rportfwds) {
11318 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
11320 freetree234(ssh->rportfwds);
11321 ssh->rportfwds = NULL;
11323 sfree(ssh->deferred_send_data);
11325 x11_free_display(ssh->x11disp);
11326 while ((auth = delpos234(ssh->x11authtree, 0)) != NULL)
11327 x11_free_fake_auth(auth);
11328 freetree234(ssh->x11authtree);
11329 sfree(ssh->do_ssh_init_state);
11330 sfree(ssh->do_ssh1_login_state);
11331 sfree(ssh->do_ssh2_transport_state);
11332 sfree(ssh->do_ssh2_authconn_state);
11335 sfree(ssh->fullhostname);
11336 sfree(ssh->hostkey_str);
11337 sfree(ssh->specials);
11338 if (ssh->crcda_ctx) {
11339 crcda_free_context(ssh->crcda_ctx);
11340 ssh->crcda_ctx = NULL;
11343 ssh_do_close(ssh, TRUE);
11344 expire_timer_context(ssh);
11346 pinger_free(ssh->pinger);
11347 bufchain_clear(&ssh->queued_incoming_data);
11348 sfree(ssh->username);
11349 conf_free(ssh->conf);
11352 ssh_gss_cleanup(ssh->gsslibs);
11360 * Reconfigure the SSH backend.
11362 static void ssh_reconfig(void *handle, Conf *conf)
11364 Ssh ssh = (Ssh) handle;
11365 const char *rekeying = NULL;
11366 int rekey_mandatory = FALSE;
11367 unsigned long old_max_data_size;
11370 pinger_reconfig(ssh->pinger, ssh->conf, conf);
11372 ssh_setup_portfwd(ssh, conf);
11374 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
11375 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
11377 unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
11378 unsigned long now = GETTICKCOUNT();
11380 if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
11381 rekeying = "timeout shortened";
11383 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
11387 old_max_data_size = ssh->max_data_size;
11388 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11389 CONF_ssh_rekey_data));
11390 if (old_max_data_size != ssh->max_data_size &&
11391 ssh->max_data_size != 0) {
11392 if (ssh->outgoing_data_size > ssh->max_data_size ||
11393 ssh->incoming_data_size > ssh->max_data_size)
11394 rekeying = "data limit lowered";
11397 if (conf_get_int(ssh->conf, CONF_compression) !=
11398 conf_get_int(conf, CONF_compression)) {
11399 rekeying = "compression setting changed";
11400 rekey_mandatory = TRUE;
11403 for (i = 0; i < CIPHER_MAX; i++)
11404 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
11405 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
11406 rekeying = "cipher settings changed";
11407 rekey_mandatory = TRUE;
11409 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
11410 conf_get_int(conf, CONF_ssh2_des_cbc)) {
11411 rekeying = "cipher settings changed";
11412 rekey_mandatory = TRUE;
11415 conf_free(ssh->conf);
11416 ssh->conf = conf_copy(conf);
11417 ssh_cache_conf_values(ssh);
11419 if (!ssh->bare_connection && rekeying) {
11420 if (!ssh->kex_in_progress) {
11421 do_ssh2_transport(ssh, rekeying, -1, NULL);
11422 } else if (rekey_mandatory) {
11423 ssh->deferred_rekey_reason = rekeying;
11429 * Called to send data down the SSH connection.
11431 static int ssh_send(void *handle, const char *buf, int len)
11433 Ssh ssh = (Ssh) handle;
11435 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11438 ssh->protocol(ssh, (const unsigned char *)buf, len, 0);
11440 return ssh_sendbuffer(ssh);
11444 * Called to query the current amount of buffered stdin data.
11446 static int ssh_sendbuffer(void *handle)
11448 Ssh ssh = (Ssh) handle;
11449 int override_value;
11451 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11455 * If the SSH socket itself has backed up, add the total backup
11456 * size on that to any individual buffer on the stdin channel.
11458 override_value = 0;
11459 if (ssh->throttled_all)
11460 override_value = ssh->overall_bufsize;
11462 if (ssh->version == 1) {
11463 return override_value;
11464 } else if (ssh->version == 2) {
11465 if (!ssh->mainchan)
11466 return override_value;
11468 return (override_value +
11469 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
11476 * Called to set the size of the window from SSH's POV.
11478 static void ssh_size(void *handle, int width, int height)
11480 Ssh ssh = (Ssh) handle;
11481 struct Packet *pktout;
11483 ssh->term_width = width;
11484 ssh->term_height = height;
11486 switch (ssh->state) {
11487 case SSH_STATE_BEFORE_SIZE:
11488 case SSH_STATE_PREPACKET:
11489 case SSH_STATE_CLOSED:
11490 break; /* do nothing */
11491 case SSH_STATE_INTERMED:
11492 ssh->size_needed = TRUE; /* buffer for later */
11494 case SSH_STATE_SESSION:
11495 if (!conf_get_int(ssh->conf, CONF_nopty)) {
11496 if (ssh->version == 1) {
11497 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
11498 PKT_INT, ssh->term_height,
11499 PKT_INT, ssh->term_width,
11500 PKT_INT, 0, PKT_INT, 0, PKT_END);
11501 } else if (ssh->mainchan) {
11502 pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
11504 ssh2_pkt_adduint32(pktout, ssh->term_width);
11505 ssh2_pkt_adduint32(pktout, ssh->term_height);
11506 ssh2_pkt_adduint32(pktout, 0);
11507 ssh2_pkt_adduint32(pktout, 0);
11508 ssh2_pkt_send(ssh, pktout);
11516 * Return a list of the special codes that make sense in this
11519 static const struct telnet_special *ssh_get_specials(void *handle)
11521 static const struct telnet_special ssh1_ignore_special[] = {
11522 {"IGNORE message", TS_NOP}
11524 static const struct telnet_special ssh2_ignore_special[] = {
11525 {"IGNORE message", TS_NOP},
11527 static const struct telnet_special ssh2_rekey_special[] = {
11528 {"Repeat key exchange", TS_REKEY},
11530 static const struct telnet_special ssh2_session_specials[] = {
11533 /* These are the signal names defined by RFC 4254.
11534 * They include all the ISO C signals, but are a subset of the POSIX
11535 * required signals. */
11536 {"SIGINT (Interrupt)", TS_SIGINT},
11537 {"SIGTERM (Terminate)", TS_SIGTERM},
11538 {"SIGKILL (Kill)", TS_SIGKILL},
11539 {"SIGQUIT (Quit)", TS_SIGQUIT},
11540 {"SIGHUP (Hangup)", TS_SIGHUP},
11541 {"More signals", TS_SUBMENU},
11542 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
11543 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
11544 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
11545 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
11546 {NULL, TS_EXITMENU}
11548 static const struct telnet_special specials_end[] = {
11549 {NULL, TS_EXITMENU}
11552 struct telnet_special *specials = NULL;
11553 int nspecials = 0, specialsize = 0;
11555 Ssh ssh = (Ssh) handle;
11557 sfree(ssh->specials);
11559 #define ADD_SPECIALS(name) do \
11561 int len = lenof(name); \
11562 if (nspecials + len > specialsize) { \
11563 specialsize = (nspecials + len) * 5 / 4 + 32; \
11564 specials = sresize(specials, specialsize, struct telnet_special); \
11566 memcpy(specials+nspecials, name, len*sizeof(struct telnet_special)); \
11567 nspecials += len; \
11570 if (ssh->version == 1) {
11571 /* Don't bother offering IGNORE if we've decided the remote
11572 * won't cope with it, since we wouldn't bother sending it if
11574 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11575 ADD_SPECIALS(ssh1_ignore_special);
11576 } else if (ssh->version == 2) {
11577 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
11578 ADD_SPECIALS(ssh2_ignore_special);
11579 if (!(ssh->remote_bugs & BUG_SSH2_REKEY) && !ssh->bare_connection)
11580 ADD_SPECIALS(ssh2_rekey_special);
11582 ADD_SPECIALS(ssh2_session_specials);
11584 if (ssh->n_uncert_hostkeys) {
11585 static const struct telnet_special uncert_start[] = {
11587 {"Cache new host key type", TS_SUBMENU},
11589 static const struct telnet_special uncert_end[] = {
11590 {NULL, TS_EXITMENU},
11594 ADD_SPECIALS(uncert_start);
11595 for (i = 0; i < ssh->n_uncert_hostkeys; i++) {
11596 struct telnet_special uncert[1];
11597 const struct ssh_signkey *alg =
11598 hostkey_algs[ssh->uncert_hostkeys[i]].alg;
11599 uncert[0].name = alg->name;
11600 uncert[0].code = TS_LOCALSTART + ssh->uncert_hostkeys[i];
11601 ADD_SPECIALS(uncert);
11603 ADD_SPECIALS(uncert_end);
11605 } /* else we're not ready yet */
11608 ADD_SPECIALS(specials_end);
11610 ssh->specials = specials;
11617 #undef ADD_SPECIALS
11621 * Send special codes. TS_EOF is useful for `plink', so you
11622 * can send an EOF and collect resulting output (e.g. `plink
11625 static void ssh_special(void *handle, Telnet_Special code)
11627 Ssh ssh = (Ssh) handle;
11628 struct Packet *pktout;
11630 if (code == TS_EOF) {
11631 if (ssh->state != SSH_STATE_SESSION) {
11633 * Buffer the EOF in case we are pre-SESSION, so we can
11634 * send it as soon as we reach SESSION.
11636 if (code == TS_EOF)
11637 ssh->eof_needed = TRUE;
11640 if (ssh->version == 1) {
11641 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
11642 } else if (ssh->mainchan) {
11643 sshfwd_write_eof(ssh->mainchan);
11644 ssh->send_ok = 0; /* now stop trying to read from stdin */
11646 logevent("Sent EOF message");
11647 } else if (code == TS_PING || code == TS_NOP) {
11648 if (ssh->state == SSH_STATE_CLOSED
11649 || ssh->state == SSH_STATE_PREPACKET) return;
11650 if (ssh->version == 1) {
11651 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11652 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
11654 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
11655 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
11656 ssh2_pkt_addstring_start(pktout);
11657 ssh2_pkt_send_noqueue(ssh, pktout);
11660 } else if (code == TS_REKEY) {
11661 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11662 ssh->version == 2) {
11663 do_ssh2_transport(ssh, "at user request", -1, NULL);
11665 } else if (code >= TS_LOCALSTART) {
11666 ssh->hostkey = hostkey_algs[code - TS_LOCALSTART].alg;
11667 ssh->cross_certifying = TRUE;
11668 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11669 ssh->version == 2) {
11670 do_ssh2_transport(ssh, "cross-certifying new host key", -1, NULL);
11672 } else if (code == TS_BRK) {
11673 if (ssh->state == SSH_STATE_CLOSED
11674 || ssh->state == SSH_STATE_PREPACKET) return;
11675 if (ssh->version == 1) {
11676 logevent("Unable to send BREAK signal in SSH-1");
11677 } else if (ssh->mainchan) {
11678 pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
11679 ssh2_pkt_adduint32(pktout, 0); /* default break length */
11680 ssh2_pkt_send(ssh, pktout);
11683 /* Is is a POSIX signal? */
11684 const char *signame = NULL;
11685 if (code == TS_SIGABRT) signame = "ABRT";
11686 if (code == TS_SIGALRM) signame = "ALRM";
11687 if (code == TS_SIGFPE) signame = "FPE";
11688 if (code == TS_SIGHUP) signame = "HUP";
11689 if (code == TS_SIGILL) signame = "ILL";
11690 if (code == TS_SIGINT) signame = "INT";
11691 if (code == TS_SIGKILL) signame = "KILL";
11692 if (code == TS_SIGPIPE) signame = "PIPE";
11693 if (code == TS_SIGQUIT) signame = "QUIT";
11694 if (code == TS_SIGSEGV) signame = "SEGV";
11695 if (code == TS_SIGTERM) signame = "TERM";
11696 if (code == TS_SIGUSR1) signame = "USR1";
11697 if (code == TS_SIGUSR2) signame = "USR2";
11698 /* The SSH-2 protocol does in principle support arbitrary named
11699 * signals, including signame@domain, but we don't support those. */
11701 /* It's a signal. */
11702 if (ssh->version == 2 && ssh->mainchan) {
11703 pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
11704 ssh2_pkt_addstring(pktout, signame);
11705 ssh2_pkt_send(ssh, pktout);
11706 logeventf(ssh, "Sent signal SIG%s", signame);
11709 /* Never heard of it. Do nothing */
11714 void *new_sock_channel(void *handle, struct PortForwarding *pf)
11716 Ssh ssh = (Ssh) handle;
11717 struct ssh_channel *c;
11718 c = snew(struct ssh_channel);
11721 ssh_channel_init(c);
11722 c->halfopen = TRUE;
11723 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
11728 unsigned ssh_alloc_sharing_channel(Ssh ssh, void *sharing_ctx)
11730 struct ssh_channel *c;
11731 c = snew(struct ssh_channel);
11734 ssh_channel_init(c);
11735 c->type = CHAN_SHARING;
11736 c->u.sharing.ctx = sharing_ctx;
11740 void ssh_delete_sharing_channel(Ssh ssh, unsigned localid)
11742 struct ssh_channel *c;
11744 c = find234(ssh->channels, &localid, ssh_channelfind);
11746 ssh_channel_destroy(c);
11749 void ssh_send_packet_from_downstream(Ssh ssh, unsigned id, int type,
11750 const void *data, int datalen,
11751 const char *additional_log_text)
11753 struct Packet *pkt;
11755 pkt = ssh2_pkt_init(type);
11756 pkt->downstream_id = id;
11757 pkt->additional_log_text = additional_log_text;
11758 ssh2_pkt_adddata(pkt, data, datalen);
11759 ssh2_pkt_send(ssh, pkt);
11763 * This is called when stdout/stderr (the entity to which
11764 * from_backend sends data) manages to clear some backlog.
11766 static void ssh_unthrottle(void *handle, int bufsize)
11768 Ssh ssh = (Ssh) handle;
11770 if (ssh->version == 1) {
11771 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
11772 ssh->v1_stdout_throttling = 0;
11773 ssh_throttle_conn(ssh, -1);
11777 ssh_channel_unthrottle(ssh->mainchan, bufsize);
11781 * Now process any SSH connection data that was stashed in our
11782 * queue while we were frozen.
11784 ssh_process_queued_incoming_data(ssh);
11787 void ssh_send_port_open(void *channel, const char *hostname, int port,
11790 struct ssh_channel *c = (struct ssh_channel *)channel;
11792 struct Packet *pktout;
11794 logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
11796 if (ssh->version == 1) {
11797 send_packet(ssh, SSH1_MSG_PORT_OPEN,
11798 PKT_INT, c->localid,
11801 /* PKT_STR, <org:orgport>, */
11804 pktout = ssh2_chanopen_init(c, "direct-tcpip");
11806 char *trimmed_host = host_strduptrim(hostname);
11807 ssh2_pkt_addstring(pktout, trimmed_host);
11808 sfree(trimmed_host);
11810 ssh2_pkt_adduint32(pktout, port);
11812 * We make up values for the originator data; partly it's
11813 * too much hassle to keep track, and partly I'm not
11814 * convinced the server should be told details like that
11815 * about my local network configuration.
11816 * The "originator IP address" is syntactically a numeric
11817 * IP address, and some servers (e.g., Tectia) get upset
11818 * if it doesn't match this syntax.
11820 ssh2_pkt_addstring(pktout, "0.0.0.0");
11821 ssh2_pkt_adduint32(pktout, 0);
11822 ssh2_pkt_send(ssh, pktout);
11826 static int ssh_connected(void *handle)
11828 Ssh ssh = (Ssh) handle;
11829 return ssh->s != NULL;
11832 static int ssh_sendok(void *handle)
11834 Ssh ssh = (Ssh) handle;
11835 return ssh->send_ok;
11838 static int ssh_ldisc(void *handle, int option)
11840 Ssh ssh = (Ssh) handle;
11841 if (option == LD_ECHO)
11842 return ssh->echoing;
11843 if (option == LD_EDIT)
11844 return ssh->editing;
11848 static void ssh_provide_ldisc(void *handle, void *ldisc)
11850 Ssh ssh = (Ssh) handle;
11851 ssh->ldisc = ldisc;
11854 static void ssh_provide_logctx(void *handle, void *logctx)
11856 Ssh ssh = (Ssh) handle;
11857 ssh->logctx = logctx;
11860 static int ssh_return_exitcode(void *handle)
11862 Ssh ssh = (Ssh) handle;
11863 if (ssh->s != NULL)
11866 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
11870 * cfg_info for SSH is the protocol running in this session.
11871 * (1 or 2 for the full SSH-1 or SSH-2 protocol; -1 for the bare
11872 * SSH-2 connection protocol, i.e. a downstream; 0 for not-decided-yet.)
11874 static int ssh_cfg_info(void *handle)
11876 Ssh ssh = (Ssh) handle;
11877 if (ssh->version == 0)
11878 return 0; /* don't know yet */
11879 else if (ssh->bare_connection)
11882 return ssh->version;
11886 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
11887 * that fails. This variable is the means by which scp.c can reach
11888 * into the SSH code and find out which one it got.
11890 extern int ssh_fallback_cmd(void *handle)
11892 Ssh ssh = (Ssh) handle;
11893 return ssh->fallback_cmd;
11896 Backend ssh_backend = {
11906 ssh_return_exitcode,
11910 ssh_provide_logctx,
11913 ssh_test_for_upstream,