28 * Packet type contexts, so that ssh2_pkt_type can correctly decode
29 * the ambiguous type numbers back into the correct type strings.
39 SSH2_PKTCTX_PUBLICKEY,
45 static const char *const ssh2_disconnect_reasons[] = {
47 "host not allowed to connect",
49 "key exchange failed",
50 "host authentication failed",
53 "service not available",
54 "protocol version not supported",
55 "host key not verifiable",
58 "too many connections",
59 "auth cancelled by user",
60 "no more auth methods available",
65 * Various remote-bug flags.
67 #define BUG_CHOKES_ON_SSH1_IGNORE 1
68 #define BUG_SSH2_HMAC 2
69 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
70 #define BUG_CHOKES_ON_RSA 8
71 #define BUG_SSH2_RSA_PADDING 16
72 #define BUG_SSH2_DERIVEKEY 32
73 #define BUG_SSH2_REKEY 64
74 #define BUG_SSH2_PK_SESSIONID 128
75 #define BUG_SSH2_MAXPKT 256
76 #define BUG_CHOKES_ON_SSH2_IGNORE 512
77 #define BUG_CHOKES_ON_WINADJ 1024
80 * Codes for terminal modes.
81 * Most of these are the same in SSH-1 and SSH-2.
82 * This list is derived from RFC 4254 and
86 const char* const mode;
88 enum { TTY_OP_CHAR, TTY_OP_BOOL } type;
90 /* "V" prefix discarded for special characters relative to SSH specs */
91 { "INTR", 1, TTY_OP_CHAR },
92 { "QUIT", 2, TTY_OP_CHAR },
93 { "ERASE", 3, TTY_OP_CHAR },
94 { "KILL", 4, TTY_OP_CHAR },
95 { "EOF", 5, TTY_OP_CHAR },
96 { "EOL", 6, TTY_OP_CHAR },
97 { "EOL2", 7, TTY_OP_CHAR },
98 { "START", 8, TTY_OP_CHAR },
99 { "STOP", 9, TTY_OP_CHAR },
100 { "SUSP", 10, TTY_OP_CHAR },
101 { "DSUSP", 11, TTY_OP_CHAR },
102 { "REPRINT", 12, TTY_OP_CHAR },
103 { "WERASE", 13, TTY_OP_CHAR },
104 { "LNEXT", 14, TTY_OP_CHAR },
105 { "FLUSH", 15, TTY_OP_CHAR },
106 { "SWTCH", 16, TTY_OP_CHAR },
107 { "STATUS", 17, TTY_OP_CHAR },
108 { "DISCARD", 18, TTY_OP_CHAR },
109 { "IGNPAR", 30, TTY_OP_BOOL },
110 { "PARMRK", 31, TTY_OP_BOOL },
111 { "INPCK", 32, TTY_OP_BOOL },
112 { "ISTRIP", 33, TTY_OP_BOOL },
113 { "INLCR", 34, TTY_OP_BOOL },
114 { "IGNCR", 35, TTY_OP_BOOL },
115 { "ICRNL", 36, TTY_OP_BOOL },
116 { "IUCLC", 37, TTY_OP_BOOL },
117 { "IXON", 38, TTY_OP_BOOL },
118 { "IXANY", 39, TTY_OP_BOOL },
119 { "IXOFF", 40, TTY_OP_BOOL },
120 { "IMAXBEL", 41, TTY_OP_BOOL },
121 { "ISIG", 50, TTY_OP_BOOL },
122 { "ICANON", 51, TTY_OP_BOOL },
123 { "XCASE", 52, TTY_OP_BOOL },
124 { "ECHO", 53, TTY_OP_BOOL },
125 { "ECHOE", 54, TTY_OP_BOOL },
126 { "ECHOK", 55, TTY_OP_BOOL },
127 { "ECHONL", 56, TTY_OP_BOOL },
128 { "NOFLSH", 57, TTY_OP_BOOL },
129 { "TOSTOP", 58, TTY_OP_BOOL },
130 { "IEXTEN", 59, TTY_OP_BOOL },
131 { "ECHOCTL", 60, TTY_OP_BOOL },
132 { "ECHOKE", 61, TTY_OP_BOOL },
133 { "PENDIN", 62, TTY_OP_BOOL }, /* XXX is this a real mode? */
134 { "OPOST", 70, TTY_OP_BOOL },
135 { "OLCUC", 71, TTY_OP_BOOL },
136 { "ONLCR", 72, TTY_OP_BOOL },
137 { "OCRNL", 73, TTY_OP_BOOL },
138 { "ONOCR", 74, TTY_OP_BOOL },
139 { "ONLRET", 75, TTY_OP_BOOL },
140 { "CS7", 90, TTY_OP_BOOL },
141 { "CS8", 91, TTY_OP_BOOL },
142 { "PARENB", 92, TTY_OP_BOOL },
143 { "PARODD", 93, TTY_OP_BOOL }
146 /* Miscellaneous other tty-related constants. */
147 #define SSH_TTY_OP_END 0
148 /* The opcodes for ISPEED/OSPEED differ between SSH-1 and SSH-2. */
149 #define SSH1_TTY_OP_ISPEED 192
150 #define SSH1_TTY_OP_OSPEED 193
151 #define SSH2_TTY_OP_ISPEED 128
152 #define SSH2_TTY_OP_OSPEED 129
154 /* Helper functions for parsing tty-related config. */
155 static unsigned int ssh_tty_parse_specchar(char *s)
160 ret = ctrlparse(s, &next);
161 if (!next) ret = s[0];
163 ret = 255; /* special value meaning "don't set" */
167 static unsigned int ssh_tty_parse_boolean(char *s)
169 if (stricmp(s, "yes") == 0 ||
170 stricmp(s, "on") == 0 ||
171 stricmp(s, "true") == 0 ||
172 stricmp(s, "+") == 0)
174 else if (stricmp(s, "no") == 0 ||
175 stricmp(s, "off") == 0 ||
176 stricmp(s, "false") == 0 ||
177 stricmp(s, "-") == 0)
178 return 0; /* false */
180 return (atoi(s) != 0);
183 #define translate(x) if (type == x) return #x
184 #define translatek(x,ctx) if (type == x && (pkt_kctx == ctx)) return #x
185 #define translatea(x,ctx) if (type == x && (pkt_actx == ctx)) return #x
186 static char *ssh1_pkt_type(int type)
188 translate(SSH1_MSG_DISCONNECT);
189 translate(SSH1_SMSG_PUBLIC_KEY);
190 translate(SSH1_CMSG_SESSION_KEY);
191 translate(SSH1_CMSG_USER);
192 translate(SSH1_CMSG_AUTH_RSA);
193 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
194 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
195 translate(SSH1_CMSG_AUTH_PASSWORD);
196 translate(SSH1_CMSG_REQUEST_PTY);
197 translate(SSH1_CMSG_WINDOW_SIZE);
198 translate(SSH1_CMSG_EXEC_SHELL);
199 translate(SSH1_CMSG_EXEC_CMD);
200 translate(SSH1_SMSG_SUCCESS);
201 translate(SSH1_SMSG_FAILURE);
202 translate(SSH1_CMSG_STDIN_DATA);
203 translate(SSH1_SMSG_STDOUT_DATA);
204 translate(SSH1_SMSG_STDERR_DATA);
205 translate(SSH1_CMSG_EOF);
206 translate(SSH1_SMSG_EXIT_STATUS);
207 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
208 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
209 translate(SSH1_MSG_CHANNEL_DATA);
210 translate(SSH1_MSG_CHANNEL_CLOSE);
211 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
212 translate(SSH1_SMSG_X11_OPEN);
213 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
214 translate(SSH1_MSG_PORT_OPEN);
215 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
216 translate(SSH1_SMSG_AGENT_OPEN);
217 translate(SSH1_MSG_IGNORE);
218 translate(SSH1_CMSG_EXIT_CONFIRMATION);
219 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
220 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
221 translate(SSH1_MSG_DEBUG);
222 translate(SSH1_CMSG_REQUEST_COMPRESSION);
223 translate(SSH1_CMSG_AUTH_TIS);
224 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
225 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
226 translate(SSH1_CMSG_AUTH_CCARD);
227 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
228 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
231 static char *ssh2_pkt_type(Pkt_KCtx pkt_kctx, Pkt_ACtx pkt_actx, int type)
233 translatea(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE,SSH2_PKTCTX_GSSAPI);
234 translatea(SSH2_MSG_USERAUTH_GSSAPI_TOKEN,SSH2_PKTCTX_GSSAPI);
235 translatea(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE,SSH2_PKTCTX_GSSAPI);
236 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERROR,SSH2_PKTCTX_GSSAPI);
237 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK,SSH2_PKTCTX_GSSAPI);
238 translatea(SSH2_MSG_USERAUTH_GSSAPI_MIC, SSH2_PKTCTX_GSSAPI);
239 translate(SSH2_MSG_DISCONNECT);
240 translate(SSH2_MSG_IGNORE);
241 translate(SSH2_MSG_UNIMPLEMENTED);
242 translate(SSH2_MSG_DEBUG);
243 translate(SSH2_MSG_SERVICE_REQUEST);
244 translate(SSH2_MSG_SERVICE_ACCEPT);
245 translate(SSH2_MSG_KEXINIT);
246 translate(SSH2_MSG_NEWKEYS);
247 translatek(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP);
248 translatek(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP);
249 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
250 translatek(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
251 translatek(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
252 translatek(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
253 translatek(SSH2_MSG_KEXRSA_PUBKEY, SSH2_PKTCTX_RSAKEX);
254 translatek(SSH2_MSG_KEXRSA_SECRET, SSH2_PKTCTX_RSAKEX);
255 translatek(SSH2_MSG_KEXRSA_DONE, SSH2_PKTCTX_RSAKEX);
256 translate(SSH2_MSG_USERAUTH_REQUEST);
257 translate(SSH2_MSG_USERAUTH_FAILURE);
258 translate(SSH2_MSG_USERAUTH_SUCCESS);
259 translate(SSH2_MSG_USERAUTH_BANNER);
260 translatea(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
261 translatea(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
262 translatea(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
263 translatea(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
264 translate(SSH2_MSG_GLOBAL_REQUEST);
265 translate(SSH2_MSG_REQUEST_SUCCESS);
266 translate(SSH2_MSG_REQUEST_FAILURE);
267 translate(SSH2_MSG_CHANNEL_OPEN);
268 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
269 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
270 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
271 translate(SSH2_MSG_CHANNEL_DATA);
272 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
273 translate(SSH2_MSG_CHANNEL_EOF);
274 translate(SSH2_MSG_CHANNEL_CLOSE);
275 translate(SSH2_MSG_CHANNEL_REQUEST);
276 translate(SSH2_MSG_CHANNEL_SUCCESS);
277 translate(SSH2_MSG_CHANNEL_FAILURE);
283 /* Enumeration values for fields in SSH-1 packets */
285 PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
286 /* These values are for communicating relevant semantics of
287 * fields to the packet logging code. */
288 PKTT_OTHER, PKTT_PASSWORD, PKTT_DATA
292 * Coroutine mechanics for the sillier bits of the code. If these
293 * macros look impenetrable to you, you might find it helpful to
296 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
298 * which explains the theory behind these macros.
300 * In particular, if you are getting `case expression not constant'
301 * errors when building with MS Visual Studio, this is because MS's
302 * Edit and Continue debugging feature causes their compiler to
303 * violate ANSI C. To disable Edit and Continue debugging:
305 * - right-click ssh.c in the FileView
307 * - select the C/C++ tab and the General category
308 * - under `Debug info:', select anything _other_ than `Program
309 * Database for Edit and Continue'.
311 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
312 #define crBeginState crBegin(s->crLine)
313 #define crStateP(t, v) \
315 if (!(v)) { s = (v) = snew(struct t); s->crLine = 0; } \
317 #define crState(t) crStateP(t, ssh->t)
318 #define crFinish(z) } *crLine = 0; return (z); }
319 #define crFinishV } *crLine = 0; return; }
320 #define crFinishFree(z) } sfree(s); return (z); }
321 #define crFinishFreeV } sfree(s); return; }
322 #define crReturn(z) \
324 *crLine =__LINE__; return (z); case __LINE__:;\
328 *crLine=__LINE__; return; case __LINE__:;\
330 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
331 #define crStopV do{ *crLine = 0; return; }while(0)
332 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
333 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
335 typedef struct ssh_tag *Ssh;
338 static struct Packet *ssh1_pkt_init(int pkt_type);
339 static struct Packet *ssh2_pkt_init(int pkt_type);
340 static void ssh_pkt_ensure(struct Packet *, int length);
341 static void ssh_pkt_adddata(struct Packet *, const void *data, int len);
342 static void ssh_pkt_addbyte(struct Packet *, unsigned char value);
343 static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
344 static void ssh_pkt_adduint32(struct Packet *, unsigned long value);
345 static void ssh_pkt_addstring_start(struct Packet *);
346 static void ssh_pkt_addstring_str(struct Packet *, const char *data);
347 static void ssh_pkt_addstring_data(struct Packet *, const char *data, int len);
348 static void ssh_pkt_addstring(struct Packet *, const char *data);
349 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
350 static void ssh1_pkt_addmp(struct Packet *, Bignum b);
351 static void ssh2_pkt_addmp(struct Packet *, Bignum b);
352 static int ssh2_pkt_construct(Ssh, struct Packet *);
353 static void ssh2_pkt_send(Ssh, struct Packet *);
354 static void ssh2_pkt_send_noqueue(Ssh, struct Packet *);
355 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
356 struct Packet *pktin);
357 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
358 struct Packet *pktin);
359 static void ssh2_channel_check_close(struct ssh_channel *c);
360 static void ssh_channel_destroy(struct ssh_channel *c);
363 * Buffer management constants. There are several of these for
364 * various different purposes:
366 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
367 * on a local data stream before we throttle the whole SSH
368 * connection (in SSH-1 only). Throttling the whole connection is
369 * pretty drastic so we set this high in the hope it won't
372 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
373 * on the SSH connection itself before we defensively throttle
374 * _all_ local data streams. This is pretty drastic too (though
375 * thankfully unlikely in SSH-2 since the window mechanism should
376 * ensure that the server never has any need to throttle its end
377 * of the connection), so we set this high as well.
379 * - OUR_V2_WINSIZE is the maximum window size we present on SSH-2
382 * - OUR_V2_BIGWIN is the window size we advertise for the only
383 * channel in a simple connection. It must be <= INT_MAX.
385 * - OUR_V2_MAXPKT is the official "maximum packet size" we send
386 * to the remote side. This actually has nothing to do with the
387 * size of the _packet_, but is instead a limit on the amount
388 * of data we're willing to receive in a single SSH2 channel
391 * - OUR_V2_PACKETLIMIT is actually the maximum size of SSH
392 * _packet_ we're prepared to cope with. It must be a multiple
393 * of the cipher block size, and must be at least 35000.
396 #define SSH1_BUFFER_LIMIT 32768
397 #define SSH_MAX_BACKLOG 32768
398 #define OUR_V2_WINSIZE 16384
399 #define OUR_V2_BIGWIN 0x7fffffff
400 #define OUR_V2_MAXPKT 0x4000UL
401 #define OUR_V2_PACKETLIMIT 0x9000UL
403 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
405 const static struct ssh_mac *macs[] = {
406 &ssh_hmac_sha256, &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
408 const static struct ssh_mac *buggymacs[] = {
409 &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
412 static void *ssh_comp_none_init(void)
416 static void ssh_comp_none_cleanup(void *handle)
419 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
420 unsigned char **outblock, int *outlen)
424 static int ssh_comp_none_disable(void *handle)
428 const static struct ssh_compress ssh_comp_none = {
430 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
431 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
432 ssh_comp_none_disable, NULL
434 extern const struct ssh_compress ssh_zlib;
435 const static struct ssh_compress *compressions[] = {
436 &ssh_zlib, &ssh_comp_none
439 enum { /* channel types */
444 CHAN_SOCKDATA_DORMANT, /* one the remote hasn't confirmed */
446 * CHAN_ZOMBIE is used to indicate a channel for which we've
447 * already destroyed the local data source: for instance, if a
448 * forwarded port experiences a socket error on the local side, we
449 * immediately destroy its local socket and turn the SSH channel
455 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
456 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
457 typedef void (*cchandler_fn_t)(struct ssh_channel *, struct Packet *, void *);
460 * Each channel has a queue of outstanding CHANNEL_REQUESTS and their
463 struct outstanding_channel_request {
464 cchandler_fn_t handler;
466 struct outstanding_channel_request *next;
470 * 2-3-4 tree storing channels.
473 Ssh ssh; /* pointer back to main context */
474 unsigned remoteid, localid;
476 /* True if we opened this channel but server hasn't confirmed. */
479 * In SSH-1, this value contains four bits:
481 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
482 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
483 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
484 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
486 * A channel is completely finished with when all four bits are set.
488 * In SSH-2, the four bits mean:
490 * 1 We have sent SSH2_MSG_CHANNEL_EOF.
491 * 2 We have sent SSH2_MSG_CHANNEL_CLOSE.
492 * 4 We have received SSH2_MSG_CHANNEL_EOF.
493 * 8 We have received SSH2_MSG_CHANNEL_CLOSE.
495 * A channel is completely finished with when we have both sent
496 * and received CLOSE.
498 * The symbolic constants below use the SSH-2 terminology, which
499 * is a bit confusing in SSH-1, but we have to use _something_.
501 #define CLOSES_SENT_EOF 1
502 #define CLOSES_SENT_CLOSE 2
503 #define CLOSES_RCVD_EOF 4
504 #define CLOSES_RCVD_CLOSE 8
508 * This flag indicates that an EOF is pending on the outgoing side
509 * of the channel: that is, wherever we're getting the data for
510 * this channel has sent us some data followed by EOF. We can't
511 * actually send the EOF until we've finished sending the data, so
512 * we set this flag instead to remind us to do so once our buffer
518 * True if this channel is causing the underlying connection to be
523 struct ssh2_data_channel {
525 unsigned remwindow, remmaxpkt;
526 /* locwindow is signed so we can cope with excess data. */
527 int locwindow, locmaxwin;
529 * remlocwin is the amount of local window that we think
530 * the remote end had available to it after it sent the
531 * last data packet or window adjust ack.
535 * These store the list of channel requests that haven't
538 struct outstanding_channel_request *chanreq_head, *chanreq_tail;
539 enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
543 struct ssh_agent_channel {
544 unsigned char *message;
545 unsigned char msglen[4];
546 unsigned lensofar, totallen;
547 int outstanding_requests;
549 struct ssh_x11_channel {
552 struct ssh_pfd_channel {
559 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
560 * use this structure in different ways, reflecting SSH-2's
561 * altogether saner approach to port forwarding.
563 * In SSH-1, you arrange a remote forwarding by sending the server
564 * the remote port number, and the local destination host:port.
565 * When a connection comes in, the server sends you back that
566 * host:port pair, and you connect to it. This is a ready-made
567 * security hole if you're not on the ball: a malicious server
568 * could send you back _any_ host:port pair, so if you trustingly
569 * connect to the address it gives you then you've just opened the
570 * entire inside of your corporate network just by connecting
571 * through it to a dodgy SSH server. Hence, we must store a list of
572 * host:port pairs we _are_ trying to forward to, and reject a
573 * connection request from the server if it's not in the list.
575 * In SSH-2, each side of the connection minds its own business and
576 * doesn't send unnecessary information to the other. You arrange a
577 * remote forwarding by sending the server just the remote port
578 * number. When a connection comes in, the server tells you which
579 * of its ports was connected to; and _you_ have to remember what
580 * local host:port pair went with that port number.
582 * Hence, in SSH-1 this structure is indexed by destination
583 * host:port pair, whereas in SSH-2 it is indexed by source port.
585 struct ssh_portfwd; /* forward declaration */
587 struct ssh_rportfwd {
588 unsigned sport, dport;
591 struct ssh_portfwd *pfrec;
594 static void free_rportfwd(struct ssh_rportfwd *pf)
597 sfree(pf->sportdesc);
605 * Separately to the rportfwd tree (which is for looking up port
606 * open requests from the server), a tree of _these_ structures is
607 * used to keep track of all the currently open port forwardings,
608 * so that we can reconfigure in mid-session if the user requests
612 enum { DESTROY, KEEP, CREATE } status;
614 unsigned sport, dport;
617 struct ssh_rportfwd *remote;
621 #define free_portfwd(pf) ( \
622 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
623 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
626 long length; /* length of `data' actually used */
627 long forcepad; /* SSH-2: force padding to at least this length */
628 int type; /* only used for incoming packets */
629 unsigned long sequence; /* SSH-2 incoming sequence number */
630 unsigned char *data; /* allocated storage */
631 unsigned char *body; /* offset of payload within `data' */
632 long savedpos; /* temporary index into `data' (for strings) */
633 long maxlen; /* amount of storage allocated for `data' */
634 long encrypted_len; /* for SSH-2 total-size counting */
637 * State associated with packet logging
641 struct logblank_t *blanks;
644 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
645 struct Packet *pktin);
646 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
647 struct Packet *pktin);
648 static void ssh1_protocol_setup(Ssh ssh);
649 static void ssh2_protocol_setup(Ssh ssh);
650 static void ssh_size(void *handle, int width, int height);
651 static void ssh_special(void *handle, Telnet_Special);
652 static int ssh2_try_send(struct ssh_channel *c);
653 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
654 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
655 static void ssh2_set_window(struct ssh_channel *c, int newwin);
656 static int ssh_sendbuffer(void *handle);
657 static int ssh_do_close(Ssh ssh, int notify_exit);
658 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
659 static int ssh2_pkt_getbool(struct Packet *pkt);
660 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
661 static void ssh2_timer(void *ctx, unsigned long now);
662 static void do_ssh2_transport(Ssh ssh, void *vin, int inlen,
663 struct Packet *pktin);
664 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin);
666 struct rdpkt1_state_tag {
667 long len, pad, biglen, to_read;
668 unsigned long realcrc, gotcrc;
672 struct Packet *pktin;
675 struct rdpkt2_state_tag {
676 long len, pad, payload, packetlen, maclen;
679 unsigned long incoming_sequence;
680 struct Packet *pktin;
683 struct queued_handler;
684 struct queued_handler {
686 chandler_fn_t handler;
688 struct queued_handler *next;
692 const struct plug_function_table *fn;
693 /* the above field _must_ be first in the structure */
703 unsigned char session_key[32];
705 int v1_remote_protoflags;
706 int v1_local_protoflags;
707 int agentfwd_enabled;
710 const struct ssh_cipher *cipher;
713 const struct ssh2_cipher *cscipher, *sccipher;
714 void *cs_cipher_ctx, *sc_cipher_ctx;
715 const struct ssh_mac *csmac, *scmac;
716 void *cs_mac_ctx, *sc_mac_ctx;
717 const struct ssh_compress *cscomp, *sccomp;
718 void *cs_comp_ctx, *sc_comp_ctx;
719 const struct ssh_kex *kex;
720 const struct ssh_signkey *hostkey;
721 char *hostkey_str; /* string representation, for easy checking in rekeys */
722 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
723 int v2_session_id_len;
729 int echoing, editing;
733 int ospeed, ispeed; /* temporaries */
734 int term_width, term_height;
736 tree234 *channels; /* indexed by local id */
737 struct ssh_channel *mainchan; /* primary session channel */
738 int ncmode; /* is primary channel direct-tcpip? */
743 tree234 *rportfwds, *portfwds;
747 SSH_STATE_BEFORE_SIZE,
753 int size_needed, eof_needed;
754 int sent_console_eof;
755 int got_pty; /* affects EOF behaviour on main channel */
757 struct Packet **queue;
758 int queuelen, queuesize;
760 unsigned char *deferred_send_data;
761 int deferred_len, deferred_size;
764 * Gross hack: pscp will try to start SFTP but fall back to
765 * scp1 if that fails. This variable is the means by which
766 * scp.c can reach into the SSH code and find out which one it
771 bufchain banner; /* accumulates banners during do_ssh2_authconn */
776 struct X11Display *x11disp;
779 int conn_throttle_count;
782 int v1_stdout_throttling;
783 unsigned long v2_outgoing_sequence;
785 int ssh1_rdpkt_crstate;
786 int ssh2_rdpkt_crstate;
787 int ssh_gotdata_crstate;
788 int do_ssh1_connection_crstate;
790 void *do_ssh_init_state;
791 void *do_ssh1_login_state;
792 void *do_ssh2_transport_state;
793 void *do_ssh2_authconn_state;
795 struct rdpkt1_state_tag rdpkt1_state;
796 struct rdpkt2_state_tag rdpkt2_state;
798 /* SSH-1 and SSH-2 use this for different things, but both use it */
799 int protocol_initial_phase_done;
801 void (*protocol) (Ssh ssh, void *vin, int inlen,
803 struct Packet *(*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
806 * We maintain our own copy of a Conf structure here. That way,
807 * when we're passed a new one for reconfiguration, we can check
808 * the differences and potentially reconfigure port forwardings
809 * etc in mid-session.
814 * Values cached out of conf so as to avoid the tree234 lookup
815 * cost every time they're used.
820 * Dynamically allocated username string created during SSH
821 * login. Stored in here rather than in the coroutine state so
822 * that it'll be reliably freed if we shut down the SSH session
823 * at some unexpected moment.
828 * Used to transfer data back from async callbacks.
830 void *agent_response;
831 int agent_response_len;
835 * The SSH connection can be set as `frozen', meaning we are
836 * not currently accepting incoming data from the network. This
837 * is slightly more serious than setting the _socket_ as
838 * frozen, because we may already have had data passed to us
839 * from the network which we need to delay processing until
840 * after the freeze is lifted, so we also need a bufchain to
844 bufchain queued_incoming_data;
847 * Dispatch table for packet types that we may have to deal
850 handler_fn_t packet_dispatch[256];
853 * Queues of one-off handler functions for success/failure
854 * indications from a request.
856 struct queued_handler *qhead, *qtail;
857 handler_fn_t q_saved_handler1, q_saved_handler2;
860 * This module deals with sending keepalives.
865 * Track incoming and outgoing data sizes and time, for
868 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
869 unsigned long max_data_size;
871 unsigned long next_rekey, last_rekey;
872 char *deferred_rekey_reason; /* points to STATIC string; don't free */
875 * Fully qualified host name, which we need if doing GSSAPI.
881 * GSSAPI libraries for this session.
883 struct ssh_gss_liblist *gsslibs;
887 #define logevent(s) logevent(ssh->frontend, s)
889 /* logevent, only printf-formatted. */
890 static void logeventf(Ssh ssh, const char *fmt, ...)
896 buf = dupvprintf(fmt, ap);
902 static void bomb_out(Ssh ssh, char *text)
904 ssh_do_close(ssh, FALSE);
906 connection_fatal(ssh->frontend, "%s", text);
910 #define bombout(msg) bomb_out(ssh, dupprintf msg)
912 /* Functions to leave bits out of the SSH packet log file. */
914 static void dont_log_password(Ssh ssh, struct Packet *pkt, int blanktype)
916 if (conf_get_int(ssh->conf, CONF_logomitpass))
917 pkt->logmode = blanktype;
920 static void dont_log_data(Ssh ssh, struct Packet *pkt, int blanktype)
922 if (ssh->logomitdata)
923 pkt->logmode = blanktype;
926 static void end_log_omission(Ssh ssh, struct Packet *pkt)
928 pkt->logmode = PKTLOG_EMIT;
931 /* Helper function for common bits of parsing ttymodes. */
932 static void parse_ttymodes(Ssh ssh,
933 void (*do_mode)(void *data, char *mode, char *val),
938 for (val = conf_get_str_strs(ssh->conf, CONF_ttymodes, NULL, &key);
940 val = conf_get_str_strs(ssh->conf, CONF_ttymodes, key, &key)) {
942 * val[0] is either 'V', indicating that an explicit value
943 * follows it, or 'A' indicating that we should pass the
944 * value through from the local environment via get_ttymode.
947 val = get_ttymode(ssh->frontend, key);
949 do_mode(data, key, val);
953 do_mode(data, key, val + 1); /* skip the 'V' */
957 static int ssh_channelcmp(void *av, void *bv)
959 struct ssh_channel *a = (struct ssh_channel *) av;
960 struct ssh_channel *b = (struct ssh_channel *) bv;
961 if (a->localid < b->localid)
963 if (a->localid > b->localid)
967 static int ssh_channelfind(void *av, void *bv)
969 unsigned *a = (unsigned *) av;
970 struct ssh_channel *b = (struct ssh_channel *) bv;
978 static int ssh_rportcmp_ssh1(void *av, void *bv)
980 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
981 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
983 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
984 return i < 0 ? -1 : +1;
985 if (a->dport > b->dport)
987 if (a->dport < b->dport)
992 static int ssh_rportcmp_ssh2(void *av, void *bv)
994 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
995 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
997 if ( (i = strcmp(a->shost, b->shost)) != 0)
998 return i < 0 ? -1 : +1;
999 if (a->sport > b->sport)
1001 if (a->sport < b->sport)
1007 * Special form of strcmp which can cope with NULL inputs. NULL is
1008 * defined to sort before even the empty string.
1010 static int nullstrcmp(const char *a, const char *b)
1012 if (a == NULL && b == NULL)
1018 return strcmp(a, b);
1021 static int ssh_portcmp(void *av, void *bv)
1023 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1024 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1026 if (a->type > b->type)
1028 if (a->type < b->type)
1030 if (a->addressfamily > b->addressfamily)
1032 if (a->addressfamily < b->addressfamily)
1034 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1035 return i < 0 ? -1 : +1;
1036 if (a->sport > b->sport)
1038 if (a->sport < b->sport)
1040 if (a->type != 'D') {
1041 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1042 return i < 0 ? -1 : +1;
1043 if (a->dport > b->dport)
1045 if (a->dport < b->dport)
1051 static int alloc_channel_id(Ssh ssh)
1053 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1054 unsigned low, high, mid;
1056 struct ssh_channel *c;
1059 * First-fit allocation of channel numbers: always pick the
1060 * lowest unused one. To do this, binary-search using the
1061 * counted B-tree to find the largest channel ID which is in a
1062 * contiguous sequence from the beginning. (Precisely
1063 * everything in that sequence must have ID equal to its tree
1064 * index plus CHANNEL_NUMBER_OFFSET.)
1066 tsize = count234(ssh->channels);
1070 while (high - low > 1) {
1071 mid = (high + low) / 2;
1072 c = index234(ssh->channels, mid);
1073 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1074 low = mid; /* this one is fine */
1076 high = mid; /* this one is past it */
1079 * Now low points to either -1, or the tree index of the
1080 * largest ID in the initial sequence.
1083 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1084 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1086 return low + 1 + CHANNEL_NUMBER_OFFSET;
1089 static void c_write_stderr(int trusted, const char *buf, int len)
1092 for (i = 0; i < len; i++)
1093 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1094 fputc(buf[i], stderr);
1097 static void c_write(Ssh ssh, const char *buf, int len)
1099 if (flags & FLAG_STDERR)
1100 c_write_stderr(1, buf, len);
1102 from_backend(ssh->frontend, 1, buf, len);
1105 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1107 if (flags & FLAG_STDERR)
1108 c_write_stderr(0, buf, len);
1110 from_backend_untrusted(ssh->frontend, buf, len);
1113 static void c_write_str(Ssh ssh, const char *buf)
1115 c_write(ssh, buf, strlen(buf));
1118 static void ssh_free_packet(struct Packet *pkt)
1123 static struct Packet *ssh_new_packet(void)
1125 struct Packet *pkt = snew(struct Packet);
1127 pkt->body = pkt->data = NULL;
1129 pkt->logmode = PKTLOG_EMIT;
1137 * Collect incoming data in the incoming packet buffer.
1138 * Decipher and verify the packet when it is completely read.
1139 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1140 * Update the *data and *datalen variables.
1141 * Return a Packet structure when a packet is completed.
1143 static struct Packet *ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1145 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1147 crBegin(ssh->ssh1_rdpkt_crstate);
1149 st->pktin = ssh_new_packet();
1151 st->pktin->type = 0;
1152 st->pktin->length = 0;
1154 for (st->i = st->len = 0; st->i < 4; st->i++) {
1155 while ((*datalen) == 0)
1157 st->len = (st->len << 8) + **data;
1158 (*data)++, (*datalen)--;
1161 st->pad = 8 - (st->len % 8);
1162 st->biglen = st->len + st->pad;
1163 st->pktin->length = st->len - 5;
1165 if (st->biglen < 0) {
1166 bombout(("Extremely large packet length from server suggests"
1167 " data stream corruption"));
1168 ssh_free_packet(st->pktin);
1172 st->pktin->maxlen = st->biglen;
1173 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1175 st->to_read = st->biglen;
1176 st->p = st->pktin->data;
1177 while (st->to_read > 0) {
1178 st->chunk = st->to_read;
1179 while ((*datalen) == 0)
1181 if (st->chunk > (*datalen))
1182 st->chunk = (*datalen);
1183 memcpy(st->p, *data, st->chunk);
1185 *datalen -= st->chunk;
1187 st->to_read -= st->chunk;
1190 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1191 st->biglen, NULL)) {
1192 bombout(("Network attack (CRC compensation) detected!"));
1193 ssh_free_packet(st->pktin);
1198 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1200 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1201 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1202 if (st->gotcrc != st->realcrc) {
1203 bombout(("Incorrect CRC received on packet"));
1204 ssh_free_packet(st->pktin);
1208 st->pktin->body = st->pktin->data + st->pad + 1;
1209 st->pktin->savedpos = 0;
1211 if (ssh->v1_compressing) {
1212 unsigned char *decompblk;
1214 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1215 st->pktin->body - 1, st->pktin->length + 1,
1216 &decompblk, &decomplen)) {
1217 bombout(("Zlib decompression encountered invalid data"));
1218 ssh_free_packet(st->pktin);
1222 if (st->pktin->maxlen < st->pad + decomplen) {
1223 st->pktin->maxlen = st->pad + decomplen;
1224 st->pktin->data = sresize(st->pktin->data,
1225 st->pktin->maxlen + APIEXTRA,
1227 st->pktin->body = st->pktin->data + st->pad + 1;
1230 memcpy(st->pktin->body - 1, decompblk, decomplen);
1232 st->pktin->length = decomplen - 1;
1235 st->pktin->type = st->pktin->body[-1];
1238 * Log incoming packet, possibly omitting sensitive fields.
1242 struct logblank_t blank;
1243 if (ssh->logomitdata) {
1244 int do_blank = FALSE, blank_prefix = 0;
1245 /* "Session data" packets - omit the data field */
1246 if ((st->pktin->type == SSH1_SMSG_STDOUT_DATA) ||
1247 (st->pktin->type == SSH1_SMSG_STDERR_DATA)) {
1248 do_blank = TRUE; blank_prefix = 4;
1249 } else if (st->pktin->type == SSH1_MSG_CHANNEL_DATA) {
1250 do_blank = TRUE; blank_prefix = 8;
1253 blank.offset = blank_prefix;
1254 blank.len = st->pktin->length;
1255 blank.type = PKTLOG_OMIT;
1259 log_packet(ssh->logctx,
1260 PKT_INCOMING, st->pktin->type,
1261 ssh1_pkt_type(st->pktin->type),
1262 st->pktin->body, st->pktin->length,
1263 nblanks, &blank, NULL);
1266 crFinish(st->pktin);
1269 static struct Packet *ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1271 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1273 crBegin(ssh->ssh2_rdpkt_crstate);
1275 st->pktin = ssh_new_packet();
1277 st->pktin->type = 0;
1278 st->pktin->length = 0;
1280 st->cipherblk = ssh->sccipher->blksize;
1283 if (st->cipherblk < 8)
1285 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1287 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1290 * When dealing with a CBC-mode cipher, we want to avoid the
1291 * possibility of an attacker's tweaking the ciphertext stream
1292 * so as to cause us to feed the same block to the block
1293 * cipher more than once and thus leak information
1294 * (VU#958563). The way we do this is not to take any
1295 * decisions on the basis of anything we've decrypted until
1296 * we've verified it with a MAC. That includes the packet
1297 * length, so we just read data and check the MAC repeatedly,
1298 * and when the MAC passes, see if the length we've got is
1302 /* May as well allocate the whole lot now. */
1303 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1306 /* Read an amount corresponding to the MAC. */
1307 for (st->i = 0; st->i < st->maclen; st->i++) {
1308 while ((*datalen) == 0)
1310 st->pktin->data[st->i] = *(*data)++;
1316 unsigned char seq[4];
1317 ssh->scmac->start(ssh->sc_mac_ctx);
1318 PUT_32BIT(seq, st->incoming_sequence);
1319 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1322 for (;;) { /* Once around this loop per cipher block. */
1323 /* Read another cipher-block's worth, and tack it onto the end. */
1324 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1325 while ((*datalen) == 0)
1327 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1330 /* Decrypt one more block (a little further back in the stream). */
1331 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1332 st->pktin->data + st->packetlen,
1334 /* Feed that block to the MAC. */
1335 ssh->scmac->bytes(ssh->sc_mac_ctx,
1336 st->pktin->data + st->packetlen, st->cipherblk);
1337 st->packetlen += st->cipherblk;
1338 /* See if that gives us a valid packet. */
1339 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1340 st->pktin->data + st->packetlen) &&
1341 ((st->len = toint(GET_32BIT(st->pktin->data))) ==
1344 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1345 bombout(("No valid incoming packet found"));
1346 ssh_free_packet(st->pktin);
1350 st->pktin->maxlen = st->packetlen + st->maclen;
1351 st->pktin->data = sresize(st->pktin->data,
1352 st->pktin->maxlen + APIEXTRA,
1355 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1358 * Acquire and decrypt the first block of the packet. This will
1359 * contain the length and padding details.
1361 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1362 while ((*datalen) == 0)
1364 st->pktin->data[st->i] = *(*data)++;
1369 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1370 st->pktin->data, st->cipherblk);
1373 * Now get the length figure.
1375 st->len = toint(GET_32BIT(st->pktin->data));
1378 * _Completely_ silly lengths should be stomped on before they
1379 * do us any more damage.
1381 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1382 (st->len + 4) % st->cipherblk != 0) {
1383 bombout(("Incoming packet was garbled on decryption"));
1384 ssh_free_packet(st->pktin);
1389 * So now we can work out the total packet length.
1391 st->packetlen = st->len + 4;
1394 * Allocate memory for the rest of the packet.
1396 st->pktin->maxlen = st->packetlen + st->maclen;
1397 st->pktin->data = sresize(st->pktin->data,
1398 st->pktin->maxlen + APIEXTRA,
1402 * Read and decrypt the remainder of the packet.
1404 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1406 while ((*datalen) == 0)
1408 st->pktin->data[st->i] = *(*data)++;
1411 /* Decrypt everything _except_ the MAC. */
1413 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1414 st->pktin->data + st->cipherblk,
1415 st->packetlen - st->cipherblk);
1421 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1422 st->len + 4, st->incoming_sequence)) {
1423 bombout(("Incorrect MAC received on packet"));
1424 ssh_free_packet(st->pktin);
1428 /* Get and sanity-check the amount of random padding. */
1429 st->pad = st->pktin->data[4];
1430 if (st->pad < 4 || st->len - st->pad < 1) {
1431 bombout(("Invalid padding length on received packet"));
1432 ssh_free_packet(st->pktin);
1436 * This enables us to deduce the payload length.
1438 st->payload = st->len - st->pad - 1;
1440 st->pktin->length = st->payload + 5;
1441 st->pktin->encrypted_len = st->packetlen;
1443 st->pktin->sequence = st->incoming_sequence++;
1446 * Decompress packet payload.
1449 unsigned char *newpayload;
1452 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1453 st->pktin->data + 5, st->pktin->length - 5,
1454 &newpayload, &newlen)) {
1455 if (st->pktin->maxlen < newlen + 5) {
1456 st->pktin->maxlen = newlen + 5;
1457 st->pktin->data = sresize(st->pktin->data,
1458 st->pktin->maxlen + APIEXTRA,
1461 st->pktin->length = 5 + newlen;
1462 memcpy(st->pktin->data + 5, newpayload, newlen);
1467 st->pktin->savedpos = 6;
1468 st->pktin->body = st->pktin->data;
1469 st->pktin->type = st->pktin->data[5];
1472 * Log incoming packet, possibly omitting sensitive fields.
1476 struct logblank_t blank;
1477 if (ssh->logomitdata) {
1478 int do_blank = FALSE, blank_prefix = 0;
1479 /* "Session data" packets - omit the data field */
1480 if (st->pktin->type == SSH2_MSG_CHANNEL_DATA) {
1481 do_blank = TRUE; blank_prefix = 8;
1482 } else if (st->pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
1483 do_blank = TRUE; blank_prefix = 12;
1486 blank.offset = blank_prefix;
1487 blank.len = (st->pktin->length-6) - blank_prefix;
1488 blank.type = PKTLOG_OMIT;
1492 log_packet(ssh->logctx, PKT_INCOMING, st->pktin->type,
1493 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
1495 st->pktin->data+6, st->pktin->length-6,
1496 nblanks, &blank, &st->pktin->sequence);
1499 crFinish(st->pktin);
1502 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1504 int pad, biglen, i, pktoffs;
1508 * XXX various versions of SC (including 8.8.4) screw up the
1509 * register allocation in this function and use the same register
1510 * (D6) for len and as a temporary, with predictable results. The
1511 * following sledgehammer prevents this.
1518 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1519 ssh1_pkt_type(pkt->data[12]),
1520 pkt->body, pkt->length - (pkt->body - pkt->data),
1521 pkt->nblanks, pkt->blanks, NULL);
1522 sfree(pkt->blanks); pkt->blanks = NULL;
1525 if (ssh->v1_compressing) {
1526 unsigned char *compblk;
1528 zlib_compress_block(ssh->cs_comp_ctx,
1529 pkt->data + 12, pkt->length - 12,
1530 &compblk, &complen);
1531 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1532 memcpy(pkt->data + 12, compblk, complen);
1534 pkt->length = complen + 12;
1537 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1539 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1540 pad = 8 - (len % 8);
1542 biglen = len + pad; /* len(padding+type+data+CRC) */
1544 for (i = pktoffs; i < 4+8; i++)
1545 pkt->data[i] = random_byte();
1546 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
1547 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
1548 PUT_32BIT(pkt->data + pktoffs, len);
1551 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
1552 pkt->data + pktoffs + 4, biglen);
1554 if (offset_p) *offset_p = pktoffs;
1555 return biglen + 4; /* len(length+padding+type+data+CRC) */
1558 static int s_write(Ssh ssh, void *data, int len)
1561 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
1563 return sk_write(ssh->s, (char *)data, len);
1566 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1568 int len, backlog, offset;
1569 len = s_wrpkt_prepare(ssh, pkt, &offset);
1570 backlog = s_write(ssh, pkt->data + offset, len);
1571 if (backlog > SSH_MAX_BACKLOG)
1572 ssh_throttle_all(ssh, 1, backlog);
1573 ssh_free_packet(pkt);
1576 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1579 len = s_wrpkt_prepare(ssh, pkt, &offset);
1580 if (ssh->deferred_len + len > ssh->deferred_size) {
1581 ssh->deferred_size = ssh->deferred_len + len + 128;
1582 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1586 memcpy(ssh->deferred_send_data + ssh->deferred_len,
1587 pkt->data + offset, len);
1588 ssh->deferred_len += len;
1589 ssh_free_packet(pkt);
1593 * Construct a SSH-1 packet with the specified contents.
1594 * (This all-at-once interface used to be the only one, but now SSH-1
1595 * packets can also be constructed incrementally.)
1597 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
1603 pkt = ssh1_pkt_init(pkttype);
1605 while ((argtype = va_arg(ap, int)) != PKT_END) {
1606 unsigned char *argp, argchar;
1608 unsigned long argint;
1611 /* Actual fields in the packet */
1613 argint = va_arg(ap, int);
1614 ssh_pkt_adduint32(pkt, argint);
1617 argchar = (unsigned char) va_arg(ap, int);
1618 ssh_pkt_addbyte(pkt, argchar);
1621 argp = va_arg(ap, unsigned char *);
1622 arglen = va_arg(ap, int);
1623 ssh_pkt_adddata(pkt, argp, arglen);
1626 sargp = va_arg(ap, char *);
1627 ssh_pkt_addstring(pkt, sargp);
1630 bn = va_arg(ap, Bignum);
1631 ssh1_pkt_addmp(pkt, bn);
1633 /* Tokens for modifications to packet logging */
1635 dont_log_password(ssh, pkt, PKTLOG_BLANK);
1638 dont_log_data(ssh, pkt, PKTLOG_OMIT);
1641 end_log_omission(ssh, pkt);
1649 static void send_packet(Ssh ssh, int pkttype, ...)
1653 va_start(ap, pkttype);
1654 pkt = construct_packet(ssh, pkttype, ap);
1659 static void defer_packet(Ssh ssh, int pkttype, ...)
1663 va_start(ap, pkttype);
1664 pkt = construct_packet(ssh, pkttype, ap);
1666 s_wrpkt_defer(ssh, pkt);
1669 static int ssh_versioncmp(char *a, char *b)
1672 unsigned long av, bv;
1674 av = strtoul(a, &ae, 10);
1675 bv = strtoul(b, &be, 10);
1677 return (av < bv ? -1 : +1);
1682 av = strtoul(ae, &ae, 10);
1683 bv = strtoul(be, &be, 10);
1685 return (av < bv ? -1 : +1);
1690 * Utility routines for putting an SSH-protocol `string' and
1691 * `uint32' into a hash state.
1693 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
1695 unsigned char lenblk[4];
1696 PUT_32BIT(lenblk, len);
1697 h->bytes(s, lenblk, 4);
1698 h->bytes(s, str, len);
1701 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
1703 unsigned char intblk[4];
1704 PUT_32BIT(intblk, i);
1705 h->bytes(s, intblk, 4);
1709 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
1711 static void ssh_pkt_ensure(struct Packet *pkt, int length)
1713 if (pkt->maxlen < length) {
1714 unsigned char *body = pkt->body;
1715 int offset = body ? body - pkt->data : 0;
1716 pkt->maxlen = length + 256;
1717 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
1718 if (body) pkt->body = pkt->data + offset;
1721 static void ssh_pkt_adddata(struct Packet *pkt, const void *data, int len)
1723 if (pkt->logmode != PKTLOG_EMIT) {
1725 pkt->blanks = sresize(pkt->blanks, pkt->nblanks, struct logblank_t);
1727 pkt->blanks[pkt->nblanks-1].offset = pkt->length -
1728 (pkt->body - pkt->data);
1729 pkt->blanks[pkt->nblanks-1].len = len;
1730 pkt->blanks[pkt->nblanks-1].type = pkt->logmode;
1733 ssh_pkt_ensure(pkt, pkt->length);
1734 memcpy(pkt->data + pkt->length - len, data, len);
1736 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
1738 ssh_pkt_adddata(pkt, &byte, 1);
1740 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
1742 ssh_pkt_adddata(pkt, &value, 1);
1744 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
1747 PUT_32BIT(x, value);
1748 ssh_pkt_adddata(pkt, x, 4);
1750 static void ssh_pkt_addstring_start(struct Packet *pkt)
1752 ssh_pkt_adduint32(pkt, 0);
1753 pkt->savedpos = pkt->length;
1755 static void ssh_pkt_addstring_str(struct Packet *pkt, const char *data)
1757 ssh_pkt_adddata(pkt, data, strlen(data));
1758 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1760 static void ssh_pkt_addstring_data(struct Packet *pkt, const char *data,
1763 ssh_pkt_adddata(pkt, data, len);
1764 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1766 static void ssh_pkt_addstring(struct Packet *pkt, const char *data)
1768 ssh_pkt_addstring_start(pkt);
1769 ssh_pkt_addstring_str(pkt, data);
1771 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
1773 int len = ssh1_bignum_length(b);
1774 unsigned char *data = snewn(len, unsigned char);
1775 (void) ssh1_write_bignum(data, b);
1776 ssh_pkt_adddata(pkt, data, len);
1779 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
1782 int i, n = (bignum_bitcount(b) + 7) / 8;
1783 p = snewn(n + 1, unsigned char);
1785 for (i = 1; i <= n; i++)
1786 p[i] = bignum_byte(b, n - i);
1788 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1790 memmove(p, p + i, n + 1 - i);
1794 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
1798 p = ssh2_mpint_fmt(b, &len);
1799 ssh_pkt_addstring_start(pkt);
1800 ssh_pkt_addstring_data(pkt, (char *)p, len);
1804 static struct Packet *ssh1_pkt_init(int pkt_type)
1806 struct Packet *pkt = ssh_new_packet();
1807 pkt->length = 4 + 8; /* space for length + max padding */
1808 ssh_pkt_addbyte(pkt, pkt_type);
1809 pkt->body = pkt->data + pkt->length;
1813 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
1814 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
1815 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
1816 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
1817 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
1818 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
1819 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
1820 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
1821 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
1823 static struct Packet *ssh2_pkt_init(int pkt_type)
1825 struct Packet *pkt = ssh_new_packet();
1826 pkt->length = 5; /* space for packet length + padding length */
1828 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
1829 pkt->body = pkt->data + pkt->length; /* after packet type */
1834 * Construct an SSH-2 final-form packet: compress it, encrypt it,
1835 * put the MAC on it. Final packet, ready to be sent, is stored in
1836 * pkt->data. Total length is returned.
1838 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
1840 int cipherblk, maclen, padding, i;
1843 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1844 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1845 pkt->body, pkt->length - (pkt->body - pkt->data),
1846 pkt->nblanks, pkt->blanks, &ssh->v2_outgoing_sequence);
1847 sfree(pkt->blanks); pkt->blanks = NULL;
1851 * Compress packet payload.
1854 unsigned char *newpayload;
1857 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
1859 &newpayload, &newlen)) {
1861 ssh2_pkt_adddata(pkt, newpayload, newlen);
1867 * Add padding. At least four bytes, and must also bring total
1868 * length (minus MAC) up to a multiple of the block size.
1869 * If pkt->forcepad is set, make sure the packet is at least that size
1872 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
1873 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1875 if (pkt->length + padding < pkt->forcepad)
1876 padding = pkt->forcepad - pkt->length;
1878 (cipherblk - (pkt->length + padding) % cipherblk) % cipherblk;
1879 assert(padding <= 255);
1880 maclen = ssh->csmac ? ssh->csmac->len : 0;
1881 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
1882 pkt->data[4] = padding;
1883 for (i = 0; i < padding; i++)
1884 pkt->data[pkt->length + i] = random_byte();
1885 PUT_32BIT(pkt->data, pkt->length + padding - 4);
1887 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
1888 pkt->length + padding,
1889 ssh->v2_outgoing_sequence);
1890 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
1893 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
1894 pkt->data, pkt->length + padding);
1896 pkt->encrypted_len = pkt->length + padding;
1898 /* Ready-to-send packet starts at pkt->data. We return length. */
1899 return pkt->length + padding + maclen;
1903 * Routines called from the main SSH code to send packets. There
1904 * are quite a few of these, because we have two separate
1905 * mechanisms for delaying the sending of packets:
1907 * - In order to send an IGNORE message and a password message in
1908 * a single fixed-length blob, we require the ability to
1909 * concatenate the encrypted forms of those two packets _into_ a
1910 * single blob and then pass it to our <network.h> transport
1911 * layer in one go. Hence, there's a deferment mechanism which
1912 * works after packet encryption.
1914 * - In order to avoid sending any connection-layer messages
1915 * during repeat key exchange, we have to queue up any such
1916 * outgoing messages _before_ they are encrypted (and in
1917 * particular before they're allocated sequence numbers), and
1918 * then send them once we've finished.
1920 * I call these mechanisms `defer' and `queue' respectively, so as
1921 * to distinguish them reasonably easily.
1923 * The functions send_noqueue() and defer_noqueue() free the packet
1924 * structure they are passed. Every outgoing packet goes through
1925 * precisely one of these functions in its life; packets passed to
1926 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
1927 * these or get queued, and then when the queue is later emptied
1928 * the packets are all passed to defer_noqueue().
1930 * When using a CBC-mode cipher, it's necessary to ensure that an
1931 * attacker can't provide data to be encrypted using an IV that they
1932 * know. We ensure this by prefixing each packet that might contain
1933 * user data with an SSH_MSG_IGNORE. This is done using the deferral
1934 * mechanism, so in this case send_noqueue() ends up redirecting to
1935 * defer_noqueue(). If you don't like this inefficiency, don't use
1939 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
1940 static void ssh_pkt_defersend(Ssh);
1943 * Send an SSH-2 packet immediately, without queuing or deferring.
1945 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
1949 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
1950 /* We need to send two packets, so use the deferral mechanism. */
1951 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
1952 ssh_pkt_defersend(ssh);
1955 len = ssh2_pkt_construct(ssh, pkt);
1956 backlog = s_write(ssh, pkt->data, len);
1957 if (backlog > SSH_MAX_BACKLOG)
1958 ssh_throttle_all(ssh, 1, backlog);
1960 ssh->outgoing_data_size += pkt->encrypted_len;
1961 if (!ssh->kex_in_progress &&
1962 ssh->max_data_size != 0 &&
1963 ssh->outgoing_data_size > ssh->max_data_size)
1964 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
1966 ssh_free_packet(pkt);
1970 * Defer an SSH-2 packet.
1972 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
1975 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
1976 ssh->deferred_len == 0 && !noignore &&
1977 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
1979 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
1980 * get encrypted with a known IV.
1982 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
1983 ssh2_pkt_addstring_start(ipkt);
1984 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
1986 len = ssh2_pkt_construct(ssh, pkt);
1987 if (ssh->deferred_len + len > ssh->deferred_size) {
1988 ssh->deferred_size = ssh->deferred_len + len + 128;
1989 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1993 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->data, len);
1994 ssh->deferred_len += len;
1995 ssh->deferred_data_size += pkt->encrypted_len;
1996 ssh_free_packet(pkt);
2000 * Queue an SSH-2 packet.
2002 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2004 assert(ssh->queueing);
2006 if (ssh->queuelen >= ssh->queuesize) {
2007 ssh->queuesize = ssh->queuelen + 32;
2008 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2011 ssh->queue[ssh->queuelen++] = pkt;
2015 * Either queue or send a packet, depending on whether queueing is
2018 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2021 ssh2_pkt_queue(ssh, pkt);
2023 ssh2_pkt_send_noqueue(ssh, pkt);
2027 * Either queue or defer a packet, depending on whether queueing is
2030 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2033 ssh2_pkt_queue(ssh, pkt);
2035 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2039 * Send the whole deferred data block constructed by
2040 * ssh2_pkt_defer() or SSH-1's defer_packet().
2042 * The expected use of the defer mechanism is that you call
2043 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2044 * not currently queueing, this simply sets up deferred_send_data
2045 * and then sends it. If we _are_ currently queueing, the calls to
2046 * ssh2_pkt_defer() put the deferred packets on to the queue
2047 * instead, and therefore ssh_pkt_defersend() has no deferred data
2048 * to send. Hence, there's no need to make it conditional on
2051 static void ssh_pkt_defersend(Ssh ssh)
2054 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2055 ssh->deferred_len = ssh->deferred_size = 0;
2056 sfree(ssh->deferred_send_data);
2057 ssh->deferred_send_data = NULL;
2058 if (backlog > SSH_MAX_BACKLOG)
2059 ssh_throttle_all(ssh, 1, backlog);
2061 ssh->outgoing_data_size += ssh->deferred_data_size;
2062 if (!ssh->kex_in_progress &&
2063 ssh->max_data_size != 0 &&
2064 ssh->outgoing_data_size > ssh->max_data_size)
2065 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2066 ssh->deferred_data_size = 0;
2070 * Send a packet whose length needs to be disguised (typically
2071 * passwords or keyboard-interactive responses).
2073 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2079 * The simplest way to do this is to adjust the
2080 * variable-length padding field in the outgoing packet.
2082 * Currently compiled out, because some Cisco SSH servers
2083 * don't like excessively padded packets (bah, why's it
2086 pkt->forcepad = padsize;
2087 ssh2_pkt_send(ssh, pkt);
2092 * If we can't do that, however, an alternative approach is
2093 * to use the pkt_defer mechanism to bundle the packet
2094 * tightly together with an SSH_MSG_IGNORE such that their
2095 * combined length is a constant. So first we construct the
2096 * final form of this packet and defer its sending.
2098 ssh2_pkt_defer(ssh, pkt);
2101 * Now construct an SSH_MSG_IGNORE which includes a string
2102 * that's an exact multiple of the cipher block size. (If
2103 * the cipher is NULL so that the block size is
2104 * unavailable, we don't do this trick at all, because we
2105 * gain nothing by it.)
2107 if (ssh->cscipher &&
2108 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2111 stringlen = (256 - ssh->deferred_len);
2112 stringlen += ssh->cscipher->blksize - 1;
2113 stringlen -= (stringlen % ssh->cscipher->blksize);
2116 * Temporarily disable actual compression, so we
2117 * can guarantee to get this string exactly the
2118 * length we want it. The compression-disabling
2119 * routine should return an integer indicating how
2120 * many bytes we should adjust our string length
2124 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2126 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2127 ssh2_pkt_addstring_start(pkt);
2128 for (i = 0; i < stringlen; i++) {
2129 char c = (char) random_byte();
2130 ssh2_pkt_addstring_data(pkt, &c, 1);
2132 ssh2_pkt_defer(ssh, pkt);
2134 ssh_pkt_defersend(ssh);
2139 * Send all queued SSH-2 packets. We send them by means of
2140 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2141 * packets that needed to be lumped together.
2143 static void ssh2_pkt_queuesend(Ssh ssh)
2147 assert(!ssh->queueing);
2149 for (i = 0; i < ssh->queuelen; i++)
2150 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2153 ssh_pkt_defersend(ssh);
2157 void bndebug(char *string, Bignum b)
2161 p = ssh2_mpint_fmt(b, &len);
2162 debug(("%s", string));
2163 for (i = 0; i < len; i++)
2164 debug((" %02x", p[i]));
2170 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2174 p = ssh2_mpint_fmt(b, &len);
2175 hash_string(h, s, p, len);
2180 * Packet decode functions for both SSH-1 and SSH-2.
2182 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2184 unsigned long value;
2185 if (pkt->length - pkt->savedpos < 4)
2186 return 0; /* arrgh, no way to decline (FIXME?) */
2187 value = GET_32BIT(pkt->body + pkt->savedpos);
2191 static int ssh2_pkt_getbool(struct Packet *pkt)
2193 unsigned long value;
2194 if (pkt->length - pkt->savedpos < 1)
2195 return 0; /* arrgh, no way to decline (FIXME?) */
2196 value = pkt->body[pkt->savedpos] != 0;
2200 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2205 if (pkt->length - pkt->savedpos < 4)
2207 len = toint(GET_32BIT(pkt->body + pkt->savedpos));
2212 if (pkt->length - pkt->savedpos < *length)
2214 *p = (char *)(pkt->body + pkt->savedpos);
2215 pkt->savedpos += *length;
2217 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2219 if (pkt->length - pkt->savedpos < length)
2221 pkt->savedpos += length;
2222 return pkt->body + (pkt->savedpos - length);
2224 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2225 unsigned char **keystr)
2229 j = makekey(pkt->body + pkt->savedpos,
2230 pkt->length - pkt->savedpos,
2237 assert(pkt->savedpos < pkt->length);
2241 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2246 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2247 pkt->length - pkt->savedpos, &b);
2255 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2261 ssh_pkt_getstring(pkt, &p, &length);
2266 b = bignum_from_bytes((unsigned char *)p, length);
2271 * Helper function to add an SSH-2 signature blob to a packet.
2272 * Expects to be shown the public key blob as well as the signature
2273 * blob. Normally works just like ssh2_pkt_addstring, but will
2274 * fiddle with the signature packet if necessary for
2275 * BUG_SSH2_RSA_PADDING.
2277 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2278 void *pkblob_v, int pkblob_len,
2279 void *sigblob_v, int sigblob_len)
2281 unsigned char *pkblob = (unsigned char *)pkblob_v;
2282 unsigned char *sigblob = (unsigned char *)sigblob_v;
2284 /* dmemdump(pkblob, pkblob_len); */
2285 /* dmemdump(sigblob, sigblob_len); */
2288 * See if this is in fact an ssh-rsa signature and a buggy
2289 * server; otherwise we can just do this the easy way.
2291 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) && pkblob_len > 4+7+4 &&
2292 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2293 int pos, len, siglen;
2296 * Find the byte length of the modulus.
2299 pos = 4+7; /* skip over "ssh-rsa" */
2300 len = toint(GET_32BIT(pkblob+pos)); /* get length of exponent */
2301 if (len < 0 || len > pkblob_len - pos - 4)
2303 pos += 4 + len; /* skip over exponent */
2304 if (pkblob_len - pos < 4)
2306 len = toint(GET_32BIT(pkblob+pos)); /* find length of modulus */
2307 if (len < 0 || len > pkblob_len - pos - 4)
2309 pos += 4; /* find modulus itself */
2310 while (len > 0 && pkblob[pos] == 0)
2312 /* debug(("modulus length is %d\n", len)); */
2315 * Now find the signature integer.
2317 pos = 4+7; /* skip over "ssh-rsa" */
2318 if (sigblob_len < pos+4)
2320 siglen = toint(GET_32BIT(sigblob+pos));
2321 if (siglen != sigblob_len - pos - 4)
2323 /* debug(("signature length is %d\n", siglen)); */
2325 if (len != siglen) {
2326 unsigned char newlen[4];
2327 ssh2_pkt_addstring_start(pkt);
2328 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2329 /* dmemdump(sigblob, pos); */
2330 pos += 4; /* point to start of actual sig */
2331 PUT_32BIT(newlen, len);
2332 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2333 /* dmemdump(newlen, 4); */
2335 while (len-- > siglen) {
2336 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2337 /* dmemdump(newlen, 1); */
2339 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2340 /* dmemdump(sigblob+pos, siglen); */
2344 /* Otherwise fall through and do it the easy way. We also come
2345 * here as a fallback if we discover above that the key blob
2346 * is misformatted in some way. */
2350 ssh2_pkt_addstring_start(pkt);
2351 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2355 * Examine the remote side's version string and compare it against
2356 * a list of known buggy implementations.
2358 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2360 char *imp; /* pointer to implementation part */
2362 imp += strcspn(imp, "-");
2364 imp += strcspn(imp, "-");
2367 ssh->remote_bugs = 0;
2370 * General notes on server version strings:
2371 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2372 * here -- in particular, we've heard of one that's perfectly happy
2373 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2374 * so we can't distinguish them.
2376 if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
2377 (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
2378 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2379 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2380 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2381 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2383 * These versions don't support SSH1_MSG_IGNORE, so we have
2384 * to use a different defence against password length
2387 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2388 logevent("We believe remote version has SSH-1 ignore bug");
2391 if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
2392 (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
2393 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2395 * These versions need a plain password sent; they can't
2396 * handle having a null and a random length of data after
2399 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2400 logevent("We believe remote version needs a plain SSH-1 password");
2403 if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
2404 (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
2405 (!strcmp(imp, "Cisco-1.25")))) {
2407 * These versions apparently have no clue whatever about
2408 * RSA authentication and will panic and die if they see
2409 * an AUTH_RSA message.
2411 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2412 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2415 if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
2416 (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
2417 !wc_match("* VShell", imp) &&
2418 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2419 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2420 wc_match("2.1 *", imp)))) {
2422 * These versions have the HMAC bug.
2424 ssh->remote_bugs |= BUG_SSH2_HMAC;
2425 logevent("We believe remote version has SSH-2 HMAC bug");
2428 if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
2429 (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
2430 !wc_match("* VShell", imp) &&
2431 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2433 * These versions have the key-derivation bug (failing to
2434 * include the literal shared secret in the hashes that
2435 * generate the keys).
2437 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2438 logevent("We believe remote version has SSH-2 key-derivation bug");
2441 if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
2442 (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
2443 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2444 wc_match("OpenSSH_3.[0-2]*", imp)))) {
2446 * These versions have the SSH-2 RSA padding bug.
2448 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2449 logevent("We believe remote version has SSH-2 RSA padding bug");
2452 if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
2453 (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
2454 wc_match("OpenSSH_2.[0-2]*", imp))) {
2456 * These versions have the SSH-2 session-ID bug in
2457 * public-key authentication.
2459 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2460 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2463 if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
2464 (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
2465 (wc_match("DigiSSH_2.0", imp) ||
2466 wc_match("OpenSSH_2.[0-4]*", imp) ||
2467 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2468 wc_match("Sun_SSH_1.0", imp) ||
2469 wc_match("Sun_SSH_1.0.1", imp) ||
2470 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2471 wc_match("WeOnlyDo-*", imp)))) {
2473 * These versions have the SSH-2 rekey bug.
2475 ssh->remote_bugs |= BUG_SSH2_REKEY;
2476 logevent("We believe remote version has SSH-2 rekey bug");
2479 if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
2480 (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
2481 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2482 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2484 * This version ignores our makpkt and needs to be throttled.
2486 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2487 logevent("We believe remote version ignores SSH-2 maximum packet size");
2490 if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
2492 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2493 * none detected automatically.
2495 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2496 logevent("We believe remote version has SSH-2 ignore bug");
2499 if (conf_get_int(ssh->conf, CONF_sshbug_winadj) == FORCE_ON) {
2501 * Servers that don't support our winadj request for one
2502 * reason or another. Currently, none detected automatically.
2504 ssh->remote_bugs |= BUG_CHOKES_ON_WINADJ;
2505 logevent("We believe remote version has winadj bug");
2510 * The `software version' part of an SSH version string is required
2511 * to contain no spaces or minus signs.
2513 static void ssh_fix_verstring(char *str)
2515 /* Eat "SSH-<protoversion>-". */
2516 assert(*str == 'S'); str++;
2517 assert(*str == 'S'); str++;
2518 assert(*str == 'H'); str++;
2519 assert(*str == '-'); str++;
2520 while (*str && *str != '-') str++;
2521 assert(*str == '-'); str++;
2523 /* Convert minus signs and spaces in the remaining string into
2526 if (*str == '-' || *str == ' ')
2533 * Send an appropriate SSH version string.
2535 static void ssh_send_verstring(Ssh ssh, char *svers)
2539 if (ssh->version == 2) {
2541 * Construct a v2 version string.
2543 verstring = dupprintf("SSH-2.0-%s\015\012", sshver);
2546 * Construct a v1 version string.
2548 verstring = dupprintf("SSH-%s-%s\012",
2549 (ssh_versioncmp(svers, "1.5") <= 0 ?
2554 ssh_fix_verstring(verstring);
2556 if (ssh->version == 2) {
2559 * Record our version string.
2561 len = strcspn(verstring, "\015\012");
2562 ssh->v_c = snewn(len + 1, char);
2563 memcpy(ssh->v_c, verstring, len);
2567 logeventf(ssh, "We claim version: %.*s",
2568 strcspn(verstring, "\015\012"), verstring);
2569 s_write(ssh, verstring, strlen(verstring));
2573 static int do_ssh_init(Ssh ssh, unsigned char c)
2575 struct do_ssh_init_state {
2584 crState(do_ssh_init_state);
2588 /* Search for a line beginning with the string "SSH-" in the input. */
2590 if (c != 'S') goto no;
2592 if (c != 'S') goto no;
2594 if (c != 'H') goto no;
2596 if (c != '-') goto no;
2605 s->vstring = snewn(s->vstrsize, char);
2606 strcpy(s->vstring, "SSH-");
2610 crReturn(1); /* get another char */
2611 if (s->vslen >= s->vstrsize - 1) {
2613 s->vstring = sresize(s->vstring, s->vstrsize, char);
2615 s->vstring[s->vslen++] = c;
2618 s->version[s->i] = '\0';
2620 } else if (s->i < sizeof(s->version) - 1)
2621 s->version[s->i++] = c;
2622 } else if (c == '\012')
2626 ssh->agentfwd_enabled = FALSE;
2627 ssh->rdpkt2_state.incoming_sequence = 0;
2629 s->vstring[s->vslen] = 0;
2630 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
2631 logeventf(ssh, "Server version: %s", s->vstring);
2632 ssh_detect_bugs(ssh, s->vstring);
2635 * Decide which SSH protocol version to support.
2638 /* Anything strictly below "2.0" means protocol 1 is supported. */
2639 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
2640 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2641 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
2643 if (conf_get_int(ssh->conf, CONF_sshprot) == 0 && !s->proto1) {
2644 bombout(("SSH protocol version 1 required by user but not provided by server"));
2647 if (conf_get_int(ssh->conf, CONF_sshprot) == 3 && !s->proto2) {
2648 bombout(("SSH protocol version 2 required by user but not provided by server"));
2652 if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
2657 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
2659 /* Send the version string, if we haven't already */
2660 if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
2661 ssh_send_verstring(ssh, s->version);
2663 if (ssh->version == 2) {
2666 * Record their version string.
2668 len = strcspn(s->vstring, "\015\012");
2669 ssh->v_s = snewn(len + 1, char);
2670 memcpy(ssh->v_s, s->vstring, len);
2674 * Initialise SSH-2 protocol.
2676 ssh->protocol = ssh2_protocol;
2677 ssh2_protocol_setup(ssh);
2678 ssh->s_rdpkt = ssh2_rdpkt;
2681 * Initialise SSH-1 protocol.
2683 ssh->protocol = ssh1_protocol;
2684 ssh1_protocol_setup(ssh);
2685 ssh->s_rdpkt = ssh1_rdpkt;
2687 if (ssh->version == 2)
2688 do_ssh2_transport(ssh, NULL, -1, NULL);
2690 update_specials_menu(ssh->frontend);
2691 ssh->state = SSH_STATE_BEFORE_SIZE;
2692 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
2699 static void ssh_process_incoming_data(Ssh ssh,
2700 unsigned char **data, int *datalen)
2702 struct Packet *pktin;
2704 pktin = ssh->s_rdpkt(ssh, data, datalen);
2706 ssh->protocol(ssh, NULL, 0, pktin);
2707 ssh_free_packet(pktin);
2711 static void ssh_queue_incoming_data(Ssh ssh,
2712 unsigned char **data, int *datalen)
2714 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
2719 static void ssh_process_queued_incoming_data(Ssh ssh)
2722 unsigned char *data;
2725 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
2726 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
2730 while (!ssh->frozen && len > 0)
2731 ssh_process_incoming_data(ssh, &data, &len);
2734 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
2738 static void ssh_set_frozen(Ssh ssh, int frozen)
2741 sk_set_frozen(ssh->s, frozen);
2742 ssh->frozen = frozen;
2745 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
2747 /* Log raw data, if we're in that mode. */
2749 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
2752 crBegin(ssh->ssh_gotdata_crstate);
2755 * To begin with, feed the characters one by one to the
2756 * protocol initialisation / selection function do_ssh_init().
2757 * When that returns 0, we're done with the initial greeting
2758 * exchange and can move on to packet discipline.
2761 int ret; /* need not be kept across crReturn */
2763 crReturnV; /* more data please */
2764 ret = do_ssh_init(ssh, *data);
2772 * We emerge from that loop when the initial negotiation is
2773 * over and we have selected an s_rdpkt function. Now pass
2774 * everything to s_rdpkt, and then pass the resulting packets
2775 * to the proper protocol handler.
2779 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
2781 ssh_queue_incoming_data(ssh, &data, &datalen);
2782 /* This uses up all data and cannot cause anything interesting
2783 * to happen; indeed, for anything to happen at all, we must
2784 * return, so break out. */
2786 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
2787 /* This uses up some or all data, and may freeze the
2789 ssh_process_queued_incoming_data(ssh);
2791 /* This uses up some or all data, and may freeze the
2793 ssh_process_incoming_data(ssh, &data, &datalen);
2795 /* FIXME this is probably EBW. */
2796 if (ssh->state == SSH_STATE_CLOSED)
2799 /* We're out of data. Go and get some more. */
2805 static int ssh_do_close(Ssh ssh, int notify_exit)
2808 struct ssh_channel *c;
2810 ssh->state = SSH_STATE_CLOSED;
2811 expire_timer_context(ssh);
2816 notify_remote_exit(ssh->frontend);
2821 * Now we must shut down any port- and X-forwarded channels going
2822 * through this connection.
2824 if (ssh->channels) {
2825 while (NULL != (c = index234(ssh->channels, 0))) {
2828 x11_close(c->u.x11.s);
2831 case CHAN_SOCKDATA_DORMANT:
2832 pfd_close(c->u.pfd.s);
2835 del234(ssh->channels, c); /* moving next one to index 0 */
2836 if (ssh->version == 2)
2837 bufchain_clear(&c->v.v2.outbuffer);
2842 * Go through port-forwardings, and close any associated
2843 * listening sockets.
2845 if (ssh->portfwds) {
2846 struct ssh_portfwd *pf;
2847 while (NULL != (pf = index234(ssh->portfwds, 0))) {
2848 /* Dispose of any listening socket. */
2850 pfd_terminate(pf->local);
2851 del234(ssh->portfwds, pf); /* moving next one to index 0 */
2854 freetree234(ssh->portfwds);
2855 ssh->portfwds = NULL;
2861 static void ssh_log(Plug plug, int type, SockAddr addr, int port,
2862 const char *error_msg, int error_code)
2864 Ssh ssh = (Ssh) plug;
2865 char addrbuf[256], *msg;
2867 sk_getaddr(addr, addrbuf, lenof(addrbuf));
2870 msg = dupprintf("Connecting to %s port %d", addrbuf, port);
2872 msg = dupprintf("Failed to connect to %s: %s", addrbuf, error_msg);
2878 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
2881 Ssh ssh = (Ssh) plug;
2882 int need_notify = ssh_do_close(ssh, FALSE);
2885 if (!ssh->close_expected)
2886 error_msg = "Server unexpectedly closed network connection";
2888 error_msg = "Server closed network connection";
2891 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
2895 notify_remote_exit(ssh->frontend);
2898 logevent(error_msg);
2899 if (!ssh->close_expected || !ssh->clean_exit)
2900 connection_fatal(ssh->frontend, "%s", error_msg);
2904 static int ssh_receive(Plug plug, int urgent, char *data, int len)
2906 Ssh ssh = (Ssh) plug;
2907 ssh_gotdata(ssh, (unsigned char *)data, len);
2908 if (ssh->state == SSH_STATE_CLOSED) {
2909 ssh_do_close(ssh, TRUE);
2915 static void ssh_sent(Plug plug, int bufsize)
2917 Ssh ssh = (Ssh) plug;
2919 * If the send backlog on the SSH socket itself clears, we
2920 * should unthrottle the whole world if it was throttled.
2922 if (bufsize < SSH_MAX_BACKLOG)
2923 ssh_throttle_all(ssh, 0, bufsize);
2927 * Connect to specified host and port.
2928 * Returns an error message, or NULL on success.
2929 * Also places the canonical host name into `realhost'. It must be
2930 * freed by the caller.
2932 static const char *connect_to_host(Ssh ssh, char *host, int port,
2933 char **realhost, int nodelay, int keepalive)
2935 static const struct plug_function_table fn_table = {
2946 int addressfamily, sshprot;
2948 loghost = conf_get_str(ssh->conf, CONF_loghost);
2952 ssh->savedhost = dupstr(loghost);
2953 ssh->savedport = 22; /* default ssh port */
2956 * A colon suffix on savedhost also lets us affect
2959 * (FIXME: do something about IPv6 address literals here.)
2961 colon = strrchr(ssh->savedhost, ':');
2965 ssh->savedport = atoi(colon);
2968 ssh->savedhost = dupstr(host);
2970 port = 22; /* default ssh port */
2971 ssh->savedport = port;
2977 addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
2978 logeventf(ssh, "Looking up host \"%s\"%s", host,
2979 (addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
2980 (addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" : "")));
2981 addr = name_lookup(host, port, realhost, ssh->conf, addressfamily);
2982 if ((err = sk_addr_error(addr)) != NULL) {
2986 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
2991 ssh->fn = &fn_table;
2992 ssh->s = new_connection(addr, *realhost, port,
2993 0, 1, nodelay, keepalive, (Plug) ssh, ssh->conf);
2994 if ((err = sk_socket_error(ssh->s)) != NULL) {
2996 notify_remote_exit(ssh->frontend);
3001 * If the SSH version number's fixed, set it now, and if it's SSH-2,
3002 * send the version string too.
3004 sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3009 ssh_send_verstring(ssh, NULL);
3013 * loghost, if configured, overrides realhost.
3017 *realhost = dupstr(loghost);
3024 * Throttle or unthrottle the SSH connection.
3026 static void ssh_throttle_conn(Ssh ssh, int adjust)
3028 int old_count = ssh->conn_throttle_count;
3029 ssh->conn_throttle_count += adjust;
3030 assert(ssh->conn_throttle_count >= 0);
3031 if (ssh->conn_throttle_count && !old_count) {
3032 ssh_set_frozen(ssh, 1);
3033 } else if (!ssh->conn_throttle_count && old_count) {
3034 ssh_set_frozen(ssh, 0);
3039 * Throttle or unthrottle _all_ local data streams (for when sends
3040 * on the SSH connection itself back up).
3042 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3045 struct ssh_channel *c;
3047 if (enable == ssh->throttled_all)
3049 ssh->throttled_all = enable;
3050 ssh->overall_bufsize = bufsize;
3053 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3055 case CHAN_MAINSESSION:
3057 * This is treated separately, outside the switch.
3061 x11_override_throttle(c->u.x11.s, enable);
3064 /* Agent channels require no buffer management. */
3067 pfd_override_throttle(c->u.pfd.s, enable);
3073 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3075 Ssh ssh = (Ssh) sshv;
3077 ssh->agent_response = reply;
3078 ssh->agent_response_len = replylen;
3080 if (ssh->version == 1)
3081 do_ssh1_login(ssh, NULL, -1, NULL);
3083 do_ssh2_authconn(ssh, NULL, -1, NULL);
3086 static void ssh_dialog_callback(void *sshv, int ret)
3088 Ssh ssh = (Ssh) sshv;
3090 ssh->user_response = ret;
3092 if (ssh->version == 1)
3093 do_ssh1_login(ssh, NULL, -1, NULL);
3095 do_ssh2_transport(ssh, NULL, -1, NULL);
3098 * This may have unfrozen the SSH connection, so do a
3101 ssh_process_queued_incoming_data(ssh);
3104 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3106 struct ssh_channel *c = (struct ssh_channel *)cv;
3108 void *sentreply = reply;
3110 c->u.a.outstanding_requests--;
3112 /* Fake SSH_AGENT_FAILURE. */
3113 sentreply = "\0\0\0\1\5";
3116 if (ssh->version == 2) {
3117 ssh2_add_channel_data(c, sentreply, replylen);
3120 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3121 PKT_INT, c->remoteid,
3124 PKT_DATA, sentreply, replylen,
3131 * If we've already seen an incoming EOF but haven't sent an
3132 * outgoing one, this may be the moment to send it.
3134 if (c->u.a.outstanding_requests == 0 && (c->closes & CLOSES_RCVD_EOF))
3135 sshfwd_write_eof(c);
3139 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3140 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3141 * => log `wire_reason'.
3143 static void ssh_disconnect(Ssh ssh, char *client_reason, char *wire_reason,
3144 int code, int clean_exit)
3148 client_reason = wire_reason;
3150 error = dupprintf("Disconnected: %s", client_reason);
3152 error = dupstr("Disconnected");
3154 if (ssh->version == 1) {
3155 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3157 } else if (ssh->version == 2) {
3158 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3159 ssh2_pkt_adduint32(pktout, code);
3160 ssh2_pkt_addstring(pktout, wire_reason);
3161 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3162 ssh2_pkt_send_noqueue(ssh, pktout);
3165 ssh->close_expected = TRUE;
3166 ssh->clean_exit = clean_exit;
3167 ssh_closing((Plug)ssh, error, 0, 0);
3172 * Handle the key exchange and user authentication phases.
3174 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
3175 struct Packet *pktin)
3178 unsigned char cookie[8], *ptr;
3179 struct MD5Context md5c;
3180 struct do_ssh1_login_state {
3183 unsigned char *rsabuf, *keystr1, *keystr2;
3184 unsigned long supported_ciphers_mask, supported_auths_mask;
3185 int tried_publickey, tried_agent;
3186 int tis_auth_refused, ccard_auth_refused;
3187 unsigned char session_id[16];
3189 void *publickey_blob;
3190 int publickey_bloblen;
3191 char *publickey_comment;
3192 int publickey_encrypted;
3193 prompts_t *cur_prompt;
3196 unsigned char request[5], *response, *p;
3206 struct RSAKey servkey, hostkey;
3208 crState(do_ssh1_login_state);
3215 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3216 bombout(("Public key packet not received"));
3220 logevent("Received public keys");
3222 ptr = ssh_pkt_getdata(pktin, 8);
3224 bombout(("SSH-1 public key packet stopped before random cookie"));
3227 memcpy(cookie, ptr, 8);
3229 if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
3230 !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) {
3231 bombout(("Failed to read SSH-1 public keys from public key packet"));
3236 * Log the host key fingerprint.
3240 logevent("Host key fingerprint is:");
3241 strcpy(logmsg, " ");
3242 s->hostkey.comment = NULL;
3243 rsa_fingerprint(logmsg + strlen(logmsg),
3244 sizeof(logmsg) - strlen(logmsg), &s->hostkey);
3248 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
3249 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
3250 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
3251 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
3252 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
3254 ssh->v1_local_protoflags =
3255 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
3256 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
3259 MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
3260 MD5Update(&md5c, s->keystr1, s->servkey.bytes);
3261 MD5Update(&md5c, cookie, 8);
3262 MD5Final(s->session_id, &md5c);
3264 for (i = 0; i < 32; i++)
3265 ssh->session_key[i] = random_byte();
3268 * Verify that the `bits' and `bytes' parameters match.
3270 if (s->hostkey.bits > s->hostkey.bytes * 8 ||
3271 s->servkey.bits > s->servkey.bytes * 8) {
3272 bombout(("SSH-1 public keys were badly formatted"));
3276 s->len = (s->hostkey.bytes > s->servkey.bytes ?
3277 s->hostkey.bytes : s->servkey.bytes);
3279 s->rsabuf = snewn(s->len, unsigned char);
3282 * Verify the host key.
3286 * First format the key into a string.
3288 int len = rsastr_len(&s->hostkey);
3289 char fingerprint[100];
3290 char *keystr = snewn(len, char);
3291 rsastr_fmt(keystr, &s->hostkey);
3292 rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
3294 ssh_set_frozen(ssh, 1);
3295 s->dlgret = verify_ssh_host_key(ssh->frontend,
3296 ssh->savedhost, ssh->savedport,
3297 "rsa", keystr, fingerprint,
3298 ssh_dialog_callback, ssh);
3300 if (s->dlgret < 0) {
3304 bombout(("Unexpected data from server while waiting"
3305 " for user host key response"));
3308 } while (pktin || inlen > 0);
3309 s->dlgret = ssh->user_response;
3311 ssh_set_frozen(ssh, 0);
3313 if (s->dlgret == 0) {
3314 ssh_disconnect(ssh, "User aborted at host key verification",
3320 for (i = 0; i < 32; i++) {
3321 s->rsabuf[i] = ssh->session_key[i];
3323 s->rsabuf[i] ^= s->session_id[i];
3326 if (s->hostkey.bytes > s->servkey.bytes) {
3327 ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
3329 ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
3331 ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
3333 ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
3336 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
3340 logevent("Encrypted session key");
3343 int cipher_chosen = 0, warn = 0;
3344 char *cipher_string = NULL;
3346 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
3347 int next_cipher = conf_get_int_int(ssh->conf,
3348 CONF_ssh_cipherlist, i);
3349 if (next_cipher == CIPHER_WARN) {
3350 /* If/when we choose a cipher, warn about it */
3352 } else if (next_cipher == CIPHER_AES) {
3353 /* XXX Probably don't need to mention this. */
3354 logevent("AES not supported in SSH-1, skipping");
3356 switch (next_cipher) {
3357 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
3358 cipher_string = "3DES"; break;
3359 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
3360 cipher_string = "Blowfish"; break;
3361 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
3362 cipher_string = "single-DES"; break;
3364 if (s->supported_ciphers_mask & (1 << s->cipher_type))
3368 if (!cipher_chosen) {
3369 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
3370 bombout(("Server violates SSH-1 protocol by not "
3371 "supporting 3DES encryption"));
3373 /* shouldn't happen */
3374 bombout(("No supported ciphers found"));
3378 /* Warn about chosen cipher if necessary. */
3380 ssh_set_frozen(ssh, 1);
3381 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
3382 ssh_dialog_callback, ssh);
3383 if (s->dlgret < 0) {
3387 bombout(("Unexpected data from server while waiting"
3388 " for user response"));
3391 } while (pktin || inlen > 0);
3392 s->dlgret = ssh->user_response;
3394 ssh_set_frozen(ssh, 0);
3395 if (s->dlgret == 0) {
3396 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
3403 switch (s->cipher_type) {
3404 case SSH_CIPHER_3DES:
3405 logevent("Using 3DES encryption");
3407 case SSH_CIPHER_DES:
3408 logevent("Using single-DES encryption");
3410 case SSH_CIPHER_BLOWFISH:
3411 logevent("Using Blowfish encryption");
3415 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
3416 PKT_CHAR, s->cipher_type,
3417 PKT_DATA, cookie, 8,
3418 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
3419 PKT_DATA, s->rsabuf, s->len,
3420 PKT_INT, ssh->v1_local_protoflags, PKT_END);
3422 logevent("Trying to enable encryption...");
3426 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
3427 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
3429 ssh->v1_cipher_ctx = ssh->cipher->make_context();
3430 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
3431 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
3433 ssh->crcda_ctx = crcda_make_context();
3434 logevent("Installing CRC compensation attack detector");
3436 if (s->servkey.modulus) {
3437 sfree(s->servkey.modulus);
3438 s->servkey.modulus = NULL;
3440 if (s->servkey.exponent) {
3441 sfree(s->servkey.exponent);
3442 s->servkey.exponent = NULL;
3444 if (s->hostkey.modulus) {
3445 sfree(s->hostkey.modulus);
3446 s->hostkey.modulus = NULL;
3448 if (s->hostkey.exponent) {
3449 sfree(s->hostkey.exponent);
3450 s->hostkey.exponent = NULL;
3454 if (pktin->type != SSH1_SMSG_SUCCESS) {
3455 bombout(("Encryption not successfully enabled"));
3459 logevent("Successfully started encryption");
3461 fflush(stdout); /* FIXME eh? */
3463 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
3464 int ret; /* need not be kept over crReturn */
3465 s->cur_prompt = new_prompts(ssh->frontend);
3466 s->cur_prompt->to_server = TRUE;
3467 s->cur_prompt->name = dupstr("SSH login name");
3468 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
3469 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3472 crWaitUntil(!pktin);
3473 ret = get_userpass_input(s->cur_prompt, in, inlen);
3478 * Failed to get a username. Terminate.
3480 free_prompts(s->cur_prompt);
3481 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
3484 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
3485 free_prompts(s->cur_prompt);
3488 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
3490 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
3492 if (flags & FLAG_INTERACTIVE &&
3493 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
3494 c_write_str(ssh, userlog);
3495 c_write_str(ssh, "\r\n");
3503 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
3504 /* We must not attempt PK auth. Pretend we've already tried it. */
3505 s->tried_publickey = s->tried_agent = 1;
3507 s->tried_publickey = s->tried_agent = 0;
3509 s->tis_auth_refused = s->ccard_auth_refused = 0;
3511 * Load the public half of any configured keyfile for later use.
3513 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3514 if (!filename_is_null(s->keyfile)) {
3516 logeventf(ssh, "Reading private key file \"%.150s\"",
3517 filename_to_str(s->keyfile));
3518 keytype = key_type(s->keyfile);
3519 if (keytype == SSH_KEYTYPE_SSH1) {
3521 if (rsakey_pubblob(s->keyfile,
3522 &s->publickey_blob, &s->publickey_bloblen,
3523 &s->publickey_comment, &error)) {
3524 s->publickey_encrypted = rsakey_encrypted(s->keyfile,
3528 logeventf(ssh, "Unable to load private key (%s)", error);
3529 msgbuf = dupprintf("Unable to load private key file "
3530 "\"%.150s\" (%s)\r\n",
3531 filename_to_str(s->keyfile),
3533 c_write_str(ssh, msgbuf);
3535 s->publickey_blob = NULL;
3539 logeventf(ssh, "Unable to use this key file (%s)",
3540 key_type_to_str(keytype));
3541 msgbuf = dupprintf("Unable to use key file \"%.150s\""
3543 filename_to_str(s->keyfile),
3544 key_type_to_str(keytype));
3545 c_write_str(ssh, msgbuf);
3547 s->publickey_blob = NULL;
3550 s->publickey_blob = NULL;
3552 while (pktin->type == SSH1_SMSG_FAILURE) {
3553 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
3555 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
3557 * Attempt RSA authentication using Pageant.
3563 logevent("Pageant is running. Requesting keys.");
3565 /* Request the keys held by the agent. */
3566 PUT_32BIT(s->request, 1);
3567 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
3568 if (!agent_query(s->request, 5, &r, &s->responselen,
3569 ssh_agent_callback, ssh)) {
3573 bombout(("Unexpected data from server while waiting"
3574 " for agent response"));
3577 } while (pktin || inlen > 0);
3578 r = ssh->agent_response;
3579 s->responselen = ssh->agent_response_len;
3581 s->response = (unsigned char *) r;
3582 if (s->response && s->responselen >= 5 &&
3583 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
3584 s->p = s->response + 5;
3585 s->nkeys = toint(GET_32BIT(s->p));
3587 logeventf(ssh, "Pageant reported negative key count %d",
3592 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
3593 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
3594 unsigned char *pkblob = s->p;
3598 do { /* do while (0) to make breaking easy */
3599 n = ssh1_read_bignum
3600 (s->p, toint(s->responselen-(s->p-s->response)),
3605 n = ssh1_read_bignum
3606 (s->p, toint(s->responselen-(s->p-s->response)),
3611 if (s->responselen - (s->p-s->response) < 4)
3613 s->commentlen = toint(GET_32BIT(s->p));
3615 if (s->commentlen < 0 ||
3616 toint(s->responselen - (s->p-s->response)) <
3619 s->commentp = (char *)s->p;
3620 s->p += s->commentlen;
3624 logevent("Pageant key list packet was truncated");
3628 if (s->publickey_blob) {
3629 if (!memcmp(pkblob, s->publickey_blob,
3630 s->publickey_bloblen)) {
3631 logeventf(ssh, "Pageant key #%d matches "
3632 "configured key file", s->keyi);
3633 s->tried_publickey = 1;
3635 /* Skip non-configured key */
3638 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
3639 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3640 PKT_BIGNUM, s->key.modulus, PKT_END);
3642 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3643 logevent("Key refused");
3646 logevent("Received RSA challenge");
3647 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3648 bombout(("Server's RSA challenge was badly formatted"));
3653 char *agentreq, *q, *ret;
3656 len = 1 + 4; /* message type, bit count */
3657 len += ssh1_bignum_length(s->key.exponent);
3658 len += ssh1_bignum_length(s->key.modulus);
3659 len += ssh1_bignum_length(s->challenge);
3660 len += 16; /* session id */
3661 len += 4; /* response format */
3662 agentreq = snewn(4 + len, char);
3663 PUT_32BIT(agentreq, len);
3665 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
3666 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
3668 q += ssh1_write_bignum(q, s->key.exponent);
3669 q += ssh1_write_bignum(q, s->key.modulus);
3670 q += ssh1_write_bignum(q, s->challenge);
3671 memcpy(q, s->session_id, 16);
3673 PUT_32BIT(q, 1); /* response format */
3674 if (!agent_query(agentreq, len + 4, &vret, &retlen,
3675 ssh_agent_callback, ssh)) {
3680 bombout(("Unexpected data from server"
3681 " while waiting for agent"
3685 } while (pktin || inlen > 0);
3686 vret = ssh->agent_response;
3687 retlen = ssh->agent_response_len;
3692 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
3693 logevent("Sending Pageant's response");
3694 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3695 PKT_DATA, ret + 5, 16,
3699 if (pktin->type == SSH1_SMSG_SUCCESS) {
3701 ("Pageant's response accepted");
3702 if (flags & FLAG_VERBOSE) {
3703 c_write_str(ssh, "Authenticated using"
3705 c_write(ssh, s->commentp,
3707 c_write_str(ssh, "\" from agent\r\n");
3712 ("Pageant's response not accepted");
3715 ("Pageant failed to answer challenge");
3719 logevent("No reply received from Pageant");
3722 freebn(s->key.exponent);
3723 freebn(s->key.modulus);
3724 freebn(s->challenge);
3729 if (s->publickey_blob && !s->tried_publickey)
3730 logevent("Configured key file not in Pageant");
3732 logevent("Failed to get reply from Pageant");
3737 if (s->publickey_blob && !s->tried_publickey) {
3739 * Try public key authentication with the specified
3742 int got_passphrase; /* need not be kept over crReturn */
3743 if (flags & FLAG_VERBOSE)
3744 c_write_str(ssh, "Trying public key authentication.\r\n");
3745 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3746 logeventf(ssh, "Trying public key \"%s\"",
3747 filename_to_str(s->keyfile));
3748 s->tried_publickey = 1;
3749 got_passphrase = FALSE;
3750 while (!got_passphrase) {
3752 * Get a passphrase, if necessary.
3754 char *passphrase = NULL; /* only written after crReturn */
3756 if (!s->publickey_encrypted) {
3757 if (flags & FLAG_VERBOSE)
3758 c_write_str(ssh, "No passphrase required.\r\n");
3761 int ret; /* need not be kept over crReturn */
3762 s->cur_prompt = new_prompts(ssh->frontend);
3763 s->cur_prompt->to_server = FALSE;
3764 s->cur_prompt->name = dupstr("SSH key passphrase");
3765 add_prompt(s->cur_prompt,
3766 dupprintf("Passphrase for key \"%.100s\": ",
3767 s->publickey_comment), FALSE);
3768 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3771 crWaitUntil(!pktin);
3772 ret = get_userpass_input(s->cur_prompt, in, inlen);
3776 /* Failed to get a passphrase. Terminate. */
3777 free_prompts(s->cur_prompt);
3778 ssh_disconnect(ssh, NULL, "Unable to authenticate",
3782 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
3783 free_prompts(s->cur_prompt);
3786 * Try decrypting key with passphrase.
3788 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3789 ret = loadrsakey(s->keyfile, &s->key, passphrase,
3792 smemclr(passphrase, strlen(passphrase));
3796 /* Correct passphrase. */
3797 got_passphrase = TRUE;
3798 } else if (ret == 0) {
3799 c_write_str(ssh, "Couldn't load private key from ");
3800 c_write_str(ssh, filename_to_str(s->keyfile));
3801 c_write_str(ssh, " (");
3802 c_write_str(ssh, error);
3803 c_write_str(ssh, ").\r\n");
3804 got_passphrase = FALSE;
3805 break; /* go and try something else */
3806 } else if (ret == -1) {
3807 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
3808 got_passphrase = FALSE;
3811 assert(0 && "unexpected return from loadrsakey()");
3812 got_passphrase = FALSE; /* placate optimisers */
3816 if (got_passphrase) {
3819 * Send a public key attempt.
3821 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3822 PKT_BIGNUM, s->key.modulus, PKT_END);
3825 if (pktin->type == SSH1_SMSG_FAILURE) {
3826 c_write_str(ssh, "Server refused our public key.\r\n");
3827 continue; /* go and try something else */
3829 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3830 bombout(("Bizarre response to offer of public key"));
3836 unsigned char buffer[32];
3837 Bignum challenge, response;
3839 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3840 bombout(("Server's RSA challenge was badly formatted"));
3843 response = rsadecrypt(challenge, &s->key);
3844 freebn(s->key.private_exponent);/* burn the evidence */
3846 for (i = 0; i < 32; i++) {
3847 buffer[i] = bignum_byte(response, 31 - i);
3851 MD5Update(&md5c, buffer, 32);
3852 MD5Update(&md5c, s->session_id, 16);
3853 MD5Final(buffer, &md5c);
3855 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3856 PKT_DATA, buffer, 16, PKT_END);
3863 if (pktin->type == SSH1_SMSG_FAILURE) {
3864 if (flags & FLAG_VERBOSE)
3865 c_write_str(ssh, "Failed to authenticate with"
3866 " our public key.\r\n");
3867 continue; /* go and try something else */
3868 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
3869 bombout(("Bizarre response to RSA authentication response"));
3873 break; /* we're through! */
3879 * Otherwise, try various forms of password-like authentication.
3881 s->cur_prompt = new_prompts(ssh->frontend);
3883 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
3884 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
3885 !s->tis_auth_refused) {
3886 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
3887 logevent("Requested TIS authentication");
3888 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
3890 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
3891 logevent("TIS authentication declined");
3892 if (flags & FLAG_INTERACTIVE)
3893 c_write_str(ssh, "TIS authentication refused.\r\n");
3894 s->tis_auth_refused = 1;
3899 char *instr_suf, *prompt;
3901 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3903 bombout(("TIS challenge packet was badly formed"));
3906 logevent("Received TIS challenge");
3907 s->cur_prompt->to_server = TRUE;
3908 s->cur_prompt->name = dupstr("SSH TIS authentication");
3909 /* Prompt heuristic comes from OpenSSH */
3910 if (memchr(challenge, '\n', challengelen)) {
3911 instr_suf = dupstr("");
3912 prompt = dupprintf("%.*s", challengelen, challenge);
3914 instr_suf = dupprintf("%.*s", challengelen, challenge);
3915 prompt = dupstr("Response: ");
3917 s->cur_prompt->instruction =
3918 dupprintf("Using TIS authentication.%s%s",
3919 (*instr_suf) ? "\n" : "",
3921 s->cur_prompt->instr_reqd = TRUE;
3922 add_prompt(s->cur_prompt, prompt, FALSE);
3926 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
3927 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
3928 !s->ccard_auth_refused) {
3929 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
3930 logevent("Requested CryptoCard authentication");
3931 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
3933 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
3934 logevent("CryptoCard authentication declined");
3935 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
3936 s->ccard_auth_refused = 1;
3941 char *instr_suf, *prompt;
3943 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3945 bombout(("CryptoCard challenge packet was badly formed"));
3948 logevent("Received CryptoCard challenge");
3949 s->cur_prompt->to_server = TRUE;
3950 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
3951 s->cur_prompt->name_reqd = FALSE;
3952 /* Prompt heuristic comes from OpenSSH */
3953 if (memchr(challenge, '\n', challengelen)) {
3954 instr_suf = dupstr("");
3955 prompt = dupprintf("%.*s", challengelen, challenge);
3957 instr_suf = dupprintf("%.*s", challengelen, challenge);
3958 prompt = dupstr("Response: ");
3960 s->cur_prompt->instruction =
3961 dupprintf("Using CryptoCard authentication.%s%s",
3962 (*instr_suf) ? "\n" : "",
3964 s->cur_prompt->instr_reqd = TRUE;
3965 add_prompt(s->cur_prompt, prompt, FALSE);
3969 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
3970 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
3971 bombout(("No supported authentication methods available"));
3974 s->cur_prompt->to_server = TRUE;
3975 s->cur_prompt->name = dupstr("SSH password");
3976 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
3977 ssh->username, ssh->savedhost),
3982 * Show password prompt, having first obtained it via a TIS
3983 * or CryptoCard exchange if we're doing TIS or CryptoCard
3987 int ret; /* need not be kept over crReturn */
3988 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3991 crWaitUntil(!pktin);
3992 ret = get_userpass_input(s->cur_prompt, in, inlen);
3997 * Failed to get a password (for example
3998 * because one was supplied on the command line
3999 * which has already failed to work). Terminate.
4001 free_prompts(s->cur_prompt);
4002 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4007 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4009 * Defence against traffic analysis: we send a
4010 * whole bunch of packets containing strings of
4011 * different lengths. One of these strings is the
4012 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4013 * The others are all random data in
4014 * SSH1_MSG_IGNORE packets. This way a passive
4015 * listener can't tell which is the password, and
4016 * hence can't deduce the password length.
4018 * Anybody with a password length greater than 16
4019 * bytes is going to have enough entropy in their
4020 * password that a listener won't find it _that_
4021 * much help to know how long it is. So what we'll
4024 * - if password length < 16, we send 15 packets
4025 * containing string lengths 1 through 15
4027 * - otherwise, we let N be the nearest multiple
4028 * of 8 below the password length, and send 8
4029 * packets containing string lengths N through
4030 * N+7. This won't obscure the order of
4031 * magnitude of the password length, but it will
4032 * introduce a bit of extra uncertainty.
4034 * A few servers can't deal with SSH1_MSG_IGNORE, at
4035 * least in this context. For these servers, we need
4036 * an alternative defence. We make use of the fact
4037 * that the password is interpreted as a C string:
4038 * so we can append a NUL, then some random data.
4040 * A few servers can deal with neither SSH1_MSG_IGNORE
4041 * here _nor_ a padded password string.
4042 * For these servers we are left with no defences
4043 * against password length sniffing.
4045 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4046 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4048 * The server can deal with SSH1_MSG_IGNORE, so
4049 * we can use the primary defence.
4051 int bottom, top, pwlen, i;
4054 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4056 bottom = 0; /* zero length passwords are OK! :-) */
4059 bottom = pwlen & ~7;
4063 assert(pwlen >= bottom && pwlen <= top);
4065 randomstr = snewn(top + 1, char);
4067 for (i = bottom; i <= top; i++) {
4069 defer_packet(ssh, s->pwpkt_type,
4070 PKTT_PASSWORD, PKT_STR,
4071 s->cur_prompt->prompts[0]->result,
4072 PKTT_OTHER, PKT_END);
4074 for (j = 0; j < i; j++) {
4076 randomstr[j] = random_byte();
4077 } while (randomstr[j] == '\0');
4079 randomstr[i] = '\0';
4080 defer_packet(ssh, SSH1_MSG_IGNORE,
4081 PKT_STR, randomstr, PKT_END);
4084 logevent("Sending password with camouflage packets");
4085 ssh_pkt_defersend(ssh);
4088 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4090 * The server can't deal with SSH1_MSG_IGNORE
4091 * but can deal with padded passwords, so we
4092 * can use the secondary defence.
4098 len = strlen(s->cur_prompt->prompts[0]->result);
4099 if (len < sizeof(string)) {
4101 strcpy(string, s->cur_prompt->prompts[0]->result);
4102 len++; /* cover the zero byte */
4103 while (len < sizeof(string)) {
4104 string[len++] = (char) random_byte();
4107 ss = s->cur_prompt->prompts[0]->result;
4109 logevent("Sending length-padded password");
4110 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
4111 PKT_INT, len, PKT_DATA, ss, len,
4112 PKTT_OTHER, PKT_END);
4115 * The server is believed unable to cope with
4116 * any of our password camouflage methods.
4119 len = strlen(s->cur_prompt->prompts[0]->result);
4120 logevent("Sending unpadded password");
4121 send_packet(ssh, s->pwpkt_type,
4122 PKTT_PASSWORD, PKT_INT, len,
4123 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4124 PKTT_OTHER, PKT_END);
4127 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
4128 PKT_STR, s->cur_prompt->prompts[0]->result,
4129 PKTT_OTHER, PKT_END);
4131 logevent("Sent password");
4132 free_prompts(s->cur_prompt);
4134 if (pktin->type == SSH1_SMSG_FAILURE) {
4135 if (flags & FLAG_VERBOSE)
4136 c_write_str(ssh, "Access denied\r\n");
4137 logevent("Authentication refused");
4138 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4139 bombout(("Strange packet received, type %d", pktin->type));
4145 if (s->publickey_blob) {
4146 sfree(s->publickey_blob);
4147 sfree(s->publickey_comment);
4150 logevent("Authentication successful");
4155 static void ssh_channel_try_eof(struct ssh_channel *c)
4158 assert(c->pending_eof); /* precondition for calling us */
4160 return; /* can't close: not even opened yet */
4161 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4162 return; /* can't send EOF: pending outgoing data */
4164 c->pending_eof = FALSE; /* we're about to send it */
4165 if (ssh->version == 1) {
4166 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4168 c->closes |= CLOSES_SENT_EOF;
4170 struct Packet *pktout;
4171 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4172 ssh2_pkt_adduint32(pktout, c->remoteid);
4173 ssh2_pkt_send(ssh, pktout);
4174 c->closes |= CLOSES_SENT_EOF;
4175 ssh2_channel_check_close(c);
4179 void sshfwd_write_eof(struct ssh_channel *c)
4183 if (ssh->state == SSH_STATE_CLOSED)
4186 if (c->closes & CLOSES_SENT_EOF)
4189 c->pending_eof = TRUE;
4190 ssh_channel_try_eof(c);
4193 void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
4197 if (ssh->state == SSH_STATE_CLOSED)
4202 x11_close(c->u.x11.s);
4203 logeventf(ssh, "Forwarded X11 connection terminated due to local "
4207 case CHAN_SOCKDATA_DORMANT:
4208 pfd_close(c->u.pfd.s);
4209 logeventf(ssh, "Forwarded port closed due to local error: %s", err);
4212 c->type = CHAN_ZOMBIE;
4213 c->pending_eof = FALSE; /* this will confuse a zombie channel */
4215 ssh2_channel_check_close(c);
4218 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
4222 if (ssh->state == SSH_STATE_CLOSED)
4225 if (ssh->version == 1) {
4226 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
4227 PKT_INT, c->remoteid,
4228 PKT_INT, len, PKTT_DATA, PKT_DATA, buf, len,
4229 PKTT_OTHER, PKT_END);
4231 * In SSH-1 we can return 0 here - implying that forwarded
4232 * connections are never individually throttled - because
4233 * the only circumstance that can cause throttling will be
4234 * the whole SSH connection backing up, in which case
4235 * _everything_ will be throttled as a whole.
4239 ssh2_add_channel_data(c, buf, len);
4240 return ssh2_try_send(c);
4244 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
4249 if (ssh->state == SSH_STATE_CLOSED)
4252 if (ssh->version == 1) {
4253 buflimit = SSH1_BUFFER_LIMIT;
4255 buflimit = c->v.v2.locmaxwin;
4256 ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
4258 if (c->throttling_conn && bufsize <= buflimit) {
4259 c->throttling_conn = 0;
4260 ssh_throttle_conn(ssh, -1);
4264 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
4266 struct queued_handler *qh = ssh->qhead;
4270 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
4273 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
4274 ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
4277 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
4278 ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
4282 ssh->qhead = qh->next;
4284 if (ssh->qhead->msg1 > 0) {
4285 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
4286 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
4288 if (ssh->qhead->msg2 > 0) {
4289 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
4290 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
4293 ssh->qhead = ssh->qtail = NULL;
4296 qh->handler(ssh, pktin, qh->ctx);
4301 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
4302 chandler_fn_t handler, void *ctx)
4304 struct queued_handler *qh;
4306 qh = snew(struct queued_handler);
4309 qh->handler = handler;
4313 if (ssh->qtail == NULL) {
4317 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
4318 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
4321 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
4322 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
4325 ssh->qtail->next = qh;
4330 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
4332 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
4334 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
4335 SSH2_MSG_REQUEST_SUCCESS)) {
4336 logeventf(ssh, "Remote port forwarding from %s enabled",
4339 logeventf(ssh, "Remote port forwarding from %s refused",
4342 rpf = del234(ssh->rportfwds, pf);
4344 pf->pfrec->remote = NULL;
4349 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
4351 struct ssh_portfwd *epf;
4355 if (!ssh->portfwds) {
4356 ssh->portfwds = newtree234(ssh_portcmp);
4359 * Go through the existing port forwardings and tag them
4360 * with status==DESTROY. Any that we want to keep will be
4361 * re-enabled (status==KEEP) as we go through the
4362 * configuration and find out which bits are the same as
4365 struct ssh_portfwd *epf;
4367 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4368 epf->status = DESTROY;
4371 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
4373 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
4374 char *kp, *kp2, *vp, *vp2;
4375 char address_family, type;
4376 int sport,dport,sserv,dserv;
4377 char *sports, *dports, *saddr, *host;
4381 address_family = 'A';
4383 if (*kp == 'A' || *kp == '4' || *kp == '6')
4384 address_family = *kp++;
4385 if (*kp == 'L' || *kp == 'R')
4388 if ((kp2 = strchr(kp, ':')) != NULL) {
4390 * There's a colon in the middle of the source port
4391 * string, which means that the part before it is
4392 * actually a source address.
4394 saddr = dupprintf("%.*s", (int)(kp2 - kp), kp);
4400 sport = atoi(sports);
4404 sport = net_service_lookup(sports);
4406 logeventf(ssh, "Service lookup failed for source"
4407 " port \"%s\"", sports);
4411 if (type == 'L' && !strcmp(val, "D")) {
4412 /* dynamic forwarding */
4419 /* ordinary forwarding */
4421 vp2 = vp + strcspn(vp, ":");
4422 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
4426 dport = atoi(dports);
4430 dport = net_service_lookup(dports);
4432 logeventf(ssh, "Service lookup failed for destination"
4433 " port \"%s\"", dports);
4438 if (sport && dport) {
4439 /* Set up a description of the source port. */
4440 struct ssh_portfwd *pfrec, *epfrec;
4442 pfrec = snew(struct ssh_portfwd);
4444 pfrec->saddr = saddr;
4445 pfrec->sserv = sserv ? dupstr(sports) : NULL;
4446 pfrec->sport = sport;
4447 pfrec->daddr = host;
4448 pfrec->dserv = dserv ? dupstr(dports) : NULL;
4449 pfrec->dport = dport;
4450 pfrec->local = NULL;
4451 pfrec->remote = NULL;
4452 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
4453 address_family == '6' ? ADDRTYPE_IPV6 :
4456 epfrec = add234(ssh->portfwds, pfrec);
4457 if (epfrec != pfrec) {
4458 if (epfrec->status == DESTROY) {
4460 * We already have a port forwarding up and running
4461 * with precisely these parameters. Hence, no need
4462 * to do anything; simply re-tag the existing one
4465 epfrec->status = KEEP;
4468 * Anything else indicates that there was a duplicate
4469 * in our input, which we'll silently ignore.
4471 free_portfwd(pfrec);
4473 pfrec->status = CREATE;
4482 * Now go through and destroy any port forwardings which were
4485 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4486 if (epf->status == DESTROY) {
4489 message = dupprintf("%s port forwarding from %s%s%d",
4490 epf->type == 'L' ? "local" :
4491 epf->type == 'R' ? "remote" : "dynamic",
4492 epf->saddr ? epf->saddr : "",
4493 epf->saddr ? ":" : "",
4496 if (epf->type != 'D') {
4497 char *msg2 = dupprintf("%s to %s:%d", message,
4498 epf->daddr, epf->dport);
4503 logeventf(ssh, "Cancelling %s", message);
4506 /* epf->remote or epf->local may be NULL if setting up a
4507 * forwarding failed. */
4509 struct ssh_rportfwd *rpf = epf->remote;
4510 struct Packet *pktout;
4513 * Cancel the port forwarding at the server
4516 if (ssh->version == 1) {
4518 * We cannot cancel listening ports on the
4519 * server side in SSH-1! There's no message
4520 * to support it. Instead, we simply remove
4521 * the rportfwd record from the local end
4522 * so that any connections the server tries
4523 * to make on it are rejected.
4526 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4527 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
4528 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
4530 ssh2_pkt_addstring(pktout, epf->saddr);
4531 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
4532 /* XXX: rport_acceptall may not represent
4533 * what was used to open the original connection,
4534 * since it's reconfigurable. */
4535 ssh2_pkt_addstring(pktout, "");
4537 ssh2_pkt_addstring(pktout, "localhost");
4539 ssh2_pkt_adduint32(pktout, epf->sport);
4540 ssh2_pkt_send(ssh, pktout);
4543 del234(ssh->rportfwds, rpf);
4545 } else if (epf->local) {
4546 pfd_terminate(epf->local);
4549 delpos234(ssh->portfwds, i);
4551 i--; /* so we don't skip one in the list */
4555 * And finally, set up any new port forwardings (status==CREATE).
4557 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4558 if (epf->status == CREATE) {
4559 char *sportdesc, *dportdesc;
4560 sportdesc = dupprintf("%s%s%s%s%d%s",
4561 epf->saddr ? epf->saddr : "",
4562 epf->saddr ? ":" : "",
4563 epf->sserv ? epf->sserv : "",
4564 epf->sserv ? "(" : "",
4566 epf->sserv ? ")" : "");
4567 if (epf->type == 'D') {
4570 dportdesc = dupprintf("%s:%s%s%d%s",
4572 epf->dserv ? epf->dserv : "",
4573 epf->dserv ? "(" : "",
4575 epf->dserv ? ")" : "");
4578 if (epf->type == 'L') {
4579 const char *err = pfd_addforward(epf->daddr, epf->dport,
4580 epf->saddr, epf->sport,
4583 epf->addressfamily);
4585 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
4586 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4587 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4588 sportdesc, dportdesc,
4589 err ? " failed: " : "", err ? err : "");
4590 } else if (epf->type == 'D') {
4591 const char *err = pfd_addforward(NULL, -1,
4592 epf->saddr, epf->sport,
4595 epf->addressfamily);
4597 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
4598 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4599 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4601 err ? " failed: " : "", err ? err : "");
4603 struct ssh_rportfwd *pf;
4606 * Ensure the remote port forwardings tree exists.
4608 if (!ssh->rportfwds) {
4609 if (ssh->version == 1)
4610 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
4612 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
4615 pf = snew(struct ssh_rportfwd);
4616 pf->dhost = dupstr(epf->daddr);
4617 pf->dport = epf->dport;
4619 pf->shost = dupstr(epf->saddr);
4620 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
4621 pf->shost = dupstr("");
4623 pf->shost = dupstr("localhost");
4625 pf->sport = epf->sport;
4626 if (add234(ssh->rportfwds, pf) != pf) {
4627 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
4628 epf->daddr, epf->dport);
4631 logeventf(ssh, "Requesting remote port %s"
4632 " forward to %s", sportdesc, dportdesc);
4634 pf->sportdesc = sportdesc;
4639 if (ssh->version == 1) {
4640 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
4641 PKT_INT, epf->sport,
4642 PKT_STR, epf->daddr,
4643 PKT_INT, epf->dport,
4645 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
4647 ssh_rportfwd_succfail, pf);
4649 struct Packet *pktout;
4650 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4651 ssh2_pkt_addstring(pktout, "tcpip-forward");
4652 ssh2_pkt_addbool(pktout, 1);/* want reply */
4653 ssh2_pkt_addstring(pktout, pf->shost);
4654 ssh2_pkt_adduint32(pktout, pf->sport);
4655 ssh2_pkt_send(ssh, pktout);
4657 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
4658 SSH2_MSG_REQUEST_FAILURE,
4659 ssh_rportfwd_succfail, pf);
4668 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
4671 int stringlen, bufsize;
4673 ssh_pkt_getstring(pktin, &string, &stringlen);
4674 if (string == NULL) {
4675 bombout(("Incoming terminal data packet was badly formed"));
4679 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
4681 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
4682 ssh->v1_stdout_throttling = 1;
4683 ssh_throttle_conn(ssh, +1);
4687 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
4689 /* Remote side is trying to open a channel to talk to our
4690 * X-Server. Give them back a local channel number. */
4691 struct ssh_channel *c;
4692 int remoteid = ssh_pkt_getuint32(pktin);
4694 logevent("Received X11 connect request");
4695 /* Refuse if X11 forwarding is disabled. */
4696 if (!ssh->X11_fwd_enabled) {
4697 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4698 PKT_INT, remoteid, PKT_END);
4699 logevent("Rejected X11 connect request");
4701 c = snew(struct ssh_channel);
4704 if (x11_init(&c->u.x11.s, ssh->x11disp, c,
4705 NULL, -1, ssh->conf) != NULL) {
4706 logevent("Opening X11 forward connection failed");
4708 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4709 PKT_INT, remoteid, PKT_END);
4712 ("Opening X11 forward connection succeeded");
4713 c->remoteid = remoteid;
4714 c->halfopen = FALSE;
4715 c->localid = alloc_channel_id(ssh);
4717 c->pending_eof = FALSE;
4718 c->throttling_conn = 0;
4719 c->type = CHAN_X11; /* identify channel type */
4720 add234(ssh->channels, c);
4721 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4722 PKT_INT, c->remoteid, PKT_INT,
4723 c->localid, PKT_END);
4724 logevent("Opened X11 forward channel");
4729 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
4731 /* Remote side is trying to open a channel to talk to our
4732 * agent. Give them back a local channel number. */
4733 struct ssh_channel *c;
4734 int remoteid = ssh_pkt_getuint32(pktin);
4736 /* Refuse if agent forwarding is disabled. */
4737 if (!ssh->agentfwd_enabled) {
4738 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4739 PKT_INT, remoteid, PKT_END);
4741 c = snew(struct ssh_channel);
4743 c->remoteid = remoteid;
4744 c->halfopen = FALSE;
4745 c->localid = alloc_channel_id(ssh);
4747 c->pending_eof = FALSE;
4748 c->throttling_conn = 0;
4749 c->type = CHAN_AGENT; /* identify channel type */
4750 c->u.a.lensofar = 0;
4751 c->u.a.message = NULL;
4752 c->u.a.outstanding_requests = 0;
4753 add234(ssh->channels, c);
4754 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4755 PKT_INT, c->remoteid, PKT_INT, c->localid,
4760 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
4762 /* Remote side is trying to open a channel to talk to a
4763 * forwarded port. Give them back a local channel number. */
4764 struct ssh_rportfwd pf, *pfp;
4770 remoteid = ssh_pkt_getuint32(pktin);
4771 ssh_pkt_getstring(pktin, &host, &hostsize);
4772 port = ssh_pkt_getuint32(pktin);
4774 pf.dhost = dupprintf(".*s", hostsize, host);
4776 pfp = find234(ssh->rportfwds, &pf, NULL);
4779 logeventf(ssh, "Rejected remote port open request for %s:%d",
4781 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4782 PKT_INT, remoteid, PKT_END);
4784 struct ssh_channel *c = snew(struct ssh_channel);
4787 logeventf(ssh, "Received remote port open request for %s:%d",
4789 e = pfd_newconnect(&c->u.pfd.s, pf.dhost, port,
4790 c, ssh->conf, pfp->pfrec->addressfamily);
4792 logeventf(ssh, "Port open failed: %s", e);
4794 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4795 PKT_INT, remoteid, PKT_END);
4797 c->remoteid = remoteid;
4798 c->halfopen = FALSE;
4799 c->localid = alloc_channel_id(ssh);
4801 c->pending_eof = FALSE;
4802 c->throttling_conn = 0;
4803 c->type = CHAN_SOCKDATA; /* identify channel type */
4804 add234(ssh->channels, c);
4805 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4806 PKT_INT, c->remoteid, PKT_INT,
4807 c->localid, PKT_END);
4808 logevent("Forwarded port opened successfully");
4815 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
4817 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4818 unsigned int localid = ssh_pkt_getuint32(pktin);
4819 struct ssh_channel *c;
4821 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4822 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4823 c->remoteid = localid;
4824 c->halfopen = FALSE;
4825 c->type = CHAN_SOCKDATA;
4826 c->throttling_conn = 0;
4827 pfd_confirm(c->u.pfd.s);
4830 if (c && c->pending_eof) {
4832 * We have a pending close on this channel,
4833 * which we decided on before the server acked
4834 * the channel open. So now we know the
4835 * remoteid, we can close it again.
4837 ssh_channel_try_eof(c);
4841 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
4843 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4844 struct ssh_channel *c;
4846 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4847 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4848 logevent("Forwarded connection refused by server");
4849 pfd_close(c->u.pfd.s);
4850 del234(ssh->channels, c);
4855 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
4857 /* Remote side closes a channel. */
4858 unsigned i = ssh_pkt_getuint32(pktin);
4859 struct ssh_channel *c;
4860 c = find234(ssh->channels, &i, ssh_channelfind);
4861 if (c && !c->halfopen) {
4863 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
4864 !(c->closes & CLOSES_RCVD_EOF)) {
4866 * Received CHANNEL_CLOSE, which we translate into
4869 int send_close = FALSE;
4871 c->closes |= CLOSES_RCVD_EOF;
4876 x11_send_eof(c->u.x11.s);
4882 pfd_send_eof(c->u.pfd.s);
4891 if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
4892 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4894 c->closes |= CLOSES_SENT_EOF;
4898 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
4899 !(c->closes & CLOSES_RCVD_CLOSE)) {
4901 if (!(c->closes & CLOSES_SENT_EOF)) {
4902 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %d"
4903 " for which we never sent CHANNEL_CLOSE\n", i));
4906 c->closes |= CLOSES_RCVD_CLOSE;
4909 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
4910 !(c->closes & CLOSES_SENT_CLOSE)) {
4911 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
4912 PKT_INT, c->remoteid, PKT_END);
4913 c->closes |= CLOSES_SENT_CLOSE;
4916 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
4917 ssh_channel_destroy(c);
4919 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
4920 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
4921 "_CONFIRMATION", c ? "half-open" : "nonexistent",
4926 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
4928 /* Data sent down one of our channels. */
4929 int i = ssh_pkt_getuint32(pktin);
4932 struct ssh_channel *c;
4934 ssh_pkt_getstring(pktin, &p, &len);
4936 c = find234(ssh->channels, &i, ssh_channelfind);
4941 bufsize = x11_send(c->u.x11.s, p, len);
4944 bufsize = pfd_send(c->u.pfd.s, p, len);
4947 /* Data for an agent message. Buffer it. */
4949 if (c->u.a.lensofar < 4) {
4950 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)len);
4951 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
4955 c->u.a.lensofar += l;
4957 if (c->u.a.lensofar == 4) {
4959 4 + GET_32BIT(c->u.a.msglen);
4960 c->u.a.message = snewn(c->u.a.totallen,
4962 memcpy(c->u.a.message, c->u.a.msglen, 4);
4964 if (c->u.a.lensofar >= 4 && len > 0) {
4966 min(c->u.a.totallen - c->u.a.lensofar,
4968 memcpy(c->u.a.message + c->u.a.lensofar, p,
4972 c->u.a.lensofar += l;
4974 if (c->u.a.lensofar == c->u.a.totallen) {
4977 c->u.a.outstanding_requests++;
4978 if (agent_query(c->u.a.message,
4981 ssh_agentf_callback, c))
4982 ssh_agentf_callback(c, reply, replylen);
4983 sfree(c->u.a.message);
4984 c->u.a.lensofar = 0;
4987 bufsize = 0; /* agent channels never back up */
4990 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
4991 c->throttling_conn = 1;
4992 ssh_throttle_conn(ssh, +1);
4997 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
4999 ssh->exitcode = ssh_pkt_getuint32(pktin);
5000 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5001 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5003 * In case `helpful' firewalls or proxies tack
5004 * extra human-readable text on the end of the
5005 * session which we might mistake for another
5006 * encrypted packet, we close the session once
5007 * we've sent EXIT_CONFIRMATION.
5009 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5012 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5013 static void ssh1_send_ttymode(void *data, char *mode, char *val)
5015 struct Packet *pktout = (struct Packet *)data;
5017 unsigned int arg = 0;
5018 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
5019 if (i == lenof(ssh_ttymodes)) return;
5020 switch (ssh_ttymodes[i].type) {
5022 arg = ssh_tty_parse_specchar(val);
5025 arg = ssh_tty_parse_boolean(val);
5028 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
5029 ssh2_pkt_addbyte(pktout, arg);
5033 static void do_ssh1_connection(Ssh ssh, unsigned char *in, int inlen,
5034 struct Packet *pktin)
5036 crBegin(ssh->do_ssh1_connection_crstate);
5038 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5039 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5040 ssh1_smsg_stdout_stderr_data;
5042 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5043 ssh1_msg_channel_open_confirmation;
5044 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5045 ssh1_msg_channel_open_failure;
5046 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5047 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5048 ssh1_msg_channel_close;
5049 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5050 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5052 if (conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists()) {
5053 logevent("Requesting agent forwarding");
5054 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5058 if (pktin->type != SSH1_SMSG_SUCCESS
5059 && pktin->type != SSH1_SMSG_FAILURE) {
5060 bombout(("Protocol confusion"));
5062 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5063 logevent("Agent forwarding refused");
5065 logevent("Agent forwarding enabled");
5066 ssh->agentfwd_enabled = TRUE;
5067 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5071 if (conf_get_int(ssh->conf, CONF_x11_forward) &&
5072 (ssh->x11disp = x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5073 conf_get_int(ssh->conf, CONF_x11_auth), ssh->conf))) {
5074 logevent("Requesting X11 forwarding");
5076 * Note that while we blank the X authentication data here, we don't
5077 * take any special action to blank the start of an X11 channel,
5078 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
5079 * without having session blanking enabled is likely to leak your
5080 * cookie into the log.
5082 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5083 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5084 PKT_STR, ssh->x11disp->remoteauthprotoname,
5086 PKT_STR, ssh->x11disp->remoteauthdatastring,
5088 PKT_INT, ssh->x11disp->screennum,
5091 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5092 PKT_STR, ssh->x11disp->remoteauthprotoname,
5094 PKT_STR, ssh->x11disp->remoteauthdatastring,
5101 if (pktin->type != SSH1_SMSG_SUCCESS
5102 && pktin->type != SSH1_SMSG_FAILURE) {
5103 bombout(("Protocol confusion"));
5105 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5106 logevent("X11 forwarding refused");
5108 logevent("X11 forwarding enabled");
5109 ssh->X11_fwd_enabled = TRUE;
5110 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5114 ssh_setup_portfwd(ssh, ssh->conf);
5115 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5117 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5119 /* Unpick the terminal-speed string. */
5120 /* XXX perhaps we should allow no speeds to be sent. */
5121 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5122 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5123 /* Send the pty request. */
5124 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5125 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5126 ssh_pkt_adduint32(pkt, ssh->term_height);
5127 ssh_pkt_adduint32(pkt, ssh->term_width);
5128 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5129 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5130 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5131 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5132 ssh_pkt_adduint32(pkt, ssh->ispeed);
5133 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5134 ssh_pkt_adduint32(pkt, ssh->ospeed);
5135 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5137 ssh->state = SSH_STATE_INTERMED;
5141 if (pktin->type != SSH1_SMSG_SUCCESS
5142 && pktin->type != SSH1_SMSG_FAILURE) {
5143 bombout(("Protocol confusion"));
5145 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5146 c_write_str(ssh, "Server refused to allocate pty\r\n");
5147 ssh->editing = ssh->echoing = 1;
5149 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5150 ssh->ospeed, ssh->ispeed);
5151 ssh->got_pty = TRUE;
5154 ssh->editing = ssh->echoing = 1;
5157 if (conf_get_int(ssh->conf, CONF_compression)) {
5158 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5162 if (pktin->type != SSH1_SMSG_SUCCESS
5163 && pktin->type != SSH1_SMSG_FAILURE) {
5164 bombout(("Protocol confusion"));
5166 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5167 c_write_str(ssh, "Server refused to compress\r\n");
5169 logevent("Started compression");
5170 ssh->v1_compressing = TRUE;
5171 ssh->cs_comp_ctx = zlib_compress_init();
5172 logevent("Initialised zlib (RFC1950) compression");
5173 ssh->sc_comp_ctx = zlib_decompress_init();
5174 logevent("Initialised zlib (RFC1950) decompression");
5178 * Start the shell or command.
5180 * Special case: if the first-choice command is an SSH-2
5181 * subsystem (hence not usable here) and the second choice
5182 * exists, we fall straight back to that.
5185 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
5187 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
5188 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
5189 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
5190 ssh->fallback_cmd = TRUE;
5193 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
5195 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
5196 logevent("Started session");
5199 ssh->state = SSH_STATE_SESSION;
5200 if (ssh->size_needed)
5201 ssh_size(ssh, ssh->term_width, ssh->term_height);
5202 if (ssh->eof_needed)
5203 ssh_special(ssh, TS_EOF);
5206 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
5208 ssh->channels = newtree234(ssh_channelcmp);
5212 * By this point, most incoming packets are already being
5213 * handled by the dispatch table, and we need only pay
5214 * attention to the unusual ones.
5219 if (pktin->type == SSH1_SMSG_SUCCESS) {
5220 /* may be from EXEC_SHELL on some servers */
5221 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5222 /* may be from EXEC_SHELL on some servers
5223 * if no pty is available or in other odd cases. Ignore */
5225 bombout(("Strange packet received: type %d", pktin->type));
5230 int len = min(inlen, 512);
5231 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
5232 PKT_INT, len, PKTT_DATA, PKT_DATA, in, len,
5233 PKTT_OTHER, PKT_END);
5244 * Handle the top-level SSH-2 protocol.
5246 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
5251 ssh_pkt_getstring(pktin, &msg, &msglen);
5252 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
5255 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
5257 /* log reason code in disconnect message */
5261 ssh_pkt_getstring(pktin, &msg, &msglen);
5262 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
5265 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
5267 /* Do nothing, because we're ignoring it! Duhh. */
5270 static void ssh1_protocol_setup(Ssh ssh)
5275 * Most messages are handled by the coroutines.
5277 for (i = 0; i < 256; i++)
5278 ssh->packet_dispatch[i] = NULL;
5281 * These special message types we install handlers for.
5283 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
5284 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
5285 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
5288 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
5289 struct Packet *pktin)
5291 unsigned char *in=(unsigned char*)vin;
5292 if (ssh->state == SSH_STATE_CLOSED)
5295 if (pktin && ssh->packet_dispatch[pktin->type]) {
5296 ssh->packet_dispatch[pktin->type](ssh, pktin);
5300 if (!ssh->protocol_initial_phase_done) {
5301 if (do_ssh1_login(ssh, in, inlen, pktin))
5302 ssh->protocol_initial_phase_done = TRUE;
5307 do_ssh1_connection(ssh, in, inlen, pktin);
5311 * Utility routine for decoding comma-separated strings in KEXINIT.
5313 static int in_commasep_string(char *needle, char *haystack, int haylen)
5316 if (!needle || !haystack) /* protect against null pointers */
5318 needlen = strlen(needle);
5321 * Is it at the start of the string?
5323 if (haylen >= needlen && /* haystack is long enough */
5324 !memcmp(needle, haystack, needlen) && /* initial match */
5325 (haylen == needlen || haystack[needlen] == ',')
5326 /* either , or EOS follows */
5330 * If not, search for the next comma and resume after that.
5331 * If no comma found, terminate.
5333 while (haylen > 0 && *haystack != ',')
5334 haylen--, haystack++;
5337 haylen--, haystack++; /* skip over comma itself */
5342 * Similar routine for checking whether we have the first string in a list.
5344 static int first_in_commasep_string(char *needle, char *haystack, int haylen)
5347 if (!needle || !haystack) /* protect against null pointers */
5349 needlen = strlen(needle);
5351 * Is it at the start of the string?
5353 if (haylen >= needlen && /* haystack is long enough */
5354 !memcmp(needle, haystack, needlen) && /* initial match */
5355 (haylen == needlen || haystack[needlen] == ',')
5356 /* either , or EOS follows */
5364 * SSH-2 key creation method.
5365 * (Currently assumes 2 lots of any hash are sufficient to generate
5366 * keys/IVs for any cipher/MAC. SSH2_MKKEY_ITERS documents this assumption.)
5368 #define SSH2_MKKEY_ITERS (2)
5369 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H, char chr,
5370 unsigned char *keyspace)
5372 const struct ssh_hash *h = ssh->kex->hash;
5374 /* First hlen bytes. */
5376 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5377 hash_mpint(h, s, K);
5378 h->bytes(s, H, h->hlen);
5379 h->bytes(s, &chr, 1);
5380 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
5381 h->final(s, keyspace);
5382 /* Next hlen bytes. */
5384 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5385 hash_mpint(h, s, K);
5386 h->bytes(s, H, h->hlen);
5387 h->bytes(s, keyspace, h->hlen);
5388 h->final(s, keyspace + h->hlen);
5392 * Handle the SSH-2 transport layer.
5394 static void do_ssh2_transport(Ssh ssh, void *vin, int inlen,
5395 struct Packet *pktin)
5397 unsigned char *in = (unsigned char *)vin;
5398 struct do_ssh2_transport_state {
5400 int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
5401 Bignum p, g, e, f, K;
5404 int kex_init_value, kex_reply_value;
5405 const struct ssh_mac **maclist;
5407 const struct ssh2_cipher *cscipher_tobe;
5408 const struct ssh2_cipher *sccipher_tobe;
5409 const struct ssh_mac *csmac_tobe;
5410 const struct ssh_mac *scmac_tobe;
5411 const struct ssh_compress *cscomp_tobe;
5412 const struct ssh_compress *sccomp_tobe;
5413 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
5414 int hostkeylen, siglen, rsakeylen;
5415 void *hkey; /* actual host key */
5416 void *rsakey; /* for RSA kex */
5417 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
5418 int n_preferred_kex;
5419 const struct ssh_kexes *preferred_kex[KEX_MAX];
5420 int n_preferred_ciphers;
5421 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
5422 const struct ssh_compress *preferred_comp;
5423 int userauth_succeeded; /* for delayed compression */
5424 int pending_compression;
5425 int got_session_id, activated_authconn;
5426 struct Packet *pktout;
5431 crState(do_ssh2_transport_state);
5435 s->cscipher_tobe = s->sccipher_tobe = NULL;
5436 s->csmac_tobe = s->scmac_tobe = NULL;
5437 s->cscomp_tobe = s->sccomp_tobe = NULL;
5439 s->got_session_id = s->activated_authconn = FALSE;
5440 s->userauth_succeeded = FALSE;
5441 s->pending_compression = FALSE;
5444 * Be prepared to work around the buggy MAC problem.
5446 if (ssh->remote_bugs & BUG_SSH2_HMAC)
5447 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
5449 s->maclist = macs, s->nmacs = lenof(macs);
5452 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
5454 int i, j, k, commalist_started;
5457 * Set up the preferred key exchange. (NULL => warn below here)
5459 s->n_preferred_kex = 0;
5460 for (i = 0; i < KEX_MAX; i++) {
5461 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
5463 s->preferred_kex[s->n_preferred_kex++] =
5464 &ssh_diffiehellman_gex;
5467 s->preferred_kex[s->n_preferred_kex++] =
5468 &ssh_diffiehellman_group14;
5471 s->preferred_kex[s->n_preferred_kex++] =
5472 &ssh_diffiehellman_group1;
5475 s->preferred_kex[s->n_preferred_kex++] =
5479 /* Flag for later. Don't bother if it's the last in
5481 if (i < KEX_MAX - 1) {
5482 s->preferred_kex[s->n_preferred_kex++] = NULL;
5489 * Set up the preferred ciphers. (NULL => warn below here)
5491 s->n_preferred_ciphers = 0;
5492 for (i = 0; i < CIPHER_MAX; i++) {
5493 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
5494 case CIPHER_BLOWFISH:
5495 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
5498 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
5499 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
5503 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
5506 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
5508 case CIPHER_ARCFOUR:
5509 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
5512 /* Flag for later. Don't bother if it's the last in
5514 if (i < CIPHER_MAX - 1) {
5515 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
5522 * Set up preferred compression.
5524 if (conf_get_int(ssh->conf, CONF_compression))
5525 s->preferred_comp = &ssh_zlib;
5527 s->preferred_comp = &ssh_comp_none;
5530 * Enable queueing of outgoing auth- or connection-layer
5531 * packets while we are in the middle of a key exchange.
5533 ssh->queueing = TRUE;
5536 * Flag that KEX is in progress.
5538 ssh->kex_in_progress = TRUE;
5541 * Construct and send our key exchange packet.
5543 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
5544 for (i = 0; i < 16; i++)
5545 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
5546 /* List key exchange algorithms. */
5547 ssh2_pkt_addstring_start(s->pktout);
5548 commalist_started = 0;
5549 for (i = 0; i < s->n_preferred_kex; i++) {
5550 const struct ssh_kexes *k = s->preferred_kex[i];
5551 if (!k) continue; /* warning flag */
5552 for (j = 0; j < k->nkexes; j++) {
5553 if (commalist_started)
5554 ssh2_pkt_addstring_str(s->pktout, ",");
5555 ssh2_pkt_addstring_str(s->pktout, k->list[j]->name);
5556 commalist_started = 1;
5559 /* List server host key algorithms. */
5560 if (!s->got_session_id) {
5562 * In the first key exchange, we list all the algorithms
5563 * we're prepared to cope with.
5565 ssh2_pkt_addstring_start(s->pktout);
5566 for (i = 0; i < lenof(hostkey_algs); i++) {
5567 ssh2_pkt_addstring_str(s->pktout, hostkey_algs[i]->name);
5568 if (i < lenof(hostkey_algs) - 1)
5569 ssh2_pkt_addstring_str(s->pktout, ",");
5573 * In subsequent key exchanges, we list only the kex
5574 * algorithm that was selected in the first key exchange,
5575 * so that we keep getting the same host key and hence
5576 * don't have to interrupt the user's session to ask for
5580 ssh2_pkt_addstring(s->pktout, ssh->hostkey->name);
5582 /* List encryption algorithms (client->server then server->client). */
5583 for (k = 0; k < 2; k++) {
5584 ssh2_pkt_addstring_start(s->pktout);
5585 commalist_started = 0;
5586 for (i = 0; i < s->n_preferred_ciphers; i++) {
5587 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5588 if (!c) continue; /* warning flag */
5589 for (j = 0; j < c->nciphers; j++) {
5590 if (commalist_started)
5591 ssh2_pkt_addstring_str(s->pktout, ",");
5592 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
5593 commalist_started = 1;
5597 /* List MAC algorithms (client->server then server->client). */
5598 for (j = 0; j < 2; j++) {
5599 ssh2_pkt_addstring_start(s->pktout);
5600 for (i = 0; i < s->nmacs; i++) {
5601 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5602 if (i < s->nmacs - 1)
5603 ssh2_pkt_addstring_str(s->pktout, ",");
5606 /* List client->server compression algorithms,
5607 * then server->client compression algorithms. (We use the
5608 * same set twice.) */
5609 for (j = 0; j < 2; j++) {
5610 ssh2_pkt_addstring_start(s->pktout);
5611 assert(lenof(compressions) > 1);
5612 /* Prefer non-delayed versions */
5613 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
5614 /* We don't even list delayed versions of algorithms until
5615 * they're allowed to be used, to avoid a race. See the end of
5617 if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
5618 ssh2_pkt_addstring_str(s->pktout, ",");
5619 ssh2_pkt_addstring_str(s->pktout,
5620 s->preferred_comp->delayed_name);
5622 for (i = 0; i < lenof(compressions); i++) {
5623 const struct ssh_compress *c = compressions[i];
5624 if (c != s->preferred_comp) {
5625 ssh2_pkt_addstring_str(s->pktout, ",");
5626 ssh2_pkt_addstring_str(s->pktout, c->name);
5627 if (s->userauth_succeeded && c->delayed_name) {
5628 ssh2_pkt_addstring_str(s->pktout, ",");
5629 ssh2_pkt_addstring_str(s->pktout, c->delayed_name);
5634 /* List client->server languages. Empty list. */
5635 ssh2_pkt_addstring_start(s->pktout);
5636 /* List server->client languages. Empty list. */
5637 ssh2_pkt_addstring_start(s->pktout);
5638 /* First KEX packet does _not_ follow, because we're not that brave. */
5639 ssh2_pkt_addbool(s->pktout, FALSE);
5641 ssh2_pkt_adduint32(s->pktout, 0);
5644 s->our_kexinitlen = s->pktout->length - 5;
5645 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
5646 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
5648 ssh2_pkt_send_noqueue(ssh, s->pktout);
5651 crWaitUntilV(pktin);
5654 * Now examine the other side's KEXINIT to see what we're up
5658 char *str, *preferred;
5661 if (pktin->type != SSH2_MSG_KEXINIT) {
5662 bombout(("expected key exchange packet from server"));
5666 ssh->hostkey = NULL;
5667 s->cscipher_tobe = NULL;
5668 s->sccipher_tobe = NULL;
5669 s->csmac_tobe = NULL;
5670 s->scmac_tobe = NULL;
5671 s->cscomp_tobe = NULL;
5672 s->sccomp_tobe = NULL;
5673 s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
5675 pktin->savedpos += 16; /* skip garbage cookie */
5676 ssh_pkt_getstring(pktin, &str, &len); /* key exchange algorithms */
5679 for (i = 0; i < s->n_preferred_kex; i++) {
5680 const struct ssh_kexes *k = s->preferred_kex[i];
5684 for (j = 0; j < k->nkexes; j++) {
5685 if (!preferred) preferred = k->list[j]->name;
5686 if (in_commasep_string(k->list[j]->name, str, len)) {
5687 ssh->kex = k->list[j];
5696 bombout(("Couldn't agree a key exchange algorithm (available: %s)",
5697 str ? str : "(null)"));
5701 * Note that the server's guess is considered wrong if it doesn't match
5702 * the first algorithm in our list, even if it's still the algorithm
5705 s->guessok = first_in_commasep_string(preferred, str, len);
5706 ssh_pkt_getstring(pktin, &str, &len); /* host key algorithms */
5707 for (i = 0; i < lenof(hostkey_algs); i++) {
5708 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
5709 ssh->hostkey = hostkey_algs[i];
5713 if (!ssh->hostkey) {
5714 bombout(("Couldn't agree a host key algorithm (available: %s)",
5715 str ? str : "(null)"));
5719 s->guessok = s->guessok &&
5720 first_in_commasep_string(hostkey_algs[0]->name, str, len);
5721 ssh_pkt_getstring(pktin, &str, &len); /* client->server cipher */
5722 for (i = 0; i < s->n_preferred_ciphers; i++) {
5723 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5725 s->warn_cscipher = TRUE;
5727 for (j = 0; j < c->nciphers; j++) {
5728 if (in_commasep_string(c->list[j]->name, str, len)) {
5729 s->cscipher_tobe = c->list[j];
5734 if (s->cscipher_tobe)
5737 if (!s->cscipher_tobe) {
5738 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
5739 str ? str : "(null)"));
5743 ssh_pkt_getstring(pktin, &str, &len); /* server->client cipher */
5744 for (i = 0; i < s->n_preferred_ciphers; i++) {
5745 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5747 s->warn_sccipher = TRUE;
5749 for (j = 0; j < c->nciphers; j++) {
5750 if (in_commasep_string(c->list[j]->name, str, len)) {
5751 s->sccipher_tobe = c->list[j];
5756 if (s->sccipher_tobe)
5759 if (!s->sccipher_tobe) {
5760 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
5761 str ? str : "(null)"));
5765 ssh_pkt_getstring(pktin, &str, &len); /* client->server mac */
5766 for (i = 0; i < s->nmacs; i++) {
5767 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5768 s->csmac_tobe = s->maclist[i];
5772 ssh_pkt_getstring(pktin, &str, &len); /* server->client mac */
5773 for (i = 0; i < s->nmacs; i++) {
5774 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5775 s->scmac_tobe = s->maclist[i];
5779 ssh_pkt_getstring(pktin, &str, &len); /* client->server compression */
5780 for (i = 0; i < lenof(compressions) + 1; i++) {
5781 const struct ssh_compress *c =
5782 i == 0 ? s->preferred_comp : compressions[i - 1];
5783 if (in_commasep_string(c->name, str, len)) {
5786 } else if (in_commasep_string(c->delayed_name, str, len)) {
5787 if (s->userauth_succeeded) {
5791 s->pending_compression = TRUE; /* try this later */
5795 ssh_pkt_getstring(pktin, &str, &len); /* server->client compression */
5796 for (i = 0; i < lenof(compressions) + 1; i++) {
5797 const struct ssh_compress *c =
5798 i == 0 ? s->preferred_comp : compressions[i - 1];
5799 if (in_commasep_string(c->name, str, len)) {
5802 } else if (in_commasep_string(c->delayed_name, str, len)) {
5803 if (s->userauth_succeeded) {
5807 s->pending_compression = TRUE; /* try this later */
5811 if (s->pending_compression) {
5812 logevent("Server supports delayed compression; "
5813 "will try this later");
5815 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
5816 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
5817 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
5819 ssh->exhash = ssh->kex->hash->init();
5820 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
5821 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
5822 hash_string(ssh->kex->hash, ssh->exhash,
5823 s->our_kexinit, s->our_kexinitlen);
5824 sfree(s->our_kexinit);
5825 if (pktin->length > 5)
5826 hash_string(ssh->kex->hash, ssh->exhash,
5827 pktin->data + 5, pktin->length - 5);
5830 ssh_set_frozen(ssh, 1);
5831 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
5833 ssh_dialog_callback, ssh);
5834 if (s->dlgret < 0) {
5838 bombout(("Unexpected data from server while"
5839 " waiting for user response"));
5842 } while (pktin || inlen > 0);
5843 s->dlgret = ssh->user_response;
5845 ssh_set_frozen(ssh, 0);
5846 if (s->dlgret == 0) {
5847 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
5853 if (s->warn_cscipher) {
5854 ssh_set_frozen(ssh, 1);
5855 s->dlgret = askalg(ssh->frontend,
5856 "client-to-server cipher",
5857 s->cscipher_tobe->name,
5858 ssh_dialog_callback, ssh);
5859 if (s->dlgret < 0) {
5863 bombout(("Unexpected data from server while"
5864 " waiting for user response"));
5867 } while (pktin || inlen > 0);
5868 s->dlgret = ssh->user_response;
5870 ssh_set_frozen(ssh, 0);
5871 if (s->dlgret == 0) {
5872 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
5878 if (s->warn_sccipher) {
5879 ssh_set_frozen(ssh, 1);
5880 s->dlgret = askalg(ssh->frontend,
5881 "server-to-client cipher",
5882 s->sccipher_tobe->name,
5883 ssh_dialog_callback, ssh);
5884 if (s->dlgret < 0) {
5888 bombout(("Unexpected data from server while"
5889 " waiting for user response"));
5892 } while (pktin || inlen > 0);
5893 s->dlgret = ssh->user_response;
5895 ssh_set_frozen(ssh, 0);
5896 if (s->dlgret == 0) {
5897 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
5903 if (s->ignorepkt) /* first_kex_packet_follows */
5904 crWaitUntilV(pktin); /* Ignore packet */
5907 if (ssh->kex->main_type == KEXTYPE_DH) {
5909 * Work out the number of bits of key we will need from the
5910 * key exchange. We start with the maximum key length of
5916 csbits = s->cscipher_tobe->keylen;
5917 scbits = s->sccipher_tobe->keylen;
5918 s->nbits = (csbits > scbits ? csbits : scbits);
5920 /* The keys only have hlen-bit entropy, since they're based on
5921 * a hash. So cap the key size at hlen bits. */
5922 if (s->nbits > ssh->kex->hash->hlen * 8)
5923 s->nbits = ssh->kex->hash->hlen * 8;
5926 * If we're doing Diffie-Hellman group exchange, start by
5927 * requesting a group.
5929 if (!ssh->kex->pdata) {
5930 logevent("Doing Diffie-Hellman group exchange");
5931 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
5933 * Work out how big a DH group we will need to allow that
5936 s->pbits = 512 << ((s->nbits - 1) / 64);
5937 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
5938 ssh2_pkt_adduint32(s->pktout, s->pbits);
5939 ssh2_pkt_send_noqueue(ssh, s->pktout);
5941 crWaitUntilV(pktin);
5942 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
5943 bombout(("expected key exchange group packet from server"));
5946 s->p = ssh2_pkt_getmp(pktin);
5947 s->g = ssh2_pkt_getmp(pktin);
5948 if (!s->p || !s->g) {
5949 bombout(("unable to read mp-ints from incoming group packet"));
5952 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
5953 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
5954 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
5956 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
5957 ssh->kex_ctx = dh_setup_group(ssh->kex);
5958 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
5959 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
5960 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
5961 ssh->kex->groupname);
5964 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
5965 ssh->kex->hash->text_name);
5967 * Now generate and send e for Diffie-Hellman.
5969 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
5970 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
5971 s->pktout = ssh2_pkt_init(s->kex_init_value);
5972 ssh2_pkt_addmp(s->pktout, s->e);
5973 ssh2_pkt_send_noqueue(ssh, s->pktout);
5975 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
5976 crWaitUntilV(pktin);
5977 if (pktin->type != s->kex_reply_value) {
5978 bombout(("expected key exchange reply packet from server"));
5981 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
5982 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
5983 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
5984 s->f = ssh2_pkt_getmp(pktin);
5986 bombout(("unable to parse key exchange reply packet"));
5989 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
5991 s->K = dh_find_K(ssh->kex_ctx, s->f);
5993 /* We assume everything from now on will be quick, and it might
5994 * involve user interaction. */
5995 set_busy_status(ssh->frontend, BUSY_NOT);
5997 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
5998 if (!ssh->kex->pdata) {
5999 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
6000 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
6001 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
6003 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
6004 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
6006 dh_cleanup(ssh->kex_ctx);
6008 if (!ssh->kex->pdata) {
6013 logeventf(ssh, "Doing RSA key exchange with hash %s",
6014 ssh->kex->hash->text_name);
6015 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
6017 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
6020 crWaitUntilV(pktin);
6021 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
6022 bombout(("expected RSA public key packet from server"));
6026 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6027 hash_string(ssh->kex->hash, ssh->exhash,
6028 s->hostkeydata, s->hostkeylen);
6029 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6033 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
6034 s->rsakeydata = snewn(s->rsakeylen, char);
6035 memcpy(s->rsakeydata, keydata, s->rsakeylen);
6038 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
6040 sfree(s->rsakeydata);
6041 bombout(("unable to parse RSA public key from server"));
6045 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
6048 * Next, set up a shared secret K, of precisely KLEN -
6049 * 2*HLEN - 49 bits, where KLEN is the bit length of the
6050 * RSA key modulus and HLEN is the bit length of the hash
6054 int klen = ssh_rsakex_klen(s->rsakey);
6055 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
6057 unsigned char *kstr1, *kstr2, *outstr;
6058 int kstr1len, kstr2len, outstrlen;
6060 s->K = bn_power_2(nbits - 1);
6062 for (i = 0; i < nbits; i++) {
6064 byte = random_byte();
6066 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
6070 * Encode this as an mpint.
6072 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
6073 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
6074 PUT_32BIT(kstr2, kstr1len);
6075 memcpy(kstr2 + 4, kstr1, kstr1len);
6078 * Encrypt it with the given RSA key.
6080 outstrlen = (klen + 7) / 8;
6081 outstr = snewn(outstrlen, unsigned char);
6082 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
6083 outstr, outstrlen, s->rsakey);
6086 * And send it off in a return packet.
6088 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
6089 ssh2_pkt_addstring_start(s->pktout);
6090 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
6091 ssh2_pkt_send_noqueue(ssh, s->pktout);
6093 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
6100 ssh_rsakex_freekey(s->rsakey);
6102 crWaitUntilV(pktin);
6103 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
6104 sfree(s->rsakeydata);
6105 bombout(("expected signature packet from server"));
6109 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6111 sfree(s->rsakeydata);
6114 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
6115 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
6116 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
6118 ssh->kex_ctx = NULL;
6121 debug(("Exchange hash is:\n"));
6122 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
6126 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
6127 (char *)s->exchange_hash,
6128 ssh->kex->hash->hlen)) {
6129 bombout(("Server's host key did not match the signature supplied"));
6133 s->keystr = ssh->hostkey->fmtkey(s->hkey);
6134 if (!s->got_session_id) {
6136 * Authenticate remote host: verify host key. (We've already
6137 * checked the signature of the exchange hash.)
6139 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
6140 ssh_set_frozen(ssh, 1);
6141 s->dlgret = verify_ssh_host_key(ssh->frontend,
6142 ssh->savedhost, ssh->savedport,
6143 ssh->hostkey->keytype, s->keystr,
6145 ssh_dialog_callback, ssh);
6146 if (s->dlgret < 0) {
6150 bombout(("Unexpected data from server while waiting"
6151 " for user host key response"));
6154 } while (pktin || inlen > 0);
6155 s->dlgret = ssh->user_response;
6157 ssh_set_frozen(ssh, 0);
6158 if (s->dlgret == 0) {
6159 ssh_disconnect(ssh, "User aborted at host key verification", NULL,
6163 logevent("Host key fingerprint is:");
6164 logevent(s->fingerprint);
6165 sfree(s->fingerprint);
6167 * Save this host key, to check against the one presented in
6168 * subsequent rekeys.
6170 ssh->hostkey_str = s->keystr;
6173 * In a rekey, we never present an interactive host key
6174 * verification request to the user. Instead, we simply
6175 * enforce that the key we're seeing this time is identical to
6176 * the one we saw before.
6178 if (strcmp(ssh->hostkey_str, s->keystr)) {
6179 bombout(("Host key was different in repeat key exchange"));
6184 ssh->hostkey->freekey(s->hkey);
6187 * The exchange hash from the very first key exchange is also
6188 * the session id, used in session key construction and
6191 if (!s->got_session_id) {
6192 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
6193 memcpy(ssh->v2_session_id, s->exchange_hash,
6194 sizeof(s->exchange_hash));
6195 ssh->v2_session_id_len = ssh->kex->hash->hlen;
6196 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
6197 s->got_session_id = TRUE;
6201 * Send SSH2_MSG_NEWKEYS.
6203 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
6204 ssh2_pkt_send_noqueue(ssh, s->pktout);
6205 ssh->outgoing_data_size = 0; /* start counting from here */
6208 * We've sent client NEWKEYS, so create and initialise
6209 * client-to-server session keys.
6211 if (ssh->cs_cipher_ctx)
6212 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
6213 ssh->cscipher = s->cscipher_tobe;
6214 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
6216 if (ssh->cs_mac_ctx)
6217 ssh->csmac->free_context(ssh->cs_mac_ctx);
6218 ssh->csmac = s->csmac_tobe;
6219 ssh->cs_mac_ctx = ssh->csmac->make_context();
6221 if (ssh->cs_comp_ctx)
6222 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
6223 ssh->cscomp = s->cscomp_tobe;
6224 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
6227 * Set IVs on client-to-server keys. Here we use the exchange
6228 * hash from the _first_ key exchange.
6231 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6232 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6233 ssh2_mkkey(ssh,s->K,s->exchange_hash,'C',keyspace);
6234 assert((ssh->cscipher->keylen+7) / 8 <=
6235 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6236 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
6237 ssh2_mkkey(ssh,s->K,s->exchange_hash,'A',keyspace);
6238 assert(ssh->cscipher->blksize <=
6239 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6240 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
6241 ssh2_mkkey(ssh,s->K,s->exchange_hash,'E',keyspace);
6242 assert(ssh->csmac->len <=
6243 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6244 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
6245 smemclr(keyspace, sizeof(keyspace));
6248 logeventf(ssh, "Initialised %.200s client->server encryption",
6249 ssh->cscipher->text_name);
6250 logeventf(ssh, "Initialised %.200s client->server MAC algorithm",
6251 ssh->csmac->text_name);
6252 if (ssh->cscomp->text_name)
6253 logeventf(ssh, "Initialised %s compression",
6254 ssh->cscomp->text_name);
6257 * Now our end of the key exchange is complete, we can send all
6258 * our queued higher-layer packets.
6260 ssh->queueing = FALSE;
6261 ssh2_pkt_queuesend(ssh);
6264 * Expect SSH2_MSG_NEWKEYS from server.
6266 crWaitUntilV(pktin);
6267 if (pktin->type != SSH2_MSG_NEWKEYS) {
6268 bombout(("expected new-keys packet from server"));
6271 ssh->incoming_data_size = 0; /* start counting from here */
6274 * We've seen server NEWKEYS, so create and initialise
6275 * server-to-client session keys.
6277 if (ssh->sc_cipher_ctx)
6278 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
6279 ssh->sccipher = s->sccipher_tobe;
6280 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
6282 if (ssh->sc_mac_ctx)
6283 ssh->scmac->free_context(ssh->sc_mac_ctx);
6284 ssh->scmac = s->scmac_tobe;
6285 ssh->sc_mac_ctx = ssh->scmac->make_context();
6287 if (ssh->sc_comp_ctx)
6288 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
6289 ssh->sccomp = s->sccomp_tobe;
6290 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
6293 * Set IVs on server-to-client keys. Here we use the exchange
6294 * hash from the _first_ key exchange.
6297 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6298 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6299 ssh2_mkkey(ssh,s->K,s->exchange_hash,'D',keyspace);
6300 assert((ssh->sccipher->keylen+7) / 8 <=
6301 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6302 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
6303 ssh2_mkkey(ssh,s->K,s->exchange_hash,'B',keyspace);
6304 assert(ssh->sccipher->blksize <=
6305 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6306 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
6307 ssh2_mkkey(ssh,s->K,s->exchange_hash,'F',keyspace);
6308 assert(ssh->scmac->len <=
6309 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6310 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
6311 smemclr(keyspace, sizeof(keyspace));
6313 logeventf(ssh, "Initialised %.200s server->client encryption",
6314 ssh->sccipher->text_name);
6315 logeventf(ssh, "Initialised %.200s server->client MAC algorithm",
6316 ssh->scmac->text_name);
6317 if (ssh->sccomp->text_name)
6318 logeventf(ssh, "Initialised %s decompression",
6319 ssh->sccomp->text_name);
6322 * Free shared secret.
6327 * Key exchange is over. Loop straight back round if we have a
6328 * deferred rekey reason.
6330 if (ssh->deferred_rekey_reason) {
6331 logevent(ssh->deferred_rekey_reason);
6333 ssh->deferred_rekey_reason = NULL;
6334 goto begin_key_exchange;
6338 * Otherwise, schedule a timer for our next rekey.
6340 ssh->kex_in_progress = FALSE;
6341 ssh->last_rekey = GETTICKCOUNT();
6342 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
6343 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
6347 * Now we're encrypting. Begin returning 1 to the protocol main
6348 * function so that other things can run on top of the
6349 * transport. If we ever see a KEXINIT, we must go back to the
6352 * We _also_ go back to the start if we see pktin==NULL and
6353 * inlen negative, because this is a special signal meaning
6354 * `initiate client-driven rekey', and `in' contains a message
6355 * giving the reason for the rekey.
6357 * inlen==-1 means always initiate a rekey;
6358 * inlen==-2 means that userauth has completed successfully and
6359 * we should consider rekeying (for delayed compression).
6361 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
6362 (!pktin && inlen < 0))) {
6364 if (!ssh->protocol_initial_phase_done) {
6365 ssh->protocol_initial_phase_done = TRUE;
6367 * Allow authconn to initialise itself.
6369 do_ssh2_authconn(ssh, NULL, 0, NULL);
6374 logevent("Server initiated key re-exchange");
6378 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
6379 * delayed compression, if it's available.
6381 * draft-miller-secsh-compression-delayed-00 says that you
6382 * negotiate delayed compression in the first key exchange, and
6383 * both sides start compressing when the server has sent
6384 * USERAUTH_SUCCESS. This has a race condition -- the server
6385 * can't know when the client has seen it, and thus which incoming
6386 * packets it should treat as compressed.
6388 * Instead, we do the initial key exchange without offering the
6389 * delayed methods, but note if the server offers them; when we
6390 * get here, if a delayed method was available that was higher
6391 * on our list than what we got, we initiate a rekey in which we
6392 * _do_ list the delayed methods (and hopefully get it as a
6393 * result). Subsequent rekeys will do the same.
6395 assert(!s->userauth_succeeded); /* should only happen once */
6396 s->userauth_succeeded = TRUE;
6397 if (!s->pending_compression)
6398 /* Can't see any point rekeying. */
6399 goto wait_for_rekey; /* this is utterly horrid */
6400 /* else fall through to rekey... */
6401 s->pending_compression = FALSE;
6404 * Now we've decided to rekey.
6406 * Special case: if the server bug is set that doesn't
6407 * allow rekeying, we give a different log message and
6408 * continue waiting. (If such a server _initiates_ a rekey,
6409 * we process it anyway!)
6411 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
6412 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
6414 /* Reset the counters, so that at least this message doesn't
6415 * hit the event log _too_ often. */
6416 ssh->outgoing_data_size = 0;
6417 ssh->incoming_data_size = 0;
6418 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
6420 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
6423 goto wait_for_rekey; /* this is still utterly horrid */
6425 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
6428 goto begin_key_exchange;
6434 * Add data to an SSH-2 channel output buffer.
6436 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
6439 bufchain_add(&c->v.v2.outbuffer, buf, len);
6443 * Attempt to send data on an SSH-2 channel.
6445 static int ssh2_try_send(struct ssh_channel *c)
6448 struct Packet *pktout;
6451 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
6454 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
6455 if ((unsigned)len > c->v.v2.remwindow)
6456 len = c->v.v2.remwindow;
6457 if ((unsigned)len > c->v.v2.remmaxpkt)
6458 len = c->v.v2.remmaxpkt;
6459 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
6460 ssh2_pkt_adduint32(pktout, c->remoteid);
6461 ssh2_pkt_addstring_start(pktout);
6462 dont_log_data(ssh, pktout, PKTLOG_OMIT);
6463 ssh2_pkt_addstring_data(pktout, data, len);
6464 end_log_omission(ssh, pktout);
6465 ssh2_pkt_send(ssh, pktout);
6466 bufchain_consume(&c->v.v2.outbuffer, len);
6467 c->v.v2.remwindow -= len;
6471 * After having sent as much data as we can, return the amount
6474 ret = bufchain_size(&c->v.v2.outbuffer);
6477 * And if there's no data pending but we need to send an EOF, send
6480 if (!ret && c->pending_eof)
6481 ssh_channel_try_eof(c);
6486 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
6489 if (c->closes & CLOSES_SENT_EOF)
6490 return; /* don't send on channels we've EOFed */
6491 bufsize = ssh2_try_send(c);
6494 case CHAN_MAINSESSION:
6495 /* stdin need not receive an unthrottle
6496 * notification since it will be polled */
6499 x11_unthrottle(c->u.x11.s);
6502 /* agent sockets are request/response and need no
6503 * buffer management */
6506 pfd_unthrottle(c->u.pfd.s);
6513 * Set up most of a new ssh_channel for SSH-2.
6515 static void ssh2_channel_init(struct ssh_channel *c)
6518 c->localid = alloc_channel_id(ssh);
6520 c->pending_eof = FALSE;
6521 c->throttling_conn = FALSE;
6522 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
6523 conf_get_int(ssh->conf, CONF_ssh_simple) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
6524 c->v.v2.chanreq_head = NULL;
6525 c->v.v2.throttle_state = UNTHROTTLED;
6526 bufchain_init(&c->v.v2.outbuffer);
6530 * Construct the common parts of a CHANNEL_OPEN.
6532 static struct Packet *ssh2_chanopen_init(struct ssh_channel *c, char *type)
6534 struct Packet *pktout;
6536 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
6537 ssh2_pkt_addstring(pktout, type);
6538 ssh2_pkt_adduint32(pktout, c->localid);
6539 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
6540 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
6545 * CHANNEL_FAILURE doesn't come with any indication of what message
6546 * caused it, so we have to keep track of the outstanding
6547 * CHANNEL_REQUESTs ourselves.
6549 static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
6550 cchandler_fn_t handler, void *ctx)
6552 struct outstanding_channel_request *ocr =
6553 snew(struct outstanding_channel_request);
6555 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
6556 ocr->handler = handler;
6559 if (!c->v.v2.chanreq_head)
6560 c->v.v2.chanreq_head = ocr;
6562 c->v.v2.chanreq_tail->next = ocr;
6563 c->v.v2.chanreq_tail = ocr;
6567 * Construct the common parts of a CHANNEL_REQUEST. If handler is not
6568 * NULL then a reply will be requested and the handler will be called
6569 * when it arrives. The returned packet is ready to have any
6570 * request-specific data added and be sent. Note that if a handler is
6571 * provided, it's essential that the request actually be sent.
6573 * The handler will usually be passed the response packet in pktin.
6574 * If pktin is NULL, this means that no reply will ever be forthcoming
6575 * (e.g. because the entire connection is being destroyed) and the
6576 * handler should free any storage it's holding.
6578 static struct Packet *ssh2_chanreq_init(struct ssh_channel *c, char *type,
6579 cchandler_fn_t handler, void *ctx)
6581 struct Packet *pktout;
6583 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
6584 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6585 ssh2_pkt_adduint32(pktout, c->remoteid);
6586 ssh2_pkt_addstring(pktout, type);
6587 ssh2_pkt_addbool(pktout, handler != NULL);
6588 if (handler != NULL)
6589 ssh2_queue_chanreq_handler(c, handler, ctx);
6594 * Potentially enlarge the window on an SSH-2 channel.
6596 static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
6598 static void ssh2_set_window(struct ssh_channel *c, int newwin)
6603 * Never send WINDOW_ADJUST for a channel that the remote side has
6604 * already sent EOF on; there's no point, since it won't be
6605 * sending any more data anyway. Ditto if _we've_ already sent
6608 if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
6612 * If the remote end has a habit of ignoring maxpkt, limit the
6613 * window so that it has no choice (assuming it doesn't ignore the
6616 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
6617 newwin = OUR_V2_MAXPKT;
6620 * Only send a WINDOW_ADJUST if there's significantly more window
6621 * available than the other end thinks there is. This saves us
6622 * sending a WINDOW_ADJUST for every character in a shell session.
6624 * "Significant" is arbitrarily defined as half the window size.
6626 if (newwin / 2 >= c->v.v2.locwindow) {
6627 struct Packet *pktout;
6631 * In order to keep track of how much window the client
6632 * actually has available, we'd like it to acknowledge each
6633 * WINDOW_ADJUST. We can't do that directly, so we accompany
6634 * it with a CHANNEL_REQUEST that has to be acknowledged.
6636 * This is only necessary if we're opening the window wide.
6637 * If we're not, then throughput is being constrained by
6638 * something other than the maximum window size anyway.
6640 if (newwin == c->v.v2.locmaxwin &&
6641 !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
6642 up = snew(unsigned);
6643 *up = newwin - c->v.v2.locwindow;
6644 pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org",
6645 ssh2_handle_winadj_response, up);
6646 ssh2_pkt_send(ssh, pktout);
6648 if (c->v.v2.throttle_state != UNTHROTTLED)
6649 c->v.v2.throttle_state = UNTHROTTLING;
6651 /* Pretend the WINDOW_ADJUST was acked immediately. */
6652 c->v.v2.remlocwin = newwin;
6653 c->v.v2.throttle_state = THROTTLED;
6655 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
6656 ssh2_pkt_adduint32(pktout, c->remoteid);
6657 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
6658 ssh2_pkt_send(ssh, pktout);
6659 c->v.v2.locwindow = newwin;
6664 * Find the channel associated with a message. If there's no channel,
6665 * or it's not properly open, make a noise about it and return NULL.
6667 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
6669 unsigned localid = ssh_pkt_getuint32(pktin);
6670 struct ssh_channel *c;
6672 c = find234(ssh->channels, &localid, ssh_channelfind);
6674 (c->halfopen && pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
6675 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
6676 char *buf = dupprintf("Received %s for %s channel %u",
6677 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
6679 c ? "half-open" : "nonexistent", localid);
6680 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6687 static void ssh2_handle_winadj_response(struct ssh_channel *c,
6688 struct Packet *pktin, void *ctx)
6690 unsigned *sizep = ctx;
6693 * Winadj responses should always be failures. However, at least
6694 * one server ("boks_sshd") is known to return SUCCESS for channel
6695 * requests it's never heard of, such as "winadj@putty". Raised
6696 * with foxt.com as bug 090916-090424, but for the sake of a quiet
6697 * life, we don't worry about what kind of response we got.
6700 c->v.v2.remlocwin += *sizep;
6703 * winadj messages are only sent when the window is fully open, so
6704 * if we get an ack of one, we know any pending unthrottle is
6707 if (c->v.v2.throttle_state == UNTHROTTLING)
6708 c->v.v2.throttle_state = UNTHROTTLED;
6711 static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
6713 struct ssh_channel *c = ssh2_channel_msg(ssh, pktin);
6714 struct outstanding_channel_request *ocr;
6717 ocr = c->v.v2.chanreq_head;
6719 ssh2_msg_unexpected(ssh, pktin);
6722 ocr->handler(c, pktin, ocr->ctx);
6723 c->v.v2.chanreq_head = ocr->next;
6726 * We may now initiate channel-closing procedures, if that
6727 * CHANNEL_REQUEST was the last thing outstanding before we send
6730 ssh2_channel_check_close(c);
6733 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
6735 struct ssh_channel *c;
6736 c = ssh2_channel_msg(ssh, pktin);
6739 if (!(c->closes & CLOSES_SENT_EOF)) {
6740 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
6741 ssh2_try_send_and_unthrottle(ssh, c);
6745 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
6749 struct ssh_channel *c;
6750 c = ssh2_channel_msg(ssh, pktin);
6753 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
6754 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
6755 return; /* extended but not stderr */
6756 ssh_pkt_getstring(pktin, &data, &length);
6759 c->v.v2.locwindow -= length;
6760 c->v.v2.remlocwin -= length;
6762 case CHAN_MAINSESSION:
6764 from_backend(ssh->frontend, pktin->type ==
6765 SSH2_MSG_CHANNEL_EXTENDED_DATA,
6769 bufsize = x11_send(c->u.x11.s, data, length);
6772 bufsize = pfd_send(c->u.pfd.s, data, length);
6775 while (length > 0) {
6776 if (c->u.a.lensofar < 4) {
6777 unsigned int l = min(4 - c->u.a.lensofar,
6779 memcpy(c->u.a.msglen + c->u.a.lensofar,
6783 c->u.a.lensofar += l;
6785 if (c->u.a.lensofar == 4) {
6787 4 + GET_32BIT(c->u.a.msglen);
6788 c->u.a.message = snewn(c->u.a.totallen,
6790 memcpy(c->u.a.message, c->u.a.msglen, 4);
6792 if (c->u.a.lensofar >= 4 && length > 0) {
6794 min(c->u.a.totallen - c->u.a.lensofar,
6796 memcpy(c->u.a.message + c->u.a.lensofar,
6800 c->u.a.lensofar += l;
6802 if (c->u.a.lensofar == c->u.a.totallen) {
6805 c->u.a.outstanding_requests++;
6806 if (agent_query(c->u.a.message,
6809 ssh_agentf_callback, c))
6810 ssh_agentf_callback(c, reply, replylen);
6811 sfree(c->u.a.message);
6812 c->u.a.message = NULL;
6813 c->u.a.lensofar = 0;
6820 * If it looks like the remote end hit the end of its window,
6821 * and we didn't want it to do that, think about using a
6824 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
6825 c->v.v2.locmaxwin < 0x40000000)
6826 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
6828 * If we are not buffering too much data,
6829 * enlarge the window again at the remote side.
6830 * If we are buffering too much, we may still
6831 * need to adjust the window if the server's
6834 ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
6835 c->v.v2.locmaxwin - bufsize : 0);
6837 * If we're either buffering way too much data, or if we're
6838 * buffering anything at all and we're in "simple" mode,
6839 * throttle the whole channel.
6841 if ((bufsize > c->v.v2.locmaxwin ||
6842 (conf_get_int(ssh->conf, CONF_ssh_simple) && bufsize > 0)) &&
6843 !c->throttling_conn) {
6844 c->throttling_conn = 1;
6845 ssh_throttle_conn(ssh, +1);
6850 static void ssh_channel_destroy(struct ssh_channel *c)
6855 case CHAN_MAINSESSION:
6856 ssh->mainchan = NULL;
6857 update_specials_menu(ssh->frontend);
6860 if (c->u.x11.s != NULL)
6861 x11_close(c->u.x11.s);
6862 logevent("Forwarded X11 connection terminated");
6865 sfree(c->u.a.message);
6868 if (c->u.pfd.s != NULL)
6869 pfd_close(c->u.pfd.s);
6870 logevent("Forwarded port closed");
6874 del234(ssh->channels, c);
6875 if (ssh->version == 2) {
6876 bufchain_clear(&c->v.v2.outbuffer);
6877 assert(c->v.v2.chanreq_head == NULL);
6882 * See if that was the last channel left open.
6883 * (This is only our termination condition if we're
6884 * not running in -N mode.)
6886 if (ssh->version == 2 &&
6887 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
6888 count234(ssh->channels) == 0) {
6890 * We used to send SSH_MSG_DISCONNECT here,
6891 * because I'd believed that _every_ conforming
6892 * SSH-2 connection had to end with a disconnect
6893 * being sent by at least one side; apparently
6894 * I was wrong and it's perfectly OK to
6895 * unceremoniously slam the connection shut
6896 * when you're done, and indeed OpenSSH feels
6897 * this is more polite than sending a
6898 * DISCONNECT. So now we don't.
6900 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
6904 static void ssh2_channel_check_close(struct ssh_channel *c)
6907 struct Packet *pktout;
6911 * If we've sent out our own CHANNEL_OPEN but not yet seen
6912 * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
6913 * it's too early to be sending close messages of any kind.
6918 if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
6919 c->type == CHAN_ZOMBIE) &&
6920 !c->v.v2.chanreq_head &&
6921 !(c->closes & CLOSES_SENT_CLOSE)) {
6923 * We have both sent and received EOF (or the channel is a
6924 * zombie), and we have no outstanding channel requests, which
6925 * means the channel is in final wind-up. But we haven't sent
6926 * CLOSE, so let's do so now.
6928 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
6929 ssh2_pkt_adduint32(pktout, c->remoteid);
6930 ssh2_pkt_send(ssh, pktout);
6931 c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
6934 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
6935 assert(c->v.v2.chanreq_head == NULL);
6937 * We have both sent and received CLOSE, which means we're
6938 * completely done with the channel.
6940 ssh_channel_destroy(c);
6944 static void ssh2_channel_got_eof(struct ssh_channel *c)
6946 if (c->closes & CLOSES_RCVD_EOF)
6947 return; /* already seen EOF */
6948 c->closes |= CLOSES_RCVD_EOF;
6950 if (c->type == CHAN_X11) {
6951 x11_send_eof(c->u.x11.s);
6952 } else if (c->type == CHAN_AGENT) {
6953 if (c->u.a.outstanding_requests == 0) {
6954 /* Manufacture an outgoing EOF in response to the incoming one. */
6955 sshfwd_write_eof(c);
6957 } else if (c->type == CHAN_SOCKDATA) {
6958 pfd_send_eof(c->u.pfd.s);
6959 } else if (c->type == CHAN_MAINSESSION) {
6962 if (!ssh->sent_console_eof &&
6963 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
6965 * Either from_backend_eof told us that the front end
6966 * wants us to close the outgoing side of the connection
6967 * as soon as we see EOF from the far end, or else we've
6968 * unilaterally decided to do that because we've allocated
6969 * a remote pty and hence EOF isn't a particularly
6970 * meaningful concept.
6972 sshfwd_write_eof(c);
6974 ssh->sent_console_eof = TRUE;
6977 ssh2_channel_check_close(c);
6980 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
6982 struct ssh_channel *c;
6984 c = ssh2_channel_msg(ssh, pktin);
6987 ssh2_channel_got_eof(c);
6990 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
6992 struct ssh_channel *c;
6994 c = ssh2_channel_msg(ssh, pktin);
6999 * When we receive CLOSE on a channel, we assume it comes with an
7000 * implied EOF if we haven't seen EOF yet.
7002 ssh2_channel_got_eof(c);
7005 * And we also send an outgoing EOF, if we haven't already, on the
7006 * assumption that CLOSE is a pretty forceful announcement that
7007 * the remote side is doing away with the entire channel. (If it
7008 * had wanted to send us EOF and continue receiving data from us,
7009 * it would have just sent CHANNEL_EOF.)
7011 if (!(c->closes & CLOSES_SENT_EOF)) {
7013 * Make sure we don't read any more from whatever our local
7014 * data source is for this channel.
7017 case CHAN_MAINSESSION:
7018 ssh->send_ok = 0; /* stop trying to read from stdin */
7021 x11_override_throttle(c->u.x11.s, 1);
7024 pfd_override_throttle(c->u.pfd.s, 1);
7029 * Abandon any buffered data we still wanted to send to this
7030 * channel. Receiving a CHANNEL_CLOSE is an indication that
7031 * the server really wants to get on and _destroy_ this
7032 * channel, and it isn't going to send us any further
7033 * WINDOW_ADJUSTs to permit us to send pending stuff.
7035 bufchain_clear(&c->v.v2.outbuffer);
7038 * Send outgoing EOF.
7040 sshfwd_write_eof(c);
7044 * Now process the actual close.
7046 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
7047 c->closes |= CLOSES_RCVD_CLOSE;
7048 ssh2_channel_check_close(c);
7052 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
7054 struct ssh_channel *c;
7056 c = ssh2_channel_msg(ssh, pktin);
7059 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
7060 c->remoteid = ssh_pkt_getuint32(pktin);
7061 c->halfopen = FALSE;
7062 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
7063 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
7065 if (c->type == CHAN_SOCKDATA_DORMANT) {
7066 c->type = CHAN_SOCKDATA;
7068 pfd_confirm(c->u.pfd.s);
7069 } else if (c->type == CHAN_ZOMBIE) {
7071 * This case can occur if a local socket error occurred
7072 * between us sending out CHANNEL_OPEN and receiving
7073 * OPEN_CONFIRMATION. In this case, all we can do is
7074 * immediately initiate close proceedings now that we know the
7075 * server's id to put in the close message.
7077 ssh2_channel_check_close(c);
7080 * We never expect to receive OPEN_CONFIRMATION for any
7081 * *other* channel type (since only local-to-remote port
7082 * forwardings cause us to send CHANNEL_OPEN after the main
7083 * channel is live - all other auxiliary channel types are
7084 * initiated from the server end). It's safe to enforce this
7085 * by assertion rather than by ssh_disconnect, because the
7086 * real point is that we never constructed a half-open channel
7087 * structure in the first place with any type other than the
7090 assert(!"Funny channel type in ssh2_msg_channel_open_confirmation");
7094 ssh_channel_try_eof(c); /* in case we had a pending EOF */
7097 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
7099 static const char *const reasons[] = {
7100 "<unknown reason code>",
7101 "Administratively prohibited",
7103 "Unknown channel type",
7104 "Resource shortage",
7106 unsigned reason_code;
7107 char *reason_string;
7109 struct ssh_channel *c;
7111 c = ssh2_channel_msg(ssh, pktin);
7114 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
7116 if (c->type == CHAN_SOCKDATA_DORMANT) {
7117 reason_code = ssh_pkt_getuint32(pktin);
7118 if (reason_code >= lenof(reasons))
7119 reason_code = 0; /* ensure reasons[reason_code] in range */
7120 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
7121 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
7122 reasons[reason_code], reason_length, reason_string);
7124 pfd_close(c->u.pfd.s);
7125 } else if (c->type == CHAN_ZOMBIE) {
7127 * This case can occur if a local socket error occurred
7128 * between us sending out CHANNEL_OPEN and receiving
7129 * OPEN_FAILURE. In this case, we need do nothing except allow
7130 * the code below to throw the half-open channel away.
7134 * We never expect to receive OPEN_FAILURE for any *other*
7135 * channel type (since only local-to-remote port forwardings
7136 * cause us to send CHANNEL_OPEN after the main channel is
7137 * live - all other auxiliary channel types are initiated from
7138 * the server end). It's safe to enforce this by assertion
7139 * rather than by ssh_disconnect, because the real point is
7140 * that we never constructed a half-open channel structure in
7141 * the first place with any type other than the above.
7143 assert(!"Funny channel type in ssh2_msg_channel_open_failure");
7146 del234(ssh->channels, c);
7150 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
7153 int typelen, want_reply;
7154 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
7155 struct ssh_channel *c;
7156 struct Packet *pktout;
7158 c = ssh2_channel_msg(ssh, pktin);
7161 ssh_pkt_getstring(pktin, &type, &typelen);
7162 want_reply = ssh2_pkt_getbool(pktin);
7165 * Having got the channel number, we now look at
7166 * the request type string to see if it's something
7169 if (c == ssh->mainchan) {
7171 * We recognise "exit-status" and "exit-signal" on
7172 * the primary channel.
7174 if (typelen == 11 &&
7175 !memcmp(type, "exit-status", 11)) {
7177 ssh->exitcode = ssh_pkt_getuint32(pktin);
7178 logeventf(ssh, "Server sent command exit status %d",
7180 reply = SSH2_MSG_CHANNEL_SUCCESS;
7182 } else if (typelen == 11 &&
7183 !memcmp(type, "exit-signal", 11)) {
7185 int is_plausible = TRUE, is_int = FALSE;
7186 char *fmt_sig = "", *fmt_msg = "";
7188 int msglen = 0, core = FALSE;
7189 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
7190 * provide an `int' for the signal, despite its
7191 * having been a `string' in the drafts of RFC 4254 since at
7192 * least 2001. (Fixed in session.c 1.147.) Try to
7193 * infer which we can safely parse it as. */
7195 unsigned char *p = pktin->body +
7197 long len = pktin->length - pktin->savedpos;
7198 unsigned long num = GET_32BIT(p); /* what is it? */
7199 /* If it's 0, it hardly matters; assume string */
7203 int maybe_int = FALSE, maybe_str = FALSE;
7204 #define CHECK_HYPOTHESIS(offset, result) \
7207 int q = toint(offset); \
7208 if (q >= 0 && q+4 <= len) { \
7209 q = toint(q + 4 + GET_32BIT(p+q)); \
7210 if (q >= 0 && q+4 <= len && \
7211 ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
7216 CHECK_HYPOTHESIS(4+1, maybe_int);
7217 CHECK_HYPOTHESIS(4+num+1, maybe_str);
7218 #undef CHECK_HYPOTHESIS
7219 if (maybe_int && !maybe_str)
7221 else if (!maybe_int && maybe_str)
7224 /* Crikey. Either or neither. Panic. */
7225 is_plausible = FALSE;
7228 ssh->exitcode = 128; /* means `unknown signal' */
7231 /* Old non-standard OpenSSH. */
7232 int signum = ssh_pkt_getuint32(pktin);
7233 fmt_sig = dupprintf(" %d", signum);
7234 ssh->exitcode = 128 + signum;
7236 /* As per RFC 4254. */
7239 ssh_pkt_getstring(pktin, &sig, &siglen);
7240 /* Signal name isn't supposed to be blank, but
7241 * let's cope gracefully if it is. */
7243 fmt_sig = dupprintf(" \"%.*s\"",
7248 * Really hideous method of translating the
7249 * signal description back into a locally
7250 * meaningful number.
7255 #define TRANSLATE_SIGNAL(s) \
7256 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
7257 ssh->exitcode = 128 + SIG ## s
7259 TRANSLATE_SIGNAL(ABRT);
7262 TRANSLATE_SIGNAL(ALRM);
7265 TRANSLATE_SIGNAL(FPE);
7268 TRANSLATE_SIGNAL(HUP);
7271 TRANSLATE_SIGNAL(ILL);
7274 TRANSLATE_SIGNAL(INT);
7277 TRANSLATE_SIGNAL(KILL);
7280 TRANSLATE_SIGNAL(PIPE);
7283 TRANSLATE_SIGNAL(QUIT);
7286 TRANSLATE_SIGNAL(SEGV);
7289 TRANSLATE_SIGNAL(TERM);
7292 TRANSLATE_SIGNAL(USR1);
7295 TRANSLATE_SIGNAL(USR2);
7297 #undef TRANSLATE_SIGNAL
7299 ssh->exitcode = 128;
7301 core = ssh2_pkt_getbool(pktin);
7302 ssh_pkt_getstring(pktin, &msg, &msglen);
7304 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
7306 /* ignore lang tag */
7307 } /* else don't attempt to parse */
7308 logeventf(ssh, "Server exited on signal%s%s%s",
7309 fmt_sig, core ? " (core dumped)" : "",
7311 if (*fmt_sig) sfree(fmt_sig);
7312 if (*fmt_msg) sfree(fmt_msg);
7313 reply = SSH2_MSG_CHANNEL_SUCCESS;
7318 * This is a channel request we don't know
7319 * about, so we now either ignore the request
7320 * or respond with CHANNEL_FAILURE, depending
7323 reply = SSH2_MSG_CHANNEL_FAILURE;
7326 pktout = ssh2_pkt_init(reply);
7327 ssh2_pkt_adduint32(pktout, c->remoteid);
7328 ssh2_pkt_send(ssh, pktout);
7332 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
7335 int typelen, want_reply;
7336 struct Packet *pktout;
7338 ssh_pkt_getstring(pktin, &type, &typelen);
7339 want_reply = ssh2_pkt_getbool(pktin);
7342 * We currently don't support any global requests
7343 * at all, so we either ignore the request or
7344 * respond with REQUEST_FAILURE, depending on
7348 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
7349 ssh2_pkt_send(ssh, pktout);
7353 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
7361 struct ssh_channel *c;
7362 unsigned remid, winsize, pktsize;
7363 struct Packet *pktout;
7365 ssh_pkt_getstring(pktin, &type, &typelen);
7366 c = snew(struct ssh_channel);
7369 remid = ssh_pkt_getuint32(pktin);
7370 winsize = ssh_pkt_getuint32(pktin);
7371 pktsize = ssh_pkt_getuint32(pktin);
7373 if (typelen == 3 && !memcmp(type, "x11", 3)) {
7377 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
7378 addrstr = snewn(peeraddrlen+1, char);
7379 memcpy(addrstr, peeraddr, peeraddrlen);
7380 addrstr[peeraddrlen] = '\0';
7381 peerport = ssh_pkt_getuint32(pktin);
7383 logeventf(ssh, "Received X11 connect request from %s:%d",
7386 if (!ssh->X11_fwd_enabled)
7387 error = "X11 forwarding is not enabled";
7388 else if ((x11err = x11_init(&c->u.x11.s, ssh->x11disp, c,
7389 addrstr, peerport, ssh->conf)) != NULL) {
7390 logeventf(ssh, "Local X11 connection failed: %s", x11err);
7391 error = "Unable to open an X11 connection";
7393 logevent("Opening X11 forward connection succeeded");
7398 } else if (typelen == 15 &&
7399 !memcmp(type, "forwarded-tcpip", 15)) {
7400 struct ssh_rportfwd pf, *realpf;
7403 ssh_pkt_getstring(pktin, &shost, &shostlen);/* skip address */
7404 pf.shost = dupprintf("%.*s", shostlen, shost);
7405 pf.sport = ssh_pkt_getuint32(pktin);
7406 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
7407 peerport = ssh_pkt_getuint32(pktin);
7408 realpf = find234(ssh->rportfwds, &pf, NULL);
7409 logeventf(ssh, "Received remote port %s:%d open request "
7410 "from %s:%d", pf.shost, pf.sport, peeraddr, peerport);
7413 if (realpf == NULL) {
7414 error = "Remote port is not recognised";
7416 const char *e = pfd_newconnect(&c->u.pfd.s,
7420 realpf->pfrec->addressfamily);
7421 logeventf(ssh, "Attempting to forward remote port to "
7422 "%s:%d", realpf->dhost, realpf->dport);
7424 logeventf(ssh, "Port open failed: %s", e);
7425 error = "Port open failed";
7427 logevent("Forwarded port opened successfully");
7428 c->type = CHAN_SOCKDATA;
7431 } else if (typelen == 22 &&
7432 !memcmp(type, "auth-agent@openssh.com", 22)) {
7433 if (!ssh->agentfwd_enabled)
7434 error = "Agent forwarding is not enabled";
7436 c->type = CHAN_AGENT; /* identify channel type */
7437 c->u.a.lensofar = 0;
7438 c->u.a.message = NULL;
7439 c->u.a.outstanding_requests = 0;
7442 error = "Unsupported channel type requested";
7445 c->remoteid = remid;
7446 c->halfopen = FALSE;
7448 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
7449 ssh2_pkt_adduint32(pktout, c->remoteid);
7450 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
7451 ssh2_pkt_addstring(pktout, error);
7452 ssh2_pkt_addstring(pktout, "en"); /* language tag */
7453 ssh2_pkt_send(ssh, pktout);
7454 logeventf(ssh, "Rejected channel open: %s", error);
7457 ssh2_channel_init(c);
7458 c->v.v2.remwindow = winsize;
7459 c->v.v2.remmaxpkt = pktsize;
7460 add234(ssh->channels, c);
7461 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
7462 ssh2_pkt_adduint32(pktout, c->remoteid);
7463 ssh2_pkt_adduint32(pktout, c->localid);
7464 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
7465 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7466 ssh2_pkt_send(ssh, pktout);
7471 * Buffer banner messages for later display at some convenient point,
7472 * if we're going to display them.
7474 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
7476 /* Arbitrary limit to prevent unbounded inflation of buffer */
7477 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
7478 bufchain_size(&ssh->banner) <= 131072) {
7479 char *banner = NULL;
7481 ssh_pkt_getstring(pktin, &banner, &size);
7483 bufchain_add(&ssh->banner, banner, size);
7487 /* Helper function to deal with sending tty modes for "pty-req" */
7488 static void ssh2_send_ttymode(void *data, char *mode, char *val)
7490 struct Packet *pktout = (struct Packet *)data;
7492 unsigned int arg = 0;
7493 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
7494 if (i == lenof(ssh_ttymodes)) return;
7495 switch (ssh_ttymodes[i].type) {
7497 arg = ssh_tty_parse_specchar(val);
7500 arg = ssh_tty_parse_boolean(val);
7503 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
7504 ssh2_pkt_adduint32(pktout, arg);
7507 static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
7510 struct ssh2_setup_x11_state {
7514 struct Packet *pktout;
7515 crStateP(ssh2_setup_x11_state, ctx);
7519 logevent("Requesting X11 forwarding");
7520 pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
7522 ssh2_pkt_addbool(pktout, 0); /* many connections */
7523 ssh2_pkt_addstring(pktout, ssh->x11disp->remoteauthprotoname);
7525 * Note that while we blank the X authentication data here, we don't
7526 * take any special action to blank the start of an X11 channel,
7527 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
7528 * without having session blanking enabled is likely to leak your
7529 * cookie into the log.
7531 dont_log_password(ssh, pktout, PKTLOG_BLANK);
7532 ssh2_pkt_addstring(pktout, ssh->x11disp->remoteauthdatastring);
7533 end_log_omission(ssh, pktout);
7534 ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
7535 ssh2_pkt_send(ssh, pktout);
7537 /* Wait to be called back with either a response packet, or NULL
7538 * meaning clean up and free our data */
7542 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
7543 logevent("X11 forwarding enabled");
7544 ssh->X11_fwd_enabled = TRUE;
7546 logevent("X11 forwarding refused");
7552 static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
7555 struct ssh2_setup_agent_state {
7559 struct Packet *pktout;
7560 crStateP(ssh2_setup_agent_state, ctx);
7564 logevent("Requesting OpenSSH-style agent forwarding");
7565 pktout = ssh2_chanreq_init(ssh->mainchan, "auth-agent-req@openssh.com",
7566 ssh2_setup_agent, s);
7567 ssh2_pkt_send(ssh, pktout);
7569 /* Wait to be called back with either a response packet, or NULL
7570 * meaning clean up and free our data */
7574 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
7575 logevent("Agent forwarding enabled");
7576 ssh->agentfwd_enabled = TRUE;
7578 logevent("Agent forwarding refused");
7584 static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
7587 struct ssh2_setup_pty_state {
7591 struct Packet *pktout;
7592 crStateP(ssh2_setup_pty_state, ctx);
7596 /* Unpick the terminal-speed string. */
7597 /* XXX perhaps we should allow no speeds to be sent. */
7598 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
7599 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
7600 /* Build the pty request. */
7601 pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
7603 ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
7604 ssh2_pkt_adduint32(pktout, ssh->term_width);
7605 ssh2_pkt_adduint32(pktout, ssh->term_height);
7606 ssh2_pkt_adduint32(pktout, 0); /* pixel width */
7607 ssh2_pkt_adduint32(pktout, 0); /* pixel height */
7608 ssh2_pkt_addstring_start(pktout);
7609 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
7610 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
7611 ssh2_pkt_adduint32(pktout, ssh->ispeed);
7612 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
7613 ssh2_pkt_adduint32(pktout, ssh->ospeed);
7614 ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
7615 ssh2_pkt_send(ssh, pktout);
7616 ssh->state = SSH_STATE_INTERMED;
7618 /* Wait to be called back with either a response packet, or NULL
7619 * meaning clean up and free our data */
7623 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
7624 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
7625 ssh->ospeed, ssh->ispeed);
7626 ssh->got_pty = TRUE;
7628 c_write_str(ssh, "Server refused to allocate pty\r\n");
7629 ssh->editing = ssh->echoing = 1;
7636 static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
7639 struct ssh2_setup_env_state {
7641 int num_env, env_left, env_ok;
7644 struct Packet *pktout;
7645 crStateP(ssh2_setup_env_state, ctx);
7650 * Send environment variables.
7652 * Simplest thing here is to send all the requests at once, and
7653 * then wait for a whole bunch of successes or failures.
7659 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
7661 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
7662 pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
7663 ssh2_pkt_addstring(pktout, key);
7664 ssh2_pkt_addstring(pktout, val);
7665 ssh2_pkt_send(ssh, pktout);
7670 logeventf(ssh, "Sent %d environment variables", s->num_env);
7675 s->env_left = s->num_env;
7677 while (s->env_left > 0) {
7678 /* Wait to be called back with either a response packet,
7679 * or NULL meaning clean up and free our data */
7681 if (!pktin) goto out;
7682 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
7687 if (s->env_ok == s->num_env) {
7688 logevent("All environment variables successfully set");
7689 } else if (s->env_ok == 0) {
7690 logevent("All environment variables refused");
7691 c_write_str(ssh, "Server refused to set environment variables\r\n");
7693 logeventf(ssh, "%d environment variables refused",
7694 s->num_env - s->env_ok);
7695 c_write_str(ssh, "Server refused to set all environment variables\r\n");
7703 * Handle the SSH-2 userauth and connection layers.
7705 static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
7707 do_ssh2_authconn(ssh, NULL, 0, pktin);
7710 static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
7713 do_ssh2_authconn(c->ssh, NULL, 0, pktin);
7716 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
7717 struct Packet *pktin)
7719 struct do_ssh2_authconn_state {
7723 AUTH_TYPE_PUBLICKEY,
7724 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
7725 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
7727 AUTH_TYPE_GSSAPI, /* always QUIET */
7728 AUTH_TYPE_KEYBOARD_INTERACTIVE,
7729 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
7731 int done_service_req;
7732 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
7733 int tried_pubkey_config, done_agent;
7738 int kbd_inter_refused;
7739 int we_are_in, userauth_success;
7740 prompts_t *cur_prompt;
7745 void *publickey_blob;
7746 int publickey_bloblen;
7747 int publickey_encrypted;
7748 char *publickey_algorithm;
7749 char *publickey_comment;
7750 unsigned char agent_request[5], *agent_response, *agentp;
7751 int agent_responselen;
7752 unsigned char *pkblob_in_agent;
7754 char *pkblob, *alg, *commentp;
7755 int pklen, alglen, commentlen;
7756 int siglen, retlen, len;
7757 char *q, *agentreq, *ret;
7759 struct Packet *pktout;
7762 struct ssh_gss_library *gsslib;
7763 Ssh_gss_ctx gss_ctx;
7764 Ssh_gss_buf gss_buf;
7765 Ssh_gss_buf gss_rcvtok, gss_sndtok;
7766 Ssh_gss_name gss_srv_name;
7767 Ssh_gss_stat gss_stat;
7770 crState(do_ssh2_authconn_state);
7774 /* Register as a handler for all the messages this coroutine handles. */
7775 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
7776 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
7777 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
7778 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
7779 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
7780 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
7781 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
7782 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
7783 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
7784 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
7785 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
7786 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
7787 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
7788 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
7789 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
7790 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
7791 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
7792 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
7793 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
7794 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
7796 s->done_service_req = FALSE;
7797 s->we_are_in = s->userauth_success = FALSE;
7799 s->tried_gssapi = FALSE;
7802 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
7804 * Request userauth protocol, and await a response to it.
7806 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7807 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
7808 ssh2_pkt_send(ssh, s->pktout);
7809 crWaitUntilV(pktin);
7810 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
7811 s->done_service_req = TRUE;
7813 if (!s->done_service_req) {
7815 * Request connection protocol directly, without authentication.
7817 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7818 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7819 ssh2_pkt_send(ssh, s->pktout);
7820 crWaitUntilV(pktin);
7821 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
7822 s->we_are_in = TRUE; /* no auth required */
7824 bombout(("Server refused service request"));
7829 /* Arrange to be able to deal with any BANNERs that come in.
7830 * (We do this now as packets may come in during the next bit.) */
7831 bufchain_init(&ssh->banner);
7832 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
7833 ssh2_msg_userauth_banner;
7836 * Misc one-time setup for authentication.
7838 s->publickey_blob = NULL;
7839 if (!s->we_are_in) {
7842 * Load the public half of any configured public key file
7845 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
7846 if (!filename_is_null(s->keyfile)) {
7848 logeventf(ssh, "Reading private key file \"%.150s\"",
7849 filename_to_str(s->keyfile));
7850 keytype = key_type(s->keyfile);
7851 if (keytype == SSH_KEYTYPE_SSH2) {
7854 ssh2_userkey_loadpub(s->keyfile,
7855 &s->publickey_algorithm,
7856 &s->publickey_bloblen,
7857 &s->publickey_comment, &error);
7858 if (s->publickey_blob) {
7859 s->publickey_encrypted =
7860 ssh2_userkey_encrypted(s->keyfile, NULL);
7863 logeventf(ssh, "Unable to load private key (%s)",
7865 msgbuf = dupprintf("Unable to load private key file "
7866 "\"%.150s\" (%s)\r\n",
7867 filename_to_str(s->keyfile),
7869 c_write_str(ssh, msgbuf);
7874 logeventf(ssh, "Unable to use this key file (%s)",
7875 key_type_to_str(keytype));
7876 msgbuf = dupprintf("Unable to use key file \"%.150s\""
7878 filename_to_str(s->keyfile),
7879 key_type_to_str(keytype));
7880 c_write_str(ssh, msgbuf);
7882 s->publickey_blob = NULL;
7887 * Find out about any keys Pageant has (but if there's a
7888 * public key configured, filter out all others).
7891 s->agent_response = NULL;
7892 s->pkblob_in_agent = NULL;
7893 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
7897 logevent("Pageant is running. Requesting keys.");
7899 /* Request the keys held by the agent. */
7900 PUT_32BIT(s->agent_request, 1);
7901 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
7902 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
7903 ssh_agent_callback, ssh)) {
7907 bombout(("Unexpected data from server while"
7908 " waiting for agent response"));
7911 } while (pktin || inlen > 0);
7912 r = ssh->agent_response;
7913 s->agent_responselen = ssh->agent_response_len;
7915 s->agent_response = (unsigned char *) r;
7916 if (s->agent_response && s->agent_responselen >= 5 &&
7917 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
7920 p = s->agent_response + 5;
7921 s->nkeys = toint(GET_32BIT(p));
7924 * Vet the Pageant response to ensure that the key
7925 * count and blob lengths make sense.
7928 logeventf(ssh, "Pageant response contained a negative"
7929 " key count %d", s->nkeys);
7931 goto done_agent_query;
7933 unsigned char *q = p + 4;
7934 int lenleft = s->agent_responselen - 5 - 4;
7936 for (keyi = 0; keyi < s->nkeys; keyi++) {
7937 int bloblen, commentlen;
7939 logeventf(ssh, "Pageant response was truncated");
7941 goto done_agent_query;
7943 bloblen = toint(GET_32BIT(q));
7944 if (bloblen < 0 || bloblen > lenleft) {
7945 logeventf(ssh, "Pageant response was truncated");
7947 goto done_agent_query;
7949 lenleft -= 4 + bloblen;
7951 commentlen = toint(GET_32BIT(q));
7952 if (commentlen < 0 || commentlen > lenleft) {
7953 logeventf(ssh, "Pageant response was truncated");
7955 goto done_agent_query;
7957 lenleft -= 4 + commentlen;
7958 q += 4 + commentlen;
7963 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
7964 if (s->publickey_blob) {
7965 /* See if configured key is in agent. */
7966 for (keyi = 0; keyi < s->nkeys; keyi++) {
7967 s->pklen = toint(GET_32BIT(p));
7968 if (s->pklen == s->publickey_bloblen &&
7969 !memcmp(p+4, s->publickey_blob,
7970 s->publickey_bloblen)) {
7971 logeventf(ssh, "Pageant key #%d matches "
7972 "configured key file", keyi);
7974 s->pkblob_in_agent = p;
7978 p += toint(GET_32BIT(p)) + 4; /* comment */
7980 if (!s->pkblob_in_agent) {
7981 logevent("Configured key file not in Pageant");
7986 logevent("Failed to get reply from Pageant");
7994 * We repeat this whole loop, including the username prompt,
7995 * until we manage a successful authentication. If the user
7996 * types the wrong _password_, they can be sent back to the
7997 * beginning to try another username, if this is configured on.
7998 * (If they specify a username in the config, they are never
7999 * asked, even if they do give a wrong password.)
8001 * I think this best serves the needs of
8003 * - the people who have no configuration, no keys, and just
8004 * want to try repeated (username,password) pairs until they
8005 * type both correctly
8007 * - people who have keys and configuration but occasionally
8008 * need to fall back to passwords
8010 * - people with a key held in Pageant, who might not have
8011 * logged in to a particular machine before; so they want to
8012 * type a username, and then _either_ their key will be
8013 * accepted, _or_ they will type a password. If they mistype
8014 * the username they will want to be able to get back and
8017 s->got_username = FALSE;
8018 while (!s->we_are_in) {
8022 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
8024 * We got a username last time round this loop, and
8025 * with change_username turned off we don't try to get
8028 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
8029 int ret; /* need not be kept over crReturn */
8030 s->cur_prompt = new_prompts(ssh->frontend);
8031 s->cur_prompt->to_server = TRUE;
8032 s->cur_prompt->name = dupstr("SSH login name");
8033 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
8034 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8037 crWaitUntilV(!pktin);
8038 ret = get_userpass_input(s->cur_prompt, in, inlen);
8043 * get_userpass_input() failed to get a username.
8046 free_prompts(s->cur_prompt);
8047 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
8050 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
8051 free_prompts(s->cur_prompt);
8054 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
8055 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
8056 c_write_str(ssh, stuff);
8060 s->got_username = TRUE;
8063 * Send an authentication request using method "none": (a)
8064 * just in case it succeeds, and (b) so that we know what
8065 * authentication methods we can usefully try next.
8067 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
8069 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8070 ssh2_pkt_addstring(s->pktout, ssh->username);
8071 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
8072 ssh2_pkt_addstring(s->pktout, "none"); /* method */
8073 ssh2_pkt_send(ssh, s->pktout);
8074 s->type = AUTH_TYPE_NONE;
8076 s->we_are_in = FALSE;
8078 s->tried_pubkey_config = FALSE;
8079 s->kbd_inter_refused = FALSE;
8081 /* Reset agent request state. */
8082 s->done_agent = FALSE;
8083 if (s->agent_response) {
8084 if (s->pkblob_in_agent) {
8085 s->agentp = s->pkblob_in_agent;
8087 s->agentp = s->agent_response + 5 + 4;
8093 char *methods = NULL;
8097 * Wait for the result of the last authentication request.
8100 crWaitUntilV(pktin);
8102 * Now is a convenient point to spew any banner material
8103 * that we've accumulated. (This should ensure that when
8104 * we exit the auth loop, we haven't any left to deal
8108 int size = bufchain_size(&ssh->banner);
8110 * Don't show the banner if we're operating in
8111 * non-verbose non-interactive mode. (It's probably
8112 * a script, which means nobody will read the
8113 * banner _anyway_, and moreover the printing of
8114 * the banner will screw up processing on the
8115 * output of (say) plink.)
8117 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
8118 char *banner = snewn(size, char);
8119 bufchain_fetch(&ssh->banner, banner, size);
8120 c_write_untrusted(ssh, banner, size);
8123 bufchain_clear(&ssh->banner);
8125 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
8126 logevent("Access granted");
8127 s->we_are_in = s->userauth_success = TRUE;
8131 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
8132 bombout(("Strange packet received during authentication: "
8133 "type %d", pktin->type));
8140 * OK, we're now sitting on a USERAUTH_FAILURE message, so
8141 * we can look at the string in it and know what we can
8142 * helpfully try next.
8144 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
8145 ssh_pkt_getstring(pktin, &methods, &methlen);
8146 if (!ssh2_pkt_getbool(pktin)) {
8148 * We have received an unequivocal Access
8149 * Denied. This can translate to a variety of
8150 * messages, or no message at all.
8152 * For forms of authentication which are attempted
8153 * implicitly, by which I mean without printing
8154 * anything in the window indicating that we're
8155 * trying them, we should never print 'Access
8158 * If we do print a message saying that we're
8159 * attempting some kind of authentication, it's OK
8160 * to print a followup message saying it failed -
8161 * but the message may sometimes be more specific
8162 * than simply 'Access denied'.
8164 * Additionally, if we'd just tried password
8165 * authentication, we should break out of this
8166 * whole loop so as to go back to the username
8167 * prompt (iff we're configured to allow
8168 * username change attempts).
8170 if (s->type == AUTH_TYPE_NONE) {
8172 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
8173 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
8174 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
8175 c_write_str(ssh, "Server refused our key\r\n");
8176 logevent("Server refused our key");
8177 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
8178 /* This _shouldn't_ happen except by a
8179 * protocol bug causing client and server to
8180 * disagree on what is a correct signature. */
8181 c_write_str(ssh, "Server refused public-key signature"
8182 " despite accepting key!\r\n");
8183 logevent("Server refused public-key signature"
8184 " despite accepting key!");
8185 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
8186 /* quiet, so no c_write */
8187 logevent("Server refused keyboard-interactive authentication");
8188 } else if (s->type==AUTH_TYPE_GSSAPI) {
8189 /* always quiet, so no c_write */
8190 /* also, the code down in the GSSAPI block has
8191 * already logged this in the Event Log */
8192 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
8193 logevent("Keyboard-interactive authentication failed");
8194 c_write_str(ssh, "Access denied\r\n");
8196 assert(s->type == AUTH_TYPE_PASSWORD);
8197 logevent("Password authentication failed");
8198 c_write_str(ssh, "Access denied\r\n");
8200 if (conf_get_int(ssh->conf, CONF_change_username)) {
8201 /* XXX perhaps we should allow
8202 * keyboard-interactive to do this too? */
8203 s->we_are_in = FALSE;
8208 c_write_str(ssh, "Further authentication required\r\n");
8209 logevent("Further authentication required");
8213 in_commasep_string("publickey", methods, methlen);
8215 in_commasep_string("password", methods, methlen);
8216 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
8217 in_commasep_string("keyboard-interactive", methods, methlen);
8220 ssh->gsslibs = ssh_gss_setup(ssh->conf);
8221 s->can_gssapi = conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
8222 in_commasep_string("gssapi-with-mic", methods, methlen) &&
8223 ssh->gsslibs->nlibraries > 0;
8227 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
8229 if (s->can_pubkey && !s->done_agent && s->nkeys) {
8232 * Attempt public-key authentication using a key from Pageant.
8235 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
8237 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
8239 /* Unpack key from agent response */
8240 s->pklen = toint(GET_32BIT(s->agentp));
8242 s->pkblob = (char *)s->agentp;
8243 s->agentp += s->pklen;
8244 s->alglen = toint(GET_32BIT(s->pkblob));
8245 s->alg = s->pkblob + 4;
8246 s->commentlen = toint(GET_32BIT(s->agentp));
8248 s->commentp = (char *)s->agentp;
8249 s->agentp += s->commentlen;
8250 /* s->agentp now points at next key, if any */
8252 /* See if server will accept it */
8253 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8254 ssh2_pkt_addstring(s->pktout, ssh->username);
8255 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8256 /* service requested */
8257 ssh2_pkt_addstring(s->pktout, "publickey");
8259 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
8260 ssh2_pkt_addstring_start(s->pktout);
8261 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
8262 ssh2_pkt_addstring_start(s->pktout);
8263 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
8264 ssh2_pkt_send(ssh, s->pktout);
8265 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
8267 crWaitUntilV(pktin);
8268 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
8270 /* Offer of key refused. */
8277 if (flags & FLAG_VERBOSE) {
8278 c_write_str(ssh, "Authenticating with "
8280 c_write(ssh, s->commentp, s->commentlen);
8281 c_write_str(ssh, "\" from agent\r\n");
8285 * Server is willing to accept the key.
8286 * Construct a SIGN_REQUEST.
8288 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8289 ssh2_pkt_addstring(s->pktout, ssh->username);
8290 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8291 /* service requested */
8292 ssh2_pkt_addstring(s->pktout, "publickey");
8294 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
8295 ssh2_pkt_addstring_start(s->pktout);
8296 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
8297 ssh2_pkt_addstring_start(s->pktout);
8298 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
8300 /* Ask agent for signature. */
8301 s->siglen = s->pktout->length - 5 + 4 +
8302 ssh->v2_session_id_len;
8303 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
8305 s->len = 1; /* message type */
8306 s->len += 4 + s->pklen; /* key blob */
8307 s->len += 4 + s->siglen; /* data to sign */
8308 s->len += 4; /* flags */
8309 s->agentreq = snewn(4 + s->len, char);
8310 PUT_32BIT(s->agentreq, s->len);
8311 s->q = s->agentreq + 4;
8312 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
8313 PUT_32BIT(s->q, s->pklen);
8315 memcpy(s->q, s->pkblob, s->pklen);
8317 PUT_32BIT(s->q, s->siglen);
8319 /* Now the data to be signed... */
8320 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
8321 PUT_32BIT(s->q, ssh->v2_session_id_len);
8324 memcpy(s->q, ssh->v2_session_id,
8325 ssh->v2_session_id_len);
8326 s->q += ssh->v2_session_id_len;
8327 memcpy(s->q, s->pktout->data + 5,
8328 s->pktout->length - 5);
8329 s->q += s->pktout->length - 5;
8330 /* And finally the (zero) flags word. */
8332 if (!agent_query(s->agentreq, s->len + 4,
8334 ssh_agent_callback, ssh)) {
8338 bombout(("Unexpected data from server"
8339 " while waiting for agent"
8343 } while (pktin || inlen > 0);
8344 vret = ssh->agent_response;
8345 s->retlen = ssh->agent_response_len;
8350 if (s->retlen >= 9 &&
8351 s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
8352 GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
8353 logevent("Sending Pageant's response");
8354 ssh2_add_sigblob(ssh, s->pktout,
8355 s->pkblob, s->pklen,
8357 GET_32BIT(s->ret + 5));
8358 ssh2_pkt_send(ssh, s->pktout);
8359 s->type = AUTH_TYPE_PUBLICKEY;
8361 /* FIXME: less drastic response */
8362 bombout(("Pageant failed to answer challenge"));
8368 /* Do we have any keys left to try? */
8369 if (s->pkblob_in_agent) {
8370 s->done_agent = TRUE;
8371 s->tried_pubkey_config = TRUE;
8374 if (s->keyi >= s->nkeys)
8375 s->done_agent = TRUE;
8378 } else if (s->can_pubkey && s->publickey_blob &&
8379 !s->tried_pubkey_config) {
8381 struct ssh2_userkey *key; /* not live over crReturn */
8382 char *passphrase; /* not live over crReturn */
8384 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
8386 s->tried_pubkey_config = TRUE;
8389 * Try the public key supplied in the configuration.
8391 * First, offer the public blob to see if the server is
8392 * willing to accept it.
8394 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8395 ssh2_pkt_addstring(s->pktout, ssh->username);
8396 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8397 /* service requested */
8398 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
8399 ssh2_pkt_addbool(s->pktout, FALSE);
8400 /* no signature included */
8401 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
8402 ssh2_pkt_addstring_start(s->pktout);
8403 ssh2_pkt_addstring_data(s->pktout,
8404 (char *)s->publickey_blob,
8405 s->publickey_bloblen);
8406 ssh2_pkt_send(ssh, s->pktout);
8407 logevent("Offered public key");
8409 crWaitUntilV(pktin);
8410 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
8411 /* Key refused. Give up. */
8412 s->gotit = TRUE; /* reconsider message next loop */
8413 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
8414 continue; /* process this new message */
8416 logevent("Offer of public key accepted");
8419 * Actually attempt a serious authentication using
8422 if (flags & FLAG_VERBOSE) {
8423 c_write_str(ssh, "Authenticating with public key \"");
8424 c_write_str(ssh, s->publickey_comment);
8425 c_write_str(ssh, "\"\r\n");
8429 const char *error; /* not live over crReturn */
8430 if (s->publickey_encrypted) {
8432 * Get a passphrase from the user.
8434 int ret; /* need not be kept over crReturn */
8435 s->cur_prompt = new_prompts(ssh->frontend);
8436 s->cur_prompt->to_server = FALSE;
8437 s->cur_prompt->name = dupstr("SSH key passphrase");
8438 add_prompt(s->cur_prompt,
8439 dupprintf("Passphrase for key \"%.100s\": ",
8440 s->publickey_comment),
8442 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8445 crWaitUntilV(!pktin);
8446 ret = get_userpass_input(s->cur_prompt,
8451 /* Failed to get a passphrase. Terminate. */
8452 free_prompts(s->cur_prompt);
8453 ssh_disconnect(ssh, NULL,
8454 "Unable to authenticate",
8455 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8460 dupstr(s->cur_prompt->prompts[0]->result);
8461 free_prompts(s->cur_prompt);
8463 passphrase = NULL; /* no passphrase needed */
8467 * Try decrypting the key.
8469 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
8470 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
8472 /* burn the evidence */
8473 smemclr(passphrase, strlen(passphrase));
8476 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
8478 (key == SSH2_WRONG_PASSPHRASE)) {
8479 c_write_str(ssh, "Wrong passphrase\r\n");
8481 /* and loop again */
8483 c_write_str(ssh, "Unable to load private key (");
8484 c_write_str(ssh, error);
8485 c_write_str(ssh, ")\r\n");
8487 break; /* try something else */
8493 unsigned char *pkblob, *sigblob, *sigdata;
8494 int pkblob_len, sigblob_len, sigdata_len;
8498 * We have loaded the private key and the server
8499 * has announced that it's willing to accept it.
8500 * Hallelujah. Generate a signature and send it.
8502 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8503 ssh2_pkt_addstring(s->pktout, ssh->username);
8504 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8505 /* service requested */
8506 ssh2_pkt_addstring(s->pktout, "publickey");
8508 ssh2_pkt_addbool(s->pktout, TRUE);
8509 /* signature follows */
8510 ssh2_pkt_addstring(s->pktout, key->alg->name);
8511 pkblob = key->alg->public_blob(key->data,
8513 ssh2_pkt_addstring_start(s->pktout);
8514 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
8518 * The data to be signed is:
8522 * followed by everything so far placed in the
8525 sigdata_len = s->pktout->length - 5 + 4 +
8526 ssh->v2_session_id_len;
8527 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
8529 sigdata = snewn(sigdata_len, unsigned char);
8531 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
8532 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
8535 memcpy(sigdata+p, ssh->v2_session_id,
8536 ssh->v2_session_id_len);
8537 p += ssh->v2_session_id_len;
8538 memcpy(sigdata+p, s->pktout->data + 5,
8539 s->pktout->length - 5);
8540 p += s->pktout->length - 5;
8541 assert(p == sigdata_len);
8542 sigblob = key->alg->sign(key->data, (char *)sigdata,
8543 sigdata_len, &sigblob_len);
8544 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
8545 sigblob, sigblob_len);
8550 ssh2_pkt_send(ssh, s->pktout);
8551 logevent("Sent public key signature");
8552 s->type = AUTH_TYPE_PUBLICKEY;
8553 key->alg->freekey(key->data);
8557 } else if (s->can_gssapi && !s->tried_gssapi) {
8559 /* GSSAPI Authentication */
8564 s->type = AUTH_TYPE_GSSAPI;
8565 s->tried_gssapi = TRUE;
8567 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
8570 * Pick the highest GSS library on the preference
8576 for (i = 0; i < ngsslibs; i++) {
8577 int want_id = conf_get_int_int(ssh->conf,
8578 CONF_ssh_gsslist, i);
8579 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
8580 if (ssh->gsslibs->libraries[j].id == want_id) {
8581 s->gsslib = &ssh->gsslibs->libraries[j];
8582 goto got_gsslib; /* double break */
8587 * We always expect to have found something in
8588 * the above loop: we only came here if there
8589 * was at least one viable GSS library, and the
8590 * preference list should always mention
8591 * everything and only change the order.
8596 if (s->gsslib->gsslogmsg)
8597 logevent(s->gsslib->gsslogmsg);
8599 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
8600 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8601 ssh2_pkt_addstring(s->pktout, ssh->username);
8602 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8603 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
8604 logevent("Attempting GSSAPI authentication");
8606 /* add mechanism info */
8607 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
8609 /* number of GSSAPI mechanisms */
8610 ssh2_pkt_adduint32(s->pktout,1);
8612 /* length of OID + 2 */
8613 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
8614 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
8617 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
8619 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
8621 ssh2_pkt_send(ssh, s->pktout);
8622 crWaitUntilV(pktin);
8623 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
8624 logevent("GSSAPI authentication request refused");
8628 /* check returned packet ... */
8630 ssh_pkt_getstring(pktin, &data, &len);
8631 s->gss_rcvtok.value = data;
8632 s->gss_rcvtok.length = len;
8633 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
8634 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
8635 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
8636 memcmp((char *)s->gss_rcvtok.value + 2,
8637 s->gss_buf.value,s->gss_buf.length) ) {
8638 logevent("GSSAPI authentication - wrong response from server");
8642 /* now start running */
8643 s->gss_stat = s->gsslib->import_name(s->gsslib,
8646 if (s->gss_stat != SSH_GSS_OK) {
8647 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
8648 logevent("GSSAPI import name failed - Bad service name");
8650 logevent("GSSAPI import name failed");
8654 /* fetch TGT into GSS engine */
8655 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
8657 if (s->gss_stat != SSH_GSS_OK) {
8658 logevent("GSSAPI authentication failed to get credentials");
8659 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8663 /* initial tokens are empty */
8664 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
8665 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
8667 /* now enter the loop */
8669 s->gss_stat = s->gsslib->init_sec_context
8673 conf_get_int(ssh->conf, CONF_gssapifwd),
8677 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
8678 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
8679 logevent("GSSAPI authentication initialisation failed");
8681 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
8682 &s->gss_buf) == SSH_GSS_OK) {
8683 logevent(s->gss_buf.value);
8684 sfree(s->gss_buf.value);
8689 logevent("GSSAPI authentication initialised");
8691 /* Client and server now exchange tokens until GSSAPI
8692 * no longer says CONTINUE_NEEDED */
8694 if (s->gss_sndtok.length != 0) {
8695 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
8696 ssh_pkt_addstring_start(s->pktout);
8697 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
8698 ssh2_pkt_send(ssh, s->pktout);
8699 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
8702 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
8703 crWaitUntilV(pktin);
8704 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
8705 logevent("GSSAPI authentication - bad server response");
8706 s->gss_stat = SSH_GSS_FAILURE;
8709 ssh_pkt_getstring(pktin, &data, &len);
8710 s->gss_rcvtok.value = data;
8711 s->gss_rcvtok.length = len;
8713 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
8715 if (s->gss_stat != SSH_GSS_OK) {
8716 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8717 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
8720 logevent("GSSAPI authentication loop finished OK");
8722 /* Now send the MIC */
8724 s->pktout = ssh2_pkt_init(0);
8725 micoffset = s->pktout->length;
8726 ssh_pkt_addstring_start(s->pktout);
8727 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
8728 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
8729 ssh_pkt_addstring(s->pktout, ssh->username);
8730 ssh_pkt_addstring(s->pktout, "ssh-connection");
8731 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
8733 s->gss_buf.value = (char *)s->pktout->data + micoffset;
8734 s->gss_buf.length = s->pktout->length - micoffset;
8736 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
8737 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
8738 ssh_pkt_addstring_start(s->pktout);
8739 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
8740 ssh2_pkt_send(ssh, s->pktout);
8741 s->gsslib->free_mic(s->gsslib, &mic);
8745 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8746 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
8749 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
8752 * Keyboard-interactive authentication.
8755 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
8757 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
8759 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8760 ssh2_pkt_addstring(s->pktout, ssh->username);
8761 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8762 /* service requested */
8763 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
8765 ssh2_pkt_addstring(s->pktout, ""); /* lang */
8766 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
8767 ssh2_pkt_send(ssh, s->pktout);
8769 logevent("Attempting keyboard-interactive authentication");
8771 crWaitUntilV(pktin);
8772 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
8773 /* Server is not willing to do keyboard-interactive
8774 * at all (or, bizarrely but legally, accepts the
8775 * user without actually issuing any prompts).
8776 * Give up on it entirely. */
8778 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
8779 s->kbd_inter_refused = TRUE; /* don't try it again */
8784 * Loop while the server continues to send INFO_REQUESTs.
8786 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
8788 char *name, *inst, *lang;
8789 int name_len, inst_len, lang_len;
8793 * We've got a fresh USERAUTH_INFO_REQUEST.
8794 * Get the preamble and start building a prompt.
8796 ssh_pkt_getstring(pktin, &name, &name_len);
8797 ssh_pkt_getstring(pktin, &inst, &inst_len);
8798 ssh_pkt_getstring(pktin, &lang, &lang_len);
8799 s->cur_prompt = new_prompts(ssh->frontend);
8800 s->cur_prompt->to_server = TRUE;
8803 * Get any prompt(s) from the packet.
8805 s->num_prompts = ssh_pkt_getuint32(pktin);
8806 for (i = 0; i < s->num_prompts; i++) {
8810 static char noprompt[] =
8811 "<server failed to send prompt>: ";
8813 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
8814 echo = ssh2_pkt_getbool(pktin);
8817 prompt_len = lenof(noprompt)-1;
8819 add_prompt(s->cur_prompt,
8820 dupprintf("%.*s", prompt_len, prompt),
8825 /* FIXME: better prefix to distinguish from
8827 s->cur_prompt->name =
8828 dupprintf("SSH server: %.*s", name_len, name);
8829 s->cur_prompt->name_reqd = TRUE;
8831 s->cur_prompt->name =
8832 dupstr("SSH server authentication");
8833 s->cur_prompt->name_reqd = FALSE;
8835 /* We add a prefix to try to make it clear that a prompt
8836 * has come from the server.
8837 * FIXME: ugly to print "Using..." in prompt _every_
8838 * time round. Can this be done more subtly? */
8839 /* Special case: for reasons best known to themselves,
8840 * some servers send k-i requests with no prompts and
8841 * nothing to display. Keep quiet in this case. */
8842 if (s->num_prompts || name_len || inst_len) {
8843 s->cur_prompt->instruction =
8844 dupprintf("Using keyboard-interactive authentication.%s%.*s",
8845 inst_len ? "\n" : "", inst_len, inst);
8846 s->cur_prompt->instr_reqd = TRUE;
8848 s->cur_prompt->instr_reqd = FALSE;
8852 * Display any instructions, and get the user's
8856 int ret; /* not live over crReturn */
8857 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8860 crWaitUntilV(!pktin);
8861 ret = get_userpass_input(s->cur_prompt, in, inlen);
8866 * Failed to get responses. Terminate.
8868 free_prompts(s->cur_prompt);
8869 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8870 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8877 * Send the response(s) to the server.
8879 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
8880 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
8881 for (i=0; i < s->num_prompts; i++) {
8882 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8883 ssh2_pkt_addstring(s->pktout,
8884 s->cur_prompt->prompts[i]->result);
8885 end_log_omission(ssh, s->pktout);
8887 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8890 * Free the prompts structure from this iteration.
8891 * If there's another, a new one will be allocated
8892 * when we return to the top of this while loop.
8894 free_prompts(s->cur_prompt);
8897 * Get the next packet in case it's another
8900 crWaitUntilV(pktin);
8905 * We should have SUCCESS or FAILURE now.
8909 } else if (s->can_passwd) {
8912 * Plain old password authentication.
8914 int ret; /* not live over crReturn */
8915 int changereq_first_time; /* not live over crReturn */
8917 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
8919 s->cur_prompt = new_prompts(ssh->frontend);
8920 s->cur_prompt->to_server = TRUE;
8921 s->cur_prompt->name = dupstr("SSH password");
8922 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
8927 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8930 crWaitUntilV(!pktin);
8931 ret = get_userpass_input(s->cur_prompt, in, inlen);
8936 * Failed to get responses. Terminate.
8938 free_prompts(s->cur_prompt);
8939 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8940 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8945 * Squirrel away the password. (We may need it later if
8946 * asked to change it.)
8948 s->password = dupstr(s->cur_prompt->prompts[0]->result);
8949 free_prompts(s->cur_prompt);
8952 * Send the password packet.
8954 * We pad out the password packet to 256 bytes to make
8955 * it harder for an attacker to find the length of the
8958 * Anyone using a password longer than 256 bytes
8959 * probably doesn't have much to worry about from
8960 * people who find out how long their password is!
8962 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8963 ssh2_pkt_addstring(s->pktout, ssh->username);
8964 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8965 /* service requested */
8966 ssh2_pkt_addstring(s->pktout, "password");
8967 ssh2_pkt_addbool(s->pktout, FALSE);
8968 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8969 ssh2_pkt_addstring(s->pktout, s->password);
8970 end_log_omission(ssh, s->pktout);
8971 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8972 logevent("Sent password");
8973 s->type = AUTH_TYPE_PASSWORD;
8976 * Wait for next packet, in case it's a password change
8979 crWaitUntilV(pktin);
8980 changereq_first_time = TRUE;
8982 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
8985 * We're being asked for a new password
8986 * (perhaps not for the first time).
8987 * Loop until the server accepts it.
8990 int got_new = FALSE; /* not live over crReturn */
8991 char *prompt; /* not live over crReturn */
8992 int prompt_len; /* not live over crReturn */
8996 if (changereq_first_time)
8997 msg = "Server requested password change";
8999 msg = "Server rejected new password";
9001 c_write_str(ssh, msg);
9002 c_write_str(ssh, "\r\n");
9005 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
9007 s->cur_prompt = new_prompts(ssh->frontend);
9008 s->cur_prompt->to_server = TRUE;
9009 s->cur_prompt->name = dupstr("New SSH password");
9010 s->cur_prompt->instruction =
9011 dupprintf("%.*s", prompt_len, prompt);
9012 s->cur_prompt->instr_reqd = TRUE;
9014 * There's no explicit requirement in the protocol
9015 * for the "old" passwords in the original and
9016 * password-change messages to be the same, and
9017 * apparently some Cisco kit supports password change
9018 * by the user entering a blank password originally
9019 * and the real password subsequently, so,
9020 * reluctantly, we prompt for the old password again.
9022 * (On the other hand, some servers don't even bother
9023 * to check this field.)
9025 add_prompt(s->cur_prompt,
9026 dupstr("Current password (blank for previously entered password): "),
9028 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
9030 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
9034 * Loop until the user manages to enter the same
9039 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9042 crWaitUntilV(!pktin);
9043 ret = get_userpass_input(s->cur_prompt, in, inlen);
9048 * Failed to get responses. Terminate.
9050 /* burn the evidence */
9051 free_prompts(s->cur_prompt);
9052 smemclr(s->password, strlen(s->password));
9054 ssh_disconnect(ssh, NULL, "Unable to authenticate",
9055 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9061 * If the user specified a new original password
9062 * (IYSWIM), overwrite any previously specified
9064 * (A side effect is that the user doesn't have to
9065 * re-enter it if they louse up the new password.)
9067 if (s->cur_prompt->prompts[0]->result[0]) {
9068 smemclr(s->password, strlen(s->password));
9069 /* burn the evidence */
9072 dupstr(s->cur_prompt->prompts[0]->result);
9076 * Check the two new passwords match.
9078 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
9079 s->cur_prompt->prompts[2]->result)
9082 /* They don't. Silly user. */
9083 c_write_str(ssh, "Passwords do not match\r\n");
9088 * Send the new password (along with the old one).
9089 * (see above for padding rationale)
9091 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9092 ssh2_pkt_addstring(s->pktout, ssh->username);
9093 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9094 /* service requested */
9095 ssh2_pkt_addstring(s->pktout, "password");
9096 ssh2_pkt_addbool(s->pktout, TRUE);
9097 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
9098 ssh2_pkt_addstring(s->pktout, s->password);
9099 ssh2_pkt_addstring(s->pktout,
9100 s->cur_prompt->prompts[1]->result);
9101 free_prompts(s->cur_prompt);
9102 end_log_omission(ssh, s->pktout);
9103 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
9104 logevent("Sent new password");
9107 * Now see what the server has to say about it.
9108 * (If it's CHANGEREQ again, it's not happy with the
9111 crWaitUntilV(pktin);
9112 changereq_first_time = FALSE;
9117 * We need to reexamine the current pktin at the top
9118 * of the loop. Either:
9119 * - we weren't asked to change password at all, in
9120 * which case it's a SUCCESS or FAILURE with the
9122 * - we sent a new password, and the server was
9123 * either OK with it (SUCCESS or FAILURE w/partial
9124 * success) or unhappy with the _old_ password
9125 * (FAILURE w/o partial success)
9126 * In any of these cases, we go back to the top of
9127 * the loop and start again.
9132 * We don't need the old password any more, in any
9133 * case. Burn the evidence.
9135 smemclr(s->password, strlen(s->password));
9139 char *str = dupprintf("No supported authentication methods available"
9140 " (server sent: %.*s)",
9143 ssh_disconnect(ssh, str,
9144 "No supported authentication methods available",
9145 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
9155 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
9157 /* Clear up various bits and pieces from authentication. */
9158 if (s->publickey_blob) {
9159 sfree(s->publickey_blob);
9160 sfree(s->publickey_comment);
9162 if (s->agent_response)
9163 sfree(s->agent_response);
9165 if (s->userauth_success) {
9167 * We've just received USERAUTH_SUCCESS, and we haven't sent any
9168 * packets since. Signal the transport layer to consider enacting
9169 * delayed compression.
9171 * (Relying on we_are_in is not sufficient, as
9172 * draft-miller-secsh-compression-delayed is quite clear that it
9173 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
9174 * become set for other reasons.)
9176 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
9180 * Now the connection protocol has started, one way or another.
9183 ssh->channels = newtree234(ssh_channelcmp);
9186 * Set up handlers for some connection protocol messages, so we
9187 * don't have to handle them repeatedly in this coroutine.
9189 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
9190 ssh2_msg_channel_window_adjust;
9191 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
9192 ssh2_msg_global_request;
9195 * Create the main session channel.
9197 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
9198 ssh->mainchan = NULL;
9200 ssh->mainchan = snew(struct ssh_channel);
9201 ssh->mainchan->ssh = ssh;
9202 ssh2_channel_init(ssh->mainchan);
9204 if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
9206 * Just start a direct-tcpip channel and use it as the main
9209 ssh_send_port_open(ssh->mainchan,
9210 conf_get_str(ssh->conf, CONF_ssh_nc_host),
9211 conf_get_int(ssh->conf, CONF_ssh_nc_port),
9215 s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
9216 logevent("Opening session as main channel");
9217 ssh2_pkt_send(ssh, s->pktout);
9218 ssh->ncmode = FALSE;
9220 crWaitUntilV(pktin);
9221 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
9222 bombout(("Server refused to open channel"));
9224 /* FIXME: error data comes back in FAILURE packet */
9226 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
9227 bombout(("Server's channel confirmation cited wrong channel"));
9230 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
9231 ssh->mainchan->halfopen = FALSE;
9232 ssh->mainchan->type = CHAN_MAINSESSION;
9233 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
9234 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
9235 add234(ssh->channels, ssh->mainchan);
9236 update_specials_menu(ssh->frontend);
9237 logevent("Opened main channel");
9241 * Now we have a channel, make dispatch table entries for
9242 * general channel-based messages.
9244 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
9245 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
9246 ssh2_msg_channel_data;
9247 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
9248 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
9249 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
9250 ssh2_msg_channel_open_confirmation;
9251 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
9252 ssh2_msg_channel_open_failure;
9253 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
9254 ssh2_msg_channel_request;
9255 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
9256 ssh2_msg_channel_open;
9257 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
9258 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
9261 if (ssh->mainchan && conf_get_int(ssh->conf, CONF_ssh_simple)) {
9263 * This message indicates to the server that we promise
9264 * not to try to run any other channel in parallel with
9265 * this one, so it's safe for it to advertise a very large
9266 * window and leave the flow control to TCP.
9268 s->pktout = ssh2_chanreq_init(ssh->mainchan,
9269 "simple@putty.projects.tartarus.org",
9271 ssh2_pkt_send(ssh, s->pktout);
9275 * Enable port forwardings.
9277 ssh_setup_portfwd(ssh, ssh->conf);
9279 if (ssh->mainchan && !ssh->ncmode) {
9281 * Send the CHANNEL_REQUESTS for the main session channel.
9282 * Each one is handled by its own little asynchronous
9286 /* Potentially enable X11 forwarding. */
9287 if (conf_get_int(ssh->conf, CONF_x11_forward) &&
9289 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
9290 conf_get_int(ssh->conf, CONF_x11_auth),
9292 ssh2_setup_x11(ssh->mainchan, NULL, NULL);
9294 /* Potentially enable agent forwarding. */
9295 if (conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists())
9296 ssh2_setup_agent(ssh->mainchan, NULL, NULL);
9298 /* Now allocate a pty for the session. */
9299 if (!conf_get_int(ssh->conf, CONF_nopty))
9300 ssh2_setup_pty(ssh->mainchan, NULL, NULL);
9302 /* Send environment variables. */
9303 ssh2_setup_env(ssh->mainchan, NULL, NULL);
9306 * Start a shell or a remote command. We may have to attempt
9307 * this twice if the config data has provided a second choice
9314 if (ssh->fallback_cmd) {
9315 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
9316 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
9318 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
9319 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
9323 s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
9324 ssh2_response_authconn, NULL);
9325 ssh2_pkt_addstring(s->pktout, cmd);
9327 s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
9328 ssh2_response_authconn, NULL);
9329 ssh2_pkt_addstring(s->pktout, cmd);
9331 s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
9332 ssh2_response_authconn, NULL);
9334 ssh2_pkt_send(ssh, s->pktout);
9336 crWaitUntilV(pktin);
9338 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9339 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
9340 bombout(("Unexpected response to shell/command request:"
9341 " packet type %d", pktin->type));
9345 * We failed to start the command. If this is the
9346 * fallback command, we really are finished; if it's
9347 * not, and if the fallback command exists, try falling
9348 * back to it before complaining.
9350 if (!ssh->fallback_cmd &&
9351 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
9352 logevent("Primary command failed; attempting fallback");
9353 ssh->fallback_cmd = TRUE;
9356 bombout(("Server refused to start a shell/command"));
9359 logevent("Started a shell/command");
9364 ssh->editing = ssh->echoing = TRUE;
9367 ssh->state = SSH_STATE_SESSION;
9368 if (ssh->size_needed)
9369 ssh_size(ssh, ssh->term_width, ssh->term_height);
9370 if (ssh->eof_needed)
9371 ssh_special(ssh, TS_EOF);
9377 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
9382 s->try_send = FALSE;
9386 * _All_ the connection-layer packets we expect to
9387 * receive are now handled by the dispatch table.
9388 * Anything that reaches here must be bogus.
9391 bombout(("Strange packet received: type %d", pktin->type));
9393 } else if (ssh->mainchan) {
9395 * We have spare data. Add it to the channel buffer.
9397 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
9402 struct ssh_channel *c;
9404 * Try to send data on all channels if we can.
9406 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
9407 ssh2_try_send_and_unthrottle(ssh, c);
9415 * Handlers for SSH-2 messages that might arrive at any moment.
9417 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
9419 /* log reason code in disconnect message */
9423 reason = ssh_pkt_getuint32(pktin);
9424 ssh_pkt_getstring(pktin, &msg, &msglen);
9426 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
9427 buf = dupprintf("Received disconnect message (%s)",
9428 ssh2_disconnect_reasons[reason]);
9430 buf = dupprintf("Received disconnect message (unknown"
9431 " type %d)", reason);
9435 buf = dupprintf("Disconnection message text: %.*s",
9438 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
9440 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
9441 ssh2_disconnect_reasons[reason] : "unknown",
9446 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
9448 /* log the debug message */
9452 /* XXX maybe we should actually take notice of the return value */
9453 ssh2_pkt_getbool(pktin);
9454 ssh_pkt_getstring(pktin, &msg, &msglen);
9456 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
9459 static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
9461 do_ssh2_transport(ssh, NULL, 0, pktin);
9465 * Called if we receive a packet that isn't allowed by the protocol.
9466 * This only applies to packets whose meaning PuTTY understands.
9467 * Entirely unknown packets are handled below.
9469 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
9471 char *buf = dupprintf("Server protocol violation: unexpected %s packet",
9472 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
9474 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
9478 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
9480 struct Packet *pktout;
9481 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
9482 ssh2_pkt_adduint32(pktout, pktin->sequence);
9484 * UNIMPLEMENTED messages MUST appear in the same order as the
9485 * messages they respond to. Hence, never queue them.
9487 ssh2_pkt_send_noqueue(ssh, pktout);
9491 * Handle the top-level SSH-2 protocol.
9493 static void ssh2_protocol_setup(Ssh ssh)
9498 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
9500 for (i = 0; i < 256; i++)
9501 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
9504 * Initially, we only accept transport messages (and a few generic
9505 * ones). do_ssh2_authconn will add more when it starts.
9506 * Messages that are understood but not currently acceptable go to
9507 * ssh2_msg_unexpected.
9509 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
9510 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
9511 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
9512 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
9513 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
9514 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
9515 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
9516 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
9517 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
9518 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
9519 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
9520 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
9521 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
9522 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
9523 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
9524 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
9525 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
9526 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
9527 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
9528 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
9529 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
9530 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
9531 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
9532 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
9533 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
9534 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
9535 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
9536 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
9537 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
9538 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
9539 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
9540 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
9541 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
9544 * These messages have a special handler from the start.
9546 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
9547 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
9548 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
9551 static void ssh2_timer(void *ctx, unsigned long now)
9555 if (ssh->state == SSH_STATE_CLOSED)
9558 if (!ssh->kex_in_progress && conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
9559 now == ssh->next_rekey) {
9560 do_ssh2_transport(ssh, "timeout", -1, NULL);
9564 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
9565 struct Packet *pktin)
9567 unsigned char *in = (unsigned char *)vin;
9568 if (ssh->state == SSH_STATE_CLOSED)
9572 ssh->incoming_data_size += pktin->encrypted_len;
9573 if (!ssh->kex_in_progress &&
9574 ssh->max_data_size != 0 &&
9575 ssh->incoming_data_size > ssh->max_data_size)
9576 do_ssh2_transport(ssh, "too much data received", -1, NULL);
9580 ssh->packet_dispatch[pktin->type](ssh, pktin);
9581 else if (!ssh->protocol_initial_phase_done)
9582 do_ssh2_transport(ssh, in, inlen, pktin);
9584 do_ssh2_authconn(ssh, in, inlen, pktin);
9587 static void ssh_cache_conf_values(Ssh ssh)
9589 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
9593 * Called to set up the connection.
9595 * Returns an error message, or NULL on success.
9597 static const char *ssh_init(void *frontend_handle, void **backend_handle,
9598 Conf *conf, char *host, int port, char **realhost,
9599 int nodelay, int keepalive)
9604 ssh = snew(struct ssh_tag);
9605 ssh->conf = conf_copy(conf);
9606 ssh_cache_conf_values(ssh);
9607 ssh->version = 0; /* when not ready yet */
9610 ssh->v1_cipher_ctx = NULL;
9611 ssh->crcda_ctx = NULL;
9612 ssh->cscipher = NULL;
9613 ssh->cs_cipher_ctx = NULL;
9614 ssh->sccipher = NULL;
9615 ssh->sc_cipher_ctx = NULL;
9617 ssh->cs_mac_ctx = NULL;
9619 ssh->sc_mac_ctx = NULL;
9621 ssh->cs_comp_ctx = NULL;
9623 ssh->sc_comp_ctx = NULL;
9625 ssh->kex_ctx = NULL;
9626 ssh->hostkey = NULL;
9627 ssh->hostkey_str = NULL;
9629 ssh->close_expected = FALSE;
9630 ssh->clean_exit = FALSE;
9631 ssh->state = SSH_STATE_PREPACKET;
9632 ssh->size_needed = FALSE;
9633 ssh->eof_needed = FALSE;
9636 ssh->deferred_send_data = NULL;
9637 ssh->deferred_len = 0;
9638 ssh->deferred_size = 0;
9639 ssh->fallback_cmd = 0;
9640 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
9641 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9642 ssh->x11disp = NULL;
9643 ssh->v1_compressing = FALSE;
9644 ssh->v2_outgoing_sequence = 0;
9645 ssh->ssh1_rdpkt_crstate = 0;
9646 ssh->ssh2_rdpkt_crstate = 0;
9647 ssh->ssh_gotdata_crstate = 0;
9648 ssh->do_ssh1_connection_crstate = 0;
9649 ssh->do_ssh_init_state = NULL;
9650 ssh->do_ssh1_login_state = NULL;
9651 ssh->do_ssh2_transport_state = NULL;
9652 ssh->do_ssh2_authconn_state = NULL;
9655 ssh->mainchan = NULL;
9656 ssh->throttled_all = 0;
9657 ssh->v1_stdout_throttling = 0;
9659 ssh->queuelen = ssh->queuesize = 0;
9660 ssh->queueing = FALSE;
9661 ssh->qhead = ssh->qtail = NULL;
9662 ssh->deferred_rekey_reason = NULL;
9663 bufchain_init(&ssh->queued_incoming_data);
9664 ssh->frozen = FALSE;
9665 ssh->username = NULL;
9666 ssh->sent_console_eof = FALSE;
9667 ssh->got_pty = FALSE;
9669 *backend_handle = ssh;
9672 if (crypto_startup() == 0)
9673 return "Microsoft high encryption pack not installed!";
9676 ssh->frontend = frontend_handle;
9677 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
9678 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
9680 ssh->channels = NULL;
9681 ssh->rportfwds = NULL;
9682 ssh->portfwds = NULL;
9687 ssh->conn_throttle_count = 0;
9688 ssh->overall_bufsize = 0;
9689 ssh->fallback_cmd = 0;
9691 ssh->protocol = NULL;
9693 ssh->protocol_initial_phase_done = FALSE;
9697 ssh->incoming_data_size = ssh->outgoing_data_size =
9698 ssh->deferred_data_size = 0L;
9699 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
9700 CONF_ssh_rekey_data));
9701 ssh->kex_in_progress = FALSE;
9704 ssh->gsslibs = NULL;
9707 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
9716 static void ssh_free(void *handle)
9718 Ssh ssh = (Ssh) handle;
9719 struct ssh_channel *c;
9720 struct ssh_rportfwd *pf;
9722 if (ssh->v1_cipher_ctx)
9723 ssh->cipher->free_context(ssh->v1_cipher_ctx);
9724 if (ssh->cs_cipher_ctx)
9725 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
9726 if (ssh->sc_cipher_ctx)
9727 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
9728 if (ssh->cs_mac_ctx)
9729 ssh->csmac->free_context(ssh->cs_mac_ctx);
9730 if (ssh->sc_mac_ctx)
9731 ssh->scmac->free_context(ssh->sc_mac_ctx);
9732 if (ssh->cs_comp_ctx) {
9734 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
9736 zlib_compress_cleanup(ssh->cs_comp_ctx);
9738 if (ssh->sc_comp_ctx) {
9740 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
9742 zlib_decompress_cleanup(ssh->sc_comp_ctx);
9745 dh_cleanup(ssh->kex_ctx);
9746 sfree(ssh->savedhost);
9748 while (ssh->queuelen-- > 0)
9749 ssh_free_packet(ssh->queue[ssh->queuelen]);
9752 while (ssh->qhead) {
9753 struct queued_handler *qh = ssh->qhead;
9754 ssh->qhead = qh->next;
9757 ssh->qhead = ssh->qtail = NULL;
9759 if (ssh->channels) {
9760 while ((c = delpos234(ssh->channels, 0)) != NULL) {
9763 if (c->u.x11.s != NULL)
9764 x11_close(c->u.x11.s);
9767 case CHAN_SOCKDATA_DORMANT:
9768 if (c->u.pfd.s != NULL)
9769 pfd_close(c->u.pfd.s);
9772 if (ssh->version == 2) {
9773 struct outstanding_channel_request *ocr, *nocr;
9774 ocr = c->v.v2.chanreq_head;
9776 ocr->handler(c, NULL, ocr->ctx);
9781 bufchain_clear(&c->v.v2.outbuffer);
9785 freetree234(ssh->channels);
9786 ssh->channels = NULL;
9789 if (ssh->rportfwds) {
9790 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
9792 freetree234(ssh->rportfwds);
9793 ssh->rportfwds = NULL;
9795 sfree(ssh->deferred_send_data);
9797 x11_free_display(ssh->x11disp);
9798 sfree(ssh->do_ssh_init_state);
9799 sfree(ssh->do_ssh1_login_state);
9800 sfree(ssh->do_ssh2_transport_state);
9801 sfree(ssh->do_ssh2_authconn_state);
9804 sfree(ssh->fullhostname);
9805 sfree(ssh->hostkey_str);
9806 if (ssh->crcda_ctx) {
9807 crcda_free_context(ssh->crcda_ctx);
9808 ssh->crcda_ctx = NULL;
9811 ssh_do_close(ssh, TRUE);
9812 expire_timer_context(ssh);
9814 pinger_free(ssh->pinger);
9815 bufchain_clear(&ssh->queued_incoming_data);
9816 sfree(ssh->username);
9817 conf_free(ssh->conf);
9820 ssh_gss_cleanup(ssh->gsslibs);
9828 * Reconfigure the SSH backend.
9830 static void ssh_reconfig(void *handle, Conf *conf)
9832 Ssh ssh = (Ssh) handle;
9833 char *rekeying = NULL, rekey_mandatory = FALSE;
9834 unsigned long old_max_data_size;
9837 pinger_reconfig(ssh->pinger, ssh->conf, conf);
9839 ssh_setup_portfwd(ssh, conf);
9841 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
9842 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
9844 unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
9845 unsigned long now = GETTICKCOUNT();
9847 if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
9848 rekeying = "timeout shortened";
9850 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
9854 old_max_data_size = ssh->max_data_size;
9855 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
9856 CONF_ssh_rekey_data));
9857 if (old_max_data_size != ssh->max_data_size &&
9858 ssh->max_data_size != 0) {
9859 if (ssh->outgoing_data_size > ssh->max_data_size ||
9860 ssh->incoming_data_size > ssh->max_data_size)
9861 rekeying = "data limit lowered";
9864 if (conf_get_int(ssh->conf, CONF_compression) !=
9865 conf_get_int(conf, CONF_compression)) {
9866 rekeying = "compression setting changed";
9867 rekey_mandatory = TRUE;
9870 for (i = 0; i < CIPHER_MAX; i++)
9871 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
9872 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
9873 rekeying = "cipher settings changed";
9874 rekey_mandatory = TRUE;
9876 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
9877 conf_get_int(conf, CONF_ssh2_des_cbc)) {
9878 rekeying = "cipher settings changed";
9879 rekey_mandatory = TRUE;
9882 conf_free(ssh->conf);
9883 ssh->conf = conf_copy(conf);
9884 ssh_cache_conf_values(ssh);
9887 if (!ssh->kex_in_progress) {
9888 do_ssh2_transport(ssh, rekeying, -1, NULL);
9889 } else if (rekey_mandatory) {
9890 ssh->deferred_rekey_reason = rekeying;
9896 * Called to send data down the SSH connection.
9898 static int ssh_send(void *handle, char *buf, int len)
9900 Ssh ssh = (Ssh) handle;
9902 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
9905 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
9907 return ssh_sendbuffer(ssh);
9911 * Called to query the current amount of buffered stdin data.
9913 static int ssh_sendbuffer(void *handle)
9915 Ssh ssh = (Ssh) handle;
9918 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
9922 * If the SSH socket itself has backed up, add the total backup
9923 * size on that to any individual buffer on the stdin channel.
9926 if (ssh->throttled_all)
9927 override_value = ssh->overall_bufsize;
9929 if (ssh->version == 1) {
9930 return override_value;
9931 } else if (ssh->version == 2) {
9933 return override_value;
9935 return (override_value +
9936 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
9943 * Called to set the size of the window from SSH's POV.
9945 static void ssh_size(void *handle, int width, int height)
9947 Ssh ssh = (Ssh) handle;
9948 struct Packet *pktout;
9950 ssh->term_width = width;
9951 ssh->term_height = height;
9953 switch (ssh->state) {
9954 case SSH_STATE_BEFORE_SIZE:
9955 case SSH_STATE_PREPACKET:
9956 case SSH_STATE_CLOSED:
9957 break; /* do nothing */
9958 case SSH_STATE_INTERMED:
9959 ssh->size_needed = TRUE; /* buffer for later */
9961 case SSH_STATE_SESSION:
9962 if (!conf_get_int(ssh->conf, CONF_nopty)) {
9963 if (ssh->version == 1) {
9964 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
9965 PKT_INT, ssh->term_height,
9966 PKT_INT, ssh->term_width,
9967 PKT_INT, 0, PKT_INT, 0, PKT_END);
9968 } else if (ssh->mainchan) {
9969 pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
9971 ssh2_pkt_adduint32(pktout, ssh->term_width);
9972 ssh2_pkt_adduint32(pktout, ssh->term_height);
9973 ssh2_pkt_adduint32(pktout, 0);
9974 ssh2_pkt_adduint32(pktout, 0);
9975 ssh2_pkt_send(ssh, pktout);
9983 * Return a list of the special codes that make sense in this
9986 static const struct telnet_special *ssh_get_specials(void *handle)
9988 static const struct telnet_special ssh1_ignore_special[] = {
9989 {"IGNORE message", TS_NOP}
9991 static const struct telnet_special ssh2_ignore_special[] = {
9992 {"IGNORE message", TS_NOP},
9994 static const struct telnet_special ssh2_rekey_special[] = {
9995 {"Repeat key exchange", TS_REKEY},
9997 static const struct telnet_special ssh2_session_specials[] = {
10000 /* These are the signal names defined by RFC 4254.
10001 * They include all the ISO C signals, but are a subset of the POSIX
10002 * required signals. */
10003 {"SIGINT (Interrupt)", TS_SIGINT},
10004 {"SIGTERM (Terminate)", TS_SIGTERM},
10005 {"SIGKILL (Kill)", TS_SIGKILL},
10006 {"SIGQUIT (Quit)", TS_SIGQUIT},
10007 {"SIGHUP (Hangup)", TS_SIGHUP},
10008 {"More signals", TS_SUBMENU},
10009 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
10010 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
10011 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
10012 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
10013 {NULL, TS_EXITMENU}
10015 static const struct telnet_special specials_end[] = {
10016 {NULL, TS_EXITMENU}
10018 /* XXX review this length for any changes: */
10019 static struct telnet_special ssh_specials[lenof(ssh2_ignore_special) +
10020 lenof(ssh2_rekey_special) +
10021 lenof(ssh2_session_specials) +
10022 lenof(specials_end)];
10023 Ssh ssh = (Ssh) handle;
10025 #define ADD_SPECIALS(name) \
10027 assert((i + lenof(name)) <= lenof(ssh_specials)); \
10028 memcpy(&ssh_specials[i], name, sizeof name); \
10029 i += lenof(name); \
10032 if (ssh->version == 1) {
10033 /* Don't bother offering IGNORE if we've decided the remote
10034 * won't cope with it, since we wouldn't bother sending it if
10036 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
10037 ADD_SPECIALS(ssh1_ignore_special);
10038 } else if (ssh->version == 2) {
10039 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
10040 ADD_SPECIALS(ssh2_ignore_special);
10041 if (!(ssh->remote_bugs & BUG_SSH2_REKEY))
10042 ADD_SPECIALS(ssh2_rekey_special);
10044 ADD_SPECIALS(ssh2_session_specials);
10045 } /* else we're not ready yet */
10048 ADD_SPECIALS(specials_end);
10049 return ssh_specials;
10053 #undef ADD_SPECIALS
10057 * Send special codes. TS_EOF is useful for `plink', so you
10058 * can send an EOF and collect resulting output (e.g. `plink
10061 static void ssh_special(void *handle, Telnet_Special code)
10063 Ssh ssh = (Ssh) handle;
10064 struct Packet *pktout;
10066 if (code == TS_EOF) {
10067 if (ssh->state != SSH_STATE_SESSION) {
10069 * Buffer the EOF in case we are pre-SESSION, so we can
10070 * send it as soon as we reach SESSION.
10072 if (code == TS_EOF)
10073 ssh->eof_needed = TRUE;
10076 if (ssh->version == 1) {
10077 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
10078 } else if (ssh->mainchan) {
10079 sshfwd_write_eof(ssh->mainchan);
10080 ssh->send_ok = 0; /* now stop trying to read from stdin */
10082 logevent("Sent EOF message");
10083 } else if (code == TS_PING || code == TS_NOP) {
10084 if (ssh->state == SSH_STATE_CLOSED
10085 || ssh->state == SSH_STATE_PREPACKET) return;
10086 if (ssh->version == 1) {
10087 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
10088 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
10090 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
10091 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
10092 ssh2_pkt_addstring_start(pktout);
10093 ssh2_pkt_send_noqueue(ssh, pktout);
10096 } else if (code == TS_REKEY) {
10097 if (!ssh->kex_in_progress && ssh->version == 2) {
10098 do_ssh2_transport(ssh, "at user request", -1, NULL);
10100 } else if (code == TS_BRK) {
10101 if (ssh->state == SSH_STATE_CLOSED
10102 || ssh->state == SSH_STATE_PREPACKET) return;
10103 if (ssh->version == 1) {
10104 logevent("Unable to send BREAK signal in SSH-1");
10105 } else if (ssh->mainchan) {
10106 pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
10107 ssh2_pkt_adduint32(pktout, 0); /* default break length */
10108 ssh2_pkt_send(ssh, pktout);
10111 /* Is is a POSIX signal? */
10112 char *signame = NULL;
10113 if (code == TS_SIGABRT) signame = "ABRT";
10114 if (code == TS_SIGALRM) signame = "ALRM";
10115 if (code == TS_SIGFPE) signame = "FPE";
10116 if (code == TS_SIGHUP) signame = "HUP";
10117 if (code == TS_SIGILL) signame = "ILL";
10118 if (code == TS_SIGINT) signame = "INT";
10119 if (code == TS_SIGKILL) signame = "KILL";
10120 if (code == TS_SIGPIPE) signame = "PIPE";
10121 if (code == TS_SIGQUIT) signame = "QUIT";
10122 if (code == TS_SIGSEGV) signame = "SEGV";
10123 if (code == TS_SIGTERM) signame = "TERM";
10124 if (code == TS_SIGUSR1) signame = "USR1";
10125 if (code == TS_SIGUSR2) signame = "USR2";
10126 /* The SSH-2 protocol does in principle support arbitrary named
10127 * signals, including signame@domain, but we don't support those. */
10129 /* It's a signal. */
10130 if (ssh->version == 2 && ssh->mainchan) {
10131 pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
10132 ssh2_pkt_addstring(pktout, signame);
10133 ssh2_pkt_send(ssh, pktout);
10134 logeventf(ssh, "Sent signal SIG%s", signame);
10137 /* Never heard of it. Do nothing */
10142 void *new_sock_channel(void *handle, Socket s)
10144 Ssh ssh = (Ssh) handle;
10145 struct ssh_channel *c;
10146 c = snew(struct ssh_channel);
10149 ssh2_channel_init(c);
10150 c->halfopen = TRUE;
10151 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
10153 add234(ssh->channels, c);
10158 * This is called when stdout/stderr (the entity to which
10159 * from_backend sends data) manages to clear some backlog.
10161 static void ssh_unthrottle(void *handle, int bufsize)
10163 Ssh ssh = (Ssh) handle;
10166 if (ssh->version == 1) {
10167 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
10168 ssh->v1_stdout_throttling = 0;
10169 ssh_throttle_conn(ssh, -1);
10172 if (ssh->mainchan) {
10173 ssh2_set_window(ssh->mainchan,
10174 bufsize < ssh->mainchan->v.v2.locmaxwin ?
10175 ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
10176 if (conf_get_int(ssh->conf, CONF_ssh_simple))
10179 buflimit = ssh->mainchan->v.v2.locmaxwin;
10180 if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
10181 ssh->mainchan->throttling_conn = 0;
10182 ssh_throttle_conn(ssh, -1);
10188 * Now process any SSH connection data that was stashed in our
10189 * queue while we were frozen.
10191 ssh_process_queued_incoming_data(ssh);
10194 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
10196 struct ssh_channel *c = (struct ssh_channel *)channel;
10198 struct Packet *pktout;
10200 logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
10202 if (ssh->version == 1) {
10203 send_packet(ssh, SSH1_MSG_PORT_OPEN,
10204 PKT_INT, c->localid,
10207 /* PKT_STR, <org:orgport>, */
10210 pktout = ssh2_chanopen_init(c, "direct-tcpip");
10211 ssh2_pkt_addstring(pktout, hostname);
10212 ssh2_pkt_adduint32(pktout, port);
10214 * We make up values for the originator data; partly it's
10215 * too much hassle to keep track, and partly I'm not
10216 * convinced the server should be told details like that
10217 * about my local network configuration.
10218 * The "originator IP address" is syntactically a numeric
10219 * IP address, and some servers (e.g., Tectia) get upset
10220 * if it doesn't match this syntax.
10222 ssh2_pkt_addstring(pktout, "0.0.0.0");
10223 ssh2_pkt_adduint32(pktout, 0);
10224 ssh2_pkt_send(ssh, pktout);
10228 static int ssh_connected(void *handle)
10230 Ssh ssh = (Ssh) handle;
10231 return ssh->s != NULL;
10234 static int ssh_sendok(void *handle)
10236 Ssh ssh = (Ssh) handle;
10237 return ssh->send_ok;
10240 static int ssh_ldisc(void *handle, int option)
10242 Ssh ssh = (Ssh) handle;
10243 if (option == LD_ECHO)
10244 return ssh->echoing;
10245 if (option == LD_EDIT)
10246 return ssh->editing;
10250 static void ssh_provide_ldisc(void *handle, void *ldisc)
10252 Ssh ssh = (Ssh) handle;
10253 ssh->ldisc = ldisc;
10256 static void ssh_provide_logctx(void *handle, void *logctx)
10258 Ssh ssh = (Ssh) handle;
10259 ssh->logctx = logctx;
10262 static int ssh_return_exitcode(void *handle)
10264 Ssh ssh = (Ssh) handle;
10265 if (ssh->s != NULL)
10268 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
10272 * cfg_info for SSH is the currently running version of the
10273 * protocol. (1 for 1; 2 for 2; 0 for not-decided-yet.)
10275 static int ssh_cfg_info(void *handle)
10277 Ssh ssh = (Ssh) handle;
10278 return ssh->version;
10282 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
10283 * that fails. This variable is the means by which scp.c can reach
10284 * into the SSH code and find out which one it got.
10286 extern int ssh_fallback_cmd(void *handle)
10288 Ssh ssh = (Ssh) handle;
10289 return ssh->fallback_cmd;
10292 Backend ssh_backend = {
10302 ssh_return_exitcode,
10306 ssh_provide_logctx,