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 packet: see below */
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; /* dual-purpose saved packet position: see below */
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 * A note on the 'length' and 'savedpos' fields above.
646 * Incoming packets are set up so that pkt->length is measured
647 * relative to pkt->body, which itself points to a few bytes after
648 * pkt->data (skipping some uninteresting header fields including
649 * the packet type code). The ssh_pkt_get* functions all expect
650 * this setup, and they also use pkt->savedpos to indicate how far
651 * through the packet being decoded they've got - and that, too,
652 * is an offset from pkt->body rather than pkt->data.
654 * During construction of an outgoing packet, however, pkt->length
655 * is measured relative to the base pointer pkt->data, and
656 * pkt->body is not really used for anything until the packet is
657 * ready for sending. In this mode, pkt->savedpos is reused as a
658 * temporary variable by the addstring functions, which write out
659 * a string length field and then keep going back and updating it
660 * as more data is appended to the subsequent string data field;
661 * pkt->savedpos stores the offset (again relative to pkt->data)
662 * of the start of the string data field.
666 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
667 struct Packet *pktin);
668 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
669 struct Packet *pktin);
670 static void ssh1_protocol_setup(Ssh ssh);
671 static void ssh2_protocol_setup(Ssh ssh);
672 static void ssh_size(void *handle, int width, int height);
673 static void ssh_special(void *handle, Telnet_Special);
674 static int ssh2_try_send(struct ssh_channel *c);
675 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
676 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
677 static void ssh2_set_window(struct ssh_channel *c, int newwin);
678 static int ssh_sendbuffer(void *handle);
679 static int ssh_do_close(Ssh ssh, int notify_exit);
680 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
681 static int ssh2_pkt_getbool(struct Packet *pkt);
682 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
683 static void ssh2_timer(void *ctx, unsigned long now);
684 static void do_ssh2_transport(Ssh ssh, void *vin, int inlen,
685 struct Packet *pktin);
686 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin);
688 struct rdpkt1_state_tag {
689 long len, pad, biglen, to_read;
690 unsigned long realcrc, gotcrc;
694 struct Packet *pktin;
697 struct rdpkt2_state_tag {
698 long len, pad, payload, packetlen, maclen;
701 unsigned long incoming_sequence;
702 struct Packet *pktin;
705 struct queued_handler;
706 struct queued_handler {
708 chandler_fn_t handler;
710 struct queued_handler *next;
714 const struct plug_function_table *fn;
715 /* the above field _must_ be first in the structure */
725 unsigned char session_key[32];
727 int v1_remote_protoflags;
728 int v1_local_protoflags;
729 int agentfwd_enabled;
732 const struct ssh_cipher *cipher;
735 const struct ssh2_cipher *cscipher, *sccipher;
736 void *cs_cipher_ctx, *sc_cipher_ctx;
737 const struct ssh_mac *csmac, *scmac;
738 void *cs_mac_ctx, *sc_mac_ctx;
739 const struct ssh_compress *cscomp, *sccomp;
740 void *cs_comp_ctx, *sc_comp_ctx;
741 const struct ssh_kex *kex;
742 const struct ssh_signkey *hostkey;
743 char *hostkey_str; /* string representation, for easy checking in rekeys */
744 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
745 int v2_session_id_len;
751 int echoing, editing;
755 int ospeed, ispeed; /* temporaries */
756 int term_width, term_height;
758 tree234 *channels; /* indexed by local id */
759 struct ssh_channel *mainchan; /* primary session channel */
760 int ncmode; /* is primary channel direct-tcpip? */
765 tree234 *rportfwds, *portfwds;
769 SSH_STATE_BEFORE_SIZE,
775 int size_needed, eof_needed;
776 int sent_console_eof;
777 int got_pty; /* affects EOF behaviour on main channel */
779 struct Packet **queue;
780 int queuelen, queuesize;
782 unsigned char *deferred_send_data;
783 int deferred_len, deferred_size;
786 * Gross hack: pscp will try to start SFTP but fall back to
787 * scp1 if that fails. This variable is the means by which
788 * scp.c can reach into the SSH code and find out which one it
793 bufchain banner; /* accumulates banners during do_ssh2_authconn */
798 struct X11Display *x11disp;
801 int conn_throttle_count;
804 int v1_stdout_throttling;
805 unsigned long v2_outgoing_sequence;
807 int ssh1_rdpkt_crstate;
808 int ssh2_rdpkt_crstate;
809 int ssh_gotdata_crstate;
810 int do_ssh1_connection_crstate;
812 void *do_ssh_init_state;
813 void *do_ssh1_login_state;
814 void *do_ssh2_transport_state;
815 void *do_ssh2_authconn_state;
817 struct rdpkt1_state_tag rdpkt1_state;
818 struct rdpkt2_state_tag rdpkt2_state;
820 /* SSH-1 and SSH-2 use this for different things, but both use it */
821 int protocol_initial_phase_done;
823 void (*protocol) (Ssh ssh, void *vin, int inlen,
825 struct Packet *(*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
828 * We maintain our own copy of a Conf structure here. That way,
829 * when we're passed a new one for reconfiguration, we can check
830 * the differences and potentially reconfigure port forwardings
831 * etc in mid-session.
836 * Values cached out of conf so as to avoid the tree234 lookup
837 * cost every time they're used.
842 * Dynamically allocated username string created during SSH
843 * login. Stored in here rather than in the coroutine state so
844 * that it'll be reliably freed if we shut down the SSH session
845 * at some unexpected moment.
850 * Used to transfer data back from async callbacks.
852 void *agent_response;
853 int agent_response_len;
857 * The SSH connection can be set as `frozen', meaning we are
858 * not currently accepting incoming data from the network. This
859 * is slightly more serious than setting the _socket_ as
860 * frozen, because we may already have had data passed to us
861 * from the network which we need to delay processing until
862 * after the freeze is lifted, so we also need a bufchain to
866 bufchain queued_incoming_data;
869 * Dispatch table for packet types that we may have to deal
872 handler_fn_t packet_dispatch[256];
875 * Queues of one-off handler functions for success/failure
876 * indications from a request.
878 struct queued_handler *qhead, *qtail;
879 handler_fn_t q_saved_handler1, q_saved_handler2;
882 * This module deals with sending keepalives.
887 * Track incoming and outgoing data sizes and time, for
890 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
891 unsigned long max_data_size;
893 unsigned long next_rekey, last_rekey;
894 char *deferred_rekey_reason; /* points to STATIC string; don't free */
897 * Fully qualified host name, which we need if doing GSSAPI.
903 * GSSAPI libraries for this session.
905 struct ssh_gss_liblist *gsslibs;
909 #define logevent(s) logevent(ssh->frontend, s)
911 /* logevent, only printf-formatted. */
912 static void logeventf(Ssh ssh, const char *fmt, ...)
918 buf = dupvprintf(fmt, ap);
924 static void bomb_out(Ssh ssh, char *text)
926 ssh_do_close(ssh, FALSE);
928 connection_fatal(ssh->frontend, "%s", text);
932 #define bombout(msg) bomb_out(ssh, dupprintf msg)
934 /* Functions to leave bits out of the SSH packet log file. */
936 static void dont_log_password(Ssh ssh, struct Packet *pkt, int blanktype)
938 if (conf_get_int(ssh->conf, CONF_logomitpass))
939 pkt->logmode = blanktype;
942 static void dont_log_data(Ssh ssh, struct Packet *pkt, int blanktype)
944 if (ssh->logomitdata)
945 pkt->logmode = blanktype;
948 static void end_log_omission(Ssh ssh, struct Packet *pkt)
950 pkt->logmode = PKTLOG_EMIT;
953 /* Helper function for common bits of parsing ttymodes. */
954 static void parse_ttymodes(Ssh ssh,
955 void (*do_mode)(void *data, char *mode, char *val),
960 for (val = conf_get_str_strs(ssh->conf, CONF_ttymodes, NULL, &key);
962 val = conf_get_str_strs(ssh->conf, CONF_ttymodes, key, &key)) {
964 * val[0] is either 'V', indicating that an explicit value
965 * follows it, or 'A' indicating that we should pass the
966 * value through from the local environment via get_ttymode.
969 val = get_ttymode(ssh->frontend, key);
971 do_mode(data, key, val);
975 do_mode(data, key, val + 1); /* skip the 'V' */
979 static int ssh_channelcmp(void *av, void *bv)
981 struct ssh_channel *a = (struct ssh_channel *) av;
982 struct ssh_channel *b = (struct ssh_channel *) bv;
983 if (a->localid < b->localid)
985 if (a->localid > b->localid)
989 static int ssh_channelfind(void *av, void *bv)
991 unsigned *a = (unsigned *) av;
992 struct ssh_channel *b = (struct ssh_channel *) bv;
1000 static int ssh_rportcmp_ssh1(void *av, void *bv)
1002 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1003 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1005 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
1006 return i < 0 ? -1 : +1;
1007 if (a->dport > b->dport)
1009 if (a->dport < b->dport)
1014 static int ssh_rportcmp_ssh2(void *av, void *bv)
1016 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1017 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1019 if ( (i = strcmp(a->shost, b->shost)) != 0)
1020 return i < 0 ? -1 : +1;
1021 if (a->sport > b->sport)
1023 if (a->sport < b->sport)
1029 * Special form of strcmp which can cope with NULL inputs. NULL is
1030 * defined to sort before even the empty string.
1032 static int nullstrcmp(const char *a, const char *b)
1034 if (a == NULL && b == NULL)
1040 return strcmp(a, b);
1043 static int ssh_portcmp(void *av, void *bv)
1045 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1046 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1048 if (a->type > b->type)
1050 if (a->type < b->type)
1052 if (a->addressfamily > b->addressfamily)
1054 if (a->addressfamily < b->addressfamily)
1056 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1057 return i < 0 ? -1 : +1;
1058 if (a->sport > b->sport)
1060 if (a->sport < b->sport)
1062 if (a->type != 'D') {
1063 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1064 return i < 0 ? -1 : +1;
1065 if (a->dport > b->dport)
1067 if (a->dport < b->dport)
1073 static int alloc_channel_id(Ssh ssh)
1075 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1076 unsigned low, high, mid;
1078 struct ssh_channel *c;
1081 * First-fit allocation of channel numbers: always pick the
1082 * lowest unused one. To do this, binary-search using the
1083 * counted B-tree to find the largest channel ID which is in a
1084 * contiguous sequence from the beginning. (Precisely
1085 * everything in that sequence must have ID equal to its tree
1086 * index plus CHANNEL_NUMBER_OFFSET.)
1088 tsize = count234(ssh->channels);
1092 while (high - low > 1) {
1093 mid = (high + low) / 2;
1094 c = index234(ssh->channels, mid);
1095 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1096 low = mid; /* this one is fine */
1098 high = mid; /* this one is past it */
1101 * Now low points to either -1, or the tree index of the
1102 * largest ID in the initial sequence.
1105 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1106 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1108 return low + 1 + CHANNEL_NUMBER_OFFSET;
1111 static void c_write_stderr(int trusted, const char *buf, int len)
1114 for (i = 0; i < len; i++)
1115 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1116 fputc(buf[i], stderr);
1119 static void c_write(Ssh ssh, const char *buf, int len)
1121 if (flags & FLAG_STDERR)
1122 c_write_stderr(1, buf, len);
1124 from_backend(ssh->frontend, 1, buf, len);
1127 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1129 if (flags & FLAG_STDERR)
1130 c_write_stderr(0, buf, len);
1132 from_backend_untrusted(ssh->frontend, buf, len);
1135 static void c_write_str(Ssh ssh, const char *buf)
1137 c_write(ssh, buf, strlen(buf));
1140 static void ssh_free_packet(struct Packet *pkt)
1145 static struct Packet *ssh_new_packet(void)
1147 struct Packet *pkt = snew(struct Packet);
1149 pkt->body = pkt->data = NULL;
1151 pkt->logmode = PKTLOG_EMIT;
1159 * Collect incoming data in the incoming packet buffer.
1160 * Decipher and verify the packet when it is completely read.
1161 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1162 * Update the *data and *datalen variables.
1163 * Return a Packet structure when a packet is completed.
1165 static struct Packet *ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1167 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1169 crBegin(ssh->ssh1_rdpkt_crstate);
1171 st->pktin = ssh_new_packet();
1173 st->pktin->type = 0;
1174 st->pktin->length = 0;
1176 for (st->i = st->len = 0; st->i < 4; st->i++) {
1177 while ((*datalen) == 0)
1179 st->len = (st->len << 8) + **data;
1180 (*data)++, (*datalen)--;
1183 st->pad = 8 - (st->len % 8);
1184 st->biglen = st->len + st->pad;
1185 st->pktin->length = st->len - 5;
1187 if (st->biglen < 0) {
1188 bombout(("Extremely large packet length from server suggests"
1189 " data stream corruption"));
1190 ssh_free_packet(st->pktin);
1194 st->pktin->maxlen = st->biglen;
1195 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1197 st->to_read = st->biglen;
1198 st->p = st->pktin->data;
1199 while (st->to_read > 0) {
1200 st->chunk = st->to_read;
1201 while ((*datalen) == 0)
1203 if (st->chunk > (*datalen))
1204 st->chunk = (*datalen);
1205 memcpy(st->p, *data, st->chunk);
1207 *datalen -= st->chunk;
1209 st->to_read -= st->chunk;
1212 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1213 st->biglen, NULL)) {
1214 bombout(("Network attack (CRC compensation) detected!"));
1215 ssh_free_packet(st->pktin);
1220 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1222 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1223 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1224 if (st->gotcrc != st->realcrc) {
1225 bombout(("Incorrect CRC received on packet"));
1226 ssh_free_packet(st->pktin);
1230 st->pktin->body = st->pktin->data + st->pad + 1;
1231 st->pktin->savedpos = 0;
1233 if (ssh->v1_compressing) {
1234 unsigned char *decompblk;
1236 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1237 st->pktin->body - 1, st->pktin->length + 1,
1238 &decompblk, &decomplen)) {
1239 bombout(("Zlib decompression encountered invalid data"));
1240 ssh_free_packet(st->pktin);
1244 if (st->pktin->maxlen < st->pad + decomplen) {
1245 st->pktin->maxlen = st->pad + decomplen;
1246 st->pktin->data = sresize(st->pktin->data,
1247 st->pktin->maxlen + APIEXTRA,
1249 st->pktin->body = st->pktin->data + st->pad + 1;
1252 memcpy(st->pktin->body - 1, decompblk, decomplen);
1254 st->pktin->length = decomplen - 1;
1257 st->pktin->type = st->pktin->body[-1];
1260 * Now pktin->body and pktin->length identify the semantic content
1261 * of the packet, excluding the initial type byte.
1265 * Log incoming packet, possibly omitting sensitive fields.
1269 struct logblank_t blank;
1270 if (ssh->logomitdata) {
1271 int do_blank = FALSE, blank_prefix = 0;
1272 /* "Session data" packets - omit the data field */
1273 if ((st->pktin->type == SSH1_SMSG_STDOUT_DATA) ||
1274 (st->pktin->type == SSH1_SMSG_STDERR_DATA)) {
1275 do_blank = TRUE; blank_prefix = 4;
1276 } else if (st->pktin->type == SSH1_MSG_CHANNEL_DATA) {
1277 do_blank = TRUE; blank_prefix = 8;
1280 blank.offset = blank_prefix;
1281 blank.len = st->pktin->length;
1282 blank.type = PKTLOG_OMIT;
1286 log_packet(ssh->logctx,
1287 PKT_INCOMING, st->pktin->type,
1288 ssh1_pkt_type(st->pktin->type),
1289 st->pktin->body, st->pktin->length,
1290 nblanks, &blank, NULL);
1293 crFinish(st->pktin);
1296 static struct Packet *ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1298 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1300 crBegin(ssh->ssh2_rdpkt_crstate);
1302 st->pktin = ssh_new_packet();
1304 st->pktin->type = 0;
1305 st->pktin->length = 0;
1307 st->cipherblk = ssh->sccipher->blksize;
1310 if (st->cipherblk < 8)
1312 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1314 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1317 * When dealing with a CBC-mode cipher, we want to avoid the
1318 * possibility of an attacker's tweaking the ciphertext stream
1319 * so as to cause us to feed the same block to the block
1320 * cipher more than once and thus leak information
1321 * (VU#958563). The way we do this is not to take any
1322 * decisions on the basis of anything we've decrypted until
1323 * we've verified it with a MAC. That includes the packet
1324 * length, so we just read data and check the MAC repeatedly,
1325 * and when the MAC passes, see if the length we've got is
1329 /* May as well allocate the whole lot now. */
1330 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1333 /* Read an amount corresponding to the MAC. */
1334 for (st->i = 0; st->i < st->maclen; st->i++) {
1335 while ((*datalen) == 0)
1337 st->pktin->data[st->i] = *(*data)++;
1343 unsigned char seq[4];
1344 ssh->scmac->start(ssh->sc_mac_ctx);
1345 PUT_32BIT(seq, st->incoming_sequence);
1346 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1349 for (;;) { /* Once around this loop per cipher block. */
1350 /* Read another cipher-block's worth, and tack it onto the end. */
1351 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1352 while ((*datalen) == 0)
1354 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1357 /* Decrypt one more block (a little further back in the stream). */
1358 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1359 st->pktin->data + st->packetlen,
1361 /* Feed that block to the MAC. */
1362 ssh->scmac->bytes(ssh->sc_mac_ctx,
1363 st->pktin->data + st->packetlen, st->cipherblk);
1364 st->packetlen += st->cipherblk;
1365 /* See if that gives us a valid packet. */
1366 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1367 st->pktin->data + st->packetlen) &&
1368 ((st->len = toint(GET_32BIT(st->pktin->data))) ==
1371 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1372 bombout(("No valid incoming packet found"));
1373 ssh_free_packet(st->pktin);
1377 st->pktin->maxlen = st->packetlen + st->maclen;
1378 st->pktin->data = sresize(st->pktin->data,
1379 st->pktin->maxlen + APIEXTRA,
1382 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1385 * Acquire and decrypt the first block of the packet. This will
1386 * contain the length and padding details.
1388 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1389 while ((*datalen) == 0)
1391 st->pktin->data[st->i] = *(*data)++;
1396 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1397 st->pktin->data, st->cipherblk);
1400 * Now get the length figure.
1402 st->len = toint(GET_32BIT(st->pktin->data));
1405 * _Completely_ silly lengths should be stomped on before they
1406 * do us any more damage.
1408 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1409 (st->len + 4) % st->cipherblk != 0) {
1410 bombout(("Incoming packet was garbled on decryption"));
1411 ssh_free_packet(st->pktin);
1416 * So now we can work out the total packet length.
1418 st->packetlen = st->len + 4;
1421 * Allocate memory for the rest of the packet.
1423 st->pktin->maxlen = st->packetlen + st->maclen;
1424 st->pktin->data = sresize(st->pktin->data,
1425 st->pktin->maxlen + APIEXTRA,
1429 * Read and decrypt the remainder of the packet.
1431 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1433 while ((*datalen) == 0)
1435 st->pktin->data[st->i] = *(*data)++;
1438 /* Decrypt everything _except_ the MAC. */
1440 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1441 st->pktin->data + st->cipherblk,
1442 st->packetlen - st->cipherblk);
1448 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1449 st->len + 4, st->incoming_sequence)) {
1450 bombout(("Incorrect MAC received on packet"));
1451 ssh_free_packet(st->pktin);
1455 /* Get and sanity-check the amount of random padding. */
1456 st->pad = st->pktin->data[4];
1457 if (st->pad < 4 || st->len - st->pad < 1) {
1458 bombout(("Invalid padding length on received packet"));
1459 ssh_free_packet(st->pktin);
1463 * This enables us to deduce the payload length.
1465 st->payload = st->len - st->pad - 1;
1467 st->pktin->length = st->payload + 5;
1468 st->pktin->encrypted_len = st->packetlen;
1470 st->pktin->sequence = st->incoming_sequence++;
1473 * Decompress packet payload.
1476 unsigned char *newpayload;
1479 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1480 st->pktin->data + 5, st->pktin->length - 5,
1481 &newpayload, &newlen)) {
1482 if (st->pktin->maxlen < newlen + 5) {
1483 st->pktin->maxlen = newlen + 5;
1484 st->pktin->data = sresize(st->pktin->data,
1485 st->pktin->maxlen + APIEXTRA,
1488 st->pktin->length = 5 + newlen;
1489 memcpy(st->pktin->data + 5, newpayload, newlen);
1495 * pktin->body and pktin->length should identify the semantic
1496 * content of the packet, excluding the initial type byte.
1498 st->pktin->type = st->pktin->data[5];
1499 st->pktin->body = st->pktin->data + 6;
1500 st->pktin->length = st->packetlen - 6 - st->pad;
1501 st->pktin->savedpos = 0;
1502 assert(st->pktin->length >= 0); /* one last double-check */
1505 * Log incoming packet, possibly omitting sensitive fields.
1509 struct logblank_t blank;
1510 if (ssh->logomitdata) {
1511 int do_blank = FALSE, blank_prefix = 0;
1512 /* "Session data" packets - omit the data field */
1513 if (st->pktin->type == SSH2_MSG_CHANNEL_DATA) {
1514 do_blank = TRUE; blank_prefix = 8;
1515 } else if (st->pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
1516 do_blank = TRUE; blank_prefix = 12;
1519 blank.offset = blank_prefix;
1520 blank.len = (st->pktin->length-6) - blank_prefix;
1521 blank.type = PKTLOG_OMIT;
1525 log_packet(ssh->logctx, PKT_INCOMING, st->pktin->type,
1526 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
1528 st->pktin->body, st->pktin->length,
1529 nblanks, &blank, &st->pktin->sequence);
1532 crFinish(st->pktin);
1535 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1537 int pad, biglen, i, pktoffs;
1541 * XXX various versions of SC (including 8.8.4) screw up the
1542 * register allocation in this function and use the same register
1543 * (D6) for len and as a temporary, with predictable results. The
1544 * following sledgehammer prevents this.
1551 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1552 ssh1_pkt_type(pkt->data[12]),
1553 pkt->body, pkt->length - (pkt->body - pkt->data),
1554 pkt->nblanks, pkt->blanks, NULL);
1555 sfree(pkt->blanks); pkt->blanks = NULL;
1558 if (ssh->v1_compressing) {
1559 unsigned char *compblk;
1561 zlib_compress_block(ssh->cs_comp_ctx,
1562 pkt->data + 12, pkt->length - 12,
1563 &compblk, &complen);
1564 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1565 memcpy(pkt->data + 12, compblk, complen);
1567 pkt->length = complen + 12;
1570 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1572 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1573 pad = 8 - (len % 8);
1575 biglen = len + pad; /* len(padding+type+data+CRC) */
1577 for (i = pktoffs; i < 4+8; i++)
1578 pkt->data[i] = random_byte();
1579 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
1580 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
1581 PUT_32BIT(pkt->data + pktoffs, len);
1584 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
1585 pkt->data + pktoffs + 4, biglen);
1587 if (offset_p) *offset_p = pktoffs;
1588 return biglen + 4; /* len(length+padding+type+data+CRC) */
1591 static int s_write(Ssh ssh, void *data, int len)
1594 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
1596 return sk_write(ssh->s, (char *)data, len);
1599 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1601 int len, backlog, offset;
1602 len = s_wrpkt_prepare(ssh, pkt, &offset);
1603 backlog = s_write(ssh, pkt->data + offset, len);
1604 if (backlog > SSH_MAX_BACKLOG)
1605 ssh_throttle_all(ssh, 1, backlog);
1606 ssh_free_packet(pkt);
1609 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1612 len = s_wrpkt_prepare(ssh, pkt, &offset);
1613 if (ssh->deferred_len + len > ssh->deferred_size) {
1614 ssh->deferred_size = ssh->deferred_len + len + 128;
1615 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1619 memcpy(ssh->deferred_send_data + ssh->deferred_len,
1620 pkt->data + offset, len);
1621 ssh->deferred_len += len;
1622 ssh_free_packet(pkt);
1626 * Construct a SSH-1 packet with the specified contents.
1627 * (This all-at-once interface used to be the only one, but now SSH-1
1628 * packets can also be constructed incrementally.)
1630 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
1636 pkt = ssh1_pkt_init(pkttype);
1638 while ((argtype = va_arg(ap, int)) != PKT_END) {
1639 unsigned char *argp, argchar;
1641 unsigned long argint;
1644 /* Actual fields in the packet */
1646 argint = va_arg(ap, int);
1647 ssh_pkt_adduint32(pkt, argint);
1650 argchar = (unsigned char) va_arg(ap, int);
1651 ssh_pkt_addbyte(pkt, argchar);
1654 argp = va_arg(ap, unsigned char *);
1655 arglen = va_arg(ap, int);
1656 ssh_pkt_adddata(pkt, argp, arglen);
1659 sargp = va_arg(ap, char *);
1660 ssh_pkt_addstring(pkt, sargp);
1663 bn = va_arg(ap, Bignum);
1664 ssh1_pkt_addmp(pkt, bn);
1666 /* Tokens for modifications to packet logging */
1668 dont_log_password(ssh, pkt, PKTLOG_BLANK);
1671 dont_log_data(ssh, pkt, PKTLOG_OMIT);
1674 end_log_omission(ssh, pkt);
1682 static void send_packet(Ssh ssh, int pkttype, ...)
1686 va_start(ap, pkttype);
1687 pkt = construct_packet(ssh, pkttype, ap);
1692 static void defer_packet(Ssh ssh, int pkttype, ...)
1696 va_start(ap, pkttype);
1697 pkt = construct_packet(ssh, pkttype, ap);
1699 s_wrpkt_defer(ssh, pkt);
1702 static int ssh_versioncmp(char *a, char *b)
1705 unsigned long av, bv;
1707 av = strtoul(a, &ae, 10);
1708 bv = strtoul(b, &be, 10);
1710 return (av < bv ? -1 : +1);
1715 av = strtoul(ae, &ae, 10);
1716 bv = strtoul(be, &be, 10);
1718 return (av < bv ? -1 : +1);
1723 * Utility routines for putting an SSH-protocol `string' and
1724 * `uint32' into a hash state.
1726 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
1728 unsigned char lenblk[4];
1729 PUT_32BIT(lenblk, len);
1730 h->bytes(s, lenblk, 4);
1731 h->bytes(s, str, len);
1734 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
1736 unsigned char intblk[4];
1737 PUT_32BIT(intblk, i);
1738 h->bytes(s, intblk, 4);
1742 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
1744 static void ssh_pkt_ensure(struct Packet *pkt, int length)
1746 if (pkt->maxlen < length) {
1747 unsigned char *body = pkt->body;
1748 int offset = body ? body - pkt->data : 0;
1749 pkt->maxlen = length + 256;
1750 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
1751 if (body) pkt->body = pkt->data + offset;
1754 static void ssh_pkt_adddata(struct Packet *pkt, const void *data, int len)
1756 if (pkt->logmode != PKTLOG_EMIT) {
1758 pkt->blanks = sresize(pkt->blanks, pkt->nblanks, struct logblank_t);
1760 pkt->blanks[pkt->nblanks-1].offset = pkt->length -
1761 (pkt->body - pkt->data);
1762 pkt->blanks[pkt->nblanks-1].len = len;
1763 pkt->blanks[pkt->nblanks-1].type = pkt->logmode;
1766 ssh_pkt_ensure(pkt, pkt->length);
1767 memcpy(pkt->data + pkt->length - len, data, len);
1769 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
1771 ssh_pkt_adddata(pkt, &byte, 1);
1773 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
1775 ssh_pkt_adddata(pkt, &value, 1);
1777 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
1780 PUT_32BIT(x, value);
1781 ssh_pkt_adddata(pkt, x, 4);
1783 static void ssh_pkt_addstring_start(struct Packet *pkt)
1785 ssh_pkt_adduint32(pkt, 0);
1786 pkt->savedpos = pkt->length;
1788 static void ssh_pkt_addstring_str(struct Packet *pkt, const char *data)
1790 ssh_pkt_adddata(pkt, data, strlen(data));
1791 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1793 static void ssh_pkt_addstring_data(struct Packet *pkt, const char *data,
1796 ssh_pkt_adddata(pkt, data, len);
1797 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1799 static void ssh_pkt_addstring(struct Packet *pkt, const char *data)
1801 ssh_pkt_addstring_start(pkt);
1802 ssh_pkt_addstring_str(pkt, data);
1804 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
1806 int len = ssh1_bignum_length(b);
1807 unsigned char *data = snewn(len, unsigned char);
1808 (void) ssh1_write_bignum(data, b);
1809 ssh_pkt_adddata(pkt, data, len);
1812 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
1815 int i, n = (bignum_bitcount(b) + 7) / 8;
1816 p = snewn(n + 1, unsigned char);
1818 for (i = 1; i <= n; i++)
1819 p[i] = bignum_byte(b, n - i);
1821 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1823 memmove(p, p + i, n + 1 - i);
1827 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
1831 p = ssh2_mpint_fmt(b, &len);
1832 ssh_pkt_addstring_start(pkt);
1833 ssh_pkt_addstring_data(pkt, (char *)p, len);
1837 static struct Packet *ssh1_pkt_init(int pkt_type)
1839 struct Packet *pkt = ssh_new_packet();
1840 pkt->length = 4 + 8; /* space for length + max padding */
1841 ssh_pkt_addbyte(pkt, pkt_type);
1842 pkt->body = pkt->data + pkt->length;
1846 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
1847 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
1848 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
1849 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
1850 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
1851 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
1852 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
1853 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
1854 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
1856 static struct Packet *ssh2_pkt_init(int pkt_type)
1858 struct Packet *pkt = ssh_new_packet();
1859 pkt->length = 5; /* space for packet length + padding length */
1861 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
1862 pkt->body = pkt->data + pkt->length; /* after packet type */
1867 * Construct an SSH-2 final-form packet: compress it, encrypt it,
1868 * put the MAC on it. Final packet, ready to be sent, is stored in
1869 * pkt->data. Total length is returned.
1871 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
1873 int cipherblk, maclen, padding, i;
1876 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1877 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1878 pkt->body, pkt->length - (pkt->body - pkt->data),
1879 pkt->nblanks, pkt->blanks, &ssh->v2_outgoing_sequence);
1880 sfree(pkt->blanks); pkt->blanks = NULL;
1884 * Compress packet payload.
1887 unsigned char *newpayload;
1890 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
1892 &newpayload, &newlen)) {
1894 ssh2_pkt_adddata(pkt, newpayload, newlen);
1900 * Add padding. At least four bytes, and must also bring total
1901 * length (minus MAC) up to a multiple of the block size.
1902 * If pkt->forcepad is set, make sure the packet is at least that size
1905 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
1906 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1908 if (pkt->length + padding < pkt->forcepad)
1909 padding = pkt->forcepad - pkt->length;
1911 (cipherblk - (pkt->length + padding) % cipherblk) % cipherblk;
1912 assert(padding <= 255);
1913 maclen = ssh->csmac ? ssh->csmac->len : 0;
1914 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
1915 pkt->data[4] = padding;
1916 for (i = 0; i < padding; i++)
1917 pkt->data[pkt->length + i] = random_byte();
1918 PUT_32BIT(pkt->data, pkt->length + padding - 4);
1920 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
1921 pkt->length + padding,
1922 ssh->v2_outgoing_sequence);
1923 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
1926 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
1927 pkt->data, pkt->length + padding);
1929 pkt->encrypted_len = pkt->length + padding;
1931 /* Ready-to-send packet starts at pkt->data. We return length. */
1932 return pkt->length + padding + maclen;
1936 * Routines called from the main SSH code to send packets. There
1937 * are quite a few of these, because we have two separate
1938 * mechanisms for delaying the sending of packets:
1940 * - In order to send an IGNORE message and a password message in
1941 * a single fixed-length blob, we require the ability to
1942 * concatenate the encrypted forms of those two packets _into_ a
1943 * single blob and then pass it to our <network.h> transport
1944 * layer in one go. Hence, there's a deferment mechanism which
1945 * works after packet encryption.
1947 * - In order to avoid sending any connection-layer messages
1948 * during repeat key exchange, we have to queue up any such
1949 * outgoing messages _before_ they are encrypted (and in
1950 * particular before they're allocated sequence numbers), and
1951 * then send them once we've finished.
1953 * I call these mechanisms `defer' and `queue' respectively, so as
1954 * to distinguish them reasonably easily.
1956 * The functions send_noqueue() and defer_noqueue() free the packet
1957 * structure they are passed. Every outgoing packet goes through
1958 * precisely one of these functions in its life; packets passed to
1959 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
1960 * these or get queued, and then when the queue is later emptied
1961 * the packets are all passed to defer_noqueue().
1963 * When using a CBC-mode cipher, it's necessary to ensure that an
1964 * attacker can't provide data to be encrypted using an IV that they
1965 * know. We ensure this by prefixing each packet that might contain
1966 * user data with an SSH_MSG_IGNORE. This is done using the deferral
1967 * mechanism, so in this case send_noqueue() ends up redirecting to
1968 * defer_noqueue(). If you don't like this inefficiency, don't use
1972 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
1973 static void ssh_pkt_defersend(Ssh);
1976 * Send an SSH-2 packet immediately, without queuing or deferring.
1978 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
1982 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
1983 /* We need to send two packets, so use the deferral mechanism. */
1984 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
1985 ssh_pkt_defersend(ssh);
1988 len = ssh2_pkt_construct(ssh, pkt);
1989 backlog = s_write(ssh, pkt->data, len);
1990 if (backlog > SSH_MAX_BACKLOG)
1991 ssh_throttle_all(ssh, 1, backlog);
1993 ssh->outgoing_data_size += pkt->encrypted_len;
1994 if (!ssh->kex_in_progress &&
1995 ssh->max_data_size != 0 &&
1996 ssh->outgoing_data_size > ssh->max_data_size)
1997 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
1999 ssh_free_packet(pkt);
2003 * Defer an SSH-2 packet.
2005 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2008 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2009 ssh->deferred_len == 0 && !noignore &&
2010 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2012 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2013 * get encrypted with a known IV.
2015 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2016 ssh2_pkt_addstring_start(ipkt);
2017 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2019 len = ssh2_pkt_construct(ssh, pkt);
2020 if (ssh->deferred_len + len > ssh->deferred_size) {
2021 ssh->deferred_size = ssh->deferred_len + len + 128;
2022 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2026 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->data, len);
2027 ssh->deferred_len += len;
2028 ssh->deferred_data_size += pkt->encrypted_len;
2029 ssh_free_packet(pkt);
2033 * Queue an SSH-2 packet.
2035 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2037 assert(ssh->queueing);
2039 if (ssh->queuelen >= ssh->queuesize) {
2040 ssh->queuesize = ssh->queuelen + 32;
2041 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2044 ssh->queue[ssh->queuelen++] = pkt;
2048 * Either queue or send a packet, depending on whether queueing is
2051 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2054 ssh2_pkt_queue(ssh, pkt);
2056 ssh2_pkt_send_noqueue(ssh, pkt);
2060 * Either queue or defer a packet, depending on whether queueing is
2063 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2066 ssh2_pkt_queue(ssh, pkt);
2068 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2072 * Send the whole deferred data block constructed by
2073 * ssh2_pkt_defer() or SSH-1's defer_packet().
2075 * The expected use of the defer mechanism is that you call
2076 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2077 * not currently queueing, this simply sets up deferred_send_data
2078 * and then sends it. If we _are_ currently queueing, the calls to
2079 * ssh2_pkt_defer() put the deferred packets on to the queue
2080 * instead, and therefore ssh_pkt_defersend() has no deferred data
2081 * to send. Hence, there's no need to make it conditional on
2084 static void ssh_pkt_defersend(Ssh ssh)
2087 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2088 ssh->deferred_len = ssh->deferred_size = 0;
2089 sfree(ssh->deferred_send_data);
2090 ssh->deferred_send_data = NULL;
2091 if (backlog > SSH_MAX_BACKLOG)
2092 ssh_throttle_all(ssh, 1, backlog);
2094 ssh->outgoing_data_size += ssh->deferred_data_size;
2095 if (!ssh->kex_in_progress &&
2096 ssh->max_data_size != 0 &&
2097 ssh->outgoing_data_size > ssh->max_data_size)
2098 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2099 ssh->deferred_data_size = 0;
2103 * Send a packet whose length needs to be disguised (typically
2104 * passwords or keyboard-interactive responses).
2106 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2112 * The simplest way to do this is to adjust the
2113 * variable-length padding field in the outgoing packet.
2115 * Currently compiled out, because some Cisco SSH servers
2116 * don't like excessively padded packets (bah, why's it
2119 pkt->forcepad = padsize;
2120 ssh2_pkt_send(ssh, pkt);
2125 * If we can't do that, however, an alternative approach is
2126 * to use the pkt_defer mechanism to bundle the packet
2127 * tightly together with an SSH_MSG_IGNORE such that their
2128 * combined length is a constant. So first we construct the
2129 * final form of this packet and defer its sending.
2131 ssh2_pkt_defer(ssh, pkt);
2134 * Now construct an SSH_MSG_IGNORE which includes a string
2135 * that's an exact multiple of the cipher block size. (If
2136 * the cipher is NULL so that the block size is
2137 * unavailable, we don't do this trick at all, because we
2138 * gain nothing by it.)
2140 if (ssh->cscipher &&
2141 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2144 stringlen = (256 - ssh->deferred_len);
2145 stringlen += ssh->cscipher->blksize - 1;
2146 stringlen -= (stringlen % ssh->cscipher->blksize);
2149 * Temporarily disable actual compression, so we
2150 * can guarantee to get this string exactly the
2151 * length we want it. The compression-disabling
2152 * routine should return an integer indicating how
2153 * many bytes we should adjust our string length
2157 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2159 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2160 ssh2_pkt_addstring_start(pkt);
2161 for (i = 0; i < stringlen; i++) {
2162 char c = (char) random_byte();
2163 ssh2_pkt_addstring_data(pkt, &c, 1);
2165 ssh2_pkt_defer(ssh, pkt);
2167 ssh_pkt_defersend(ssh);
2172 * Send all queued SSH-2 packets. We send them by means of
2173 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2174 * packets that needed to be lumped together.
2176 static void ssh2_pkt_queuesend(Ssh ssh)
2180 assert(!ssh->queueing);
2182 for (i = 0; i < ssh->queuelen; i++)
2183 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2186 ssh_pkt_defersend(ssh);
2190 void bndebug(char *string, Bignum b)
2194 p = ssh2_mpint_fmt(b, &len);
2195 debug(("%s", string));
2196 for (i = 0; i < len; i++)
2197 debug((" %02x", p[i]));
2203 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2207 p = ssh2_mpint_fmt(b, &len);
2208 hash_string(h, s, p, len);
2213 * Packet decode functions for both SSH-1 and SSH-2.
2215 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2217 unsigned long value;
2218 if (pkt->length - pkt->savedpos < 4)
2219 return 0; /* arrgh, no way to decline (FIXME?) */
2220 value = GET_32BIT(pkt->body + pkt->savedpos);
2224 static int ssh2_pkt_getbool(struct Packet *pkt)
2226 unsigned long value;
2227 if (pkt->length - pkt->savedpos < 1)
2228 return 0; /* arrgh, no way to decline (FIXME?) */
2229 value = pkt->body[pkt->savedpos] != 0;
2233 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2238 if (pkt->length - pkt->savedpos < 4)
2240 len = toint(GET_32BIT(pkt->body + pkt->savedpos));
2245 if (pkt->length - pkt->savedpos < *length)
2247 *p = (char *)(pkt->body + pkt->savedpos);
2248 pkt->savedpos += *length;
2250 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2252 if (pkt->length - pkt->savedpos < length)
2254 pkt->savedpos += length;
2255 return pkt->body + (pkt->savedpos - length);
2257 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2258 unsigned char **keystr)
2262 j = makekey(pkt->body + pkt->savedpos,
2263 pkt->length - pkt->savedpos,
2270 assert(pkt->savedpos < pkt->length);
2274 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2279 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2280 pkt->length - pkt->savedpos, &b);
2288 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2294 ssh_pkt_getstring(pkt, &p, &length);
2299 b = bignum_from_bytes((unsigned char *)p, length);
2304 * Helper function to add an SSH-2 signature blob to a packet.
2305 * Expects to be shown the public key blob as well as the signature
2306 * blob. Normally works just like ssh2_pkt_addstring, but will
2307 * fiddle with the signature packet if necessary for
2308 * BUG_SSH2_RSA_PADDING.
2310 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2311 void *pkblob_v, int pkblob_len,
2312 void *sigblob_v, int sigblob_len)
2314 unsigned char *pkblob = (unsigned char *)pkblob_v;
2315 unsigned char *sigblob = (unsigned char *)sigblob_v;
2317 /* dmemdump(pkblob, pkblob_len); */
2318 /* dmemdump(sigblob, sigblob_len); */
2321 * See if this is in fact an ssh-rsa signature and a buggy
2322 * server; otherwise we can just do this the easy way.
2324 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) && pkblob_len > 4+7+4 &&
2325 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2326 int pos, len, siglen;
2329 * Find the byte length of the modulus.
2332 pos = 4+7; /* skip over "ssh-rsa" */
2333 len = toint(GET_32BIT(pkblob+pos)); /* get length of exponent */
2334 if (len < 0 || len > pkblob_len - pos - 4)
2336 pos += 4 + len; /* skip over exponent */
2337 if (pkblob_len - pos < 4)
2339 len = toint(GET_32BIT(pkblob+pos)); /* find length of modulus */
2340 if (len < 0 || len > pkblob_len - pos - 4)
2342 pos += 4; /* find modulus itself */
2343 while (len > 0 && pkblob[pos] == 0)
2345 /* debug(("modulus length is %d\n", len)); */
2348 * Now find the signature integer.
2350 pos = 4+7; /* skip over "ssh-rsa" */
2351 if (sigblob_len < pos+4)
2353 siglen = toint(GET_32BIT(sigblob+pos));
2354 if (siglen != sigblob_len - pos - 4)
2356 /* debug(("signature length is %d\n", siglen)); */
2358 if (len != siglen) {
2359 unsigned char newlen[4];
2360 ssh2_pkt_addstring_start(pkt);
2361 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2362 /* dmemdump(sigblob, pos); */
2363 pos += 4; /* point to start of actual sig */
2364 PUT_32BIT(newlen, len);
2365 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2366 /* dmemdump(newlen, 4); */
2368 while (len-- > siglen) {
2369 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2370 /* dmemdump(newlen, 1); */
2372 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2373 /* dmemdump(sigblob+pos, siglen); */
2377 /* Otherwise fall through and do it the easy way. We also come
2378 * here as a fallback if we discover above that the key blob
2379 * is misformatted in some way. */
2383 ssh2_pkt_addstring_start(pkt);
2384 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2388 * Examine the remote side's version string and compare it against
2389 * a list of known buggy implementations.
2391 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2393 char *imp; /* pointer to implementation part */
2395 imp += strcspn(imp, "-");
2397 imp += strcspn(imp, "-");
2400 ssh->remote_bugs = 0;
2403 * General notes on server version strings:
2404 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2405 * here -- in particular, we've heard of one that's perfectly happy
2406 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2407 * so we can't distinguish them.
2409 if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
2410 (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
2411 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2412 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2413 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2414 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2416 * These versions don't support SSH1_MSG_IGNORE, so we have
2417 * to use a different defence against password length
2420 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2421 logevent("We believe remote version has SSH-1 ignore bug");
2424 if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
2425 (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
2426 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2428 * These versions need a plain password sent; they can't
2429 * handle having a null and a random length of data after
2432 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2433 logevent("We believe remote version needs a plain SSH-1 password");
2436 if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
2437 (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
2438 (!strcmp(imp, "Cisco-1.25")))) {
2440 * These versions apparently have no clue whatever about
2441 * RSA authentication and will panic and die if they see
2442 * an AUTH_RSA message.
2444 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2445 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2448 if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
2449 (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
2450 !wc_match("* VShell", imp) &&
2451 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2452 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2453 wc_match("2.1 *", imp)))) {
2455 * These versions have the HMAC bug.
2457 ssh->remote_bugs |= BUG_SSH2_HMAC;
2458 logevent("We believe remote version has SSH-2 HMAC bug");
2461 if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
2462 (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
2463 !wc_match("* VShell", imp) &&
2464 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2466 * These versions have the key-derivation bug (failing to
2467 * include the literal shared secret in the hashes that
2468 * generate the keys).
2470 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2471 logevent("We believe remote version has SSH-2 key-derivation bug");
2474 if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
2475 (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
2476 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2477 wc_match("OpenSSH_3.[0-2]*", imp)))) {
2479 * These versions have the SSH-2 RSA padding bug.
2481 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2482 logevent("We believe remote version has SSH-2 RSA padding bug");
2485 if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
2486 (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
2487 wc_match("OpenSSH_2.[0-2]*", imp))) {
2489 * These versions have the SSH-2 session-ID bug in
2490 * public-key authentication.
2492 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2493 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2496 if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
2497 (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
2498 (wc_match("DigiSSH_2.0", imp) ||
2499 wc_match("OpenSSH_2.[0-4]*", imp) ||
2500 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2501 wc_match("Sun_SSH_1.0", imp) ||
2502 wc_match("Sun_SSH_1.0.1", imp) ||
2503 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2504 wc_match("WeOnlyDo-*", imp)))) {
2506 * These versions have the SSH-2 rekey bug.
2508 ssh->remote_bugs |= BUG_SSH2_REKEY;
2509 logevent("We believe remote version has SSH-2 rekey bug");
2512 if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
2513 (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
2514 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2515 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2517 * This version ignores our makpkt and needs to be throttled.
2519 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2520 logevent("We believe remote version ignores SSH-2 maximum packet size");
2523 if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
2525 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2526 * none detected automatically.
2528 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2529 logevent("We believe remote version has SSH-2 ignore bug");
2532 if (conf_get_int(ssh->conf, CONF_sshbug_winadj) == FORCE_ON) {
2534 * Servers that don't support our winadj request for one
2535 * reason or another. Currently, none detected automatically.
2537 ssh->remote_bugs |= BUG_CHOKES_ON_WINADJ;
2538 logevent("We believe remote version has winadj bug");
2543 * The `software version' part of an SSH version string is required
2544 * to contain no spaces or minus signs.
2546 static void ssh_fix_verstring(char *str)
2548 /* Eat "SSH-<protoversion>-". */
2549 assert(*str == 'S'); str++;
2550 assert(*str == 'S'); str++;
2551 assert(*str == 'H'); str++;
2552 assert(*str == '-'); str++;
2553 while (*str && *str != '-') str++;
2554 assert(*str == '-'); str++;
2556 /* Convert minus signs and spaces in the remaining string into
2559 if (*str == '-' || *str == ' ')
2566 * Send an appropriate SSH version string.
2568 static void ssh_send_verstring(Ssh ssh, char *svers)
2572 if (ssh->version == 2) {
2574 * Construct a v2 version string.
2576 verstring = dupprintf("SSH-2.0-%s\015\012", sshver);
2579 * Construct a v1 version string.
2581 verstring = dupprintf("SSH-%s-%s\012",
2582 (ssh_versioncmp(svers, "1.5") <= 0 ?
2587 ssh_fix_verstring(verstring);
2589 if (ssh->version == 2) {
2592 * Record our version string.
2594 len = strcspn(verstring, "\015\012");
2595 ssh->v_c = snewn(len + 1, char);
2596 memcpy(ssh->v_c, verstring, len);
2600 logeventf(ssh, "We claim version: %.*s",
2601 strcspn(verstring, "\015\012"), verstring);
2602 s_write(ssh, verstring, strlen(verstring));
2606 static int do_ssh_init(Ssh ssh, unsigned char c)
2608 struct do_ssh_init_state {
2617 crState(do_ssh_init_state);
2621 /* Search for a line beginning with the string "SSH-" in the input. */
2623 if (c != 'S') goto no;
2625 if (c != 'S') goto no;
2627 if (c != 'H') goto no;
2629 if (c != '-') goto no;
2638 s->vstring = snewn(s->vstrsize, char);
2639 strcpy(s->vstring, "SSH-");
2643 crReturn(1); /* get another char */
2644 if (s->vslen >= s->vstrsize - 1) {
2646 s->vstring = sresize(s->vstring, s->vstrsize, char);
2648 s->vstring[s->vslen++] = c;
2651 s->version[s->i] = '\0';
2653 } else if (s->i < sizeof(s->version) - 1)
2654 s->version[s->i++] = c;
2655 } else if (c == '\012')
2659 ssh->agentfwd_enabled = FALSE;
2660 ssh->rdpkt2_state.incoming_sequence = 0;
2662 s->vstring[s->vslen] = 0;
2663 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
2664 logeventf(ssh, "Server version: %s", s->vstring);
2665 ssh_detect_bugs(ssh, s->vstring);
2668 * Decide which SSH protocol version to support.
2671 /* Anything strictly below "2.0" means protocol 1 is supported. */
2672 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
2673 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2674 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
2676 if (conf_get_int(ssh->conf, CONF_sshprot) == 0 && !s->proto1) {
2677 bombout(("SSH protocol version 1 required by user but not provided by server"));
2680 if (conf_get_int(ssh->conf, CONF_sshprot) == 3 && !s->proto2) {
2681 bombout(("SSH protocol version 2 required by user but not provided by server"));
2685 if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
2690 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
2692 /* Send the version string, if we haven't already */
2693 if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
2694 ssh_send_verstring(ssh, s->version);
2696 if (ssh->version == 2) {
2699 * Record their version string.
2701 len = strcspn(s->vstring, "\015\012");
2702 ssh->v_s = snewn(len + 1, char);
2703 memcpy(ssh->v_s, s->vstring, len);
2707 * Initialise SSH-2 protocol.
2709 ssh->protocol = ssh2_protocol;
2710 ssh2_protocol_setup(ssh);
2711 ssh->s_rdpkt = ssh2_rdpkt;
2714 * Initialise SSH-1 protocol.
2716 ssh->protocol = ssh1_protocol;
2717 ssh1_protocol_setup(ssh);
2718 ssh->s_rdpkt = ssh1_rdpkt;
2720 if (ssh->version == 2)
2721 do_ssh2_transport(ssh, NULL, -1, NULL);
2723 update_specials_menu(ssh->frontend);
2724 ssh->state = SSH_STATE_BEFORE_SIZE;
2725 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
2732 static void ssh_process_incoming_data(Ssh ssh,
2733 unsigned char **data, int *datalen)
2735 struct Packet *pktin;
2737 pktin = ssh->s_rdpkt(ssh, data, datalen);
2739 ssh->protocol(ssh, NULL, 0, pktin);
2740 ssh_free_packet(pktin);
2744 static void ssh_queue_incoming_data(Ssh ssh,
2745 unsigned char **data, int *datalen)
2747 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
2752 static void ssh_process_queued_incoming_data(Ssh ssh)
2755 unsigned char *data;
2758 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
2759 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
2763 while (!ssh->frozen && len > 0)
2764 ssh_process_incoming_data(ssh, &data, &len);
2767 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
2771 static void ssh_set_frozen(Ssh ssh, int frozen)
2774 sk_set_frozen(ssh->s, frozen);
2775 ssh->frozen = frozen;
2778 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
2780 /* Log raw data, if we're in that mode. */
2782 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
2785 crBegin(ssh->ssh_gotdata_crstate);
2788 * To begin with, feed the characters one by one to the
2789 * protocol initialisation / selection function do_ssh_init().
2790 * When that returns 0, we're done with the initial greeting
2791 * exchange and can move on to packet discipline.
2794 int ret; /* need not be kept across crReturn */
2796 crReturnV; /* more data please */
2797 ret = do_ssh_init(ssh, *data);
2805 * We emerge from that loop when the initial negotiation is
2806 * over and we have selected an s_rdpkt function. Now pass
2807 * everything to s_rdpkt, and then pass the resulting packets
2808 * to the proper protocol handler.
2812 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
2814 ssh_queue_incoming_data(ssh, &data, &datalen);
2815 /* This uses up all data and cannot cause anything interesting
2816 * to happen; indeed, for anything to happen at all, we must
2817 * return, so break out. */
2819 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
2820 /* This uses up some or all data, and may freeze the
2822 ssh_process_queued_incoming_data(ssh);
2824 /* This uses up some or all data, and may freeze the
2826 ssh_process_incoming_data(ssh, &data, &datalen);
2828 /* FIXME this is probably EBW. */
2829 if (ssh->state == SSH_STATE_CLOSED)
2832 /* We're out of data. Go and get some more. */
2838 static int ssh_do_close(Ssh ssh, int notify_exit)
2841 struct ssh_channel *c;
2843 ssh->state = SSH_STATE_CLOSED;
2844 expire_timer_context(ssh);
2849 notify_remote_exit(ssh->frontend);
2854 * Now we must shut down any port- and X-forwarded channels going
2855 * through this connection.
2857 if (ssh->channels) {
2858 while (NULL != (c = index234(ssh->channels, 0))) {
2861 x11_close(c->u.x11.s);
2864 case CHAN_SOCKDATA_DORMANT:
2865 pfd_close(c->u.pfd.s);
2868 del234(ssh->channels, c); /* moving next one to index 0 */
2869 if (ssh->version == 2)
2870 bufchain_clear(&c->v.v2.outbuffer);
2875 * Go through port-forwardings, and close any associated
2876 * listening sockets.
2878 if (ssh->portfwds) {
2879 struct ssh_portfwd *pf;
2880 while (NULL != (pf = index234(ssh->portfwds, 0))) {
2881 /* Dispose of any listening socket. */
2883 pfd_terminate(pf->local);
2884 del234(ssh->portfwds, pf); /* moving next one to index 0 */
2887 freetree234(ssh->portfwds);
2888 ssh->portfwds = NULL;
2894 static void ssh_log(Plug plug, int type, SockAddr addr, int port,
2895 const char *error_msg, int error_code)
2897 Ssh ssh = (Ssh) plug;
2898 char addrbuf[256], *msg;
2900 sk_getaddr(addr, addrbuf, lenof(addrbuf));
2903 msg = dupprintf("Connecting to %s port %d", addrbuf, port);
2905 msg = dupprintf("Failed to connect to %s: %s", addrbuf, error_msg);
2911 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
2914 Ssh ssh = (Ssh) plug;
2915 int need_notify = ssh_do_close(ssh, FALSE);
2918 if (!ssh->close_expected)
2919 error_msg = "Server unexpectedly closed network connection";
2921 error_msg = "Server closed network connection";
2924 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
2928 notify_remote_exit(ssh->frontend);
2931 logevent(error_msg);
2932 if (!ssh->close_expected || !ssh->clean_exit)
2933 connection_fatal(ssh->frontend, "%s", error_msg);
2937 static int ssh_receive(Plug plug, int urgent, char *data, int len)
2939 Ssh ssh = (Ssh) plug;
2940 ssh_gotdata(ssh, (unsigned char *)data, len);
2941 if (ssh->state == SSH_STATE_CLOSED) {
2942 ssh_do_close(ssh, TRUE);
2948 static void ssh_sent(Plug plug, int bufsize)
2950 Ssh ssh = (Ssh) plug;
2952 * If the send backlog on the SSH socket itself clears, we
2953 * should unthrottle the whole world if it was throttled.
2955 if (bufsize < SSH_MAX_BACKLOG)
2956 ssh_throttle_all(ssh, 0, bufsize);
2960 * Connect to specified host and port.
2961 * Returns an error message, or NULL on success.
2962 * Also places the canonical host name into `realhost'. It must be
2963 * freed by the caller.
2965 static const char *connect_to_host(Ssh ssh, char *host, int port,
2966 char **realhost, int nodelay, int keepalive)
2968 static const struct plug_function_table fn_table = {
2979 int addressfamily, sshprot;
2981 loghost = conf_get_str(ssh->conf, CONF_loghost);
2985 ssh->savedhost = dupstr(loghost);
2986 ssh->savedport = 22; /* default ssh port */
2989 * A colon suffix on savedhost also lets us affect
2992 * (FIXME: do something about IPv6 address literals here.)
2994 colon = strrchr(ssh->savedhost, ':');
2998 ssh->savedport = atoi(colon);
3001 ssh->savedhost = dupstr(host);
3003 port = 22; /* default ssh port */
3004 ssh->savedport = port;
3010 addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
3011 logeventf(ssh, "Looking up host \"%s\"%s", host,
3012 (addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
3013 (addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" : "")));
3014 addr = name_lookup(host, port, realhost, ssh->conf, addressfamily);
3015 if ((err = sk_addr_error(addr)) != NULL) {
3019 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
3024 ssh->fn = &fn_table;
3025 ssh->s = new_connection(addr, *realhost, port,
3026 0, 1, nodelay, keepalive, (Plug) ssh, ssh->conf);
3027 if ((err = sk_socket_error(ssh->s)) != NULL) {
3029 notify_remote_exit(ssh->frontend);
3034 * If the SSH version number's fixed, set it now, and if it's SSH-2,
3035 * send the version string too.
3037 sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3042 ssh_send_verstring(ssh, NULL);
3046 * loghost, if configured, overrides realhost.
3050 *realhost = dupstr(loghost);
3057 * Throttle or unthrottle the SSH connection.
3059 static void ssh_throttle_conn(Ssh ssh, int adjust)
3061 int old_count = ssh->conn_throttle_count;
3062 ssh->conn_throttle_count += adjust;
3063 assert(ssh->conn_throttle_count >= 0);
3064 if (ssh->conn_throttle_count && !old_count) {
3065 ssh_set_frozen(ssh, 1);
3066 } else if (!ssh->conn_throttle_count && old_count) {
3067 ssh_set_frozen(ssh, 0);
3072 * Throttle or unthrottle _all_ local data streams (for when sends
3073 * on the SSH connection itself back up).
3075 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3078 struct ssh_channel *c;
3080 if (enable == ssh->throttled_all)
3082 ssh->throttled_all = enable;
3083 ssh->overall_bufsize = bufsize;
3086 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3088 case CHAN_MAINSESSION:
3090 * This is treated separately, outside the switch.
3094 x11_override_throttle(c->u.x11.s, enable);
3097 /* Agent channels require no buffer management. */
3100 pfd_override_throttle(c->u.pfd.s, enable);
3106 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3108 Ssh ssh = (Ssh) sshv;
3110 ssh->agent_response = reply;
3111 ssh->agent_response_len = replylen;
3113 if (ssh->version == 1)
3114 do_ssh1_login(ssh, NULL, -1, NULL);
3116 do_ssh2_authconn(ssh, NULL, -1, NULL);
3119 static void ssh_dialog_callback(void *sshv, int ret)
3121 Ssh ssh = (Ssh) sshv;
3123 ssh->user_response = ret;
3125 if (ssh->version == 1)
3126 do_ssh1_login(ssh, NULL, -1, NULL);
3128 do_ssh2_transport(ssh, NULL, -1, NULL);
3131 * This may have unfrozen the SSH connection, so do a
3134 ssh_process_queued_incoming_data(ssh);
3137 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3139 struct ssh_channel *c = (struct ssh_channel *)cv;
3141 void *sentreply = reply;
3143 c->u.a.outstanding_requests--;
3145 /* Fake SSH_AGENT_FAILURE. */
3146 sentreply = "\0\0\0\1\5";
3149 if (ssh->version == 2) {
3150 ssh2_add_channel_data(c, sentreply, replylen);
3153 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3154 PKT_INT, c->remoteid,
3157 PKT_DATA, sentreply, replylen,
3164 * If we've already seen an incoming EOF but haven't sent an
3165 * outgoing one, this may be the moment to send it.
3167 if (c->u.a.outstanding_requests == 0 && (c->closes & CLOSES_RCVD_EOF))
3168 sshfwd_write_eof(c);
3172 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3173 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3174 * => log `wire_reason'.
3176 static void ssh_disconnect(Ssh ssh, char *client_reason, char *wire_reason,
3177 int code, int clean_exit)
3181 client_reason = wire_reason;
3183 error = dupprintf("Disconnected: %s", client_reason);
3185 error = dupstr("Disconnected");
3187 if (ssh->version == 1) {
3188 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3190 } else if (ssh->version == 2) {
3191 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3192 ssh2_pkt_adduint32(pktout, code);
3193 ssh2_pkt_addstring(pktout, wire_reason);
3194 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3195 ssh2_pkt_send_noqueue(ssh, pktout);
3198 ssh->close_expected = TRUE;
3199 ssh->clean_exit = clean_exit;
3200 ssh_closing((Plug)ssh, error, 0, 0);
3205 * Handle the key exchange and user authentication phases.
3207 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
3208 struct Packet *pktin)
3211 unsigned char cookie[8], *ptr;
3212 struct MD5Context md5c;
3213 struct do_ssh1_login_state {
3216 unsigned char *rsabuf, *keystr1, *keystr2;
3217 unsigned long supported_ciphers_mask, supported_auths_mask;
3218 int tried_publickey, tried_agent;
3219 int tis_auth_refused, ccard_auth_refused;
3220 unsigned char session_id[16];
3222 void *publickey_blob;
3223 int publickey_bloblen;
3224 char *publickey_comment;
3225 int publickey_encrypted;
3226 prompts_t *cur_prompt;
3229 unsigned char request[5], *response, *p;
3239 struct RSAKey servkey, hostkey;
3241 crState(do_ssh1_login_state);
3248 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3249 bombout(("Public key packet not received"));
3253 logevent("Received public keys");
3255 ptr = ssh_pkt_getdata(pktin, 8);
3257 bombout(("SSH-1 public key packet stopped before random cookie"));
3260 memcpy(cookie, ptr, 8);
3262 if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
3263 !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) {
3264 bombout(("Failed to read SSH-1 public keys from public key packet"));
3269 * Log the host key fingerprint.
3273 logevent("Host key fingerprint is:");
3274 strcpy(logmsg, " ");
3275 s->hostkey.comment = NULL;
3276 rsa_fingerprint(logmsg + strlen(logmsg),
3277 sizeof(logmsg) - strlen(logmsg), &s->hostkey);
3281 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
3282 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
3283 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
3284 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
3285 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
3287 ssh->v1_local_protoflags =
3288 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
3289 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
3292 MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
3293 MD5Update(&md5c, s->keystr1, s->servkey.bytes);
3294 MD5Update(&md5c, cookie, 8);
3295 MD5Final(s->session_id, &md5c);
3297 for (i = 0; i < 32; i++)
3298 ssh->session_key[i] = random_byte();
3301 * Verify that the `bits' and `bytes' parameters match.
3303 if (s->hostkey.bits > s->hostkey.bytes * 8 ||
3304 s->servkey.bits > s->servkey.bytes * 8) {
3305 bombout(("SSH-1 public keys were badly formatted"));
3309 s->len = (s->hostkey.bytes > s->servkey.bytes ?
3310 s->hostkey.bytes : s->servkey.bytes);
3312 s->rsabuf = snewn(s->len, unsigned char);
3315 * Verify the host key.
3319 * First format the key into a string.
3321 int len = rsastr_len(&s->hostkey);
3322 char fingerprint[100];
3323 char *keystr = snewn(len, char);
3324 rsastr_fmt(keystr, &s->hostkey);
3325 rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
3327 ssh_set_frozen(ssh, 1);
3328 s->dlgret = verify_ssh_host_key(ssh->frontend,
3329 ssh->savedhost, ssh->savedport,
3330 "rsa", keystr, fingerprint,
3331 ssh_dialog_callback, ssh);
3333 if (s->dlgret < 0) {
3337 bombout(("Unexpected data from server while waiting"
3338 " for user host key response"));
3341 } while (pktin || inlen > 0);
3342 s->dlgret = ssh->user_response;
3344 ssh_set_frozen(ssh, 0);
3346 if (s->dlgret == 0) {
3347 ssh_disconnect(ssh, "User aborted at host key verification",
3353 for (i = 0; i < 32; i++) {
3354 s->rsabuf[i] = ssh->session_key[i];
3356 s->rsabuf[i] ^= s->session_id[i];
3359 if (s->hostkey.bytes > s->servkey.bytes) {
3360 ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
3362 ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
3364 ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
3366 ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
3369 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
3373 logevent("Encrypted session key");
3376 int cipher_chosen = 0, warn = 0;
3377 char *cipher_string = NULL;
3379 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
3380 int next_cipher = conf_get_int_int(ssh->conf,
3381 CONF_ssh_cipherlist, i);
3382 if (next_cipher == CIPHER_WARN) {
3383 /* If/when we choose a cipher, warn about it */
3385 } else if (next_cipher == CIPHER_AES) {
3386 /* XXX Probably don't need to mention this. */
3387 logevent("AES not supported in SSH-1, skipping");
3389 switch (next_cipher) {
3390 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
3391 cipher_string = "3DES"; break;
3392 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
3393 cipher_string = "Blowfish"; break;
3394 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
3395 cipher_string = "single-DES"; break;
3397 if (s->supported_ciphers_mask & (1 << s->cipher_type))
3401 if (!cipher_chosen) {
3402 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
3403 bombout(("Server violates SSH-1 protocol by not "
3404 "supporting 3DES encryption"));
3406 /* shouldn't happen */
3407 bombout(("No supported ciphers found"));
3411 /* Warn about chosen cipher if necessary. */
3413 ssh_set_frozen(ssh, 1);
3414 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
3415 ssh_dialog_callback, ssh);
3416 if (s->dlgret < 0) {
3420 bombout(("Unexpected data from server while waiting"
3421 " for user response"));
3424 } while (pktin || inlen > 0);
3425 s->dlgret = ssh->user_response;
3427 ssh_set_frozen(ssh, 0);
3428 if (s->dlgret == 0) {
3429 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
3436 switch (s->cipher_type) {
3437 case SSH_CIPHER_3DES:
3438 logevent("Using 3DES encryption");
3440 case SSH_CIPHER_DES:
3441 logevent("Using single-DES encryption");
3443 case SSH_CIPHER_BLOWFISH:
3444 logevent("Using Blowfish encryption");
3448 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
3449 PKT_CHAR, s->cipher_type,
3450 PKT_DATA, cookie, 8,
3451 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
3452 PKT_DATA, s->rsabuf, s->len,
3453 PKT_INT, ssh->v1_local_protoflags, PKT_END);
3455 logevent("Trying to enable encryption...");
3459 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
3460 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
3462 ssh->v1_cipher_ctx = ssh->cipher->make_context();
3463 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
3464 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
3466 ssh->crcda_ctx = crcda_make_context();
3467 logevent("Installing CRC compensation attack detector");
3469 if (s->servkey.modulus) {
3470 sfree(s->servkey.modulus);
3471 s->servkey.modulus = NULL;
3473 if (s->servkey.exponent) {
3474 sfree(s->servkey.exponent);
3475 s->servkey.exponent = NULL;
3477 if (s->hostkey.modulus) {
3478 sfree(s->hostkey.modulus);
3479 s->hostkey.modulus = NULL;
3481 if (s->hostkey.exponent) {
3482 sfree(s->hostkey.exponent);
3483 s->hostkey.exponent = NULL;
3487 if (pktin->type != SSH1_SMSG_SUCCESS) {
3488 bombout(("Encryption not successfully enabled"));
3492 logevent("Successfully started encryption");
3494 fflush(stdout); /* FIXME eh? */
3496 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
3497 int ret; /* need not be kept over crReturn */
3498 s->cur_prompt = new_prompts(ssh->frontend);
3499 s->cur_prompt->to_server = TRUE;
3500 s->cur_prompt->name = dupstr("SSH login name");
3501 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
3502 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3505 crWaitUntil(!pktin);
3506 ret = get_userpass_input(s->cur_prompt, in, inlen);
3511 * Failed to get a username. Terminate.
3513 free_prompts(s->cur_prompt);
3514 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
3517 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
3518 free_prompts(s->cur_prompt);
3521 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
3523 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
3525 if (flags & FLAG_INTERACTIVE &&
3526 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
3527 c_write_str(ssh, userlog);
3528 c_write_str(ssh, "\r\n");
3536 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
3537 /* We must not attempt PK auth. Pretend we've already tried it. */
3538 s->tried_publickey = s->tried_agent = 1;
3540 s->tried_publickey = s->tried_agent = 0;
3542 s->tis_auth_refused = s->ccard_auth_refused = 0;
3544 * Load the public half of any configured keyfile for later use.
3546 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3547 if (!filename_is_null(s->keyfile)) {
3549 logeventf(ssh, "Reading private key file \"%.150s\"",
3550 filename_to_str(s->keyfile));
3551 keytype = key_type(s->keyfile);
3552 if (keytype == SSH_KEYTYPE_SSH1) {
3554 if (rsakey_pubblob(s->keyfile,
3555 &s->publickey_blob, &s->publickey_bloblen,
3556 &s->publickey_comment, &error)) {
3557 s->publickey_encrypted = rsakey_encrypted(s->keyfile,
3561 logeventf(ssh, "Unable to load private key (%s)", error);
3562 msgbuf = dupprintf("Unable to load private key file "
3563 "\"%.150s\" (%s)\r\n",
3564 filename_to_str(s->keyfile),
3566 c_write_str(ssh, msgbuf);
3568 s->publickey_blob = NULL;
3572 logeventf(ssh, "Unable to use this key file (%s)",
3573 key_type_to_str(keytype));
3574 msgbuf = dupprintf("Unable to use key file \"%.150s\""
3576 filename_to_str(s->keyfile),
3577 key_type_to_str(keytype));
3578 c_write_str(ssh, msgbuf);
3580 s->publickey_blob = NULL;
3583 s->publickey_blob = NULL;
3585 while (pktin->type == SSH1_SMSG_FAILURE) {
3586 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
3588 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
3590 * Attempt RSA authentication using Pageant.
3596 logevent("Pageant is running. Requesting keys.");
3598 /* Request the keys held by the agent. */
3599 PUT_32BIT(s->request, 1);
3600 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
3601 if (!agent_query(s->request, 5, &r, &s->responselen,
3602 ssh_agent_callback, ssh)) {
3606 bombout(("Unexpected data from server while waiting"
3607 " for agent response"));
3610 } while (pktin || inlen > 0);
3611 r = ssh->agent_response;
3612 s->responselen = ssh->agent_response_len;
3614 s->response = (unsigned char *) r;
3615 if (s->response && s->responselen >= 5 &&
3616 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
3617 s->p = s->response + 5;
3618 s->nkeys = toint(GET_32BIT(s->p));
3620 logeventf(ssh, "Pageant reported negative key count %d",
3625 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
3626 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
3627 unsigned char *pkblob = s->p;
3631 do { /* do while (0) to make breaking easy */
3632 n = ssh1_read_bignum
3633 (s->p, toint(s->responselen-(s->p-s->response)),
3638 n = ssh1_read_bignum
3639 (s->p, toint(s->responselen-(s->p-s->response)),
3644 if (s->responselen - (s->p-s->response) < 4)
3646 s->commentlen = toint(GET_32BIT(s->p));
3648 if (s->commentlen < 0 ||
3649 toint(s->responselen - (s->p-s->response)) <
3652 s->commentp = (char *)s->p;
3653 s->p += s->commentlen;
3657 logevent("Pageant key list packet was truncated");
3661 if (s->publickey_blob) {
3662 if (!memcmp(pkblob, s->publickey_blob,
3663 s->publickey_bloblen)) {
3664 logeventf(ssh, "Pageant key #%d matches "
3665 "configured key file", s->keyi);
3666 s->tried_publickey = 1;
3668 /* Skip non-configured key */
3671 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
3672 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3673 PKT_BIGNUM, s->key.modulus, PKT_END);
3675 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3676 logevent("Key refused");
3679 logevent("Received RSA challenge");
3680 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3681 bombout(("Server's RSA challenge was badly formatted"));
3686 char *agentreq, *q, *ret;
3689 len = 1 + 4; /* message type, bit count */
3690 len += ssh1_bignum_length(s->key.exponent);
3691 len += ssh1_bignum_length(s->key.modulus);
3692 len += ssh1_bignum_length(s->challenge);
3693 len += 16; /* session id */
3694 len += 4; /* response format */
3695 agentreq = snewn(4 + len, char);
3696 PUT_32BIT(agentreq, len);
3698 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
3699 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
3701 q += ssh1_write_bignum(q, s->key.exponent);
3702 q += ssh1_write_bignum(q, s->key.modulus);
3703 q += ssh1_write_bignum(q, s->challenge);
3704 memcpy(q, s->session_id, 16);
3706 PUT_32BIT(q, 1); /* response format */
3707 if (!agent_query(agentreq, len + 4, &vret, &retlen,
3708 ssh_agent_callback, ssh)) {
3713 bombout(("Unexpected data from server"
3714 " while waiting for agent"
3718 } while (pktin || inlen > 0);
3719 vret = ssh->agent_response;
3720 retlen = ssh->agent_response_len;
3725 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
3726 logevent("Sending Pageant's response");
3727 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3728 PKT_DATA, ret + 5, 16,
3732 if (pktin->type == SSH1_SMSG_SUCCESS) {
3734 ("Pageant's response accepted");
3735 if (flags & FLAG_VERBOSE) {
3736 c_write_str(ssh, "Authenticated using"
3738 c_write(ssh, s->commentp,
3740 c_write_str(ssh, "\" from agent\r\n");
3745 ("Pageant's response not accepted");
3748 ("Pageant failed to answer challenge");
3752 logevent("No reply received from Pageant");
3755 freebn(s->key.exponent);
3756 freebn(s->key.modulus);
3757 freebn(s->challenge);
3762 if (s->publickey_blob && !s->tried_publickey)
3763 logevent("Configured key file not in Pageant");
3765 logevent("Failed to get reply from Pageant");
3770 if (s->publickey_blob && !s->tried_publickey) {
3772 * Try public key authentication with the specified
3775 int got_passphrase; /* need not be kept over crReturn */
3776 if (flags & FLAG_VERBOSE)
3777 c_write_str(ssh, "Trying public key authentication.\r\n");
3778 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3779 logeventf(ssh, "Trying public key \"%s\"",
3780 filename_to_str(s->keyfile));
3781 s->tried_publickey = 1;
3782 got_passphrase = FALSE;
3783 while (!got_passphrase) {
3785 * Get a passphrase, if necessary.
3787 char *passphrase = NULL; /* only written after crReturn */
3789 if (!s->publickey_encrypted) {
3790 if (flags & FLAG_VERBOSE)
3791 c_write_str(ssh, "No passphrase required.\r\n");
3794 int ret; /* need not be kept over crReturn */
3795 s->cur_prompt = new_prompts(ssh->frontend);
3796 s->cur_prompt->to_server = FALSE;
3797 s->cur_prompt->name = dupstr("SSH key passphrase");
3798 add_prompt(s->cur_prompt,
3799 dupprintf("Passphrase for key \"%.100s\": ",
3800 s->publickey_comment), FALSE);
3801 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3804 crWaitUntil(!pktin);
3805 ret = get_userpass_input(s->cur_prompt, in, inlen);
3809 /* Failed to get a passphrase. Terminate. */
3810 free_prompts(s->cur_prompt);
3811 ssh_disconnect(ssh, NULL, "Unable to authenticate",
3815 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
3816 free_prompts(s->cur_prompt);
3819 * Try decrypting key with passphrase.
3821 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3822 ret = loadrsakey(s->keyfile, &s->key, passphrase,
3825 smemclr(passphrase, strlen(passphrase));
3829 /* Correct passphrase. */
3830 got_passphrase = TRUE;
3831 } else if (ret == 0) {
3832 c_write_str(ssh, "Couldn't load private key from ");
3833 c_write_str(ssh, filename_to_str(s->keyfile));
3834 c_write_str(ssh, " (");
3835 c_write_str(ssh, error);
3836 c_write_str(ssh, ").\r\n");
3837 got_passphrase = FALSE;
3838 break; /* go and try something else */
3839 } else if (ret == -1) {
3840 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
3841 got_passphrase = FALSE;
3844 assert(0 && "unexpected return from loadrsakey()");
3845 got_passphrase = FALSE; /* placate optimisers */
3849 if (got_passphrase) {
3852 * Send a public key attempt.
3854 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3855 PKT_BIGNUM, s->key.modulus, PKT_END);
3858 if (pktin->type == SSH1_SMSG_FAILURE) {
3859 c_write_str(ssh, "Server refused our public key.\r\n");
3860 continue; /* go and try something else */
3862 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3863 bombout(("Bizarre response to offer of public key"));
3869 unsigned char buffer[32];
3870 Bignum challenge, response;
3872 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3873 bombout(("Server's RSA challenge was badly formatted"));
3876 response = rsadecrypt(challenge, &s->key);
3877 freebn(s->key.private_exponent);/* burn the evidence */
3879 for (i = 0; i < 32; i++) {
3880 buffer[i] = bignum_byte(response, 31 - i);
3884 MD5Update(&md5c, buffer, 32);
3885 MD5Update(&md5c, s->session_id, 16);
3886 MD5Final(buffer, &md5c);
3888 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3889 PKT_DATA, buffer, 16, PKT_END);
3896 if (pktin->type == SSH1_SMSG_FAILURE) {
3897 if (flags & FLAG_VERBOSE)
3898 c_write_str(ssh, "Failed to authenticate with"
3899 " our public key.\r\n");
3900 continue; /* go and try something else */
3901 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
3902 bombout(("Bizarre response to RSA authentication response"));
3906 break; /* we're through! */
3912 * Otherwise, try various forms of password-like authentication.
3914 s->cur_prompt = new_prompts(ssh->frontend);
3916 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
3917 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
3918 !s->tis_auth_refused) {
3919 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
3920 logevent("Requested TIS authentication");
3921 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
3923 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
3924 logevent("TIS authentication declined");
3925 if (flags & FLAG_INTERACTIVE)
3926 c_write_str(ssh, "TIS authentication refused.\r\n");
3927 s->tis_auth_refused = 1;
3932 char *instr_suf, *prompt;
3934 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3936 bombout(("TIS challenge packet was badly formed"));
3939 logevent("Received TIS challenge");
3940 s->cur_prompt->to_server = TRUE;
3941 s->cur_prompt->name = dupstr("SSH TIS authentication");
3942 /* Prompt heuristic comes from OpenSSH */
3943 if (memchr(challenge, '\n', challengelen)) {
3944 instr_suf = dupstr("");
3945 prompt = dupprintf("%.*s", challengelen, challenge);
3947 instr_suf = dupprintf("%.*s", challengelen, challenge);
3948 prompt = dupstr("Response: ");
3950 s->cur_prompt->instruction =
3951 dupprintf("Using TIS authentication.%s%s",
3952 (*instr_suf) ? "\n" : "",
3954 s->cur_prompt->instr_reqd = TRUE;
3955 add_prompt(s->cur_prompt, prompt, FALSE);
3959 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
3960 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
3961 !s->ccard_auth_refused) {
3962 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
3963 logevent("Requested CryptoCard authentication");
3964 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
3966 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
3967 logevent("CryptoCard authentication declined");
3968 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
3969 s->ccard_auth_refused = 1;
3974 char *instr_suf, *prompt;
3976 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3978 bombout(("CryptoCard challenge packet was badly formed"));
3981 logevent("Received CryptoCard challenge");
3982 s->cur_prompt->to_server = TRUE;
3983 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
3984 s->cur_prompt->name_reqd = FALSE;
3985 /* Prompt heuristic comes from OpenSSH */
3986 if (memchr(challenge, '\n', challengelen)) {
3987 instr_suf = dupstr("");
3988 prompt = dupprintf("%.*s", challengelen, challenge);
3990 instr_suf = dupprintf("%.*s", challengelen, challenge);
3991 prompt = dupstr("Response: ");
3993 s->cur_prompt->instruction =
3994 dupprintf("Using CryptoCard authentication.%s%s",
3995 (*instr_suf) ? "\n" : "",
3997 s->cur_prompt->instr_reqd = TRUE;
3998 add_prompt(s->cur_prompt, prompt, FALSE);
4002 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4003 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4004 bombout(("No supported authentication methods available"));
4007 s->cur_prompt->to_server = TRUE;
4008 s->cur_prompt->name = dupstr("SSH password");
4009 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4010 ssh->username, ssh->savedhost),
4015 * Show password prompt, having first obtained it via a TIS
4016 * or CryptoCard exchange if we're doing TIS or CryptoCard
4020 int ret; /* need not be kept over crReturn */
4021 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4024 crWaitUntil(!pktin);
4025 ret = get_userpass_input(s->cur_prompt, in, inlen);
4030 * Failed to get a password (for example
4031 * because one was supplied on the command line
4032 * which has already failed to work). Terminate.
4034 free_prompts(s->cur_prompt);
4035 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4040 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4042 * Defence against traffic analysis: we send a
4043 * whole bunch of packets containing strings of
4044 * different lengths. One of these strings is the
4045 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4046 * The others are all random data in
4047 * SSH1_MSG_IGNORE packets. This way a passive
4048 * listener can't tell which is the password, and
4049 * hence can't deduce the password length.
4051 * Anybody with a password length greater than 16
4052 * bytes is going to have enough entropy in their
4053 * password that a listener won't find it _that_
4054 * much help to know how long it is. So what we'll
4057 * - if password length < 16, we send 15 packets
4058 * containing string lengths 1 through 15
4060 * - otherwise, we let N be the nearest multiple
4061 * of 8 below the password length, and send 8
4062 * packets containing string lengths N through
4063 * N+7. This won't obscure the order of
4064 * magnitude of the password length, but it will
4065 * introduce a bit of extra uncertainty.
4067 * A few servers can't deal with SSH1_MSG_IGNORE, at
4068 * least in this context. For these servers, we need
4069 * an alternative defence. We make use of the fact
4070 * that the password is interpreted as a C string:
4071 * so we can append a NUL, then some random data.
4073 * A few servers can deal with neither SSH1_MSG_IGNORE
4074 * here _nor_ a padded password string.
4075 * For these servers we are left with no defences
4076 * against password length sniffing.
4078 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4079 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4081 * The server can deal with SSH1_MSG_IGNORE, so
4082 * we can use the primary defence.
4084 int bottom, top, pwlen, i;
4087 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4089 bottom = 0; /* zero length passwords are OK! :-) */
4092 bottom = pwlen & ~7;
4096 assert(pwlen >= bottom && pwlen <= top);
4098 randomstr = snewn(top + 1, char);
4100 for (i = bottom; i <= top; i++) {
4102 defer_packet(ssh, s->pwpkt_type,
4103 PKTT_PASSWORD, PKT_STR,
4104 s->cur_prompt->prompts[0]->result,
4105 PKTT_OTHER, PKT_END);
4107 for (j = 0; j < i; j++) {
4109 randomstr[j] = random_byte();
4110 } while (randomstr[j] == '\0');
4112 randomstr[i] = '\0';
4113 defer_packet(ssh, SSH1_MSG_IGNORE,
4114 PKT_STR, randomstr, PKT_END);
4117 logevent("Sending password with camouflage packets");
4118 ssh_pkt_defersend(ssh);
4121 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4123 * The server can't deal with SSH1_MSG_IGNORE
4124 * but can deal with padded passwords, so we
4125 * can use the secondary defence.
4131 len = strlen(s->cur_prompt->prompts[0]->result);
4132 if (len < sizeof(string)) {
4134 strcpy(string, s->cur_prompt->prompts[0]->result);
4135 len++; /* cover the zero byte */
4136 while (len < sizeof(string)) {
4137 string[len++] = (char) random_byte();
4140 ss = s->cur_prompt->prompts[0]->result;
4142 logevent("Sending length-padded password");
4143 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
4144 PKT_INT, len, PKT_DATA, ss, len,
4145 PKTT_OTHER, PKT_END);
4148 * The server is believed unable to cope with
4149 * any of our password camouflage methods.
4152 len = strlen(s->cur_prompt->prompts[0]->result);
4153 logevent("Sending unpadded password");
4154 send_packet(ssh, s->pwpkt_type,
4155 PKTT_PASSWORD, PKT_INT, len,
4156 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4157 PKTT_OTHER, PKT_END);
4160 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
4161 PKT_STR, s->cur_prompt->prompts[0]->result,
4162 PKTT_OTHER, PKT_END);
4164 logevent("Sent password");
4165 free_prompts(s->cur_prompt);
4167 if (pktin->type == SSH1_SMSG_FAILURE) {
4168 if (flags & FLAG_VERBOSE)
4169 c_write_str(ssh, "Access denied\r\n");
4170 logevent("Authentication refused");
4171 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4172 bombout(("Strange packet received, type %d", pktin->type));
4178 if (s->publickey_blob) {
4179 sfree(s->publickey_blob);
4180 sfree(s->publickey_comment);
4183 logevent("Authentication successful");
4188 static void ssh_channel_try_eof(struct ssh_channel *c)
4191 assert(c->pending_eof); /* precondition for calling us */
4193 return; /* can't close: not even opened yet */
4194 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4195 return; /* can't send EOF: pending outgoing data */
4197 c->pending_eof = FALSE; /* we're about to send it */
4198 if (ssh->version == 1) {
4199 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4201 c->closes |= CLOSES_SENT_EOF;
4203 struct Packet *pktout;
4204 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4205 ssh2_pkt_adduint32(pktout, c->remoteid);
4206 ssh2_pkt_send(ssh, pktout);
4207 c->closes |= CLOSES_SENT_EOF;
4208 ssh2_channel_check_close(c);
4212 void sshfwd_write_eof(struct ssh_channel *c)
4216 if (ssh->state == SSH_STATE_CLOSED)
4219 if (c->closes & CLOSES_SENT_EOF)
4222 c->pending_eof = TRUE;
4223 ssh_channel_try_eof(c);
4226 void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
4230 if (ssh->state == SSH_STATE_CLOSED)
4235 x11_close(c->u.x11.s);
4236 logeventf(ssh, "Forwarded X11 connection terminated due to local "
4240 case CHAN_SOCKDATA_DORMANT:
4241 pfd_close(c->u.pfd.s);
4242 logeventf(ssh, "Forwarded port closed due to local error: %s", err);
4245 c->type = CHAN_ZOMBIE;
4246 c->pending_eof = FALSE; /* this will confuse a zombie channel */
4248 ssh2_channel_check_close(c);
4251 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
4255 if (ssh->state == SSH_STATE_CLOSED)
4258 if (ssh->version == 1) {
4259 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
4260 PKT_INT, c->remoteid,
4261 PKT_INT, len, PKTT_DATA, PKT_DATA, buf, len,
4262 PKTT_OTHER, PKT_END);
4264 * In SSH-1 we can return 0 here - implying that forwarded
4265 * connections are never individually throttled - because
4266 * the only circumstance that can cause throttling will be
4267 * the whole SSH connection backing up, in which case
4268 * _everything_ will be throttled as a whole.
4272 ssh2_add_channel_data(c, buf, len);
4273 return ssh2_try_send(c);
4277 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
4282 if (ssh->state == SSH_STATE_CLOSED)
4285 if (ssh->version == 1) {
4286 buflimit = SSH1_BUFFER_LIMIT;
4288 buflimit = c->v.v2.locmaxwin;
4289 ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
4291 if (c->throttling_conn && bufsize <= buflimit) {
4292 c->throttling_conn = 0;
4293 ssh_throttle_conn(ssh, -1);
4297 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
4299 struct queued_handler *qh = ssh->qhead;
4303 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
4306 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
4307 ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
4310 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
4311 ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
4315 ssh->qhead = qh->next;
4317 if (ssh->qhead->msg1 > 0) {
4318 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
4319 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
4321 if (ssh->qhead->msg2 > 0) {
4322 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
4323 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
4326 ssh->qhead = ssh->qtail = NULL;
4329 qh->handler(ssh, pktin, qh->ctx);
4334 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
4335 chandler_fn_t handler, void *ctx)
4337 struct queued_handler *qh;
4339 qh = snew(struct queued_handler);
4342 qh->handler = handler;
4346 if (ssh->qtail == NULL) {
4350 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
4351 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
4354 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
4355 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
4358 ssh->qtail->next = qh;
4363 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
4365 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
4367 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
4368 SSH2_MSG_REQUEST_SUCCESS)) {
4369 logeventf(ssh, "Remote port forwarding from %s enabled",
4372 logeventf(ssh, "Remote port forwarding from %s refused",
4375 rpf = del234(ssh->rportfwds, pf);
4377 pf->pfrec->remote = NULL;
4382 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
4384 struct ssh_portfwd *epf;
4388 if (!ssh->portfwds) {
4389 ssh->portfwds = newtree234(ssh_portcmp);
4392 * Go through the existing port forwardings and tag them
4393 * with status==DESTROY. Any that we want to keep will be
4394 * re-enabled (status==KEEP) as we go through the
4395 * configuration and find out which bits are the same as
4398 struct ssh_portfwd *epf;
4400 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4401 epf->status = DESTROY;
4404 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
4406 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
4407 char *kp, *kp2, *vp, *vp2;
4408 char address_family, type;
4409 int sport,dport,sserv,dserv;
4410 char *sports, *dports, *saddr, *host;
4414 address_family = 'A';
4416 if (*kp == 'A' || *kp == '4' || *kp == '6')
4417 address_family = *kp++;
4418 if (*kp == 'L' || *kp == 'R')
4421 if ((kp2 = strchr(kp, ':')) != NULL) {
4423 * There's a colon in the middle of the source port
4424 * string, which means that the part before it is
4425 * actually a source address.
4427 saddr = dupprintf("%.*s", (int)(kp2 - kp), kp);
4433 sport = atoi(sports);
4437 sport = net_service_lookup(sports);
4439 logeventf(ssh, "Service lookup failed for source"
4440 " port \"%s\"", sports);
4444 if (type == 'L' && !strcmp(val, "D")) {
4445 /* dynamic forwarding */
4452 /* ordinary forwarding */
4454 vp2 = vp + strcspn(vp, ":");
4455 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
4459 dport = atoi(dports);
4463 dport = net_service_lookup(dports);
4465 logeventf(ssh, "Service lookup failed for destination"
4466 " port \"%s\"", dports);
4471 if (sport && dport) {
4472 /* Set up a description of the source port. */
4473 struct ssh_portfwd *pfrec, *epfrec;
4475 pfrec = snew(struct ssh_portfwd);
4477 pfrec->saddr = saddr;
4478 pfrec->sserv = sserv ? dupstr(sports) : NULL;
4479 pfrec->sport = sport;
4480 pfrec->daddr = host;
4481 pfrec->dserv = dserv ? dupstr(dports) : NULL;
4482 pfrec->dport = dport;
4483 pfrec->local = NULL;
4484 pfrec->remote = NULL;
4485 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
4486 address_family == '6' ? ADDRTYPE_IPV6 :
4489 epfrec = add234(ssh->portfwds, pfrec);
4490 if (epfrec != pfrec) {
4491 if (epfrec->status == DESTROY) {
4493 * We already have a port forwarding up and running
4494 * with precisely these parameters. Hence, no need
4495 * to do anything; simply re-tag the existing one
4498 epfrec->status = KEEP;
4501 * Anything else indicates that there was a duplicate
4502 * in our input, which we'll silently ignore.
4504 free_portfwd(pfrec);
4506 pfrec->status = CREATE;
4515 * Now go through and destroy any port forwardings which were
4518 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4519 if (epf->status == DESTROY) {
4522 message = dupprintf("%s port forwarding from %s%s%d",
4523 epf->type == 'L' ? "local" :
4524 epf->type == 'R' ? "remote" : "dynamic",
4525 epf->saddr ? epf->saddr : "",
4526 epf->saddr ? ":" : "",
4529 if (epf->type != 'D') {
4530 char *msg2 = dupprintf("%s to %s:%d", message,
4531 epf->daddr, epf->dport);
4536 logeventf(ssh, "Cancelling %s", message);
4539 /* epf->remote or epf->local may be NULL if setting up a
4540 * forwarding failed. */
4542 struct ssh_rportfwd *rpf = epf->remote;
4543 struct Packet *pktout;
4546 * Cancel the port forwarding at the server
4549 if (ssh->version == 1) {
4551 * We cannot cancel listening ports on the
4552 * server side in SSH-1! There's no message
4553 * to support it. Instead, we simply remove
4554 * the rportfwd record from the local end
4555 * so that any connections the server tries
4556 * to make on it are rejected.
4559 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4560 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
4561 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
4563 ssh2_pkt_addstring(pktout, epf->saddr);
4564 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
4565 /* XXX: rport_acceptall may not represent
4566 * what was used to open the original connection,
4567 * since it's reconfigurable. */
4568 ssh2_pkt_addstring(pktout, "");
4570 ssh2_pkt_addstring(pktout, "localhost");
4572 ssh2_pkt_adduint32(pktout, epf->sport);
4573 ssh2_pkt_send(ssh, pktout);
4576 del234(ssh->rportfwds, rpf);
4578 } else if (epf->local) {
4579 pfd_terminate(epf->local);
4582 delpos234(ssh->portfwds, i);
4584 i--; /* so we don't skip one in the list */
4588 * And finally, set up any new port forwardings (status==CREATE).
4590 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4591 if (epf->status == CREATE) {
4592 char *sportdesc, *dportdesc;
4593 sportdesc = dupprintf("%s%s%s%s%d%s",
4594 epf->saddr ? epf->saddr : "",
4595 epf->saddr ? ":" : "",
4596 epf->sserv ? epf->sserv : "",
4597 epf->sserv ? "(" : "",
4599 epf->sserv ? ")" : "");
4600 if (epf->type == 'D') {
4603 dportdesc = dupprintf("%s:%s%s%d%s",
4605 epf->dserv ? epf->dserv : "",
4606 epf->dserv ? "(" : "",
4608 epf->dserv ? ")" : "");
4611 if (epf->type == 'L') {
4612 const char *err = pfd_addforward(epf->daddr, epf->dport,
4613 epf->saddr, epf->sport,
4616 epf->addressfamily);
4618 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
4619 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4620 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4621 sportdesc, dportdesc,
4622 err ? " failed: " : "", err ? err : "");
4623 } else if (epf->type == 'D') {
4624 const char *err = pfd_addforward(NULL, -1,
4625 epf->saddr, epf->sport,
4628 epf->addressfamily);
4630 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
4631 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4632 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4634 err ? " failed: " : "", err ? err : "");
4636 struct ssh_rportfwd *pf;
4639 * Ensure the remote port forwardings tree exists.
4641 if (!ssh->rportfwds) {
4642 if (ssh->version == 1)
4643 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
4645 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
4648 pf = snew(struct ssh_rportfwd);
4649 pf->dhost = dupstr(epf->daddr);
4650 pf->dport = epf->dport;
4652 pf->shost = dupstr(epf->saddr);
4653 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
4654 pf->shost = dupstr("");
4656 pf->shost = dupstr("localhost");
4658 pf->sport = epf->sport;
4659 if (add234(ssh->rportfwds, pf) != pf) {
4660 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
4661 epf->daddr, epf->dport);
4664 logeventf(ssh, "Requesting remote port %s"
4665 " forward to %s", sportdesc, dportdesc);
4667 pf->sportdesc = sportdesc;
4672 if (ssh->version == 1) {
4673 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
4674 PKT_INT, epf->sport,
4675 PKT_STR, epf->daddr,
4676 PKT_INT, epf->dport,
4678 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
4680 ssh_rportfwd_succfail, pf);
4682 struct Packet *pktout;
4683 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4684 ssh2_pkt_addstring(pktout, "tcpip-forward");
4685 ssh2_pkt_addbool(pktout, 1);/* want reply */
4686 ssh2_pkt_addstring(pktout, pf->shost);
4687 ssh2_pkt_adduint32(pktout, pf->sport);
4688 ssh2_pkt_send(ssh, pktout);
4690 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
4691 SSH2_MSG_REQUEST_FAILURE,
4692 ssh_rportfwd_succfail, pf);
4701 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
4704 int stringlen, bufsize;
4706 ssh_pkt_getstring(pktin, &string, &stringlen);
4707 if (string == NULL) {
4708 bombout(("Incoming terminal data packet was badly formed"));
4712 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
4714 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
4715 ssh->v1_stdout_throttling = 1;
4716 ssh_throttle_conn(ssh, +1);
4720 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
4722 /* Remote side is trying to open a channel to talk to our
4723 * X-Server. Give them back a local channel number. */
4724 struct ssh_channel *c;
4725 int remoteid = ssh_pkt_getuint32(pktin);
4727 logevent("Received X11 connect request");
4728 /* Refuse if X11 forwarding is disabled. */
4729 if (!ssh->X11_fwd_enabled) {
4730 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4731 PKT_INT, remoteid, PKT_END);
4732 logevent("Rejected X11 connect request");
4734 c = snew(struct ssh_channel);
4737 if (x11_init(&c->u.x11.s, ssh->x11disp, c,
4738 NULL, -1, ssh->conf) != NULL) {
4739 logevent("Opening X11 forward connection failed");
4741 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4742 PKT_INT, remoteid, PKT_END);
4745 ("Opening X11 forward connection succeeded");
4746 c->remoteid = remoteid;
4747 c->halfopen = FALSE;
4748 c->localid = alloc_channel_id(ssh);
4750 c->pending_eof = FALSE;
4751 c->throttling_conn = 0;
4752 c->type = CHAN_X11; /* identify channel type */
4753 add234(ssh->channels, c);
4754 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4755 PKT_INT, c->remoteid, PKT_INT,
4756 c->localid, PKT_END);
4757 logevent("Opened X11 forward channel");
4762 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
4764 /* Remote side is trying to open a channel to talk to our
4765 * agent. Give them back a local channel number. */
4766 struct ssh_channel *c;
4767 int remoteid = ssh_pkt_getuint32(pktin);
4769 /* Refuse if agent forwarding is disabled. */
4770 if (!ssh->agentfwd_enabled) {
4771 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4772 PKT_INT, remoteid, PKT_END);
4774 c = snew(struct ssh_channel);
4776 c->remoteid = remoteid;
4777 c->halfopen = FALSE;
4778 c->localid = alloc_channel_id(ssh);
4780 c->pending_eof = FALSE;
4781 c->throttling_conn = 0;
4782 c->type = CHAN_AGENT; /* identify channel type */
4783 c->u.a.lensofar = 0;
4784 c->u.a.message = NULL;
4785 c->u.a.outstanding_requests = 0;
4786 add234(ssh->channels, c);
4787 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4788 PKT_INT, c->remoteid, PKT_INT, c->localid,
4793 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
4795 /* Remote side is trying to open a channel to talk to a
4796 * forwarded port. Give them back a local channel number. */
4797 struct ssh_rportfwd pf, *pfp;
4803 remoteid = ssh_pkt_getuint32(pktin);
4804 ssh_pkt_getstring(pktin, &host, &hostsize);
4805 port = ssh_pkt_getuint32(pktin);
4807 pf.dhost = dupprintf(".*s", hostsize, host);
4809 pfp = find234(ssh->rportfwds, &pf, NULL);
4812 logeventf(ssh, "Rejected remote port open request for %s:%d",
4814 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4815 PKT_INT, remoteid, PKT_END);
4817 struct ssh_channel *c = snew(struct ssh_channel);
4820 logeventf(ssh, "Received remote port open request for %s:%d",
4822 e = pfd_newconnect(&c->u.pfd.s, pf.dhost, port,
4823 c, ssh->conf, pfp->pfrec->addressfamily);
4825 logeventf(ssh, "Port open failed: %s", e);
4827 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4828 PKT_INT, remoteid, PKT_END);
4830 c->remoteid = remoteid;
4831 c->halfopen = FALSE;
4832 c->localid = alloc_channel_id(ssh);
4834 c->pending_eof = FALSE;
4835 c->throttling_conn = 0;
4836 c->type = CHAN_SOCKDATA; /* identify channel type */
4837 add234(ssh->channels, c);
4838 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4839 PKT_INT, c->remoteid, PKT_INT,
4840 c->localid, PKT_END);
4841 logevent("Forwarded port opened successfully");
4848 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
4850 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4851 unsigned int localid = ssh_pkt_getuint32(pktin);
4852 struct ssh_channel *c;
4854 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4855 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4856 c->remoteid = localid;
4857 c->halfopen = FALSE;
4858 c->type = CHAN_SOCKDATA;
4859 c->throttling_conn = 0;
4860 pfd_confirm(c->u.pfd.s);
4863 if (c && c->pending_eof) {
4865 * We have a pending close on this channel,
4866 * which we decided on before the server acked
4867 * the channel open. So now we know the
4868 * remoteid, we can close it again.
4870 ssh_channel_try_eof(c);
4874 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
4876 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4877 struct ssh_channel *c;
4879 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4880 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4881 logevent("Forwarded connection refused by server");
4882 pfd_close(c->u.pfd.s);
4883 del234(ssh->channels, c);
4888 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
4890 /* Remote side closes a channel. */
4891 unsigned i = ssh_pkt_getuint32(pktin);
4892 struct ssh_channel *c;
4893 c = find234(ssh->channels, &i, ssh_channelfind);
4894 if (c && !c->halfopen) {
4896 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
4897 !(c->closes & CLOSES_RCVD_EOF)) {
4899 * Received CHANNEL_CLOSE, which we translate into
4902 int send_close = FALSE;
4904 c->closes |= CLOSES_RCVD_EOF;
4909 x11_send_eof(c->u.x11.s);
4915 pfd_send_eof(c->u.pfd.s);
4924 if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
4925 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4927 c->closes |= CLOSES_SENT_EOF;
4931 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
4932 !(c->closes & CLOSES_RCVD_CLOSE)) {
4934 if (!(c->closes & CLOSES_SENT_EOF)) {
4935 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %d"
4936 " for which we never sent CHANNEL_CLOSE\n", i));
4939 c->closes |= CLOSES_RCVD_CLOSE;
4942 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
4943 !(c->closes & CLOSES_SENT_CLOSE)) {
4944 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
4945 PKT_INT, c->remoteid, PKT_END);
4946 c->closes |= CLOSES_SENT_CLOSE;
4949 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
4950 ssh_channel_destroy(c);
4952 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
4953 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
4954 "_CONFIRMATION", c ? "half-open" : "nonexistent",
4959 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
4961 /* Data sent down one of our channels. */
4962 int i = ssh_pkt_getuint32(pktin);
4965 struct ssh_channel *c;
4967 ssh_pkt_getstring(pktin, &p, &len);
4969 c = find234(ssh->channels, &i, ssh_channelfind);
4974 bufsize = x11_send(c->u.x11.s, p, len);
4977 bufsize = pfd_send(c->u.pfd.s, p, len);
4980 /* Data for an agent message. Buffer it. */
4982 if (c->u.a.lensofar < 4) {
4983 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)len);
4984 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
4988 c->u.a.lensofar += l;
4990 if (c->u.a.lensofar == 4) {
4992 4 + GET_32BIT(c->u.a.msglen);
4993 c->u.a.message = snewn(c->u.a.totallen,
4995 memcpy(c->u.a.message, c->u.a.msglen, 4);
4997 if (c->u.a.lensofar >= 4 && len > 0) {
4999 min(c->u.a.totallen - c->u.a.lensofar,
5001 memcpy(c->u.a.message + c->u.a.lensofar, p,
5005 c->u.a.lensofar += l;
5007 if (c->u.a.lensofar == c->u.a.totallen) {
5010 c->u.a.outstanding_requests++;
5011 if (agent_query(c->u.a.message,
5014 ssh_agentf_callback, c))
5015 ssh_agentf_callback(c, reply, replylen);
5016 sfree(c->u.a.message);
5017 c->u.a.lensofar = 0;
5020 bufsize = 0; /* agent channels never back up */
5023 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5024 c->throttling_conn = 1;
5025 ssh_throttle_conn(ssh, +1);
5030 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5032 ssh->exitcode = ssh_pkt_getuint32(pktin);
5033 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5034 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5036 * In case `helpful' firewalls or proxies tack
5037 * extra human-readable text on the end of the
5038 * session which we might mistake for another
5039 * encrypted packet, we close the session once
5040 * we've sent EXIT_CONFIRMATION.
5042 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5045 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5046 static void ssh1_send_ttymode(void *data, char *mode, char *val)
5048 struct Packet *pktout = (struct Packet *)data;
5050 unsigned int arg = 0;
5051 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
5052 if (i == lenof(ssh_ttymodes)) return;
5053 switch (ssh_ttymodes[i].type) {
5055 arg = ssh_tty_parse_specchar(val);
5058 arg = ssh_tty_parse_boolean(val);
5061 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
5062 ssh2_pkt_addbyte(pktout, arg);
5066 static void do_ssh1_connection(Ssh ssh, unsigned char *in, int inlen,
5067 struct Packet *pktin)
5069 crBegin(ssh->do_ssh1_connection_crstate);
5071 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5072 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5073 ssh1_smsg_stdout_stderr_data;
5075 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5076 ssh1_msg_channel_open_confirmation;
5077 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5078 ssh1_msg_channel_open_failure;
5079 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5080 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5081 ssh1_msg_channel_close;
5082 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5083 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5085 if (conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists()) {
5086 logevent("Requesting agent forwarding");
5087 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5091 if (pktin->type != SSH1_SMSG_SUCCESS
5092 && pktin->type != SSH1_SMSG_FAILURE) {
5093 bombout(("Protocol confusion"));
5095 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5096 logevent("Agent forwarding refused");
5098 logevent("Agent forwarding enabled");
5099 ssh->agentfwd_enabled = TRUE;
5100 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5104 if (conf_get_int(ssh->conf, CONF_x11_forward) &&
5105 (ssh->x11disp = x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5106 conf_get_int(ssh->conf, CONF_x11_auth), ssh->conf))) {
5107 logevent("Requesting X11 forwarding");
5109 * Note that while we blank the X authentication data here, we don't
5110 * take any special action to blank the start of an X11 channel,
5111 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
5112 * without having session blanking enabled is likely to leak your
5113 * cookie into the log.
5115 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5116 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5117 PKT_STR, ssh->x11disp->remoteauthprotoname,
5119 PKT_STR, ssh->x11disp->remoteauthdatastring,
5121 PKT_INT, ssh->x11disp->screennum,
5124 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5125 PKT_STR, ssh->x11disp->remoteauthprotoname,
5127 PKT_STR, ssh->x11disp->remoteauthdatastring,
5134 if (pktin->type != SSH1_SMSG_SUCCESS
5135 && pktin->type != SSH1_SMSG_FAILURE) {
5136 bombout(("Protocol confusion"));
5138 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5139 logevent("X11 forwarding refused");
5141 logevent("X11 forwarding enabled");
5142 ssh->X11_fwd_enabled = TRUE;
5143 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5147 ssh_setup_portfwd(ssh, ssh->conf);
5148 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5150 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5152 /* Unpick the terminal-speed string. */
5153 /* XXX perhaps we should allow no speeds to be sent. */
5154 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5155 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5156 /* Send the pty request. */
5157 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5158 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5159 ssh_pkt_adduint32(pkt, ssh->term_height);
5160 ssh_pkt_adduint32(pkt, ssh->term_width);
5161 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5162 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5163 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5164 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5165 ssh_pkt_adduint32(pkt, ssh->ispeed);
5166 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5167 ssh_pkt_adduint32(pkt, ssh->ospeed);
5168 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5170 ssh->state = SSH_STATE_INTERMED;
5174 if (pktin->type != SSH1_SMSG_SUCCESS
5175 && pktin->type != SSH1_SMSG_FAILURE) {
5176 bombout(("Protocol confusion"));
5178 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5179 c_write_str(ssh, "Server refused to allocate pty\r\n");
5180 ssh->editing = ssh->echoing = 1;
5182 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5183 ssh->ospeed, ssh->ispeed);
5184 ssh->got_pty = TRUE;
5187 ssh->editing = ssh->echoing = 1;
5190 if (conf_get_int(ssh->conf, CONF_compression)) {
5191 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5195 if (pktin->type != SSH1_SMSG_SUCCESS
5196 && pktin->type != SSH1_SMSG_FAILURE) {
5197 bombout(("Protocol confusion"));
5199 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5200 c_write_str(ssh, "Server refused to compress\r\n");
5202 logevent("Started compression");
5203 ssh->v1_compressing = TRUE;
5204 ssh->cs_comp_ctx = zlib_compress_init();
5205 logevent("Initialised zlib (RFC1950) compression");
5206 ssh->sc_comp_ctx = zlib_decompress_init();
5207 logevent("Initialised zlib (RFC1950) decompression");
5211 * Start the shell or command.
5213 * Special case: if the first-choice command is an SSH-2
5214 * subsystem (hence not usable here) and the second choice
5215 * exists, we fall straight back to that.
5218 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
5220 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
5221 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
5222 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
5223 ssh->fallback_cmd = TRUE;
5226 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
5228 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
5229 logevent("Started session");
5232 ssh->state = SSH_STATE_SESSION;
5233 if (ssh->size_needed)
5234 ssh_size(ssh, ssh->term_width, ssh->term_height);
5235 if (ssh->eof_needed)
5236 ssh_special(ssh, TS_EOF);
5239 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
5241 ssh->channels = newtree234(ssh_channelcmp);
5245 * By this point, most incoming packets are already being
5246 * handled by the dispatch table, and we need only pay
5247 * attention to the unusual ones.
5252 if (pktin->type == SSH1_SMSG_SUCCESS) {
5253 /* may be from EXEC_SHELL on some servers */
5254 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5255 /* may be from EXEC_SHELL on some servers
5256 * if no pty is available or in other odd cases. Ignore */
5258 bombout(("Strange packet received: type %d", pktin->type));
5263 int len = min(inlen, 512);
5264 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
5265 PKT_INT, len, PKTT_DATA, PKT_DATA, in, len,
5266 PKTT_OTHER, PKT_END);
5277 * Handle the top-level SSH-2 protocol.
5279 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
5284 ssh_pkt_getstring(pktin, &msg, &msglen);
5285 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
5288 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
5290 /* log reason code in disconnect message */
5294 ssh_pkt_getstring(pktin, &msg, &msglen);
5295 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
5298 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
5300 /* Do nothing, because we're ignoring it! Duhh. */
5303 static void ssh1_protocol_setup(Ssh ssh)
5308 * Most messages are handled by the coroutines.
5310 for (i = 0; i < 256; i++)
5311 ssh->packet_dispatch[i] = NULL;
5314 * These special message types we install handlers for.
5316 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
5317 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
5318 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
5321 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
5322 struct Packet *pktin)
5324 unsigned char *in=(unsigned char*)vin;
5325 if (ssh->state == SSH_STATE_CLOSED)
5328 if (pktin && ssh->packet_dispatch[pktin->type]) {
5329 ssh->packet_dispatch[pktin->type](ssh, pktin);
5333 if (!ssh->protocol_initial_phase_done) {
5334 if (do_ssh1_login(ssh, in, inlen, pktin))
5335 ssh->protocol_initial_phase_done = TRUE;
5340 do_ssh1_connection(ssh, in, inlen, pktin);
5344 * Utility routine for decoding comma-separated strings in KEXINIT.
5346 static int in_commasep_string(char *needle, char *haystack, int haylen)
5349 if (!needle || !haystack) /* protect against null pointers */
5351 needlen = strlen(needle);
5354 * Is it at the start of the string?
5356 if (haylen >= needlen && /* haystack is long enough */
5357 !memcmp(needle, haystack, needlen) && /* initial match */
5358 (haylen == needlen || haystack[needlen] == ',')
5359 /* either , or EOS follows */
5363 * If not, search for the next comma and resume after that.
5364 * If no comma found, terminate.
5366 while (haylen > 0 && *haystack != ',')
5367 haylen--, haystack++;
5370 haylen--, haystack++; /* skip over comma itself */
5375 * Similar routine for checking whether we have the first string in a list.
5377 static int first_in_commasep_string(char *needle, char *haystack, int haylen)
5380 if (!needle || !haystack) /* protect against null pointers */
5382 needlen = strlen(needle);
5384 * Is it at the start of the string?
5386 if (haylen >= needlen && /* haystack is long enough */
5387 !memcmp(needle, haystack, needlen) && /* initial match */
5388 (haylen == needlen || haystack[needlen] == ',')
5389 /* either , or EOS follows */
5397 * SSH-2 key creation method.
5398 * (Currently assumes 2 lots of any hash are sufficient to generate
5399 * keys/IVs for any cipher/MAC. SSH2_MKKEY_ITERS documents this assumption.)
5401 #define SSH2_MKKEY_ITERS (2)
5402 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H, char chr,
5403 unsigned char *keyspace)
5405 const struct ssh_hash *h = ssh->kex->hash;
5407 /* First hlen bytes. */
5409 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5410 hash_mpint(h, s, K);
5411 h->bytes(s, H, h->hlen);
5412 h->bytes(s, &chr, 1);
5413 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
5414 h->final(s, keyspace);
5415 /* Next hlen bytes. */
5417 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5418 hash_mpint(h, s, K);
5419 h->bytes(s, H, h->hlen);
5420 h->bytes(s, keyspace, h->hlen);
5421 h->final(s, keyspace + h->hlen);
5425 * Handle the SSH-2 transport layer.
5427 static void do_ssh2_transport(Ssh ssh, void *vin, int inlen,
5428 struct Packet *pktin)
5430 unsigned char *in = (unsigned char *)vin;
5431 struct do_ssh2_transport_state {
5433 int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
5434 Bignum p, g, e, f, K;
5437 int kex_init_value, kex_reply_value;
5438 const struct ssh_mac **maclist;
5440 const struct ssh2_cipher *cscipher_tobe;
5441 const struct ssh2_cipher *sccipher_tobe;
5442 const struct ssh_mac *csmac_tobe;
5443 const struct ssh_mac *scmac_tobe;
5444 const struct ssh_compress *cscomp_tobe;
5445 const struct ssh_compress *sccomp_tobe;
5446 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
5447 int hostkeylen, siglen, rsakeylen;
5448 void *hkey; /* actual host key */
5449 void *rsakey; /* for RSA kex */
5450 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
5451 int n_preferred_kex;
5452 const struct ssh_kexes *preferred_kex[KEX_MAX];
5453 int n_preferred_ciphers;
5454 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
5455 const struct ssh_compress *preferred_comp;
5456 int userauth_succeeded; /* for delayed compression */
5457 int pending_compression;
5458 int got_session_id, activated_authconn;
5459 struct Packet *pktout;
5464 crState(do_ssh2_transport_state);
5468 s->cscipher_tobe = s->sccipher_tobe = NULL;
5469 s->csmac_tobe = s->scmac_tobe = NULL;
5470 s->cscomp_tobe = s->sccomp_tobe = NULL;
5472 s->got_session_id = s->activated_authconn = FALSE;
5473 s->userauth_succeeded = FALSE;
5474 s->pending_compression = FALSE;
5477 * Be prepared to work around the buggy MAC problem.
5479 if (ssh->remote_bugs & BUG_SSH2_HMAC)
5480 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
5482 s->maclist = macs, s->nmacs = lenof(macs);
5485 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
5487 int i, j, k, commalist_started;
5490 * Set up the preferred key exchange. (NULL => warn below here)
5492 s->n_preferred_kex = 0;
5493 for (i = 0; i < KEX_MAX; i++) {
5494 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
5496 s->preferred_kex[s->n_preferred_kex++] =
5497 &ssh_diffiehellman_gex;
5500 s->preferred_kex[s->n_preferred_kex++] =
5501 &ssh_diffiehellman_group14;
5504 s->preferred_kex[s->n_preferred_kex++] =
5505 &ssh_diffiehellman_group1;
5508 s->preferred_kex[s->n_preferred_kex++] =
5512 /* Flag for later. Don't bother if it's the last in
5514 if (i < KEX_MAX - 1) {
5515 s->preferred_kex[s->n_preferred_kex++] = NULL;
5522 * Set up the preferred ciphers. (NULL => warn below here)
5524 s->n_preferred_ciphers = 0;
5525 for (i = 0; i < CIPHER_MAX; i++) {
5526 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
5527 case CIPHER_BLOWFISH:
5528 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
5531 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
5532 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
5536 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
5539 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
5541 case CIPHER_ARCFOUR:
5542 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
5545 /* Flag for later. Don't bother if it's the last in
5547 if (i < CIPHER_MAX - 1) {
5548 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
5555 * Set up preferred compression.
5557 if (conf_get_int(ssh->conf, CONF_compression))
5558 s->preferred_comp = &ssh_zlib;
5560 s->preferred_comp = &ssh_comp_none;
5563 * Enable queueing of outgoing auth- or connection-layer
5564 * packets while we are in the middle of a key exchange.
5566 ssh->queueing = TRUE;
5569 * Flag that KEX is in progress.
5571 ssh->kex_in_progress = TRUE;
5574 * Construct and send our key exchange packet.
5576 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
5577 for (i = 0; i < 16; i++)
5578 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
5579 /* List key exchange algorithms. */
5580 ssh2_pkt_addstring_start(s->pktout);
5581 commalist_started = 0;
5582 for (i = 0; i < s->n_preferred_kex; i++) {
5583 const struct ssh_kexes *k = s->preferred_kex[i];
5584 if (!k) continue; /* warning flag */
5585 for (j = 0; j < k->nkexes; j++) {
5586 if (commalist_started)
5587 ssh2_pkt_addstring_str(s->pktout, ",");
5588 ssh2_pkt_addstring_str(s->pktout, k->list[j]->name);
5589 commalist_started = 1;
5592 /* List server host key algorithms. */
5593 if (!s->got_session_id) {
5595 * In the first key exchange, we list all the algorithms
5596 * we're prepared to cope with.
5598 ssh2_pkt_addstring_start(s->pktout);
5599 for (i = 0; i < lenof(hostkey_algs); i++) {
5600 ssh2_pkt_addstring_str(s->pktout, hostkey_algs[i]->name);
5601 if (i < lenof(hostkey_algs) - 1)
5602 ssh2_pkt_addstring_str(s->pktout, ",");
5606 * In subsequent key exchanges, we list only the kex
5607 * algorithm that was selected in the first key exchange,
5608 * so that we keep getting the same host key and hence
5609 * don't have to interrupt the user's session to ask for
5613 ssh2_pkt_addstring(s->pktout, ssh->hostkey->name);
5615 /* List encryption algorithms (client->server then server->client). */
5616 for (k = 0; k < 2; k++) {
5617 ssh2_pkt_addstring_start(s->pktout);
5618 commalist_started = 0;
5619 for (i = 0; i < s->n_preferred_ciphers; i++) {
5620 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5621 if (!c) continue; /* warning flag */
5622 for (j = 0; j < c->nciphers; j++) {
5623 if (commalist_started)
5624 ssh2_pkt_addstring_str(s->pktout, ",");
5625 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
5626 commalist_started = 1;
5630 /* List MAC algorithms (client->server then server->client). */
5631 for (j = 0; j < 2; j++) {
5632 ssh2_pkt_addstring_start(s->pktout);
5633 for (i = 0; i < s->nmacs; i++) {
5634 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5635 if (i < s->nmacs - 1)
5636 ssh2_pkt_addstring_str(s->pktout, ",");
5639 /* List client->server compression algorithms,
5640 * then server->client compression algorithms. (We use the
5641 * same set twice.) */
5642 for (j = 0; j < 2; j++) {
5643 ssh2_pkt_addstring_start(s->pktout);
5644 assert(lenof(compressions) > 1);
5645 /* Prefer non-delayed versions */
5646 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
5647 /* We don't even list delayed versions of algorithms until
5648 * they're allowed to be used, to avoid a race. See the end of
5650 if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
5651 ssh2_pkt_addstring_str(s->pktout, ",");
5652 ssh2_pkt_addstring_str(s->pktout,
5653 s->preferred_comp->delayed_name);
5655 for (i = 0; i < lenof(compressions); i++) {
5656 const struct ssh_compress *c = compressions[i];
5657 if (c != s->preferred_comp) {
5658 ssh2_pkt_addstring_str(s->pktout, ",");
5659 ssh2_pkt_addstring_str(s->pktout, c->name);
5660 if (s->userauth_succeeded && c->delayed_name) {
5661 ssh2_pkt_addstring_str(s->pktout, ",");
5662 ssh2_pkt_addstring_str(s->pktout, c->delayed_name);
5667 /* List client->server languages. Empty list. */
5668 ssh2_pkt_addstring_start(s->pktout);
5669 /* List server->client languages. Empty list. */
5670 ssh2_pkt_addstring_start(s->pktout);
5671 /* First KEX packet does _not_ follow, because we're not that brave. */
5672 ssh2_pkt_addbool(s->pktout, FALSE);
5674 ssh2_pkt_adduint32(s->pktout, 0);
5677 s->our_kexinitlen = s->pktout->length - 5;
5678 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
5679 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
5681 ssh2_pkt_send_noqueue(ssh, s->pktout);
5684 crWaitUntilV(pktin);
5687 * Now examine the other side's KEXINIT to see what we're up
5691 char *str, *preferred;
5694 if (pktin->type != SSH2_MSG_KEXINIT) {
5695 bombout(("expected key exchange packet from server"));
5699 ssh->hostkey = NULL;
5700 s->cscipher_tobe = NULL;
5701 s->sccipher_tobe = NULL;
5702 s->csmac_tobe = NULL;
5703 s->scmac_tobe = NULL;
5704 s->cscomp_tobe = NULL;
5705 s->sccomp_tobe = NULL;
5706 s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
5708 pktin->savedpos += 16; /* skip garbage cookie */
5709 ssh_pkt_getstring(pktin, &str, &len); /* key exchange algorithms */
5712 for (i = 0; i < s->n_preferred_kex; i++) {
5713 const struct ssh_kexes *k = s->preferred_kex[i];
5717 for (j = 0; j < k->nkexes; j++) {
5718 if (!preferred) preferred = k->list[j]->name;
5719 if (in_commasep_string(k->list[j]->name, str, len)) {
5720 ssh->kex = k->list[j];
5729 bombout(("Couldn't agree a key exchange algorithm (available: %s)",
5730 str ? str : "(null)"));
5734 * Note that the server's guess is considered wrong if it doesn't match
5735 * the first algorithm in our list, even if it's still the algorithm
5738 s->guessok = first_in_commasep_string(preferred, str, len);
5739 ssh_pkt_getstring(pktin, &str, &len); /* host key algorithms */
5740 for (i = 0; i < lenof(hostkey_algs); i++) {
5741 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
5742 ssh->hostkey = hostkey_algs[i];
5746 if (!ssh->hostkey) {
5747 bombout(("Couldn't agree a host key algorithm (available: %s)",
5748 str ? str : "(null)"));
5752 s->guessok = s->guessok &&
5753 first_in_commasep_string(hostkey_algs[0]->name, str, len);
5754 ssh_pkt_getstring(pktin, &str, &len); /* client->server cipher */
5755 for (i = 0; i < s->n_preferred_ciphers; i++) {
5756 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5758 s->warn_cscipher = TRUE;
5760 for (j = 0; j < c->nciphers; j++) {
5761 if (in_commasep_string(c->list[j]->name, str, len)) {
5762 s->cscipher_tobe = c->list[j];
5767 if (s->cscipher_tobe)
5770 if (!s->cscipher_tobe) {
5771 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
5772 str ? str : "(null)"));
5776 ssh_pkt_getstring(pktin, &str, &len); /* server->client cipher */
5777 for (i = 0; i < s->n_preferred_ciphers; i++) {
5778 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5780 s->warn_sccipher = TRUE;
5782 for (j = 0; j < c->nciphers; j++) {
5783 if (in_commasep_string(c->list[j]->name, str, len)) {
5784 s->sccipher_tobe = c->list[j];
5789 if (s->sccipher_tobe)
5792 if (!s->sccipher_tobe) {
5793 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
5794 str ? str : "(null)"));
5798 ssh_pkt_getstring(pktin, &str, &len); /* client->server mac */
5799 for (i = 0; i < s->nmacs; i++) {
5800 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5801 s->csmac_tobe = s->maclist[i];
5805 ssh_pkt_getstring(pktin, &str, &len); /* server->client mac */
5806 for (i = 0; i < s->nmacs; i++) {
5807 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5808 s->scmac_tobe = s->maclist[i];
5812 ssh_pkt_getstring(pktin, &str, &len); /* client->server compression */
5813 for (i = 0; i < lenof(compressions) + 1; i++) {
5814 const struct ssh_compress *c =
5815 i == 0 ? s->preferred_comp : compressions[i - 1];
5816 if (in_commasep_string(c->name, str, len)) {
5819 } else if (in_commasep_string(c->delayed_name, str, len)) {
5820 if (s->userauth_succeeded) {
5824 s->pending_compression = TRUE; /* try this later */
5828 ssh_pkt_getstring(pktin, &str, &len); /* server->client compression */
5829 for (i = 0; i < lenof(compressions) + 1; i++) {
5830 const struct ssh_compress *c =
5831 i == 0 ? s->preferred_comp : compressions[i - 1];
5832 if (in_commasep_string(c->name, str, len)) {
5835 } else if (in_commasep_string(c->delayed_name, str, len)) {
5836 if (s->userauth_succeeded) {
5840 s->pending_compression = TRUE; /* try this later */
5844 if (s->pending_compression) {
5845 logevent("Server supports delayed compression; "
5846 "will try this later");
5848 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
5849 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
5850 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
5852 ssh->exhash = ssh->kex->hash->init();
5853 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
5854 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
5855 hash_string(ssh->kex->hash, ssh->exhash,
5856 s->our_kexinit, s->our_kexinitlen);
5857 sfree(s->our_kexinit);
5858 /* Include the type byte in the hash of server's KEXINIT */
5859 hash_string(ssh->kex->hash, ssh->exhash,
5860 pktin->body - 1, pktin->length + 1);
5863 ssh_set_frozen(ssh, 1);
5864 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
5866 ssh_dialog_callback, ssh);
5867 if (s->dlgret < 0) {
5871 bombout(("Unexpected data from server while"
5872 " waiting for user response"));
5875 } while (pktin || inlen > 0);
5876 s->dlgret = ssh->user_response;
5878 ssh_set_frozen(ssh, 0);
5879 if (s->dlgret == 0) {
5880 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
5886 if (s->warn_cscipher) {
5887 ssh_set_frozen(ssh, 1);
5888 s->dlgret = askalg(ssh->frontend,
5889 "client-to-server cipher",
5890 s->cscipher_tobe->name,
5891 ssh_dialog_callback, ssh);
5892 if (s->dlgret < 0) {
5896 bombout(("Unexpected data from server while"
5897 " waiting for user response"));
5900 } while (pktin || inlen > 0);
5901 s->dlgret = ssh->user_response;
5903 ssh_set_frozen(ssh, 0);
5904 if (s->dlgret == 0) {
5905 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
5911 if (s->warn_sccipher) {
5912 ssh_set_frozen(ssh, 1);
5913 s->dlgret = askalg(ssh->frontend,
5914 "server-to-client cipher",
5915 s->sccipher_tobe->name,
5916 ssh_dialog_callback, ssh);
5917 if (s->dlgret < 0) {
5921 bombout(("Unexpected data from server while"
5922 " waiting for user response"));
5925 } while (pktin || inlen > 0);
5926 s->dlgret = ssh->user_response;
5928 ssh_set_frozen(ssh, 0);
5929 if (s->dlgret == 0) {
5930 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
5936 if (s->ignorepkt) /* first_kex_packet_follows */
5937 crWaitUntilV(pktin); /* Ignore packet */
5940 if (ssh->kex->main_type == KEXTYPE_DH) {
5942 * Work out the number of bits of key we will need from the
5943 * key exchange. We start with the maximum key length of
5949 csbits = s->cscipher_tobe->keylen;
5950 scbits = s->sccipher_tobe->keylen;
5951 s->nbits = (csbits > scbits ? csbits : scbits);
5953 /* The keys only have hlen-bit entropy, since they're based on
5954 * a hash. So cap the key size at hlen bits. */
5955 if (s->nbits > ssh->kex->hash->hlen * 8)
5956 s->nbits = ssh->kex->hash->hlen * 8;
5959 * If we're doing Diffie-Hellman group exchange, start by
5960 * requesting a group.
5962 if (!ssh->kex->pdata) {
5963 logevent("Doing Diffie-Hellman group exchange");
5964 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
5966 * Work out how big a DH group we will need to allow that
5969 s->pbits = 512 << ((s->nbits - 1) / 64);
5970 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
5971 ssh2_pkt_adduint32(s->pktout, s->pbits);
5972 ssh2_pkt_send_noqueue(ssh, s->pktout);
5974 crWaitUntilV(pktin);
5975 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
5976 bombout(("expected key exchange group packet from server"));
5979 s->p = ssh2_pkt_getmp(pktin);
5980 s->g = ssh2_pkt_getmp(pktin);
5981 if (!s->p || !s->g) {
5982 bombout(("unable to read mp-ints from incoming group packet"));
5985 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
5986 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
5987 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
5989 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
5990 ssh->kex_ctx = dh_setup_group(ssh->kex);
5991 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
5992 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
5993 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
5994 ssh->kex->groupname);
5997 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
5998 ssh->kex->hash->text_name);
6000 * Now generate and send e for Diffie-Hellman.
6002 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
6003 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
6004 s->pktout = ssh2_pkt_init(s->kex_init_value);
6005 ssh2_pkt_addmp(s->pktout, s->e);
6006 ssh2_pkt_send_noqueue(ssh, s->pktout);
6008 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
6009 crWaitUntilV(pktin);
6010 if (pktin->type != s->kex_reply_value) {
6011 bombout(("expected key exchange reply packet from server"));
6014 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
6015 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6016 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6017 s->f = ssh2_pkt_getmp(pktin);
6019 bombout(("unable to parse key exchange reply packet"));
6022 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6024 s->K = dh_find_K(ssh->kex_ctx, s->f);
6026 /* We assume everything from now on will be quick, and it might
6027 * involve user interaction. */
6028 set_busy_status(ssh->frontend, BUSY_NOT);
6030 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6031 if (!ssh->kex->pdata) {
6032 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
6033 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
6034 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
6036 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
6037 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
6039 dh_cleanup(ssh->kex_ctx);
6041 if (!ssh->kex->pdata) {
6046 logeventf(ssh, "Doing RSA key exchange with hash %s",
6047 ssh->kex->hash->text_name);
6048 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
6050 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
6053 crWaitUntilV(pktin);
6054 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
6055 bombout(("expected RSA public key packet from server"));
6059 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6060 hash_string(ssh->kex->hash, ssh->exhash,
6061 s->hostkeydata, s->hostkeylen);
6062 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6066 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
6067 s->rsakeydata = snewn(s->rsakeylen, char);
6068 memcpy(s->rsakeydata, keydata, s->rsakeylen);
6071 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
6073 sfree(s->rsakeydata);
6074 bombout(("unable to parse RSA public key from server"));
6078 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
6081 * Next, set up a shared secret K, of precisely KLEN -
6082 * 2*HLEN - 49 bits, where KLEN is the bit length of the
6083 * RSA key modulus and HLEN is the bit length of the hash
6087 int klen = ssh_rsakex_klen(s->rsakey);
6088 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
6090 unsigned char *kstr1, *kstr2, *outstr;
6091 int kstr1len, kstr2len, outstrlen;
6093 s->K = bn_power_2(nbits - 1);
6095 for (i = 0; i < nbits; i++) {
6097 byte = random_byte();
6099 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
6103 * Encode this as an mpint.
6105 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
6106 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
6107 PUT_32BIT(kstr2, kstr1len);
6108 memcpy(kstr2 + 4, kstr1, kstr1len);
6111 * Encrypt it with the given RSA key.
6113 outstrlen = (klen + 7) / 8;
6114 outstr = snewn(outstrlen, unsigned char);
6115 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
6116 outstr, outstrlen, s->rsakey);
6119 * And send it off in a return packet.
6121 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
6122 ssh2_pkt_addstring_start(s->pktout);
6123 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
6124 ssh2_pkt_send_noqueue(ssh, s->pktout);
6126 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
6133 ssh_rsakex_freekey(s->rsakey);
6135 crWaitUntilV(pktin);
6136 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
6137 sfree(s->rsakeydata);
6138 bombout(("expected signature packet from server"));
6142 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6144 sfree(s->rsakeydata);
6147 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
6148 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
6149 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
6151 ssh->kex_ctx = NULL;
6154 debug(("Exchange hash is:\n"));
6155 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
6159 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
6160 (char *)s->exchange_hash,
6161 ssh->kex->hash->hlen)) {
6162 bombout(("Server's host key did not match the signature supplied"));
6166 s->keystr = ssh->hostkey->fmtkey(s->hkey);
6167 if (!s->got_session_id) {
6169 * Authenticate remote host: verify host key. (We've already
6170 * checked the signature of the exchange hash.)
6172 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
6173 ssh_set_frozen(ssh, 1);
6174 s->dlgret = verify_ssh_host_key(ssh->frontend,
6175 ssh->savedhost, ssh->savedport,
6176 ssh->hostkey->keytype, s->keystr,
6178 ssh_dialog_callback, ssh);
6179 if (s->dlgret < 0) {
6183 bombout(("Unexpected data from server while waiting"
6184 " for user host key response"));
6187 } while (pktin || inlen > 0);
6188 s->dlgret = ssh->user_response;
6190 ssh_set_frozen(ssh, 0);
6191 if (s->dlgret == 0) {
6192 ssh_disconnect(ssh, "User aborted at host key verification", NULL,
6196 logevent("Host key fingerprint is:");
6197 logevent(s->fingerprint);
6198 sfree(s->fingerprint);
6200 * Save this host key, to check against the one presented in
6201 * subsequent rekeys.
6203 ssh->hostkey_str = s->keystr;
6206 * In a rekey, we never present an interactive host key
6207 * verification request to the user. Instead, we simply
6208 * enforce that the key we're seeing this time is identical to
6209 * the one we saw before.
6211 if (strcmp(ssh->hostkey_str, s->keystr)) {
6212 bombout(("Host key was different in repeat key exchange"));
6217 ssh->hostkey->freekey(s->hkey);
6220 * The exchange hash from the very first key exchange is also
6221 * the session id, used in session key construction and
6224 if (!s->got_session_id) {
6225 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
6226 memcpy(ssh->v2_session_id, s->exchange_hash,
6227 sizeof(s->exchange_hash));
6228 ssh->v2_session_id_len = ssh->kex->hash->hlen;
6229 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
6230 s->got_session_id = TRUE;
6234 * Send SSH2_MSG_NEWKEYS.
6236 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
6237 ssh2_pkt_send_noqueue(ssh, s->pktout);
6238 ssh->outgoing_data_size = 0; /* start counting from here */
6241 * We've sent client NEWKEYS, so create and initialise
6242 * client-to-server session keys.
6244 if (ssh->cs_cipher_ctx)
6245 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
6246 ssh->cscipher = s->cscipher_tobe;
6247 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
6249 if (ssh->cs_mac_ctx)
6250 ssh->csmac->free_context(ssh->cs_mac_ctx);
6251 ssh->csmac = s->csmac_tobe;
6252 ssh->cs_mac_ctx = ssh->csmac->make_context();
6254 if (ssh->cs_comp_ctx)
6255 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
6256 ssh->cscomp = s->cscomp_tobe;
6257 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
6260 * Set IVs on client-to-server keys. Here we use the exchange
6261 * hash from the _first_ key exchange.
6264 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6265 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6266 ssh2_mkkey(ssh,s->K,s->exchange_hash,'C',keyspace);
6267 assert((ssh->cscipher->keylen+7) / 8 <=
6268 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6269 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
6270 ssh2_mkkey(ssh,s->K,s->exchange_hash,'A',keyspace);
6271 assert(ssh->cscipher->blksize <=
6272 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6273 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
6274 ssh2_mkkey(ssh,s->K,s->exchange_hash,'E',keyspace);
6275 assert(ssh->csmac->len <=
6276 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6277 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
6278 smemclr(keyspace, sizeof(keyspace));
6281 logeventf(ssh, "Initialised %.200s client->server encryption",
6282 ssh->cscipher->text_name);
6283 logeventf(ssh, "Initialised %.200s client->server MAC algorithm",
6284 ssh->csmac->text_name);
6285 if (ssh->cscomp->text_name)
6286 logeventf(ssh, "Initialised %s compression",
6287 ssh->cscomp->text_name);
6290 * Now our end of the key exchange is complete, we can send all
6291 * our queued higher-layer packets.
6293 ssh->queueing = FALSE;
6294 ssh2_pkt_queuesend(ssh);
6297 * Expect SSH2_MSG_NEWKEYS from server.
6299 crWaitUntilV(pktin);
6300 if (pktin->type != SSH2_MSG_NEWKEYS) {
6301 bombout(("expected new-keys packet from server"));
6304 ssh->incoming_data_size = 0; /* start counting from here */
6307 * We've seen server NEWKEYS, so create and initialise
6308 * server-to-client session keys.
6310 if (ssh->sc_cipher_ctx)
6311 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
6312 ssh->sccipher = s->sccipher_tobe;
6313 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
6315 if (ssh->sc_mac_ctx)
6316 ssh->scmac->free_context(ssh->sc_mac_ctx);
6317 ssh->scmac = s->scmac_tobe;
6318 ssh->sc_mac_ctx = ssh->scmac->make_context();
6320 if (ssh->sc_comp_ctx)
6321 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
6322 ssh->sccomp = s->sccomp_tobe;
6323 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
6326 * Set IVs on server-to-client keys. Here we use the exchange
6327 * hash from the _first_ key exchange.
6330 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6331 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6332 ssh2_mkkey(ssh,s->K,s->exchange_hash,'D',keyspace);
6333 assert((ssh->sccipher->keylen+7) / 8 <=
6334 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6335 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
6336 ssh2_mkkey(ssh,s->K,s->exchange_hash,'B',keyspace);
6337 assert(ssh->sccipher->blksize <=
6338 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6339 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
6340 ssh2_mkkey(ssh,s->K,s->exchange_hash,'F',keyspace);
6341 assert(ssh->scmac->len <=
6342 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6343 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
6344 smemclr(keyspace, sizeof(keyspace));
6346 logeventf(ssh, "Initialised %.200s server->client encryption",
6347 ssh->sccipher->text_name);
6348 logeventf(ssh, "Initialised %.200s server->client MAC algorithm",
6349 ssh->scmac->text_name);
6350 if (ssh->sccomp->text_name)
6351 logeventf(ssh, "Initialised %s decompression",
6352 ssh->sccomp->text_name);
6355 * Free shared secret.
6360 * Key exchange is over. Loop straight back round if we have a
6361 * deferred rekey reason.
6363 if (ssh->deferred_rekey_reason) {
6364 logevent(ssh->deferred_rekey_reason);
6366 ssh->deferred_rekey_reason = NULL;
6367 goto begin_key_exchange;
6371 * Otherwise, schedule a timer for our next rekey.
6373 ssh->kex_in_progress = FALSE;
6374 ssh->last_rekey = GETTICKCOUNT();
6375 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
6376 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
6380 * Now we're encrypting. Begin returning 1 to the protocol main
6381 * function so that other things can run on top of the
6382 * transport. If we ever see a KEXINIT, we must go back to the
6385 * We _also_ go back to the start if we see pktin==NULL and
6386 * inlen negative, because this is a special signal meaning
6387 * `initiate client-driven rekey', and `in' contains a message
6388 * giving the reason for the rekey.
6390 * inlen==-1 means always initiate a rekey;
6391 * inlen==-2 means that userauth has completed successfully and
6392 * we should consider rekeying (for delayed compression).
6394 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
6395 (!pktin && inlen < 0))) {
6397 if (!ssh->protocol_initial_phase_done) {
6398 ssh->protocol_initial_phase_done = TRUE;
6400 * Allow authconn to initialise itself.
6402 do_ssh2_authconn(ssh, NULL, 0, NULL);
6407 logevent("Server initiated key re-exchange");
6411 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
6412 * delayed compression, if it's available.
6414 * draft-miller-secsh-compression-delayed-00 says that you
6415 * negotiate delayed compression in the first key exchange, and
6416 * both sides start compressing when the server has sent
6417 * USERAUTH_SUCCESS. This has a race condition -- the server
6418 * can't know when the client has seen it, and thus which incoming
6419 * packets it should treat as compressed.
6421 * Instead, we do the initial key exchange without offering the
6422 * delayed methods, but note if the server offers them; when we
6423 * get here, if a delayed method was available that was higher
6424 * on our list than what we got, we initiate a rekey in which we
6425 * _do_ list the delayed methods (and hopefully get it as a
6426 * result). Subsequent rekeys will do the same.
6428 assert(!s->userauth_succeeded); /* should only happen once */
6429 s->userauth_succeeded = TRUE;
6430 if (!s->pending_compression)
6431 /* Can't see any point rekeying. */
6432 goto wait_for_rekey; /* this is utterly horrid */
6433 /* else fall through to rekey... */
6434 s->pending_compression = FALSE;
6437 * Now we've decided to rekey.
6439 * Special case: if the server bug is set that doesn't
6440 * allow rekeying, we give a different log message and
6441 * continue waiting. (If such a server _initiates_ a rekey,
6442 * we process it anyway!)
6444 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
6445 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
6447 /* Reset the counters, so that at least this message doesn't
6448 * hit the event log _too_ often. */
6449 ssh->outgoing_data_size = 0;
6450 ssh->incoming_data_size = 0;
6451 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
6453 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
6456 goto wait_for_rekey; /* this is still utterly horrid */
6458 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
6461 goto begin_key_exchange;
6467 * Add data to an SSH-2 channel output buffer.
6469 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
6472 bufchain_add(&c->v.v2.outbuffer, buf, len);
6476 * Attempt to send data on an SSH-2 channel.
6478 static int ssh2_try_send(struct ssh_channel *c)
6481 struct Packet *pktout;
6484 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
6487 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
6488 if ((unsigned)len > c->v.v2.remwindow)
6489 len = c->v.v2.remwindow;
6490 if ((unsigned)len > c->v.v2.remmaxpkt)
6491 len = c->v.v2.remmaxpkt;
6492 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
6493 ssh2_pkt_adduint32(pktout, c->remoteid);
6494 ssh2_pkt_addstring_start(pktout);
6495 dont_log_data(ssh, pktout, PKTLOG_OMIT);
6496 ssh2_pkt_addstring_data(pktout, data, len);
6497 end_log_omission(ssh, pktout);
6498 ssh2_pkt_send(ssh, pktout);
6499 bufchain_consume(&c->v.v2.outbuffer, len);
6500 c->v.v2.remwindow -= len;
6504 * After having sent as much data as we can, return the amount
6507 ret = bufchain_size(&c->v.v2.outbuffer);
6510 * And if there's no data pending but we need to send an EOF, send
6513 if (!ret && c->pending_eof)
6514 ssh_channel_try_eof(c);
6519 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
6522 if (c->closes & CLOSES_SENT_EOF)
6523 return; /* don't send on channels we've EOFed */
6524 bufsize = ssh2_try_send(c);
6527 case CHAN_MAINSESSION:
6528 /* stdin need not receive an unthrottle
6529 * notification since it will be polled */
6532 x11_unthrottle(c->u.x11.s);
6535 /* agent sockets are request/response and need no
6536 * buffer management */
6539 pfd_unthrottle(c->u.pfd.s);
6546 * Set up most of a new ssh_channel for SSH-2.
6548 static void ssh2_channel_init(struct ssh_channel *c)
6551 c->localid = alloc_channel_id(ssh);
6553 c->pending_eof = FALSE;
6554 c->throttling_conn = FALSE;
6555 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
6556 conf_get_int(ssh->conf, CONF_ssh_simple) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
6557 c->v.v2.chanreq_head = NULL;
6558 c->v.v2.throttle_state = UNTHROTTLED;
6559 bufchain_init(&c->v.v2.outbuffer);
6563 * Construct the common parts of a CHANNEL_OPEN.
6565 static struct Packet *ssh2_chanopen_init(struct ssh_channel *c, char *type)
6567 struct Packet *pktout;
6569 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
6570 ssh2_pkt_addstring(pktout, type);
6571 ssh2_pkt_adduint32(pktout, c->localid);
6572 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
6573 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
6578 * CHANNEL_FAILURE doesn't come with any indication of what message
6579 * caused it, so we have to keep track of the outstanding
6580 * CHANNEL_REQUESTs ourselves.
6582 static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
6583 cchandler_fn_t handler, void *ctx)
6585 struct outstanding_channel_request *ocr =
6586 snew(struct outstanding_channel_request);
6588 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
6589 ocr->handler = handler;
6592 if (!c->v.v2.chanreq_head)
6593 c->v.v2.chanreq_head = ocr;
6595 c->v.v2.chanreq_tail->next = ocr;
6596 c->v.v2.chanreq_tail = ocr;
6600 * Construct the common parts of a CHANNEL_REQUEST. If handler is not
6601 * NULL then a reply will be requested and the handler will be called
6602 * when it arrives. The returned packet is ready to have any
6603 * request-specific data added and be sent. Note that if a handler is
6604 * provided, it's essential that the request actually be sent.
6606 * The handler will usually be passed the response packet in pktin.
6607 * If pktin is NULL, this means that no reply will ever be forthcoming
6608 * (e.g. because the entire connection is being destroyed) and the
6609 * handler should free any storage it's holding.
6611 static struct Packet *ssh2_chanreq_init(struct ssh_channel *c, char *type,
6612 cchandler_fn_t handler, void *ctx)
6614 struct Packet *pktout;
6616 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
6617 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6618 ssh2_pkt_adduint32(pktout, c->remoteid);
6619 ssh2_pkt_addstring(pktout, type);
6620 ssh2_pkt_addbool(pktout, handler != NULL);
6621 if (handler != NULL)
6622 ssh2_queue_chanreq_handler(c, handler, ctx);
6627 * Potentially enlarge the window on an SSH-2 channel.
6629 static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
6631 static void ssh2_set_window(struct ssh_channel *c, int newwin)
6636 * Never send WINDOW_ADJUST for a channel that the remote side has
6637 * already sent EOF on; there's no point, since it won't be
6638 * sending any more data anyway. Ditto if _we've_ already sent
6641 if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
6645 * If the remote end has a habit of ignoring maxpkt, limit the
6646 * window so that it has no choice (assuming it doesn't ignore the
6649 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
6650 newwin = OUR_V2_MAXPKT;
6653 * Only send a WINDOW_ADJUST if there's significantly more window
6654 * available than the other end thinks there is. This saves us
6655 * sending a WINDOW_ADJUST for every character in a shell session.
6657 * "Significant" is arbitrarily defined as half the window size.
6659 if (newwin / 2 >= c->v.v2.locwindow) {
6660 struct Packet *pktout;
6664 * In order to keep track of how much window the client
6665 * actually has available, we'd like it to acknowledge each
6666 * WINDOW_ADJUST. We can't do that directly, so we accompany
6667 * it with a CHANNEL_REQUEST that has to be acknowledged.
6669 * This is only necessary if we're opening the window wide.
6670 * If we're not, then throughput is being constrained by
6671 * something other than the maximum window size anyway.
6673 if (newwin == c->v.v2.locmaxwin &&
6674 !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
6675 up = snew(unsigned);
6676 *up = newwin - c->v.v2.locwindow;
6677 pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org",
6678 ssh2_handle_winadj_response, up);
6679 ssh2_pkt_send(ssh, pktout);
6681 if (c->v.v2.throttle_state != UNTHROTTLED)
6682 c->v.v2.throttle_state = UNTHROTTLING;
6684 /* Pretend the WINDOW_ADJUST was acked immediately. */
6685 c->v.v2.remlocwin = newwin;
6686 c->v.v2.throttle_state = THROTTLED;
6688 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
6689 ssh2_pkt_adduint32(pktout, c->remoteid);
6690 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
6691 ssh2_pkt_send(ssh, pktout);
6692 c->v.v2.locwindow = newwin;
6697 * Find the channel associated with a message. If there's no channel,
6698 * or it's not properly open, make a noise about it and return NULL.
6700 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
6702 unsigned localid = ssh_pkt_getuint32(pktin);
6703 struct ssh_channel *c;
6705 c = find234(ssh->channels, &localid, ssh_channelfind);
6707 (c->halfopen && pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
6708 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
6709 char *buf = dupprintf("Received %s for %s channel %u",
6710 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
6712 c ? "half-open" : "nonexistent", localid);
6713 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6720 static void ssh2_handle_winadj_response(struct ssh_channel *c,
6721 struct Packet *pktin, void *ctx)
6723 unsigned *sizep = ctx;
6726 * Winadj responses should always be failures. However, at least
6727 * one server ("boks_sshd") is known to return SUCCESS for channel
6728 * requests it's never heard of, such as "winadj@putty". Raised
6729 * with foxt.com as bug 090916-090424, but for the sake of a quiet
6730 * life, we don't worry about what kind of response we got.
6733 c->v.v2.remlocwin += *sizep;
6736 * winadj messages are only sent when the window is fully open, so
6737 * if we get an ack of one, we know any pending unthrottle is
6740 if (c->v.v2.throttle_state == UNTHROTTLING)
6741 c->v.v2.throttle_state = UNTHROTTLED;
6744 static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
6746 struct ssh_channel *c = ssh2_channel_msg(ssh, pktin);
6747 struct outstanding_channel_request *ocr;
6750 ocr = c->v.v2.chanreq_head;
6752 ssh2_msg_unexpected(ssh, pktin);
6755 ocr->handler(c, pktin, ocr->ctx);
6756 c->v.v2.chanreq_head = ocr->next;
6759 * We may now initiate channel-closing procedures, if that
6760 * CHANNEL_REQUEST was the last thing outstanding before we send
6763 ssh2_channel_check_close(c);
6766 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
6768 struct ssh_channel *c;
6769 c = ssh2_channel_msg(ssh, pktin);
6772 if (!(c->closes & CLOSES_SENT_EOF)) {
6773 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
6774 ssh2_try_send_and_unthrottle(ssh, c);
6778 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
6782 struct ssh_channel *c;
6783 c = ssh2_channel_msg(ssh, pktin);
6786 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
6787 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
6788 return; /* extended but not stderr */
6789 ssh_pkt_getstring(pktin, &data, &length);
6792 c->v.v2.locwindow -= length;
6793 c->v.v2.remlocwin -= length;
6795 case CHAN_MAINSESSION:
6797 from_backend(ssh->frontend, pktin->type ==
6798 SSH2_MSG_CHANNEL_EXTENDED_DATA,
6802 bufsize = x11_send(c->u.x11.s, data, length);
6805 bufsize = pfd_send(c->u.pfd.s, data, length);
6808 while (length > 0) {
6809 if (c->u.a.lensofar < 4) {
6810 unsigned int l = min(4 - c->u.a.lensofar,
6812 memcpy(c->u.a.msglen + c->u.a.lensofar,
6816 c->u.a.lensofar += l;
6818 if (c->u.a.lensofar == 4) {
6820 4 + GET_32BIT(c->u.a.msglen);
6821 c->u.a.message = snewn(c->u.a.totallen,
6823 memcpy(c->u.a.message, c->u.a.msglen, 4);
6825 if (c->u.a.lensofar >= 4 && length > 0) {
6827 min(c->u.a.totallen - c->u.a.lensofar,
6829 memcpy(c->u.a.message + c->u.a.lensofar,
6833 c->u.a.lensofar += l;
6835 if (c->u.a.lensofar == c->u.a.totallen) {
6838 c->u.a.outstanding_requests++;
6839 if (agent_query(c->u.a.message,
6842 ssh_agentf_callback, c))
6843 ssh_agentf_callback(c, reply, replylen);
6844 sfree(c->u.a.message);
6845 c->u.a.message = NULL;
6846 c->u.a.lensofar = 0;
6853 * If it looks like the remote end hit the end of its window,
6854 * and we didn't want it to do that, think about using a
6857 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
6858 c->v.v2.locmaxwin < 0x40000000)
6859 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
6861 * If we are not buffering too much data,
6862 * enlarge the window again at the remote side.
6863 * If we are buffering too much, we may still
6864 * need to adjust the window if the server's
6867 ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
6868 c->v.v2.locmaxwin - bufsize : 0);
6870 * If we're either buffering way too much data, or if we're
6871 * buffering anything at all and we're in "simple" mode,
6872 * throttle the whole channel.
6874 if ((bufsize > c->v.v2.locmaxwin ||
6875 (conf_get_int(ssh->conf, CONF_ssh_simple) && bufsize > 0)) &&
6876 !c->throttling_conn) {
6877 c->throttling_conn = 1;
6878 ssh_throttle_conn(ssh, +1);
6883 static void ssh_channel_destroy(struct ssh_channel *c)
6888 case CHAN_MAINSESSION:
6889 ssh->mainchan = NULL;
6890 update_specials_menu(ssh->frontend);
6893 if (c->u.x11.s != NULL)
6894 x11_close(c->u.x11.s);
6895 logevent("Forwarded X11 connection terminated");
6898 sfree(c->u.a.message);
6901 if (c->u.pfd.s != NULL)
6902 pfd_close(c->u.pfd.s);
6903 logevent("Forwarded port closed");
6907 del234(ssh->channels, c);
6908 if (ssh->version == 2) {
6909 bufchain_clear(&c->v.v2.outbuffer);
6910 assert(c->v.v2.chanreq_head == NULL);
6915 * See if that was the last channel left open.
6916 * (This is only our termination condition if we're
6917 * not running in -N mode.)
6919 if (ssh->version == 2 &&
6920 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
6921 count234(ssh->channels) == 0) {
6923 * We used to send SSH_MSG_DISCONNECT here,
6924 * because I'd believed that _every_ conforming
6925 * SSH-2 connection had to end with a disconnect
6926 * being sent by at least one side; apparently
6927 * I was wrong and it's perfectly OK to
6928 * unceremoniously slam the connection shut
6929 * when you're done, and indeed OpenSSH feels
6930 * this is more polite than sending a
6931 * DISCONNECT. So now we don't.
6933 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
6937 static void ssh2_channel_check_close(struct ssh_channel *c)
6940 struct Packet *pktout;
6944 * If we've sent out our own CHANNEL_OPEN but not yet seen
6945 * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
6946 * it's too early to be sending close messages of any kind.
6951 if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
6952 c->type == CHAN_ZOMBIE) &&
6953 !c->v.v2.chanreq_head &&
6954 !(c->closes & CLOSES_SENT_CLOSE)) {
6956 * We have both sent and received EOF (or the channel is a
6957 * zombie), and we have no outstanding channel requests, which
6958 * means the channel is in final wind-up. But we haven't sent
6959 * CLOSE, so let's do so now.
6961 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
6962 ssh2_pkt_adduint32(pktout, c->remoteid);
6963 ssh2_pkt_send(ssh, pktout);
6964 c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
6967 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
6968 assert(c->v.v2.chanreq_head == NULL);
6970 * We have both sent and received CLOSE, which means we're
6971 * completely done with the channel.
6973 ssh_channel_destroy(c);
6977 static void ssh2_channel_got_eof(struct ssh_channel *c)
6979 if (c->closes & CLOSES_RCVD_EOF)
6980 return; /* already seen EOF */
6981 c->closes |= CLOSES_RCVD_EOF;
6983 if (c->type == CHAN_X11) {
6984 x11_send_eof(c->u.x11.s);
6985 } else if (c->type == CHAN_AGENT) {
6986 if (c->u.a.outstanding_requests == 0) {
6987 /* Manufacture an outgoing EOF in response to the incoming one. */
6988 sshfwd_write_eof(c);
6990 } else if (c->type == CHAN_SOCKDATA) {
6991 pfd_send_eof(c->u.pfd.s);
6992 } else if (c->type == CHAN_MAINSESSION) {
6995 if (!ssh->sent_console_eof &&
6996 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
6998 * Either from_backend_eof told us that the front end
6999 * wants us to close the outgoing side of the connection
7000 * as soon as we see EOF from the far end, or else we've
7001 * unilaterally decided to do that because we've allocated
7002 * a remote pty and hence EOF isn't a particularly
7003 * meaningful concept.
7005 sshfwd_write_eof(c);
7007 ssh->sent_console_eof = TRUE;
7010 ssh2_channel_check_close(c);
7013 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
7015 struct ssh_channel *c;
7017 c = ssh2_channel_msg(ssh, pktin);
7020 ssh2_channel_got_eof(c);
7023 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
7025 struct ssh_channel *c;
7027 c = ssh2_channel_msg(ssh, pktin);
7032 * When we receive CLOSE on a channel, we assume it comes with an
7033 * implied EOF if we haven't seen EOF yet.
7035 ssh2_channel_got_eof(c);
7038 * And we also send an outgoing EOF, if we haven't already, on the
7039 * assumption that CLOSE is a pretty forceful announcement that
7040 * the remote side is doing away with the entire channel. (If it
7041 * had wanted to send us EOF and continue receiving data from us,
7042 * it would have just sent CHANNEL_EOF.)
7044 if (!(c->closes & CLOSES_SENT_EOF)) {
7046 * Make sure we don't read any more from whatever our local
7047 * data source is for this channel.
7050 case CHAN_MAINSESSION:
7051 ssh->send_ok = 0; /* stop trying to read from stdin */
7054 x11_override_throttle(c->u.x11.s, 1);
7057 pfd_override_throttle(c->u.pfd.s, 1);
7062 * Abandon any buffered data we still wanted to send to this
7063 * channel. Receiving a CHANNEL_CLOSE is an indication that
7064 * the server really wants to get on and _destroy_ this
7065 * channel, and it isn't going to send us any further
7066 * WINDOW_ADJUSTs to permit us to send pending stuff.
7068 bufchain_clear(&c->v.v2.outbuffer);
7071 * Send outgoing EOF.
7073 sshfwd_write_eof(c);
7077 * Now process the actual close.
7079 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
7080 c->closes |= CLOSES_RCVD_CLOSE;
7081 ssh2_channel_check_close(c);
7085 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
7087 struct ssh_channel *c;
7089 c = ssh2_channel_msg(ssh, pktin);
7092 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
7093 c->remoteid = ssh_pkt_getuint32(pktin);
7094 c->halfopen = FALSE;
7095 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
7096 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
7098 if (c->type == CHAN_SOCKDATA_DORMANT) {
7099 c->type = CHAN_SOCKDATA;
7101 pfd_confirm(c->u.pfd.s);
7102 } else if (c->type == CHAN_ZOMBIE) {
7104 * This case can occur if a local socket error occurred
7105 * between us sending out CHANNEL_OPEN and receiving
7106 * OPEN_CONFIRMATION. In this case, all we can do is
7107 * immediately initiate close proceedings now that we know the
7108 * server's id to put in the close message.
7110 ssh2_channel_check_close(c);
7113 * We never expect to receive OPEN_CONFIRMATION for any
7114 * *other* channel type (since only local-to-remote port
7115 * forwardings cause us to send CHANNEL_OPEN after the main
7116 * channel is live - all other auxiliary channel types are
7117 * initiated from the server end). It's safe to enforce this
7118 * by assertion rather than by ssh_disconnect, because the
7119 * real point is that we never constructed a half-open channel
7120 * structure in the first place with any type other than the
7123 assert(!"Funny channel type in ssh2_msg_channel_open_confirmation");
7127 ssh_channel_try_eof(c); /* in case we had a pending EOF */
7130 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
7132 static const char *const reasons[] = {
7133 "<unknown reason code>",
7134 "Administratively prohibited",
7136 "Unknown channel type",
7137 "Resource shortage",
7139 unsigned reason_code;
7140 char *reason_string;
7142 struct ssh_channel *c;
7144 c = ssh2_channel_msg(ssh, pktin);
7147 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
7149 if (c->type == CHAN_SOCKDATA_DORMANT) {
7150 reason_code = ssh_pkt_getuint32(pktin);
7151 if (reason_code >= lenof(reasons))
7152 reason_code = 0; /* ensure reasons[reason_code] in range */
7153 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
7154 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
7155 reasons[reason_code], reason_length, reason_string);
7157 pfd_close(c->u.pfd.s);
7158 } else if (c->type == CHAN_ZOMBIE) {
7160 * This case can occur if a local socket error occurred
7161 * between us sending out CHANNEL_OPEN and receiving
7162 * OPEN_FAILURE. In this case, we need do nothing except allow
7163 * the code below to throw the half-open channel away.
7167 * We never expect to receive OPEN_FAILURE for any *other*
7168 * channel type (since only local-to-remote port forwardings
7169 * cause us to send CHANNEL_OPEN after the main channel is
7170 * live - all other auxiliary channel types are initiated from
7171 * the server end). It's safe to enforce this by assertion
7172 * rather than by ssh_disconnect, because the real point is
7173 * that we never constructed a half-open channel structure in
7174 * the first place with any type other than the above.
7176 assert(!"Funny channel type in ssh2_msg_channel_open_failure");
7179 del234(ssh->channels, c);
7183 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
7186 int typelen, want_reply;
7187 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
7188 struct ssh_channel *c;
7189 struct Packet *pktout;
7191 c = ssh2_channel_msg(ssh, pktin);
7194 ssh_pkt_getstring(pktin, &type, &typelen);
7195 want_reply = ssh2_pkt_getbool(pktin);
7198 * Having got the channel number, we now look at
7199 * the request type string to see if it's something
7202 if (c == ssh->mainchan) {
7204 * We recognise "exit-status" and "exit-signal" on
7205 * the primary channel.
7207 if (typelen == 11 &&
7208 !memcmp(type, "exit-status", 11)) {
7210 ssh->exitcode = ssh_pkt_getuint32(pktin);
7211 logeventf(ssh, "Server sent command exit status %d",
7213 reply = SSH2_MSG_CHANNEL_SUCCESS;
7215 } else if (typelen == 11 &&
7216 !memcmp(type, "exit-signal", 11)) {
7218 int is_plausible = TRUE, is_int = FALSE;
7219 char *fmt_sig = "", *fmt_msg = "";
7221 int msglen = 0, core = FALSE;
7222 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
7223 * provide an `int' for the signal, despite its
7224 * having been a `string' in the drafts of RFC 4254 since at
7225 * least 2001. (Fixed in session.c 1.147.) Try to
7226 * infer which we can safely parse it as. */
7228 unsigned char *p = pktin->body +
7230 long len = pktin->length - pktin->savedpos;
7231 unsigned long num = GET_32BIT(p); /* what is it? */
7232 /* If it's 0, it hardly matters; assume string */
7236 int maybe_int = FALSE, maybe_str = FALSE;
7237 #define CHECK_HYPOTHESIS(offset, result) \
7240 int q = toint(offset); \
7241 if (q >= 0 && q+4 <= len) { \
7242 q = toint(q + 4 + GET_32BIT(p+q)); \
7243 if (q >= 0 && q+4 <= len && \
7244 ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
7249 CHECK_HYPOTHESIS(4+1, maybe_int);
7250 CHECK_HYPOTHESIS(4+num+1, maybe_str);
7251 #undef CHECK_HYPOTHESIS
7252 if (maybe_int && !maybe_str)
7254 else if (!maybe_int && maybe_str)
7257 /* Crikey. Either or neither. Panic. */
7258 is_plausible = FALSE;
7261 ssh->exitcode = 128; /* means `unknown signal' */
7264 /* Old non-standard OpenSSH. */
7265 int signum = ssh_pkt_getuint32(pktin);
7266 fmt_sig = dupprintf(" %d", signum);
7267 ssh->exitcode = 128 + signum;
7269 /* As per RFC 4254. */
7272 ssh_pkt_getstring(pktin, &sig, &siglen);
7273 /* Signal name isn't supposed to be blank, but
7274 * let's cope gracefully if it is. */
7276 fmt_sig = dupprintf(" \"%.*s\"",
7281 * Really hideous method of translating the
7282 * signal description back into a locally
7283 * meaningful number.
7288 #define TRANSLATE_SIGNAL(s) \
7289 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
7290 ssh->exitcode = 128 + SIG ## s
7292 TRANSLATE_SIGNAL(ABRT);
7295 TRANSLATE_SIGNAL(ALRM);
7298 TRANSLATE_SIGNAL(FPE);
7301 TRANSLATE_SIGNAL(HUP);
7304 TRANSLATE_SIGNAL(ILL);
7307 TRANSLATE_SIGNAL(INT);
7310 TRANSLATE_SIGNAL(KILL);
7313 TRANSLATE_SIGNAL(PIPE);
7316 TRANSLATE_SIGNAL(QUIT);
7319 TRANSLATE_SIGNAL(SEGV);
7322 TRANSLATE_SIGNAL(TERM);
7325 TRANSLATE_SIGNAL(USR1);
7328 TRANSLATE_SIGNAL(USR2);
7330 #undef TRANSLATE_SIGNAL
7332 ssh->exitcode = 128;
7334 core = ssh2_pkt_getbool(pktin);
7335 ssh_pkt_getstring(pktin, &msg, &msglen);
7337 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
7339 /* ignore lang tag */
7340 } /* else don't attempt to parse */
7341 logeventf(ssh, "Server exited on signal%s%s%s",
7342 fmt_sig, core ? " (core dumped)" : "",
7344 if (*fmt_sig) sfree(fmt_sig);
7345 if (*fmt_msg) sfree(fmt_msg);
7346 reply = SSH2_MSG_CHANNEL_SUCCESS;
7351 * This is a channel request we don't know
7352 * about, so we now either ignore the request
7353 * or respond with CHANNEL_FAILURE, depending
7356 reply = SSH2_MSG_CHANNEL_FAILURE;
7359 pktout = ssh2_pkt_init(reply);
7360 ssh2_pkt_adduint32(pktout, c->remoteid);
7361 ssh2_pkt_send(ssh, pktout);
7365 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
7368 int typelen, want_reply;
7369 struct Packet *pktout;
7371 ssh_pkt_getstring(pktin, &type, &typelen);
7372 want_reply = ssh2_pkt_getbool(pktin);
7375 * We currently don't support any global requests
7376 * at all, so we either ignore the request or
7377 * respond with REQUEST_FAILURE, depending on
7381 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
7382 ssh2_pkt_send(ssh, pktout);
7386 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
7394 struct ssh_channel *c;
7395 unsigned remid, winsize, pktsize;
7396 struct Packet *pktout;
7398 ssh_pkt_getstring(pktin, &type, &typelen);
7399 c = snew(struct ssh_channel);
7402 remid = ssh_pkt_getuint32(pktin);
7403 winsize = ssh_pkt_getuint32(pktin);
7404 pktsize = ssh_pkt_getuint32(pktin);
7406 if (typelen == 3 && !memcmp(type, "x11", 3)) {
7410 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
7411 addrstr = snewn(peeraddrlen+1, char);
7412 memcpy(addrstr, peeraddr, peeraddrlen);
7413 addrstr[peeraddrlen] = '\0';
7414 peerport = ssh_pkt_getuint32(pktin);
7416 logeventf(ssh, "Received X11 connect request from %s:%d",
7419 if (!ssh->X11_fwd_enabled)
7420 error = "X11 forwarding is not enabled";
7421 else if ((x11err = x11_init(&c->u.x11.s, ssh->x11disp, c,
7422 addrstr, peerport, ssh->conf)) != NULL) {
7423 logeventf(ssh, "Local X11 connection failed: %s", x11err);
7424 error = "Unable to open an X11 connection";
7426 logevent("Opening X11 forward connection succeeded");
7431 } else if (typelen == 15 &&
7432 !memcmp(type, "forwarded-tcpip", 15)) {
7433 struct ssh_rportfwd pf, *realpf;
7436 ssh_pkt_getstring(pktin, &shost, &shostlen);/* skip address */
7437 pf.shost = dupprintf("%.*s", shostlen, shost);
7438 pf.sport = ssh_pkt_getuint32(pktin);
7439 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
7440 peerport = ssh_pkt_getuint32(pktin);
7441 realpf = find234(ssh->rportfwds, &pf, NULL);
7442 logeventf(ssh, "Received remote port %s:%d open request "
7443 "from %s:%d", pf.shost, pf.sport, peeraddr, peerport);
7446 if (realpf == NULL) {
7447 error = "Remote port is not recognised";
7449 const char *e = pfd_newconnect(&c->u.pfd.s,
7453 realpf->pfrec->addressfamily);
7454 logeventf(ssh, "Attempting to forward remote port to "
7455 "%s:%d", realpf->dhost, realpf->dport);
7457 logeventf(ssh, "Port open failed: %s", e);
7458 error = "Port open failed";
7460 logevent("Forwarded port opened successfully");
7461 c->type = CHAN_SOCKDATA;
7464 } else if (typelen == 22 &&
7465 !memcmp(type, "auth-agent@openssh.com", 22)) {
7466 if (!ssh->agentfwd_enabled)
7467 error = "Agent forwarding is not enabled";
7469 c->type = CHAN_AGENT; /* identify channel type */
7470 c->u.a.lensofar = 0;
7471 c->u.a.message = NULL;
7472 c->u.a.outstanding_requests = 0;
7475 error = "Unsupported channel type requested";
7478 c->remoteid = remid;
7479 c->halfopen = FALSE;
7481 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
7482 ssh2_pkt_adduint32(pktout, c->remoteid);
7483 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
7484 ssh2_pkt_addstring(pktout, error);
7485 ssh2_pkt_addstring(pktout, "en"); /* language tag */
7486 ssh2_pkt_send(ssh, pktout);
7487 logeventf(ssh, "Rejected channel open: %s", error);
7490 ssh2_channel_init(c);
7491 c->v.v2.remwindow = winsize;
7492 c->v.v2.remmaxpkt = pktsize;
7493 add234(ssh->channels, c);
7494 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
7495 ssh2_pkt_adduint32(pktout, c->remoteid);
7496 ssh2_pkt_adduint32(pktout, c->localid);
7497 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
7498 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7499 ssh2_pkt_send(ssh, pktout);
7504 * Buffer banner messages for later display at some convenient point,
7505 * if we're going to display them.
7507 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
7509 /* Arbitrary limit to prevent unbounded inflation of buffer */
7510 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
7511 bufchain_size(&ssh->banner) <= 131072) {
7512 char *banner = NULL;
7514 ssh_pkt_getstring(pktin, &banner, &size);
7516 bufchain_add(&ssh->banner, banner, size);
7520 /* Helper function to deal with sending tty modes for "pty-req" */
7521 static void ssh2_send_ttymode(void *data, char *mode, char *val)
7523 struct Packet *pktout = (struct Packet *)data;
7525 unsigned int arg = 0;
7526 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
7527 if (i == lenof(ssh_ttymodes)) return;
7528 switch (ssh_ttymodes[i].type) {
7530 arg = ssh_tty_parse_specchar(val);
7533 arg = ssh_tty_parse_boolean(val);
7536 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
7537 ssh2_pkt_adduint32(pktout, arg);
7540 static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
7543 struct ssh2_setup_x11_state {
7547 struct Packet *pktout;
7548 crStateP(ssh2_setup_x11_state, ctx);
7552 logevent("Requesting X11 forwarding");
7553 pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
7555 ssh2_pkt_addbool(pktout, 0); /* many connections */
7556 ssh2_pkt_addstring(pktout, ssh->x11disp->remoteauthprotoname);
7558 * Note that while we blank the X authentication data here, we don't
7559 * take any special action to blank the start of an X11 channel,
7560 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
7561 * without having session blanking enabled is likely to leak your
7562 * cookie into the log.
7564 dont_log_password(ssh, pktout, PKTLOG_BLANK);
7565 ssh2_pkt_addstring(pktout, ssh->x11disp->remoteauthdatastring);
7566 end_log_omission(ssh, pktout);
7567 ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
7568 ssh2_pkt_send(ssh, pktout);
7570 /* Wait to be called back with either a response packet, or NULL
7571 * meaning clean up and free our data */
7575 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
7576 logevent("X11 forwarding enabled");
7577 ssh->X11_fwd_enabled = TRUE;
7579 logevent("X11 forwarding refused");
7585 static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
7588 struct ssh2_setup_agent_state {
7592 struct Packet *pktout;
7593 crStateP(ssh2_setup_agent_state, ctx);
7597 logevent("Requesting OpenSSH-style agent forwarding");
7598 pktout = ssh2_chanreq_init(ssh->mainchan, "auth-agent-req@openssh.com",
7599 ssh2_setup_agent, s);
7600 ssh2_pkt_send(ssh, pktout);
7602 /* Wait to be called back with either a response packet, or NULL
7603 * meaning clean up and free our data */
7607 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
7608 logevent("Agent forwarding enabled");
7609 ssh->agentfwd_enabled = TRUE;
7611 logevent("Agent forwarding refused");
7617 static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
7620 struct ssh2_setup_pty_state {
7624 struct Packet *pktout;
7625 crStateP(ssh2_setup_pty_state, ctx);
7629 /* Unpick the terminal-speed string. */
7630 /* XXX perhaps we should allow no speeds to be sent. */
7631 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
7632 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
7633 /* Build the pty request. */
7634 pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
7636 ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
7637 ssh2_pkt_adduint32(pktout, ssh->term_width);
7638 ssh2_pkt_adduint32(pktout, ssh->term_height);
7639 ssh2_pkt_adduint32(pktout, 0); /* pixel width */
7640 ssh2_pkt_adduint32(pktout, 0); /* pixel height */
7641 ssh2_pkt_addstring_start(pktout);
7642 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
7643 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
7644 ssh2_pkt_adduint32(pktout, ssh->ispeed);
7645 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
7646 ssh2_pkt_adduint32(pktout, ssh->ospeed);
7647 ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
7648 ssh2_pkt_send(ssh, pktout);
7649 ssh->state = SSH_STATE_INTERMED;
7651 /* Wait to be called back with either a response packet, or NULL
7652 * meaning clean up and free our data */
7656 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
7657 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
7658 ssh->ospeed, ssh->ispeed);
7659 ssh->got_pty = TRUE;
7661 c_write_str(ssh, "Server refused to allocate pty\r\n");
7662 ssh->editing = ssh->echoing = 1;
7669 static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
7672 struct ssh2_setup_env_state {
7674 int num_env, env_left, env_ok;
7677 struct Packet *pktout;
7678 crStateP(ssh2_setup_env_state, ctx);
7683 * Send environment variables.
7685 * Simplest thing here is to send all the requests at once, and
7686 * then wait for a whole bunch of successes or failures.
7692 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
7694 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
7695 pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
7696 ssh2_pkt_addstring(pktout, key);
7697 ssh2_pkt_addstring(pktout, val);
7698 ssh2_pkt_send(ssh, pktout);
7703 logeventf(ssh, "Sent %d environment variables", s->num_env);
7708 s->env_left = s->num_env;
7710 while (s->env_left > 0) {
7711 /* Wait to be called back with either a response packet,
7712 * or NULL meaning clean up and free our data */
7714 if (!pktin) goto out;
7715 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
7720 if (s->env_ok == s->num_env) {
7721 logevent("All environment variables successfully set");
7722 } else if (s->env_ok == 0) {
7723 logevent("All environment variables refused");
7724 c_write_str(ssh, "Server refused to set environment variables\r\n");
7726 logeventf(ssh, "%d environment variables refused",
7727 s->num_env - s->env_ok);
7728 c_write_str(ssh, "Server refused to set all environment variables\r\n");
7736 * Handle the SSH-2 userauth and connection layers.
7738 static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
7740 do_ssh2_authconn(ssh, NULL, 0, pktin);
7743 static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
7746 do_ssh2_authconn(c->ssh, NULL, 0, pktin);
7749 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
7750 struct Packet *pktin)
7752 struct do_ssh2_authconn_state {
7756 AUTH_TYPE_PUBLICKEY,
7757 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
7758 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
7760 AUTH_TYPE_GSSAPI, /* always QUIET */
7761 AUTH_TYPE_KEYBOARD_INTERACTIVE,
7762 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
7764 int done_service_req;
7765 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
7766 int tried_pubkey_config, done_agent;
7771 int kbd_inter_refused;
7772 int we_are_in, userauth_success;
7773 prompts_t *cur_prompt;
7778 void *publickey_blob;
7779 int publickey_bloblen;
7780 int publickey_encrypted;
7781 char *publickey_algorithm;
7782 char *publickey_comment;
7783 unsigned char agent_request[5], *agent_response, *agentp;
7784 int agent_responselen;
7785 unsigned char *pkblob_in_agent;
7787 char *pkblob, *alg, *commentp;
7788 int pklen, alglen, commentlen;
7789 int siglen, retlen, len;
7790 char *q, *agentreq, *ret;
7792 struct Packet *pktout;
7795 struct ssh_gss_library *gsslib;
7796 Ssh_gss_ctx gss_ctx;
7797 Ssh_gss_buf gss_buf;
7798 Ssh_gss_buf gss_rcvtok, gss_sndtok;
7799 Ssh_gss_name gss_srv_name;
7800 Ssh_gss_stat gss_stat;
7803 crState(do_ssh2_authconn_state);
7807 /* Register as a handler for all the messages this coroutine handles. */
7808 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
7809 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
7810 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
7811 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
7812 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
7813 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
7814 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
7815 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
7816 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
7817 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
7818 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
7819 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
7820 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
7821 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
7822 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
7823 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
7824 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
7825 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
7826 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
7827 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
7829 s->done_service_req = FALSE;
7830 s->we_are_in = s->userauth_success = FALSE;
7832 s->tried_gssapi = FALSE;
7835 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
7837 * Request userauth protocol, and await a response to it.
7839 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7840 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
7841 ssh2_pkt_send(ssh, s->pktout);
7842 crWaitUntilV(pktin);
7843 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
7844 s->done_service_req = TRUE;
7846 if (!s->done_service_req) {
7848 * Request connection protocol directly, without authentication.
7850 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7851 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7852 ssh2_pkt_send(ssh, s->pktout);
7853 crWaitUntilV(pktin);
7854 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
7855 s->we_are_in = TRUE; /* no auth required */
7857 bombout(("Server refused service request"));
7862 /* Arrange to be able to deal with any BANNERs that come in.
7863 * (We do this now as packets may come in during the next bit.) */
7864 bufchain_init(&ssh->banner);
7865 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
7866 ssh2_msg_userauth_banner;
7869 * Misc one-time setup for authentication.
7871 s->publickey_blob = NULL;
7872 if (!s->we_are_in) {
7875 * Load the public half of any configured public key file
7878 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
7879 if (!filename_is_null(s->keyfile)) {
7881 logeventf(ssh, "Reading private key file \"%.150s\"",
7882 filename_to_str(s->keyfile));
7883 keytype = key_type(s->keyfile);
7884 if (keytype == SSH_KEYTYPE_SSH2) {
7887 ssh2_userkey_loadpub(s->keyfile,
7888 &s->publickey_algorithm,
7889 &s->publickey_bloblen,
7890 &s->publickey_comment, &error);
7891 if (s->publickey_blob) {
7892 s->publickey_encrypted =
7893 ssh2_userkey_encrypted(s->keyfile, NULL);
7896 logeventf(ssh, "Unable to load private key (%s)",
7898 msgbuf = dupprintf("Unable to load private key file "
7899 "\"%.150s\" (%s)\r\n",
7900 filename_to_str(s->keyfile),
7902 c_write_str(ssh, msgbuf);
7907 logeventf(ssh, "Unable to use this key file (%s)",
7908 key_type_to_str(keytype));
7909 msgbuf = dupprintf("Unable to use key file \"%.150s\""
7911 filename_to_str(s->keyfile),
7912 key_type_to_str(keytype));
7913 c_write_str(ssh, msgbuf);
7915 s->publickey_blob = NULL;
7920 * Find out about any keys Pageant has (but if there's a
7921 * public key configured, filter out all others).
7924 s->agent_response = NULL;
7925 s->pkblob_in_agent = NULL;
7926 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
7930 logevent("Pageant is running. Requesting keys.");
7932 /* Request the keys held by the agent. */
7933 PUT_32BIT(s->agent_request, 1);
7934 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
7935 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
7936 ssh_agent_callback, ssh)) {
7940 bombout(("Unexpected data from server while"
7941 " waiting for agent response"));
7944 } while (pktin || inlen > 0);
7945 r = ssh->agent_response;
7946 s->agent_responselen = ssh->agent_response_len;
7948 s->agent_response = (unsigned char *) r;
7949 if (s->agent_response && s->agent_responselen >= 5 &&
7950 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
7953 p = s->agent_response + 5;
7954 s->nkeys = toint(GET_32BIT(p));
7957 * Vet the Pageant response to ensure that the key
7958 * count and blob lengths make sense.
7961 logeventf(ssh, "Pageant response contained a negative"
7962 " key count %d", s->nkeys);
7964 goto done_agent_query;
7966 unsigned char *q = p + 4;
7967 int lenleft = s->agent_responselen - 5 - 4;
7969 for (keyi = 0; keyi < s->nkeys; keyi++) {
7970 int bloblen, commentlen;
7972 logeventf(ssh, "Pageant response was truncated");
7974 goto done_agent_query;
7976 bloblen = toint(GET_32BIT(q));
7977 if (bloblen < 0 || bloblen > lenleft) {
7978 logeventf(ssh, "Pageant response was truncated");
7980 goto done_agent_query;
7982 lenleft -= 4 + bloblen;
7984 commentlen = toint(GET_32BIT(q));
7985 if (commentlen < 0 || commentlen > lenleft) {
7986 logeventf(ssh, "Pageant response was truncated");
7988 goto done_agent_query;
7990 lenleft -= 4 + commentlen;
7991 q += 4 + commentlen;
7996 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
7997 if (s->publickey_blob) {
7998 /* See if configured key is in agent. */
7999 for (keyi = 0; keyi < s->nkeys; keyi++) {
8000 s->pklen = toint(GET_32BIT(p));
8001 if (s->pklen == s->publickey_bloblen &&
8002 !memcmp(p+4, s->publickey_blob,
8003 s->publickey_bloblen)) {
8004 logeventf(ssh, "Pageant key #%d matches "
8005 "configured key file", keyi);
8007 s->pkblob_in_agent = p;
8011 p += toint(GET_32BIT(p)) + 4; /* comment */
8013 if (!s->pkblob_in_agent) {
8014 logevent("Configured key file not in Pageant");
8019 logevent("Failed to get reply from Pageant");
8027 * We repeat this whole loop, including the username prompt,
8028 * until we manage a successful authentication. If the user
8029 * types the wrong _password_, they can be sent back to the
8030 * beginning to try another username, if this is configured on.
8031 * (If they specify a username in the config, they are never
8032 * asked, even if they do give a wrong password.)
8034 * I think this best serves the needs of
8036 * - the people who have no configuration, no keys, and just
8037 * want to try repeated (username,password) pairs until they
8038 * type both correctly
8040 * - people who have keys and configuration but occasionally
8041 * need to fall back to passwords
8043 * - people with a key held in Pageant, who might not have
8044 * logged in to a particular machine before; so they want to
8045 * type a username, and then _either_ their key will be
8046 * accepted, _or_ they will type a password. If they mistype
8047 * the username they will want to be able to get back and
8050 s->got_username = FALSE;
8051 while (!s->we_are_in) {
8055 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
8057 * We got a username last time round this loop, and
8058 * with change_username turned off we don't try to get
8061 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
8062 int ret; /* need not be kept over crReturn */
8063 s->cur_prompt = new_prompts(ssh->frontend);
8064 s->cur_prompt->to_server = TRUE;
8065 s->cur_prompt->name = dupstr("SSH login name");
8066 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
8067 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8070 crWaitUntilV(!pktin);
8071 ret = get_userpass_input(s->cur_prompt, in, inlen);
8076 * get_userpass_input() failed to get a username.
8079 free_prompts(s->cur_prompt);
8080 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
8083 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
8084 free_prompts(s->cur_prompt);
8087 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
8088 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
8089 c_write_str(ssh, stuff);
8093 s->got_username = TRUE;
8096 * Send an authentication request using method "none": (a)
8097 * just in case it succeeds, and (b) so that we know what
8098 * authentication methods we can usefully try next.
8100 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
8102 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8103 ssh2_pkt_addstring(s->pktout, ssh->username);
8104 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
8105 ssh2_pkt_addstring(s->pktout, "none"); /* method */
8106 ssh2_pkt_send(ssh, s->pktout);
8107 s->type = AUTH_TYPE_NONE;
8109 s->we_are_in = FALSE;
8111 s->tried_pubkey_config = FALSE;
8112 s->kbd_inter_refused = FALSE;
8114 /* Reset agent request state. */
8115 s->done_agent = FALSE;
8116 if (s->agent_response) {
8117 if (s->pkblob_in_agent) {
8118 s->agentp = s->pkblob_in_agent;
8120 s->agentp = s->agent_response + 5 + 4;
8126 char *methods = NULL;
8130 * Wait for the result of the last authentication request.
8133 crWaitUntilV(pktin);
8135 * Now is a convenient point to spew any banner material
8136 * that we've accumulated. (This should ensure that when
8137 * we exit the auth loop, we haven't any left to deal
8141 int size = bufchain_size(&ssh->banner);
8143 * Don't show the banner if we're operating in
8144 * non-verbose non-interactive mode. (It's probably
8145 * a script, which means nobody will read the
8146 * banner _anyway_, and moreover the printing of
8147 * the banner will screw up processing on the
8148 * output of (say) plink.)
8150 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
8151 char *banner = snewn(size, char);
8152 bufchain_fetch(&ssh->banner, banner, size);
8153 c_write_untrusted(ssh, banner, size);
8156 bufchain_clear(&ssh->banner);
8158 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
8159 logevent("Access granted");
8160 s->we_are_in = s->userauth_success = TRUE;
8164 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
8165 bombout(("Strange packet received during authentication: "
8166 "type %d", pktin->type));
8173 * OK, we're now sitting on a USERAUTH_FAILURE message, so
8174 * we can look at the string in it and know what we can
8175 * helpfully try next.
8177 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
8178 ssh_pkt_getstring(pktin, &methods, &methlen);
8179 if (!ssh2_pkt_getbool(pktin)) {
8181 * We have received an unequivocal Access
8182 * Denied. This can translate to a variety of
8183 * messages, or no message at all.
8185 * For forms of authentication which are attempted
8186 * implicitly, by which I mean without printing
8187 * anything in the window indicating that we're
8188 * trying them, we should never print 'Access
8191 * If we do print a message saying that we're
8192 * attempting some kind of authentication, it's OK
8193 * to print a followup message saying it failed -
8194 * but the message may sometimes be more specific
8195 * than simply 'Access denied'.
8197 * Additionally, if we'd just tried password
8198 * authentication, we should break out of this
8199 * whole loop so as to go back to the username
8200 * prompt (iff we're configured to allow
8201 * username change attempts).
8203 if (s->type == AUTH_TYPE_NONE) {
8205 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
8206 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
8207 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
8208 c_write_str(ssh, "Server refused our key\r\n");
8209 logevent("Server refused our key");
8210 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
8211 /* This _shouldn't_ happen except by a
8212 * protocol bug causing client and server to
8213 * disagree on what is a correct signature. */
8214 c_write_str(ssh, "Server refused public-key signature"
8215 " despite accepting key!\r\n");
8216 logevent("Server refused public-key signature"
8217 " despite accepting key!");
8218 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
8219 /* quiet, so no c_write */
8220 logevent("Server refused keyboard-interactive authentication");
8221 } else if (s->type==AUTH_TYPE_GSSAPI) {
8222 /* always quiet, so no c_write */
8223 /* also, the code down in the GSSAPI block has
8224 * already logged this in the Event Log */
8225 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
8226 logevent("Keyboard-interactive authentication failed");
8227 c_write_str(ssh, "Access denied\r\n");
8229 assert(s->type == AUTH_TYPE_PASSWORD);
8230 logevent("Password authentication failed");
8231 c_write_str(ssh, "Access denied\r\n");
8233 if (conf_get_int(ssh->conf, CONF_change_username)) {
8234 /* XXX perhaps we should allow
8235 * keyboard-interactive to do this too? */
8236 s->we_are_in = FALSE;
8241 c_write_str(ssh, "Further authentication required\r\n");
8242 logevent("Further authentication required");
8246 in_commasep_string("publickey", methods, methlen);
8248 in_commasep_string("password", methods, methlen);
8249 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
8250 in_commasep_string("keyboard-interactive", methods, methlen);
8253 ssh->gsslibs = ssh_gss_setup(ssh->conf);
8254 s->can_gssapi = conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
8255 in_commasep_string("gssapi-with-mic", methods, methlen) &&
8256 ssh->gsslibs->nlibraries > 0;
8260 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
8262 if (s->can_pubkey && !s->done_agent && s->nkeys) {
8265 * Attempt public-key authentication using a key from Pageant.
8268 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
8270 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
8272 /* Unpack key from agent response */
8273 s->pklen = toint(GET_32BIT(s->agentp));
8275 s->pkblob = (char *)s->agentp;
8276 s->agentp += s->pklen;
8277 s->alglen = toint(GET_32BIT(s->pkblob));
8278 s->alg = s->pkblob + 4;
8279 s->commentlen = toint(GET_32BIT(s->agentp));
8281 s->commentp = (char *)s->agentp;
8282 s->agentp += s->commentlen;
8283 /* s->agentp now points at next key, if any */
8285 /* See if server will accept it */
8286 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8287 ssh2_pkt_addstring(s->pktout, ssh->username);
8288 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8289 /* service requested */
8290 ssh2_pkt_addstring(s->pktout, "publickey");
8292 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
8293 ssh2_pkt_addstring_start(s->pktout);
8294 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
8295 ssh2_pkt_addstring_start(s->pktout);
8296 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
8297 ssh2_pkt_send(ssh, s->pktout);
8298 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
8300 crWaitUntilV(pktin);
8301 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
8303 /* Offer of key refused. */
8310 if (flags & FLAG_VERBOSE) {
8311 c_write_str(ssh, "Authenticating with "
8313 c_write(ssh, s->commentp, s->commentlen);
8314 c_write_str(ssh, "\" from agent\r\n");
8318 * Server is willing to accept the key.
8319 * Construct a SIGN_REQUEST.
8321 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8322 ssh2_pkt_addstring(s->pktout, ssh->username);
8323 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8324 /* service requested */
8325 ssh2_pkt_addstring(s->pktout, "publickey");
8327 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
8328 ssh2_pkt_addstring_start(s->pktout);
8329 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
8330 ssh2_pkt_addstring_start(s->pktout);
8331 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
8333 /* Ask agent for signature. */
8334 s->siglen = s->pktout->length - 5 + 4 +
8335 ssh->v2_session_id_len;
8336 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
8338 s->len = 1; /* message type */
8339 s->len += 4 + s->pklen; /* key blob */
8340 s->len += 4 + s->siglen; /* data to sign */
8341 s->len += 4; /* flags */
8342 s->agentreq = snewn(4 + s->len, char);
8343 PUT_32BIT(s->agentreq, s->len);
8344 s->q = s->agentreq + 4;
8345 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
8346 PUT_32BIT(s->q, s->pklen);
8348 memcpy(s->q, s->pkblob, s->pklen);
8350 PUT_32BIT(s->q, s->siglen);
8352 /* Now the data to be signed... */
8353 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
8354 PUT_32BIT(s->q, ssh->v2_session_id_len);
8357 memcpy(s->q, ssh->v2_session_id,
8358 ssh->v2_session_id_len);
8359 s->q += ssh->v2_session_id_len;
8360 memcpy(s->q, s->pktout->data + 5,
8361 s->pktout->length - 5);
8362 s->q += s->pktout->length - 5;
8363 /* And finally the (zero) flags word. */
8365 if (!agent_query(s->agentreq, s->len + 4,
8367 ssh_agent_callback, ssh)) {
8371 bombout(("Unexpected data from server"
8372 " while waiting for agent"
8376 } while (pktin || inlen > 0);
8377 vret = ssh->agent_response;
8378 s->retlen = ssh->agent_response_len;
8383 if (s->retlen >= 9 &&
8384 s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
8385 GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
8386 logevent("Sending Pageant's response");
8387 ssh2_add_sigblob(ssh, s->pktout,
8388 s->pkblob, s->pklen,
8390 GET_32BIT(s->ret + 5));
8391 ssh2_pkt_send(ssh, s->pktout);
8392 s->type = AUTH_TYPE_PUBLICKEY;
8394 /* FIXME: less drastic response */
8395 bombout(("Pageant failed to answer challenge"));
8401 /* Do we have any keys left to try? */
8402 if (s->pkblob_in_agent) {
8403 s->done_agent = TRUE;
8404 s->tried_pubkey_config = TRUE;
8407 if (s->keyi >= s->nkeys)
8408 s->done_agent = TRUE;
8411 } else if (s->can_pubkey && s->publickey_blob &&
8412 !s->tried_pubkey_config) {
8414 struct ssh2_userkey *key; /* not live over crReturn */
8415 char *passphrase; /* not live over crReturn */
8417 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
8419 s->tried_pubkey_config = TRUE;
8422 * Try the public key supplied in the configuration.
8424 * First, offer the public blob to see if the server is
8425 * willing to accept it.
8427 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8428 ssh2_pkt_addstring(s->pktout, ssh->username);
8429 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8430 /* service requested */
8431 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
8432 ssh2_pkt_addbool(s->pktout, FALSE);
8433 /* no signature included */
8434 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
8435 ssh2_pkt_addstring_start(s->pktout);
8436 ssh2_pkt_addstring_data(s->pktout,
8437 (char *)s->publickey_blob,
8438 s->publickey_bloblen);
8439 ssh2_pkt_send(ssh, s->pktout);
8440 logevent("Offered public key");
8442 crWaitUntilV(pktin);
8443 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
8444 /* Key refused. Give up. */
8445 s->gotit = TRUE; /* reconsider message next loop */
8446 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
8447 continue; /* process this new message */
8449 logevent("Offer of public key accepted");
8452 * Actually attempt a serious authentication using
8455 if (flags & FLAG_VERBOSE) {
8456 c_write_str(ssh, "Authenticating with public key \"");
8457 c_write_str(ssh, s->publickey_comment);
8458 c_write_str(ssh, "\"\r\n");
8462 const char *error; /* not live over crReturn */
8463 if (s->publickey_encrypted) {
8465 * Get a passphrase from the user.
8467 int ret; /* need not be kept over crReturn */
8468 s->cur_prompt = new_prompts(ssh->frontend);
8469 s->cur_prompt->to_server = FALSE;
8470 s->cur_prompt->name = dupstr("SSH key passphrase");
8471 add_prompt(s->cur_prompt,
8472 dupprintf("Passphrase for key \"%.100s\": ",
8473 s->publickey_comment),
8475 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8478 crWaitUntilV(!pktin);
8479 ret = get_userpass_input(s->cur_prompt,
8484 /* Failed to get a passphrase. Terminate. */
8485 free_prompts(s->cur_prompt);
8486 ssh_disconnect(ssh, NULL,
8487 "Unable to authenticate",
8488 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8493 dupstr(s->cur_prompt->prompts[0]->result);
8494 free_prompts(s->cur_prompt);
8496 passphrase = NULL; /* no passphrase needed */
8500 * Try decrypting the key.
8502 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
8503 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
8505 /* burn the evidence */
8506 smemclr(passphrase, strlen(passphrase));
8509 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
8511 (key == SSH2_WRONG_PASSPHRASE)) {
8512 c_write_str(ssh, "Wrong passphrase\r\n");
8514 /* and loop again */
8516 c_write_str(ssh, "Unable to load private key (");
8517 c_write_str(ssh, error);
8518 c_write_str(ssh, ")\r\n");
8520 break; /* try something else */
8526 unsigned char *pkblob, *sigblob, *sigdata;
8527 int pkblob_len, sigblob_len, sigdata_len;
8531 * We have loaded the private key and the server
8532 * has announced that it's willing to accept it.
8533 * Hallelujah. Generate a signature and send it.
8535 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8536 ssh2_pkt_addstring(s->pktout, ssh->username);
8537 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8538 /* service requested */
8539 ssh2_pkt_addstring(s->pktout, "publickey");
8541 ssh2_pkt_addbool(s->pktout, TRUE);
8542 /* signature follows */
8543 ssh2_pkt_addstring(s->pktout, key->alg->name);
8544 pkblob = key->alg->public_blob(key->data,
8546 ssh2_pkt_addstring_start(s->pktout);
8547 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
8551 * The data to be signed is:
8555 * followed by everything so far placed in the
8558 sigdata_len = s->pktout->length - 5 + 4 +
8559 ssh->v2_session_id_len;
8560 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
8562 sigdata = snewn(sigdata_len, unsigned char);
8564 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
8565 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
8568 memcpy(sigdata+p, ssh->v2_session_id,
8569 ssh->v2_session_id_len);
8570 p += ssh->v2_session_id_len;
8571 memcpy(sigdata+p, s->pktout->data + 5,
8572 s->pktout->length - 5);
8573 p += s->pktout->length - 5;
8574 assert(p == sigdata_len);
8575 sigblob = key->alg->sign(key->data, (char *)sigdata,
8576 sigdata_len, &sigblob_len);
8577 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
8578 sigblob, sigblob_len);
8583 ssh2_pkt_send(ssh, s->pktout);
8584 logevent("Sent public key signature");
8585 s->type = AUTH_TYPE_PUBLICKEY;
8586 key->alg->freekey(key->data);
8590 } else if (s->can_gssapi && !s->tried_gssapi) {
8592 /* GSSAPI Authentication */
8597 s->type = AUTH_TYPE_GSSAPI;
8598 s->tried_gssapi = TRUE;
8600 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
8603 * Pick the highest GSS library on the preference
8609 for (i = 0; i < ngsslibs; i++) {
8610 int want_id = conf_get_int_int(ssh->conf,
8611 CONF_ssh_gsslist, i);
8612 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
8613 if (ssh->gsslibs->libraries[j].id == want_id) {
8614 s->gsslib = &ssh->gsslibs->libraries[j];
8615 goto got_gsslib; /* double break */
8620 * We always expect to have found something in
8621 * the above loop: we only came here if there
8622 * was at least one viable GSS library, and the
8623 * preference list should always mention
8624 * everything and only change the order.
8629 if (s->gsslib->gsslogmsg)
8630 logevent(s->gsslib->gsslogmsg);
8632 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
8633 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8634 ssh2_pkt_addstring(s->pktout, ssh->username);
8635 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8636 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
8637 logevent("Attempting GSSAPI authentication");
8639 /* add mechanism info */
8640 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
8642 /* number of GSSAPI mechanisms */
8643 ssh2_pkt_adduint32(s->pktout,1);
8645 /* length of OID + 2 */
8646 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
8647 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
8650 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
8652 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
8654 ssh2_pkt_send(ssh, s->pktout);
8655 crWaitUntilV(pktin);
8656 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
8657 logevent("GSSAPI authentication request refused");
8661 /* check returned packet ... */
8663 ssh_pkt_getstring(pktin, &data, &len);
8664 s->gss_rcvtok.value = data;
8665 s->gss_rcvtok.length = len;
8666 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
8667 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
8668 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
8669 memcmp((char *)s->gss_rcvtok.value + 2,
8670 s->gss_buf.value,s->gss_buf.length) ) {
8671 logevent("GSSAPI authentication - wrong response from server");
8675 /* now start running */
8676 s->gss_stat = s->gsslib->import_name(s->gsslib,
8679 if (s->gss_stat != SSH_GSS_OK) {
8680 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
8681 logevent("GSSAPI import name failed - Bad service name");
8683 logevent("GSSAPI import name failed");
8687 /* fetch TGT into GSS engine */
8688 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
8690 if (s->gss_stat != SSH_GSS_OK) {
8691 logevent("GSSAPI authentication failed to get credentials");
8692 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8696 /* initial tokens are empty */
8697 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
8698 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
8700 /* now enter the loop */
8702 s->gss_stat = s->gsslib->init_sec_context
8706 conf_get_int(ssh->conf, CONF_gssapifwd),
8710 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
8711 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
8712 logevent("GSSAPI authentication initialisation failed");
8714 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
8715 &s->gss_buf) == SSH_GSS_OK) {
8716 logevent(s->gss_buf.value);
8717 sfree(s->gss_buf.value);
8722 logevent("GSSAPI authentication initialised");
8724 /* Client and server now exchange tokens until GSSAPI
8725 * no longer says CONTINUE_NEEDED */
8727 if (s->gss_sndtok.length != 0) {
8728 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
8729 ssh_pkt_addstring_start(s->pktout);
8730 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
8731 ssh2_pkt_send(ssh, s->pktout);
8732 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
8735 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
8736 crWaitUntilV(pktin);
8737 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
8738 logevent("GSSAPI authentication - bad server response");
8739 s->gss_stat = SSH_GSS_FAILURE;
8742 ssh_pkt_getstring(pktin, &data, &len);
8743 s->gss_rcvtok.value = data;
8744 s->gss_rcvtok.length = len;
8746 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
8748 if (s->gss_stat != SSH_GSS_OK) {
8749 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8750 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
8753 logevent("GSSAPI authentication loop finished OK");
8755 /* Now send the MIC */
8757 s->pktout = ssh2_pkt_init(0);
8758 micoffset = s->pktout->length;
8759 ssh_pkt_addstring_start(s->pktout);
8760 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
8761 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
8762 ssh_pkt_addstring(s->pktout, ssh->username);
8763 ssh_pkt_addstring(s->pktout, "ssh-connection");
8764 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
8766 s->gss_buf.value = (char *)s->pktout->data + micoffset;
8767 s->gss_buf.length = s->pktout->length - micoffset;
8769 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
8770 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
8771 ssh_pkt_addstring_start(s->pktout);
8772 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
8773 ssh2_pkt_send(ssh, s->pktout);
8774 s->gsslib->free_mic(s->gsslib, &mic);
8778 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8779 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
8782 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
8785 * Keyboard-interactive authentication.
8788 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
8790 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
8792 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8793 ssh2_pkt_addstring(s->pktout, ssh->username);
8794 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8795 /* service requested */
8796 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
8798 ssh2_pkt_addstring(s->pktout, ""); /* lang */
8799 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
8800 ssh2_pkt_send(ssh, s->pktout);
8802 logevent("Attempting keyboard-interactive authentication");
8804 crWaitUntilV(pktin);
8805 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
8806 /* Server is not willing to do keyboard-interactive
8807 * at all (or, bizarrely but legally, accepts the
8808 * user without actually issuing any prompts).
8809 * Give up on it entirely. */
8811 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
8812 s->kbd_inter_refused = TRUE; /* don't try it again */
8817 * Loop while the server continues to send INFO_REQUESTs.
8819 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
8821 char *name, *inst, *lang;
8822 int name_len, inst_len, lang_len;
8826 * We've got a fresh USERAUTH_INFO_REQUEST.
8827 * Get the preamble and start building a prompt.
8829 ssh_pkt_getstring(pktin, &name, &name_len);
8830 ssh_pkt_getstring(pktin, &inst, &inst_len);
8831 ssh_pkt_getstring(pktin, &lang, &lang_len);
8832 s->cur_prompt = new_prompts(ssh->frontend);
8833 s->cur_prompt->to_server = TRUE;
8836 * Get any prompt(s) from the packet.
8838 s->num_prompts = ssh_pkt_getuint32(pktin);
8839 for (i = 0; i < s->num_prompts; i++) {
8843 static char noprompt[] =
8844 "<server failed to send prompt>: ";
8846 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
8847 echo = ssh2_pkt_getbool(pktin);
8850 prompt_len = lenof(noprompt)-1;
8852 add_prompt(s->cur_prompt,
8853 dupprintf("%.*s", prompt_len, prompt),
8858 /* FIXME: better prefix to distinguish from
8860 s->cur_prompt->name =
8861 dupprintf("SSH server: %.*s", name_len, name);
8862 s->cur_prompt->name_reqd = TRUE;
8864 s->cur_prompt->name =
8865 dupstr("SSH server authentication");
8866 s->cur_prompt->name_reqd = FALSE;
8868 /* We add a prefix to try to make it clear that a prompt
8869 * has come from the server.
8870 * FIXME: ugly to print "Using..." in prompt _every_
8871 * time round. Can this be done more subtly? */
8872 /* Special case: for reasons best known to themselves,
8873 * some servers send k-i requests with no prompts and
8874 * nothing to display. Keep quiet in this case. */
8875 if (s->num_prompts || name_len || inst_len) {
8876 s->cur_prompt->instruction =
8877 dupprintf("Using keyboard-interactive authentication.%s%.*s",
8878 inst_len ? "\n" : "", inst_len, inst);
8879 s->cur_prompt->instr_reqd = TRUE;
8881 s->cur_prompt->instr_reqd = FALSE;
8885 * Display any instructions, and get the user's
8889 int ret; /* not live over crReturn */
8890 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8893 crWaitUntilV(!pktin);
8894 ret = get_userpass_input(s->cur_prompt, in, inlen);
8899 * Failed to get responses. Terminate.
8901 free_prompts(s->cur_prompt);
8902 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8903 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8910 * Send the response(s) to the server.
8912 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
8913 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
8914 for (i=0; i < s->num_prompts; i++) {
8915 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8916 ssh2_pkt_addstring(s->pktout,
8917 s->cur_prompt->prompts[i]->result);
8918 end_log_omission(ssh, s->pktout);
8920 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8923 * Free the prompts structure from this iteration.
8924 * If there's another, a new one will be allocated
8925 * when we return to the top of this while loop.
8927 free_prompts(s->cur_prompt);
8930 * Get the next packet in case it's another
8933 crWaitUntilV(pktin);
8938 * We should have SUCCESS or FAILURE now.
8942 } else if (s->can_passwd) {
8945 * Plain old password authentication.
8947 int ret; /* not live over crReturn */
8948 int changereq_first_time; /* not live over crReturn */
8950 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
8952 s->cur_prompt = new_prompts(ssh->frontend);
8953 s->cur_prompt->to_server = TRUE;
8954 s->cur_prompt->name = dupstr("SSH password");
8955 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
8960 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8963 crWaitUntilV(!pktin);
8964 ret = get_userpass_input(s->cur_prompt, in, inlen);
8969 * Failed to get responses. Terminate.
8971 free_prompts(s->cur_prompt);
8972 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8973 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8978 * Squirrel away the password. (We may need it later if
8979 * asked to change it.)
8981 s->password = dupstr(s->cur_prompt->prompts[0]->result);
8982 free_prompts(s->cur_prompt);
8985 * Send the password packet.
8987 * We pad out the password packet to 256 bytes to make
8988 * it harder for an attacker to find the length of the
8991 * Anyone using a password longer than 256 bytes
8992 * probably doesn't have much to worry about from
8993 * people who find out how long their password is!
8995 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8996 ssh2_pkt_addstring(s->pktout, ssh->username);
8997 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8998 /* service requested */
8999 ssh2_pkt_addstring(s->pktout, "password");
9000 ssh2_pkt_addbool(s->pktout, FALSE);
9001 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
9002 ssh2_pkt_addstring(s->pktout, s->password);
9003 end_log_omission(ssh, s->pktout);
9004 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
9005 logevent("Sent password");
9006 s->type = AUTH_TYPE_PASSWORD;
9009 * Wait for next packet, in case it's a password change
9012 crWaitUntilV(pktin);
9013 changereq_first_time = TRUE;
9015 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
9018 * We're being asked for a new password
9019 * (perhaps not for the first time).
9020 * Loop until the server accepts it.
9023 int got_new = FALSE; /* not live over crReturn */
9024 char *prompt; /* not live over crReturn */
9025 int prompt_len; /* not live over crReturn */
9029 if (changereq_first_time)
9030 msg = "Server requested password change";
9032 msg = "Server rejected new password";
9034 c_write_str(ssh, msg);
9035 c_write_str(ssh, "\r\n");
9038 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
9040 s->cur_prompt = new_prompts(ssh->frontend);
9041 s->cur_prompt->to_server = TRUE;
9042 s->cur_prompt->name = dupstr("New SSH password");
9043 s->cur_prompt->instruction =
9044 dupprintf("%.*s", prompt_len, prompt);
9045 s->cur_prompt->instr_reqd = TRUE;
9047 * There's no explicit requirement in the protocol
9048 * for the "old" passwords in the original and
9049 * password-change messages to be the same, and
9050 * apparently some Cisco kit supports password change
9051 * by the user entering a blank password originally
9052 * and the real password subsequently, so,
9053 * reluctantly, we prompt for the old password again.
9055 * (On the other hand, some servers don't even bother
9056 * to check this field.)
9058 add_prompt(s->cur_prompt,
9059 dupstr("Current password (blank for previously entered password): "),
9061 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
9063 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
9067 * Loop until the user manages to enter the same
9072 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9075 crWaitUntilV(!pktin);
9076 ret = get_userpass_input(s->cur_prompt, in, inlen);
9081 * Failed to get responses. Terminate.
9083 /* burn the evidence */
9084 free_prompts(s->cur_prompt);
9085 smemclr(s->password, strlen(s->password));
9087 ssh_disconnect(ssh, NULL, "Unable to authenticate",
9088 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9094 * If the user specified a new original password
9095 * (IYSWIM), overwrite any previously specified
9097 * (A side effect is that the user doesn't have to
9098 * re-enter it if they louse up the new password.)
9100 if (s->cur_prompt->prompts[0]->result[0]) {
9101 smemclr(s->password, strlen(s->password));
9102 /* burn the evidence */
9105 dupstr(s->cur_prompt->prompts[0]->result);
9109 * Check the two new passwords match.
9111 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
9112 s->cur_prompt->prompts[2]->result)
9115 /* They don't. Silly user. */
9116 c_write_str(ssh, "Passwords do not match\r\n");
9121 * Send the new password (along with the old one).
9122 * (see above for padding rationale)
9124 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9125 ssh2_pkt_addstring(s->pktout, ssh->username);
9126 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9127 /* service requested */
9128 ssh2_pkt_addstring(s->pktout, "password");
9129 ssh2_pkt_addbool(s->pktout, TRUE);
9130 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
9131 ssh2_pkt_addstring(s->pktout, s->password);
9132 ssh2_pkt_addstring(s->pktout,
9133 s->cur_prompt->prompts[1]->result);
9134 free_prompts(s->cur_prompt);
9135 end_log_omission(ssh, s->pktout);
9136 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
9137 logevent("Sent new password");
9140 * Now see what the server has to say about it.
9141 * (If it's CHANGEREQ again, it's not happy with the
9144 crWaitUntilV(pktin);
9145 changereq_first_time = FALSE;
9150 * We need to reexamine the current pktin at the top
9151 * of the loop. Either:
9152 * - we weren't asked to change password at all, in
9153 * which case it's a SUCCESS or FAILURE with the
9155 * - we sent a new password, and the server was
9156 * either OK with it (SUCCESS or FAILURE w/partial
9157 * success) or unhappy with the _old_ password
9158 * (FAILURE w/o partial success)
9159 * In any of these cases, we go back to the top of
9160 * the loop and start again.
9165 * We don't need the old password any more, in any
9166 * case. Burn the evidence.
9168 smemclr(s->password, strlen(s->password));
9172 char *str = dupprintf("No supported authentication methods available"
9173 " (server sent: %.*s)",
9176 ssh_disconnect(ssh, str,
9177 "No supported authentication methods available",
9178 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
9188 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
9190 /* Clear up various bits and pieces from authentication. */
9191 if (s->publickey_blob) {
9192 sfree(s->publickey_blob);
9193 sfree(s->publickey_comment);
9195 if (s->agent_response)
9196 sfree(s->agent_response);
9198 if (s->userauth_success) {
9200 * We've just received USERAUTH_SUCCESS, and we haven't sent any
9201 * packets since. Signal the transport layer to consider enacting
9202 * delayed compression.
9204 * (Relying on we_are_in is not sufficient, as
9205 * draft-miller-secsh-compression-delayed is quite clear that it
9206 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
9207 * become set for other reasons.)
9209 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
9213 * Now the connection protocol has started, one way or another.
9216 ssh->channels = newtree234(ssh_channelcmp);
9219 * Set up handlers for some connection protocol messages, so we
9220 * don't have to handle them repeatedly in this coroutine.
9222 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
9223 ssh2_msg_channel_window_adjust;
9224 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
9225 ssh2_msg_global_request;
9228 * Create the main session channel.
9230 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
9231 ssh->mainchan = NULL;
9233 ssh->mainchan = snew(struct ssh_channel);
9234 ssh->mainchan->ssh = ssh;
9235 ssh2_channel_init(ssh->mainchan);
9237 if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
9239 * Just start a direct-tcpip channel and use it as the main
9242 ssh_send_port_open(ssh->mainchan,
9243 conf_get_str(ssh->conf, CONF_ssh_nc_host),
9244 conf_get_int(ssh->conf, CONF_ssh_nc_port),
9248 s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
9249 logevent("Opening session as main channel");
9250 ssh2_pkt_send(ssh, s->pktout);
9251 ssh->ncmode = FALSE;
9253 crWaitUntilV(pktin);
9254 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
9255 bombout(("Server refused to open channel"));
9257 /* FIXME: error data comes back in FAILURE packet */
9259 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
9260 bombout(("Server's channel confirmation cited wrong channel"));
9263 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
9264 ssh->mainchan->halfopen = FALSE;
9265 ssh->mainchan->type = CHAN_MAINSESSION;
9266 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
9267 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
9268 add234(ssh->channels, ssh->mainchan);
9269 update_specials_menu(ssh->frontend);
9270 logevent("Opened main channel");
9274 * Now we have a channel, make dispatch table entries for
9275 * general channel-based messages.
9277 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
9278 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
9279 ssh2_msg_channel_data;
9280 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
9281 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
9282 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
9283 ssh2_msg_channel_open_confirmation;
9284 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
9285 ssh2_msg_channel_open_failure;
9286 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
9287 ssh2_msg_channel_request;
9288 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
9289 ssh2_msg_channel_open;
9290 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
9291 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
9294 if (ssh->mainchan && conf_get_int(ssh->conf, CONF_ssh_simple)) {
9296 * This message indicates to the server that we promise
9297 * not to try to run any other channel in parallel with
9298 * this one, so it's safe for it to advertise a very large
9299 * window and leave the flow control to TCP.
9301 s->pktout = ssh2_chanreq_init(ssh->mainchan,
9302 "simple@putty.projects.tartarus.org",
9304 ssh2_pkt_send(ssh, s->pktout);
9308 * Enable port forwardings.
9310 ssh_setup_portfwd(ssh, ssh->conf);
9312 if (ssh->mainchan && !ssh->ncmode) {
9314 * Send the CHANNEL_REQUESTS for the main session channel.
9315 * Each one is handled by its own little asynchronous
9319 /* Potentially enable X11 forwarding. */
9320 if (conf_get_int(ssh->conf, CONF_x11_forward) &&
9322 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
9323 conf_get_int(ssh->conf, CONF_x11_auth),
9325 ssh2_setup_x11(ssh->mainchan, NULL, NULL);
9327 /* Potentially enable agent forwarding. */
9328 if (conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists())
9329 ssh2_setup_agent(ssh->mainchan, NULL, NULL);
9331 /* Now allocate a pty for the session. */
9332 if (!conf_get_int(ssh->conf, CONF_nopty))
9333 ssh2_setup_pty(ssh->mainchan, NULL, NULL);
9335 /* Send environment variables. */
9336 ssh2_setup_env(ssh->mainchan, NULL, NULL);
9339 * Start a shell or a remote command. We may have to attempt
9340 * this twice if the config data has provided a second choice
9347 if (ssh->fallback_cmd) {
9348 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
9349 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
9351 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
9352 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
9356 s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
9357 ssh2_response_authconn, NULL);
9358 ssh2_pkt_addstring(s->pktout, cmd);
9360 s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
9361 ssh2_response_authconn, NULL);
9362 ssh2_pkt_addstring(s->pktout, cmd);
9364 s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
9365 ssh2_response_authconn, NULL);
9367 ssh2_pkt_send(ssh, s->pktout);
9369 crWaitUntilV(pktin);
9371 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9372 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
9373 bombout(("Unexpected response to shell/command request:"
9374 " packet type %d", pktin->type));
9378 * We failed to start the command. If this is the
9379 * fallback command, we really are finished; if it's
9380 * not, and if the fallback command exists, try falling
9381 * back to it before complaining.
9383 if (!ssh->fallback_cmd &&
9384 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
9385 logevent("Primary command failed; attempting fallback");
9386 ssh->fallback_cmd = TRUE;
9389 bombout(("Server refused to start a shell/command"));
9392 logevent("Started a shell/command");
9397 ssh->editing = ssh->echoing = TRUE;
9400 ssh->state = SSH_STATE_SESSION;
9401 if (ssh->size_needed)
9402 ssh_size(ssh, ssh->term_width, ssh->term_height);
9403 if (ssh->eof_needed)
9404 ssh_special(ssh, TS_EOF);
9410 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
9415 s->try_send = FALSE;
9419 * _All_ the connection-layer packets we expect to
9420 * receive are now handled by the dispatch table.
9421 * Anything that reaches here must be bogus.
9424 bombout(("Strange packet received: type %d", pktin->type));
9426 } else if (ssh->mainchan) {
9428 * We have spare data. Add it to the channel buffer.
9430 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
9435 struct ssh_channel *c;
9437 * Try to send data on all channels if we can.
9439 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
9440 ssh2_try_send_and_unthrottle(ssh, c);
9448 * Handlers for SSH-2 messages that might arrive at any moment.
9450 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
9452 /* log reason code in disconnect message */
9456 reason = ssh_pkt_getuint32(pktin);
9457 ssh_pkt_getstring(pktin, &msg, &msglen);
9459 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
9460 buf = dupprintf("Received disconnect message (%s)",
9461 ssh2_disconnect_reasons[reason]);
9463 buf = dupprintf("Received disconnect message (unknown"
9464 " type %d)", reason);
9468 buf = dupprintf("Disconnection message text: %.*s",
9471 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
9473 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
9474 ssh2_disconnect_reasons[reason] : "unknown",
9479 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
9481 /* log the debug message */
9485 /* XXX maybe we should actually take notice of the return value */
9486 ssh2_pkt_getbool(pktin);
9487 ssh_pkt_getstring(pktin, &msg, &msglen);
9489 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
9492 static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
9494 do_ssh2_transport(ssh, NULL, 0, pktin);
9498 * Called if we receive a packet that isn't allowed by the protocol.
9499 * This only applies to packets whose meaning PuTTY understands.
9500 * Entirely unknown packets are handled below.
9502 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
9504 char *buf = dupprintf("Server protocol violation: unexpected %s packet",
9505 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
9507 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
9511 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
9513 struct Packet *pktout;
9514 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
9515 ssh2_pkt_adduint32(pktout, pktin->sequence);
9517 * UNIMPLEMENTED messages MUST appear in the same order as the
9518 * messages they respond to. Hence, never queue them.
9520 ssh2_pkt_send_noqueue(ssh, pktout);
9524 * Handle the top-level SSH-2 protocol.
9526 static void ssh2_protocol_setup(Ssh ssh)
9531 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
9533 for (i = 0; i < 256; i++)
9534 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
9537 * Initially, we only accept transport messages (and a few generic
9538 * ones). do_ssh2_authconn will add more when it starts.
9539 * Messages that are understood but not currently acceptable go to
9540 * ssh2_msg_unexpected.
9542 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
9543 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
9544 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
9545 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
9546 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
9547 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
9548 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
9549 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
9550 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
9551 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
9552 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
9553 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
9554 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
9555 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
9556 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
9557 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
9558 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
9559 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
9560 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
9561 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
9562 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
9563 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
9564 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
9565 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
9566 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
9567 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
9568 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
9569 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
9570 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
9571 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
9572 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
9573 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
9574 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
9577 * These messages have a special handler from the start.
9579 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
9580 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
9581 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
9584 static void ssh2_timer(void *ctx, unsigned long now)
9588 if (ssh->state == SSH_STATE_CLOSED)
9591 if (!ssh->kex_in_progress && conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
9592 now == ssh->next_rekey) {
9593 do_ssh2_transport(ssh, "timeout", -1, NULL);
9597 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
9598 struct Packet *pktin)
9600 unsigned char *in = (unsigned char *)vin;
9601 if (ssh->state == SSH_STATE_CLOSED)
9605 ssh->incoming_data_size += pktin->encrypted_len;
9606 if (!ssh->kex_in_progress &&
9607 ssh->max_data_size != 0 &&
9608 ssh->incoming_data_size > ssh->max_data_size)
9609 do_ssh2_transport(ssh, "too much data received", -1, NULL);
9613 ssh->packet_dispatch[pktin->type](ssh, pktin);
9614 else if (!ssh->protocol_initial_phase_done)
9615 do_ssh2_transport(ssh, in, inlen, pktin);
9617 do_ssh2_authconn(ssh, in, inlen, pktin);
9620 static void ssh_cache_conf_values(Ssh ssh)
9622 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
9626 * Called to set up the connection.
9628 * Returns an error message, or NULL on success.
9630 static const char *ssh_init(void *frontend_handle, void **backend_handle,
9631 Conf *conf, char *host, int port, char **realhost,
9632 int nodelay, int keepalive)
9637 ssh = snew(struct ssh_tag);
9638 ssh->conf = conf_copy(conf);
9639 ssh_cache_conf_values(ssh);
9640 ssh->version = 0; /* when not ready yet */
9643 ssh->v1_cipher_ctx = NULL;
9644 ssh->crcda_ctx = NULL;
9645 ssh->cscipher = NULL;
9646 ssh->cs_cipher_ctx = NULL;
9647 ssh->sccipher = NULL;
9648 ssh->sc_cipher_ctx = NULL;
9650 ssh->cs_mac_ctx = NULL;
9652 ssh->sc_mac_ctx = NULL;
9654 ssh->cs_comp_ctx = NULL;
9656 ssh->sc_comp_ctx = NULL;
9658 ssh->kex_ctx = NULL;
9659 ssh->hostkey = NULL;
9660 ssh->hostkey_str = NULL;
9662 ssh->close_expected = FALSE;
9663 ssh->clean_exit = FALSE;
9664 ssh->state = SSH_STATE_PREPACKET;
9665 ssh->size_needed = FALSE;
9666 ssh->eof_needed = FALSE;
9669 ssh->deferred_send_data = NULL;
9670 ssh->deferred_len = 0;
9671 ssh->deferred_size = 0;
9672 ssh->fallback_cmd = 0;
9673 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
9674 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9675 ssh->x11disp = NULL;
9676 ssh->v1_compressing = FALSE;
9677 ssh->v2_outgoing_sequence = 0;
9678 ssh->ssh1_rdpkt_crstate = 0;
9679 ssh->ssh2_rdpkt_crstate = 0;
9680 ssh->ssh_gotdata_crstate = 0;
9681 ssh->do_ssh1_connection_crstate = 0;
9682 ssh->do_ssh_init_state = NULL;
9683 ssh->do_ssh1_login_state = NULL;
9684 ssh->do_ssh2_transport_state = NULL;
9685 ssh->do_ssh2_authconn_state = NULL;
9688 ssh->mainchan = NULL;
9689 ssh->throttled_all = 0;
9690 ssh->v1_stdout_throttling = 0;
9692 ssh->queuelen = ssh->queuesize = 0;
9693 ssh->queueing = FALSE;
9694 ssh->qhead = ssh->qtail = NULL;
9695 ssh->deferred_rekey_reason = NULL;
9696 bufchain_init(&ssh->queued_incoming_data);
9697 ssh->frozen = FALSE;
9698 ssh->username = NULL;
9699 ssh->sent_console_eof = FALSE;
9700 ssh->got_pty = FALSE;
9702 *backend_handle = ssh;
9705 if (crypto_startup() == 0)
9706 return "Microsoft high encryption pack not installed!";
9709 ssh->frontend = frontend_handle;
9710 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
9711 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
9713 ssh->channels = NULL;
9714 ssh->rportfwds = NULL;
9715 ssh->portfwds = NULL;
9720 ssh->conn_throttle_count = 0;
9721 ssh->overall_bufsize = 0;
9722 ssh->fallback_cmd = 0;
9724 ssh->protocol = NULL;
9726 ssh->protocol_initial_phase_done = FALSE;
9730 ssh->incoming_data_size = ssh->outgoing_data_size =
9731 ssh->deferred_data_size = 0L;
9732 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
9733 CONF_ssh_rekey_data));
9734 ssh->kex_in_progress = FALSE;
9737 ssh->gsslibs = NULL;
9740 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
9749 static void ssh_free(void *handle)
9751 Ssh ssh = (Ssh) handle;
9752 struct ssh_channel *c;
9753 struct ssh_rportfwd *pf;
9755 if (ssh->v1_cipher_ctx)
9756 ssh->cipher->free_context(ssh->v1_cipher_ctx);
9757 if (ssh->cs_cipher_ctx)
9758 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
9759 if (ssh->sc_cipher_ctx)
9760 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
9761 if (ssh->cs_mac_ctx)
9762 ssh->csmac->free_context(ssh->cs_mac_ctx);
9763 if (ssh->sc_mac_ctx)
9764 ssh->scmac->free_context(ssh->sc_mac_ctx);
9765 if (ssh->cs_comp_ctx) {
9767 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
9769 zlib_compress_cleanup(ssh->cs_comp_ctx);
9771 if (ssh->sc_comp_ctx) {
9773 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
9775 zlib_decompress_cleanup(ssh->sc_comp_ctx);
9778 dh_cleanup(ssh->kex_ctx);
9779 sfree(ssh->savedhost);
9781 while (ssh->queuelen-- > 0)
9782 ssh_free_packet(ssh->queue[ssh->queuelen]);
9785 while (ssh->qhead) {
9786 struct queued_handler *qh = ssh->qhead;
9787 ssh->qhead = qh->next;
9790 ssh->qhead = ssh->qtail = NULL;
9792 if (ssh->channels) {
9793 while ((c = delpos234(ssh->channels, 0)) != NULL) {
9796 if (c->u.x11.s != NULL)
9797 x11_close(c->u.x11.s);
9800 case CHAN_SOCKDATA_DORMANT:
9801 if (c->u.pfd.s != NULL)
9802 pfd_close(c->u.pfd.s);
9805 if (ssh->version == 2) {
9806 struct outstanding_channel_request *ocr, *nocr;
9807 ocr = c->v.v2.chanreq_head;
9809 ocr->handler(c, NULL, ocr->ctx);
9814 bufchain_clear(&c->v.v2.outbuffer);
9818 freetree234(ssh->channels);
9819 ssh->channels = NULL;
9822 if (ssh->rportfwds) {
9823 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
9825 freetree234(ssh->rportfwds);
9826 ssh->rportfwds = NULL;
9828 sfree(ssh->deferred_send_data);
9830 x11_free_display(ssh->x11disp);
9831 sfree(ssh->do_ssh_init_state);
9832 sfree(ssh->do_ssh1_login_state);
9833 sfree(ssh->do_ssh2_transport_state);
9834 sfree(ssh->do_ssh2_authconn_state);
9837 sfree(ssh->fullhostname);
9838 sfree(ssh->hostkey_str);
9839 if (ssh->crcda_ctx) {
9840 crcda_free_context(ssh->crcda_ctx);
9841 ssh->crcda_ctx = NULL;
9844 ssh_do_close(ssh, TRUE);
9845 expire_timer_context(ssh);
9847 pinger_free(ssh->pinger);
9848 bufchain_clear(&ssh->queued_incoming_data);
9849 sfree(ssh->username);
9850 conf_free(ssh->conf);
9853 ssh_gss_cleanup(ssh->gsslibs);
9861 * Reconfigure the SSH backend.
9863 static void ssh_reconfig(void *handle, Conf *conf)
9865 Ssh ssh = (Ssh) handle;
9866 char *rekeying = NULL, rekey_mandatory = FALSE;
9867 unsigned long old_max_data_size;
9870 pinger_reconfig(ssh->pinger, ssh->conf, conf);
9872 ssh_setup_portfwd(ssh, conf);
9874 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
9875 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
9877 unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
9878 unsigned long now = GETTICKCOUNT();
9880 if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
9881 rekeying = "timeout shortened";
9883 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
9887 old_max_data_size = ssh->max_data_size;
9888 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
9889 CONF_ssh_rekey_data));
9890 if (old_max_data_size != ssh->max_data_size &&
9891 ssh->max_data_size != 0) {
9892 if (ssh->outgoing_data_size > ssh->max_data_size ||
9893 ssh->incoming_data_size > ssh->max_data_size)
9894 rekeying = "data limit lowered";
9897 if (conf_get_int(ssh->conf, CONF_compression) !=
9898 conf_get_int(conf, CONF_compression)) {
9899 rekeying = "compression setting changed";
9900 rekey_mandatory = TRUE;
9903 for (i = 0; i < CIPHER_MAX; i++)
9904 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
9905 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
9906 rekeying = "cipher settings changed";
9907 rekey_mandatory = TRUE;
9909 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
9910 conf_get_int(conf, CONF_ssh2_des_cbc)) {
9911 rekeying = "cipher settings changed";
9912 rekey_mandatory = TRUE;
9915 conf_free(ssh->conf);
9916 ssh->conf = conf_copy(conf);
9917 ssh_cache_conf_values(ssh);
9920 if (!ssh->kex_in_progress) {
9921 do_ssh2_transport(ssh, rekeying, -1, NULL);
9922 } else if (rekey_mandatory) {
9923 ssh->deferred_rekey_reason = rekeying;
9929 * Called to send data down the SSH connection.
9931 static int ssh_send(void *handle, char *buf, int len)
9933 Ssh ssh = (Ssh) handle;
9935 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
9938 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
9940 return ssh_sendbuffer(ssh);
9944 * Called to query the current amount of buffered stdin data.
9946 static int ssh_sendbuffer(void *handle)
9948 Ssh ssh = (Ssh) handle;
9951 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
9955 * If the SSH socket itself has backed up, add the total backup
9956 * size on that to any individual buffer on the stdin channel.
9959 if (ssh->throttled_all)
9960 override_value = ssh->overall_bufsize;
9962 if (ssh->version == 1) {
9963 return override_value;
9964 } else if (ssh->version == 2) {
9966 return override_value;
9968 return (override_value +
9969 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
9976 * Called to set the size of the window from SSH's POV.
9978 static void ssh_size(void *handle, int width, int height)
9980 Ssh ssh = (Ssh) handle;
9981 struct Packet *pktout;
9983 ssh->term_width = width;
9984 ssh->term_height = height;
9986 switch (ssh->state) {
9987 case SSH_STATE_BEFORE_SIZE:
9988 case SSH_STATE_PREPACKET:
9989 case SSH_STATE_CLOSED:
9990 break; /* do nothing */
9991 case SSH_STATE_INTERMED:
9992 ssh->size_needed = TRUE; /* buffer for later */
9994 case SSH_STATE_SESSION:
9995 if (!conf_get_int(ssh->conf, CONF_nopty)) {
9996 if (ssh->version == 1) {
9997 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
9998 PKT_INT, ssh->term_height,
9999 PKT_INT, ssh->term_width,
10000 PKT_INT, 0, PKT_INT, 0, PKT_END);
10001 } else if (ssh->mainchan) {
10002 pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
10004 ssh2_pkt_adduint32(pktout, ssh->term_width);
10005 ssh2_pkt_adduint32(pktout, ssh->term_height);
10006 ssh2_pkt_adduint32(pktout, 0);
10007 ssh2_pkt_adduint32(pktout, 0);
10008 ssh2_pkt_send(ssh, pktout);
10016 * Return a list of the special codes that make sense in this
10019 static const struct telnet_special *ssh_get_specials(void *handle)
10021 static const struct telnet_special ssh1_ignore_special[] = {
10022 {"IGNORE message", TS_NOP}
10024 static const struct telnet_special ssh2_ignore_special[] = {
10025 {"IGNORE message", TS_NOP},
10027 static const struct telnet_special ssh2_rekey_special[] = {
10028 {"Repeat key exchange", TS_REKEY},
10030 static const struct telnet_special ssh2_session_specials[] = {
10033 /* These are the signal names defined by RFC 4254.
10034 * They include all the ISO C signals, but are a subset of the POSIX
10035 * required signals. */
10036 {"SIGINT (Interrupt)", TS_SIGINT},
10037 {"SIGTERM (Terminate)", TS_SIGTERM},
10038 {"SIGKILL (Kill)", TS_SIGKILL},
10039 {"SIGQUIT (Quit)", TS_SIGQUIT},
10040 {"SIGHUP (Hangup)", TS_SIGHUP},
10041 {"More signals", TS_SUBMENU},
10042 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
10043 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
10044 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
10045 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
10046 {NULL, TS_EXITMENU}
10048 static const struct telnet_special specials_end[] = {
10049 {NULL, TS_EXITMENU}
10051 /* XXX review this length for any changes: */
10052 static struct telnet_special ssh_specials[lenof(ssh2_ignore_special) +
10053 lenof(ssh2_rekey_special) +
10054 lenof(ssh2_session_specials) +
10055 lenof(specials_end)];
10056 Ssh ssh = (Ssh) handle;
10058 #define ADD_SPECIALS(name) \
10060 assert((i + lenof(name)) <= lenof(ssh_specials)); \
10061 memcpy(&ssh_specials[i], name, sizeof name); \
10062 i += lenof(name); \
10065 if (ssh->version == 1) {
10066 /* Don't bother offering IGNORE if we've decided the remote
10067 * won't cope with it, since we wouldn't bother sending it if
10069 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
10070 ADD_SPECIALS(ssh1_ignore_special);
10071 } else if (ssh->version == 2) {
10072 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
10073 ADD_SPECIALS(ssh2_ignore_special);
10074 if (!(ssh->remote_bugs & BUG_SSH2_REKEY))
10075 ADD_SPECIALS(ssh2_rekey_special);
10077 ADD_SPECIALS(ssh2_session_specials);
10078 } /* else we're not ready yet */
10081 ADD_SPECIALS(specials_end);
10082 return ssh_specials;
10086 #undef ADD_SPECIALS
10090 * Send special codes. TS_EOF is useful for `plink', so you
10091 * can send an EOF and collect resulting output (e.g. `plink
10094 static void ssh_special(void *handle, Telnet_Special code)
10096 Ssh ssh = (Ssh) handle;
10097 struct Packet *pktout;
10099 if (code == TS_EOF) {
10100 if (ssh->state != SSH_STATE_SESSION) {
10102 * Buffer the EOF in case we are pre-SESSION, so we can
10103 * send it as soon as we reach SESSION.
10105 if (code == TS_EOF)
10106 ssh->eof_needed = TRUE;
10109 if (ssh->version == 1) {
10110 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
10111 } else if (ssh->mainchan) {
10112 sshfwd_write_eof(ssh->mainchan);
10113 ssh->send_ok = 0; /* now stop trying to read from stdin */
10115 logevent("Sent EOF message");
10116 } else if (code == TS_PING || code == TS_NOP) {
10117 if (ssh->state == SSH_STATE_CLOSED
10118 || ssh->state == SSH_STATE_PREPACKET) return;
10119 if (ssh->version == 1) {
10120 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
10121 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
10123 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
10124 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
10125 ssh2_pkt_addstring_start(pktout);
10126 ssh2_pkt_send_noqueue(ssh, pktout);
10129 } else if (code == TS_REKEY) {
10130 if (!ssh->kex_in_progress && ssh->version == 2) {
10131 do_ssh2_transport(ssh, "at user request", -1, NULL);
10133 } else if (code == TS_BRK) {
10134 if (ssh->state == SSH_STATE_CLOSED
10135 || ssh->state == SSH_STATE_PREPACKET) return;
10136 if (ssh->version == 1) {
10137 logevent("Unable to send BREAK signal in SSH-1");
10138 } else if (ssh->mainchan) {
10139 pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
10140 ssh2_pkt_adduint32(pktout, 0); /* default break length */
10141 ssh2_pkt_send(ssh, pktout);
10144 /* Is is a POSIX signal? */
10145 char *signame = NULL;
10146 if (code == TS_SIGABRT) signame = "ABRT";
10147 if (code == TS_SIGALRM) signame = "ALRM";
10148 if (code == TS_SIGFPE) signame = "FPE";
10149 if (code == TS_SIGHUP) signame = "HUP";
10150 if (code == TS_SIGILL) signame = "ILL";
10151 if (code == TS_SIGINT) signame = "INT";
10152 if (code == TS_SIGKILL) signame = "KILL";
10153 if (code == TS_SIGPIPE) signame = "PIPE";
10154 if (code == TS_SIGQUIT) signame = "QUIT";
10155 if (code == TS_SIGSEGV) signame = "SEGV";
10156 if (code == TS_SIGTERM) signame = "TERM";
10157 if (code == TS_SIGUSR1) signame = "USR1";
10158 if (code == TS_SIGUSR2) signame = "USR2";
10159 /* The SSH-2 protocol does in principle support arbitrary named
10160 * signals, including signame@domain, but we don't support those. */
10162 /* It's a signal. */
10163 if (ssh->version == 2 && ssh->mainchan) {
10164 pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
10165 ssh2_pkt_addstring(pktout, signame);
10166 ssh2_pkt_send(ssh, pktout);
10167 logeventf(ssh, "Sent signal SIG%s", signame);
10170 /* Never heard of it. Do nothing */
10175 void *new_sock_channel(void *handle, Socket s)
10177 Ssh ssh = (Ssh) handle;
10178 struct ssh_channel *c;
10179 c = snew(struct ssh_channel);
10182 ssh2_channel_init(c);
10183 c->halfopen = TRUE;
10184 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
10186 add234(ssh->channels, c);
10191 * This is called when stdout/stderr (the entity to which
10192 * from_backend sends data) manages to clear some backlog.
10194 static void ssh_unthrottle(void *handle, int bufsize)
10196 Ssh ssh = (Ssh) handle;
10199 if (ssh->version == 1) {
10200 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
10201 ssh->v1_stdout_throttling = 0;
10202 ssh_throttle_conn(ssh, -1);
10205 if (ssh->mainchan) {
10206 ssh2_set_window(ssh->mainchan,
10207 bufsize < ssh->mainchan->v.v2.locmaxwin ?
10208 ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
10209 if (conf_get_int(ssh->conf, CONF_ssh_simple))
10212 buflimit = ssh->mainchan->v.v2.locmaxwin;
10213 if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
10214 ssh->mainchan->throttling_conn = 0;
10215 ssh_throttle_conn(ssh, -1);
10221 * Now process any SSH connection data that was stashed in our
10222 * queue while we were frozen.
10224 ssh_process_queued_incoming_data(ssh);
10227 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
10229 struct ssh_channel *c = (struct ssh_channel *)channel;
10231 struct Packet *pktout;
10233 logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
10235 if (ssh->version == 1) {
10236 send_packet(ssh, SSH1_MSG_PORT_OPEN,
10237 PKT_INT, c->localid,
10240 /* PKT_STR, <org:orgport>, */
10243 pktout = ssh2_chanopen_init(c, "direct-tcpip");
10244 ssh2_pkt_addstring(pktout, hostname);
10245 ssh2_pkt_adduint32(pktout, port);
10247 * We make up values for the originator data; partly it's
10248 * too much hassle to keep track, and partly I'm not
10249 * convinced the server should be told details like that
10250 * about my local network configuration.
10251 * The "originator IP address" is syntactically a numeric
10252 * IP address, and some servers (e.g., Tectia) get upset
10253 * if it doesn't match this syntax.
10255 ssh2_pkt_addstring(pktout, "0.0.0.0");
10256 ssh2_pkt_adduint32(pktout, 0);
10257 ssh2_pkt_send(ssh, pktout);
10261 static int ssh_connected(void *handle)
10263 Ssh ssh = (Ssh) handle;
10264 return ssh->s != NULL;
10267 static int ssh_sendok(void *handle)
10269 Ssh ssh = (Ssh) handle;
10270 return ssh->send_ok;
10273 static int ssh_ldisc(void *handle, int option)
10275 Ssh ssh = (Ssh) handle;
10276 if (option == LD_ECHO)
10277 return ssh->echoing;
10278 if (option == LD_EDIT)
10279 return ssh->editing;
10283 static void ssh_provide_ldisc(void *handle, void *ldisc)
10285 Ssh ssh = (Ssh) handle;
10286 ssh->ldisc = ldisc;
10289 static void ssh_provide_logctx(void *handle, void *logctx)
10291 Ssh ssh = (Ssh) handle;
10292 ssh->logctx = logctx;
10295 static int ssh_return_exitcode(void *handle)
10297 Ssh ssh = (Ssh) handle;
10298 if (ssh->s != NULL)
10301 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
10305 * cfg_info for SSH is the currently running version of the
10306 * protocol. (1 for 1; 2 for 2; 0 for not-decided-yet.)
10308 static int ssh_cfg_info(void *handle)
10310 Ssh ssh = (Ssh) handle;
10311 return ssh->version;
10315 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
10316 * that fails. This variable is the means by which scp.c can reach
10317 * into the SSH code and find out which one it got.
10319 extern int ssh_fallback_cmd(void *handle)
10321 Ssh ssh = (Ssh) handle;
10322 return ssh->fallback_cmd;
10325 Backend ssh_backend = {
10335 ssh_return_exitcode,
10339 ssh_provide_logctx,