18 #define logevent(s) { logevent(s); \
19 if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)) \
20 { fprintf(stderr, "%s\n", s); fflush(stderr); } }
22 /* logevent, only printf-formatted. */
23 void logeventf(char *fmt, ...)
29 vsprintf(stuff, fmt, ap);
34 #define bombout(msg) ( ssh_state = SSH_STATE_CLOSED, \
35 (s ? sk_close(s), s = NULL : 0), \
36 logeventf msg, connection_fatal msg )
38 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
39 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
40 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
41 #define SSH1_CMSG_USER 4 /* 0x4 */
42 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
43 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
44 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
45 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
46 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
47 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
48 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
49 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
50 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
51 #define SSH1_SMSG_FAILURE 15 /* 0xf */
52 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
53 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
54 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
55 #define SSH1_CMSG_EOF 19 /* 0x13 */
56 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
57 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
58 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
59 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
60 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
61 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
62 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
63 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
64 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
65 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
66 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
67 #define SSH1_MSG_IGNORE 32 /* 0x20 */
68 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
69 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
70 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
71 #define SSH1_MSG_DEBUG 36 /* 0x24 */
72 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
73 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
74 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
75 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
76 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
77 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
78 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
80 #define SSH1_AUTH_TIS 5 /* 0x5 */
81 #define SSH1_AUTH_CCARD 16 /* 0x10 */
83 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
84 /* Mask for protoflags we will echo back to server if seen */
85 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
87 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
88 #define SSH2_MSG_IGNORE 2 /* 0x2 */
89 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
90 #define SSH2_MSG_DEBUG 4 /* 0x4 */
91 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
92 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
93 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
94 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
95 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
96 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
97 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
98 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
99 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
100 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
101 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
102 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
103 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
104 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
105 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
106 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
107 #define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */
108 #define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */
109 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
110 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
111 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
112 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
113 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
114 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
115 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
116 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
117 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
118 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
119 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
120 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
121 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
122 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
125 * Packet type contexts, so that ssh2_pkt_type can correctly decode
126 * the ambiguous type numbers back into the correct type strings.
128 #define SSH2_PKTCTX_DHGROUP1 0x0001
129 #define SSH2_PKTCTX_DHGEX 0x0002
130 #define SSH2_PKTCTX_PUBLICKEY 0x0010
131 #define SSH2_PKTCTX_PASSWORD 0x0020
132 #define SSH2_PKTCTX_KBDINTER 0x0040
133 #define SSH2_PKTCTX_AUTH_MASK 0x00F0
135 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
136 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
137 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
138 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
139 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
140 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
141 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
142 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
143 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
144 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
145 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
146 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
147 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
148 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
149 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
151 static const char *const ssh2_disconnect_reasons[] = {
153 "SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT",
154 "SSH_DISCONNECT_PROTOCOL_ERROR",
155 "SSH_DISCONNECT_KEY_EXCHANGE_FAILED",
156 "SSH_DISCONNECT_HOST_AUTHENTICATION_FAILED",
157 "SSH_DISCONNECT_MAC_ERROR",
158 "SSH_DISCONNECT_COMPRESSION_ERROR",
159 "SSH_DISCONNECT_SERVICE_NOT_AVAILABLE",
160 "SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED",
161 "SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE",
162 "SSH_DISCONNECT_CONNECTION_LOST",
163 "SSH_DISCONNECT_BY_APPLICATION",
164 "SSH_DISCONNECT_TOO_MANY_CONNECTIONS",
165 "SSH_DISCONNECT_AUTH_CANCELLED_BY_USER",
166 "SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE",
167 "SSH_DISCONNECT_ILLEGAL_USER_NAME",
170 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
171 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
172 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
173 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
175 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
178 * Various remote-bug flags.
180 #define BUG_CHOKES_ON_SSH1_IGNORE 1
181 #define BUG_SSH2_HMAC 2
182 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
183 #define BUG_CHOKES_ON_RSA 8
184 #define BUG_SSH2_RSA_PADDING 16
185 #define BUG_SSH2_DERIVEKEY 32
187 static int ssh_pkt_ctx = 0;
189 #define translate(x) if (type == x) return #x
190 #define translatec(x,ctx) if (type == x && (ssh_pkt_ctx & ctx)) return #x
191 char *ssh1_pkt_type(int type)
193 translate(SSH1_MSG_DISCONNECT);
194 translate(SSH1_SMSG_PUBLIC_KEY);
195 translate(SSH1_CMSG_SESSION_KEY);
196 translate(SSH1_CMSG_USER);
197 translate(SSH1_CMSG_AUTH_RSA);
198 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
199 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
200 translate(SSH1_CMSG_AUTH_PASSWORD);
201 translate(SSH1_CMSG_REQUEST_PTY);
202 translate(SSH1_CMSG_WINDOW_SIZE);
203 translate(SSH1_CMSG_EXEC_SHELL);
204 translate(SSH1_CMSG_EXEC_CMD);
205 translate(SSH1_SMSG_SUCCESS);
206 translate(SSH1_SMSG_FAILURE);
207 translate(SSH1_CMSG_STDIN_DATA);
208 translate(SSH1_SMSG_STDOUT_DATA);
209 translate(SSH1_SMSG_STDERR_DATA);
210 translate(SSH1_CMSG_EOF);
211 translate(SSH1_SMSG_EXIT_STATUS);
212 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
213 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
214 translate(SSH1_MSG_CHANNEL_DATA);
215 translate(SSH1_MSG_CHANNEL_CLOSE);
216 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
217 translate(SSH1_SMSG_X11_OPEN);
218 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
219 translate(SSH1_MSG_PORT_OPEN);
220 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
221 translate(SSH1_SMSG_AGENT_OPEN);
222 translate(SSH1_MSG_IGNORE);
223 translate(SSH1_CMSG_EXIT_CONFIRMATION);
224 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
225 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
226 translate(SSH1_MSG_DEBUG);
227 translate(SSH1_CMSG_REQUEST_COMPRESSION);
228 translate(SSH1_CMSG_AUTH_TIS);
229 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
230 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
231 translate(SSH1_CMSG_AUTH_CCARD);
232 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
233 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
236 char *ssh2_pkt_type(int type)
238 translate(SSH2_MSG_DISCONNECT);
239 translate(SSH2_MSG_IGNORE);
240 translate(SSH2_MSG_UNIMPLEMENTED);
241 translate(SSH2_MSG_DEBUG);
242 translate(SSH2_MSG_SERVICE_REQUEST);
243 translate(SSH2_MSG_SERVICE_ACCEPT);
244 translate(SSH2_MSG_KEXINIT);
245 translate(SSH2_MSG_NEWKEYS);
246 translatec(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP1);
247 translatec(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP1);
248 translatec(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
249 translatec(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
250 translatec(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
251 translatec(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
252 translate(SSH2_MSG_USERAUTH_REQUEST);
253 translate(SSH2_MSG_USERAUTH_FAILURE);
254 translate(SSH2_MSG_USERAUTH_SUCCESS);
255 translate(SSH2_MSG_USERAUTH_BANNER);
256 translatec(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
257 translatec(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
258 translatec(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
259 translatec(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
260 translate(SSH2_MSG_GLOBAL_REQUEST);
261 translate(SSH2_MSG_REQUEST_SUCCESS);
262 translate(SSH2_MSG_REQUEST_FAILURE);
263 translate(SSH2_MSG_CHANNEL_OPEN);
264 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
265 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
266 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
267 translate(SSH2_MSG_CHANNEL_DATA);
268 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
269 translate(SSH2_MSG_CHANNEL_EOF);
270 translate(SSH2_MSG_CHANNEL_CLOSE);
271 translate(SSH2_MSG_CHANNEL_REQUEST);
272 translate(SSH2_MSG_CHANNEL_SUCCESS);
273 translate(SSH2_MSG_CHANNEL_FAILURE);
279 #define GET_32BIT(cp) \
280 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
281 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
282 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
283 ((unsigned long)(unsigned char)(cp)[3]))
285 #define PUT_32BIT(cp, value) { \
286 (cp)[0] = (unsigned char)((value) >> 24); \
287 (cp)[1] = (unsigned char)((value) >> 16); \
288 (cp)[2] = (unsigned char)((value) >> 8); \
289 (cp)[3] = (unsigned char)(value); }
291 enum { PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM };
293 /* Coroutine mechanics for the sillier bits of the code */
294 #define crBegin1 static int crLine = 0;
295 #define crBegin2 switch(crLine) { case 0:;
296 #define crBegin crBegin1; crBegin2;
297 #define crFinish(z) } crLine = 0; return (z)
298 #define crFinishV } crLine = 0; return
299 #define crReturn(z) \
301 crLine=__LINE__; return (z); case __LINE__:;\
305 crLine=__LINE__; return; case __LINE__:;\
307 #define crStop(z) do{ crLine = 0; return (z); }while(0)
308 #define crStopV do{ crLine = 0; return; }while(0)
309 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
310 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
312 extern char *x11_init(Socket *, char *, void *);
313 extern void x11_close(Socket);
314 extern int x11_send(Socket, char *, int);
315 extern void x11_invent_auth(char *, int, char *, int);
316 extern void x11_unthrottle(Socket s);
317 extern void x11_override_throttle(Socket s, int enable);
319 extern char *pfd_newconnect(Socket * s, char *hostname, int port, void *c);
320 extern char *pfd_addforward(char *desthost, int destport, int port);
321 extern void pfd_close(Socket s);
322 extern int pfd_send(Socket s, char *data, int len);
323 extern void pfd_confirm(Socket s);
324 extern void pfd_unthrottle(Socket s);
325 extern void pfd_override_throttle(Socket s, int enable);
327 static void ssh2_pkt_init(int pkt_type);
328 static void ssh2_pkt_addbool(unsigned char value);
329 static void ssh2_pkt_adduint32(unsigned long value);
330 static void ssh2_pkt_addstring_start(void);
331 static void ssh2_pkt_addstring_str(char *data);
332 static void ssh2_pkt_addstring_data(char *data, int len);
333 static void ssh2_pkt_addstring(char *data);
334 static char *ssh2_mpint_fmt(Bignum b, int *len);
335 static void ssh2_pkt_addmp(Bignum b);
336 static int ssh2_pkt_construct(void);
337 static void ssh2_pkt_send(void);
340 * Buffer management constants. There are several of these for
341 * various different purposes:
343 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
344 * on a local data stream before we throttle the whole SSH
345 * connection (in SSH1 only). Throttling the whole connection is
346 * pretty drastic so we set this high in the hope it won't
349 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
350 * on the SSH connection itself before we defensively throttle
351 * _all_ local data streams. This is pretty drastic too (though
352 * thankfully unlikely in SSH2 since the window mechanism should
353 * ensure that the server never has any need to throttle its end
354 * of the connection), so we set this high as well.
356 * - OUR_V2_WINSIZE is the maximum window size we present on SSH2
360 #define SSH1_BUFFER_LIMIT 32768
361 #define SSH_MAX_BACKLOG 32768
362 #define OUR_V2_WINSIZE 16384
364 const static struct ssh_kex *kex_algs[] = {
365 &ssh_diffiehellman_gex,
369 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
371 static void nullmac_key(unsigned char *key)
374 static void nullmac_generate(unsigned char *blk, int len,
378 static int nullmac_verify(unsigned char *blk, int len, unsigned long seq)
382 const static struct ssh_mac ssh_mac_none = {
383 nullmac_key, nullmac_key, nullmac_generate, nullmac_verify, "none", 0
385 const static struct ssh_mac *macs[] = {
386 &ssh_sha1, &ssh_md5, &ssh_mac_none
388 const static struct ssh_mac *buggymacs[] = {
389 &ssh_sha1_buggy, &ssh_md5, &ssh_mac_none
392 static void ssh_comp_none_init(void)
395 static int ssh_comp_none_block(unsigned char *block, int len,
396 unsigned char **outblock, int *outlen)
400 static int ssh_comp_none_disable(void)
404 const static struct ssh_compress ssh_comp_none = {
406 ssh_comp_none_init, ssh_comp_none_block,
407 ssh_comp_none_init, ssh_comp_none_block,
408 ssh_comp_none_disable
410 extern const struct ssh_compress ssh_zlib;
411 const static struct ssh_compress *compressions[] = {
412 &ssh_zlib, &ssh_comp_none
415 enum { /* channel types */
420 CHAN_SOCKDATA_DORMANT /* one the remote hasn't confirmed */
424 * 2-3-4 tree storing channels.
427 unsigned remoteid, localid;
430 * In SSH1, this value contains four bits:
432 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
433 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
434 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
435 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
437 * A channel is completely finished with when all four bits are set.
441 struct ssh1_data_channel {
444 struct ssh2_data_channel {
446 unsigned remwindow, remmaxpkt;
451 struct ssh_agent_channel {
452 unsigned char *message;
453 unsigned char msglen[4];
454 int lensofar, totallen;
456 struct ssh_x11_channel {
459 struct ssh_pfd_channel {
466 * 2-3-4 tree storing remote->local port forwardings. SSH 1 and SSH
467 * 2 use this structure in different ways, reflecting SSH 2's
468 * altogether saner approach to port forwarding.
470 * In SSH 1, you arrange a remote forwarding by sending the server
471 * the remote port number, and the local destination host:port.
472 * When a connection comes in, the server sends you back that
473 * host:port pair, and you connect to it. This is a ready-made
474 * security hole if you're not on the ball: a malicious server
475 * could send you back _any_ host:port pair, so if you trustingly
476 * connect to the address it gives you then you've just opened the
477 * entire inside of your corporate network just by connecting
478 * through it to a dodgy SSH server. Hence, we must store a list of
479 * host:port pairs we _are_ trying to forward to, and reject a
480 * connection request from the server if it's not in the list.
482 * In SSH 2, each side of the connection minds its own business and
483 * doesn't send unnecessary information to the other. You arrange a
484 * remote forwarding by sending the server just the remote port
485 * number. When a connection comes in, the server tells you which
486 * of its ports was connected to; and _you_ have to remember what
487 * local host:port pair went with that port number.
489 * Hence: in SSH 1 this structure stores host:port pairs we intend
490 * to allow connections to, and is indexed by those host:port
491 * pairs. In SSH 2 it stores a mapping from source port to
492 * destination host:port pair, and is indexed by source port.
494 struct ssh_rportfwd {
495 unsigned sport, dport;
508 static SHA_State exhash, exhashbase;
510 static Socket s = NULL;
512 static unsigned char session_key[32];
513 static int ssh1_compressing;
514 static int ssh1_remote_protoflags;
515 static int ssh1_local_protoflags;
516 static int ssh_agentfwd_enabled;
517 static int ssh_X11_fwd_enabled;
518 static int ssh_remote_bugs;
519 static const struct ssh_cipher *cipher = NULL;
520 static const struct ssh2_cipher *cscipher = NULL;
521 static const struct ssh2_cipher *sccipher = NULL;
522 static const struct ssh_mac *csmac = NULL;
523 static const struct ssh_mac *scmac = NULL;
524 static const struct ssh_compress *cscomp = NULL;
525 static const struct ssh_compress *sccomp = NULL;
526 static const struct ssh_kex *kex = NULL;
527 static const struct ssh_signkey *hostkey = NULL;
528 static unsigned char ssh2_session_id[20];
530 static char *savedhost;
531 static int savedport;
532 static int ssh_send_ok;
533 static int ssh_echoing, ssh_editing;
535 static tree234 *ssh_channels; /* indexed by local id */
536 static struct ssh_channel *mainchan; /* primary session channel */
537 static int ssh_exitcode = -1;
539 static tree234 *ssh_rportfwds;
543 SSH_STATE_BEFORE_SIZE,
547 } ssh_state = SSH_STATE_PREPACKET;
549 static int size_needed = FALSE, eof_needed = FALSE;
551 static struct Packet pktin = { 0, 0, NULL, NULL, 0 };
552 static struct Packet pktout = { 0, 0, NULL, NULL, 0 };
553 static unsigned char *deferred_send_data = NULL;
554 static int deferred_len = 0, deferred_size = 0;
557 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
558 * that fails. This variable is the means by which scp.c can reach
559 * into the SSH code and find out which one it got.
561 int ssh_fallback_cmd = 0;
563 static int ssh_version;
564 static int ssh1_throttle_count;
565 static int ssh_overall_bufsize;
566 static int ssh_throttled_all;
567 static int ssh1_stdout_throttling;
568 static void (*ssh_protocol) (unsigned char *in, int inlen, int ispkt);
569 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt);
570 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt);
571 static void ssh_size(void);
572 static void ssh_special(Telnet_Special);
573 static int ssh2_try_send(struct ssh_channel *c);
574 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
576 static void ssh_throttle_all(int enable, int bufsize);
577 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin);
578 static int (*s_rdpkt) (unsigned char **data, int *datalen);
579 static int ssh_sendbuffer(void);
581 static struct rdpkt1_state_tag {
582 long len, pad, biglen, to_read;
583 unsigned long realcrc, gotcrc;
589 static struct rdpkt2_state_tag {
590 long len, pad, payload, packetlen, maclen;
593 unsigned long incoming_sequence;
596 static int ssh_channelcmp(void *av, void *bv)
598 struct ssh_channel *a = (struct ssh_channel *) av;
599 struct ssh_channel *b = (struct ssh_channel *) bv;
600 if (a->localid < b->localid)
602 if (a->localid > b->localid)
606 static int ssh_channelfind(void *av, void *bv)
608 unsigned *a = (unsigned *) av;
609 struct ssh_channel *b = (struct ssh_channel *) bv;
617 static int ssh_rportcmp_ssh1(void *av, void *bv)
619 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
620 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
622 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
623 return i < 0 ? -1 : +1;
624 if (a->dport > b->dport)
626 if (a->dport < b->dport)
631 static int ssh_rportcmp_ssh2(void *av, void *bv)
633 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
634 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
636 if (a->sport > b->sport)
638 if (a->sport < b->sport)
643 static int alloc_channel_id(void)
645 const unsigned CHANNEL_NUMBER_OFFSET = 256;
646 unsigned low, high, mid;
648 struct ssh_channel *c;
651 * First-fit allocation of channel numbers: always pick the
652 * lowest unused one. To do this, binary-search using the
653 * counted B-tree to find the largest channel ID which is in a
654 * contiguous sequence from the beginning. (Precisely
655 * everything in that sequence must have ID equal to its tree
656 * index plus CHANNEL_NUMBER_OFFSET.)
658 tsize = count234(ssh_channels);
662 while (high - low > 1) {
663 mid = (high + low) / 2;
664 c = index234(ssh_channels, mid);
665 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
666 low = mid; /* this one is fine */
668 high = mid; /* this one is past it */
671 * Now low points to either -1, or the tree index of the
672 * largest ID in the initial sequence.
675 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
676 assert(NULL == find234(ssh_channels, &i, ssh_channelfind));
678 return low + 1 + CHANNEL_NUMBER_OFFSET;
681 static void c_write(char *buf, int len)
683 if ((flags & FLAG_STDERR)) {
685 for (i = 0; i < len; i++)
687 fputc(buf[i], stderr);
690 from_backend(1, buf, len);
693 static void c_write_untrusted(char *buf, int len)
696 for (i = 0; i < len; i++) {
699 else if ((buf[i] & 0x60) || (buf[i] == '\r'))
704 static void c_write_str(char *buf)
706 c_write(buf, strlen(buf));
710 * Collect incoming data in the incoming packet buffer.
711 * Decipher and verify the packet when it is completely read.
712 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
713 * Update the *data and *datalen variables.
714 * Return the additional nr of bytes needed, or 0 when
715 * a complete packet is available.
717 static int ssh1_rdpkt(unsigned char **data, int *datalen)
719 struct rdpkt1_state_tag *st = &rdpkt1_state;
728 for (st->i = st->len = 0; st->i < 4; st->i++) {
729 while ((*datalen) == 0)
731 st->len = (st->len << 8) + **data;
732 (*data)++, (*datalen)--;
735 st->pad = 8 - (st->len % 8);
736 st->biglen = st->len + st->pad;
737 pktin.length = st->len - 5;
739 if (pktin.maxlen < st->biglen) {
740 pktin.maxlen = st->biglen;
741 pktin.data = (pktin.data == NULL ? smalloc(st->biglen + APIEXTRA) :
742 srealloc(pktin.data, st->biglen + APIEXTRA));
744 fatalbox("Out of memory");
747 st->to_read = st->biglen;
749 while (st->to_read > 0) {
750 st->chunk = st->to_read;
751 while ((*datalen) == 0)
752 crReturn(st->to_read);
753 if (st->chunk > (*datalen))
754 st->chunk = (*datalen);
755 memcpy(st->p, *data, st->chunk);
757 *datalen -= st->chunk;
759 st->to_read -= st->chunk;
762 if (cipher && detect_attack(pktin.data, st->biglen, NULL)) {
763 bombout(("Network attack (CRC compensation) detected!"));
768 cipher->decrypt(pktin.data, st->biglen);
770 st->realcrc = crc32(pktin.data, st->biglen - 4);
771 st->gotcrc = GET_32BIT(pktin.data + st->biglen - 4);
772 if (st->gotcrc != st->realcrc) {
773 bombout(("Incorrect CRC received on packet"));
777 pktin.body = pktin.data + st->pad + 1;
779 if (ssh1_compressing) {
780 unsigned char *decompblk;
782 zlib_decompress_block(pktin.body - 1, pktin.length + 1,
783 &decompblk, &decomplen);
785 if (pktin.maxlen < st->pad + decomplen) {
786 pktin.maxlen = st->pad + decomplen;
787 pktin.data = srealloc(pktin.data, pktin.maxlen + APIEXTRA);
788 pktin.body = pktin.data + st->pad + 1;
790 fatalbox("Out of memory");
793 memcpy(pktin.body - 1, decompblk, decomplen);
795 pktin.length = decomplen - 1;
798 pktin.type = pktin.body[-1];
800 log_packet(PKT_INCOMING, pktin.type, ssh1_pkt_type(pktin.type),
801 pktin.body, pktin.length);
803 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
804 pktin.type == SSH1_SMSG_STDERR_DATA ||
805 pktin.type == SSH1_MSG_DEBUG ||
806 pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE ||
807 pktin.type == SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
808 long stringlen = GET_32BIT(pktin.body);
809 if (stringlen + 4 != pktin.length) {
810 bombout(("Received data packet with bogus string length"));
815 if (pktin.type == SSH1_MSG_DEBUG) {
816 /* log debug message */
818 int stringlen = GET_32BIT(pktin.body);
819 strcpy(buf, "Remote debug message: ");
822 memcpy(buf + 8, pktin.body + 4, stringlen);
823 buf[8 + stringlen] = '\0';
826 } else if (pktin.type == SSH1_MSG_IGNORE) {
831 if (pktin.type == SSH1_MSG_DISCONNECT) {
832 /* log reason code in disconnect message */
834 unsigned msglen = GET_32BIT(pktin.body);
836 strcpy(buf, "Remote sent disconnect: ");
837 nowlen = strlen(buf);
838 if (msglen > sizeof(buf) - nowlen - 1)
839 msglen = sizeof(buf) - nowlen - 1;
840 memcpy(buf + nowlen, pktin.body + 4, msglen);
841 buf[nowlen + msglen] = '\0';
842 /* logevent(buf); (this is now done within the bombout macro) */
843 bombout(("Server sent disconnect message:\n\"%s\"", buf+nowlen));
850 static int ssh2_rdpkt(unsigned char **data, int *datalen)
852 struct rdpkt2_state_tag *st = &rdpkt2_state;
860 st->cipherblk = sccipher->blksize;
863 if (st->cipherblk < 8)
866 if (pktin.maxlen < st->cipherblk) {
867 pktin.maxlen = st->cipherblk;
870 NULL ? smalloc(st->cipherblk +
871 APIEXTRA) : srealloc(pktin.data,
875 fatalbox("Out of memory");
879 * Acquire and decrypt the first block of the packet. This will
880 * contain the length and padding details.
882 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
883 while ((*datalen) == 0)
884 crReturn(st->cipherblk - st->i);
885 pktin.data[st->i] = *(*data)++;
890 sccipher->decrypt(pktin.data, st->cipherblk);
893 * Now get the length and padding figures.
895 st->len = GET_32BIT(pktin.data);
896 st->pad = pktin.data[4];
899 * _Completely_ silly lengths should be stomped on before they
900 * do us any more damage.
902 if (st->len < 0 || st->pad < 0 || st->len + st->pad < 0) {
903 bombout(("Incoming packet was garbled on decryption"));
908 * This enables us to deduce the payload length.
910 st->payload = st->len - st->pad - 1;
912 pktin.length = st->payload + 5;
915 * So now we can work out the total packet length.
917 st->packetlen = st->len + 4;
918 st->maclen = scmac ? scmac->len : 0;
921 * Adjust memory allocation if packet is too big.
923 if (pktin.maxlen < st->packetlen + st->maclen) {
924 pktin.maxlen = st->packetlen + st->maclen;
927 NULL ? smalloc(pktin.maxlen + APIEXTRA) : srealloc(pktin.data,
932 fatalbox("Out of memory");
936 * Read and decrypt the remainder of the packet.
938 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
940 while ((*datalen) == 0)
941 crReturn(st->packetlen + st->maclen - st->i);
942 pktin.data[st->i] = *(*data)++;
945 /* Decrypt everything _except_ the MAC. */
947 sccipher->decrypt(pktin.data + st->cipherblk,
948 st->packetlen - st->cipherblk);
954 && !scmac->verify(pktin.data, st->len + 4,
955 st->incoming_sequence)) {
956 bombout(("Incorrect MAC received on packet"));
959 st->incoming_sequence++; /* whether or not we MACed */
962 * Decompress packet payload.
965 unsigned char *newpayload;
967 if (sccomp && sccomp->decompress(pktin.data + 5, pktin.length - 5,
968 &newpayload, &newlen)) {
969 if (pktin.maxlen < newlen + 5) {
970 pktin.maxlen = newlen + 5;
973 NULL ? smalloc(pktin.maxlen +
974 APIEXTRA) : srealloc(pktin.data,
978 fatalbox("Out of memory");
980 pktin.length = 5 + newlen;
981 memcpy(pktin.data + 5, newpayload, newlen);
987 pktin.type = pktin.data[5];
989 log_packet(PKT_INCOMING, pktin.type, ssh2_pkt_type(pktin.type),
990 pktin.data+6, pktin.length-6);
992 switch (pktin.type) {
994 * These packets we must handle instantly.
996 case SSH2_MSG_DISCONNECT:
998 /* log reason code in disconnect message */
1000 int reason = GET_32BIT(pktin.data + 6);
1001 unsigned msglen = GET_32BIT(pktin.data + 10);
1003 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
1004 sprintf(buf, "Received disconnect message (%s)",
1005 ssh2_disconnect_reasons[reason]);
1007 sprintf(buf, "Received disconnect message (unknown type %d)",
1011 strcpy(buf, "Disconnection message text: ");
1012 nowlen = strlen(buf);
1013 if (msglen > sizeof(buf) - nowlen - 1)
1014 msglen = sizeof(buf) - nowlen - 1;
1015 memcpy(buf + nowlen, pktin.data + 14, msglen);
1016 buf[nowlen + msglen] = '\0';
1018 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
1020 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
1021 ssh2_disconnect_reasons[reason] : "unknown",
1026 case SSH2_MSG_IGNORE:
1028 case SSH2_MSG_DEBUG:
1030 /* log the debug message */
1032 /* int display = pktin.body[6]; */
1033 int stringlen = GET_32BIT(pktin.data+7);
1035 strcpy(buf, "Remote debug message: ");
1036 prefix = strlen(buf);
1037 if (stringlen > sizeof(buf)-prefix-1)
1038 stringlen = sizeof(buf)-prefix-1;
1039 memcpy(buf + prefix, pktin.data + 11, stringlen);
1040 buf[prefix + stringlen] = '\0';
1043 goto next_packet; /* FIXME: print the debug message */
1046 * These packets we need do nothing about here.
1048 case SSH2_MSG_UNIMPLEMENTED:
1049 case SSH2_MSG_SERVICE_REQUEST:
1050 case SSH2_MSG_SERVICE_ACCEPT:
1051 case SSH2_MSG_KEXINIT:
1052 case SSH2_MSG_NEWKEYS:
1053 case SSH2_MSG_KEXDH_INIT:
1054 case SSH2_MSG_KEXDH_REPLY:
1055 /* case SSH2_MSG_KEX_DH_GEX_REQUEST: duplicate case value */
1056 /* case SSH2_MSG_KEX_DH_GEX_GROUP: duplicate case value */
1057 case SSH2_MSG_KEX_DH_GEX_INIT:
1058 case SSH2_MSG_KEX_DH_GEX_REPLY:
1059 case SSH2_MSG_USERAUTH_REQUEST:
1060 case SSH2_MSG_USERAUTH_FAILURE:
1061 case SSH2_MSG_USERAUTH_SUCCESS:
1062 case SSH2_MSG_USERAUTH_BANNER:
1063 case SSH2_MSG_USERAUTH_PK_OK:
1064 /* case SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ: duplicate case value */
1065 /* case SSH2_MSG_USERAUTH_INFO_REQUEST: duplicate case value */
1066 case SSH2_MSG_USERAUTH_INFO_RESPONSE:
1067 case SSH2_MSG_GLOBAL_REQUEST:
1068 case SSH2_MSG_REQUEST_SUCCESS:
1069 case SSH2_MSG_REQUEST_FAILURE:
1070 case SSH2_MSG_CHANNEL_OPEN:
1071 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
1072 case SSH2_MSG_CHANNEL_OPEN_FAILURE:
1073 case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
1074 case SSH2_MSG_CHANNEL_DATA:
1075 case SSH2_MSG_CHANNEL_EXTENDED_DATA:
1076 case SSH2_MSG_CHANNEL_EOF:
1077 case SSH2_MSG_CHANNEL_CLOSE:
1078 case SSH2_MSG_CHANNEL_REQUEST:
1079 case SSH2_MSG_CHANNEL_SUCCESS:
1080 case SSH2_MSG_CHANNEL_FAILURE:
1084 * For anything else we send SSH2_MSG_UNIMPLEMENTED.
1087 ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
1088 ssh2_pkt_adduint32(st->incoming_sequence - 1);
1096 static void ssh1_pktout_size(int len)
1100 len += 5; /* type and CRC */
1101 pad = 8 - (len % 8);
1104 pktout.length = len - 5;
1105 if (pktout.maxlen < biglen) {
1106 pktout.maxlen = biglen;
1108 /* Allocate enough buffer space for extra block
1109 * for MS CryptEncrypt() */
1110 pktout.data = (pktout.data == NULL ? smalloc(biglen + 12) :
1111 srealloc(pktout.data, biglen + 12));
1113 pktout.data = (pktout.data == NULL ? smalloc(biglen + 4) :
1114 srealloc(pktout.data, biglen + 4));
1117 fatalbox("Out of memory");
1119 pktout.body = pktout.data + 4 + pad + 1;
1122 static void s_wrpkt_start(int type, int len)
1124 ssh1_pktout_size(len);
1128 static int s_wrpkt_prepare(void)
1130 int pad, len, biglen, i;
1133 pktout.body[-1] = pktout.type;
1135 log_packet(PKT_OUTGOING, pktout.type, ssh1_pkt_type(pktout.type),
1136 pktout.body, pktout.length);
1138 if (ssh1_compressing) {
1139 unsigned char *compblk;
1141 zlib_compress_block(pktout.body - 1, pktout.length + 1,
1142 &compblk, &complen);
1143 ssh1_pktout_size(complen - 1);
1144 memcpy(pktout.body - 1, compblk, complen);
1148 len = pktout.length + 5; /* type and CRC */
1149 pad = 8 - (len % 8);
1152 for (i = 0; i < pad; i++)
1153 pktout.data[i + 4] = random_byte();
1154 crc = crc32(pktout.data + 4, biglen - 4);
1155 PUT_32BIT(pktout.data + biglen, crc);
1156 PUT_32BIT(pktout.data, len);
1159 cipher->encrypt(pktout.data + 4, biglen);
1164 static void s_wrpkt(void)
1167 len = s_wrpkt_prepare();
1168 backlog = sk_write(s, pktout.data, len);
1169 if (backlog > SSH_MAX_BACKLOG)
1170 ssh_throttle_all(1, backlog);
1173 static void s_wrpkt_defer(void)
1176 len = s_wrpkt_prepare();
1177 if (deferred_len + len > deferred_size) {
1178 deferred_size = deferred_len + len + 128;
1179 deferred_send_data = srealloc(deferred_send_data, deferred_size);
1181 memcpy(deferred_send_data + deferred_len, pktout.data, len);
1182 deferred_len += len;
1186 * Construct a packet with the specified contents.
1188 static void construct_packet(int pkttype, va_list ap1, va_list ap2)
1190 unsigned char *p, *argp, argchar;
1191 unsigned long argint;
1192 int pktlen, argtype, arglen;
1196 while ((argtype = va_arg(ap1, int)) != PKT_END) {
1199 (void) va_arg(ap1, int);
1203 (void) va_arg(ap1, char);
1207 (void) va_arg(ap1, unsigned char *);
1208 arglen = va_arg(ap1, int);
1212 argp = va_arg(ap1, unsigned char *);
1213 arglen = strlen(argp);
1214 pktlen += 4 + arglen;
1217 bn = va_arg(ap1, Bignum);
1218 pktlen += ssh1_bignum_length(bn);
1225 s_wrpkt_start(pkttype, pktlen);
1228 while ((argtype = va_arg(ap2, int)) != PKT_END) {
1231 argint = va_arg(ap2, int);
1232 PUT_32BIT(p, argint);
1236 argchar = va_arg(ap2, unsigned char);
1241 argp = va_arg(ap2, unsigned char *);
1242 arglen = va_arg(ap2, int);
1243 memcpy(p, argp, arglen);
1247 argp = va_arg(ap2, unsigned char *);
1248 arglen = strlen(argp);
1249 PUT_32BIT(p, arglen);
1250 memcpy(p + 4, argp, arglen);
1254 bn = va_arg(ap2, Bignum);
1255 p += ssh1_write_bignum(p, bn);
1261 static void send_packet(int pkttype, ...)
1264 va_start(ap1, pkttype);
1265 va_start(ap2, pkttype);
1266 construct_packet(pkttype, ap1, ap2);
1270 static void defer_packet(int pkttype, ...)
1273 va_start(ap1, pkttype);
1274 va_start(ap2, pkttype);
1275 construct_packet(pkttype, ap1, ap2);
1279 static int ssh_versioncmp(char *a, char *b)
1282 unsigned long av, bv;
1284 av = strtoul(a, &ae, 10);
1285 bv = strtoul(b, &be, 10);
1287 return (av < bv ? -1 : +1);
1292 av = strtoul(ae, &ae, 10);
1293 bv = strtoul(be, &be, 10);
1295 return (av < bv ? -1 : +1);
1301 * Utility routines for putting an SSH-protocol `string' and
1302 * `uint32' into a SHA state.
1305 static void sha_string(SHA_State * s, void *str, int len)
1307 unsigned char lenblk[4];
1308 PUT_32BIT(lenblk, len);
1309 SHA_Bytes(s, lenblk, 4);
1310 SHA_Bytes(s, str, len);
1313 static void sha_uint32(SHA_State * s, unsigned i)
1315 unsigned char intblk[4];
1316 PUT_32BIT(intblk, i);
1317 SHA_Bytes(s, intblk, 4);
1321 * SSH2 packet construction functions.
1323 static void ssh2_pkt_ensure(int length)
1325 if (pktout.maxlen < length) {
1326 pktout.maxlen = length + 256;
1329 NULL ? smalloc(pktout.maxlen +
1330 APIEXTRA) : srealloc(pktout.data,
1334 fatalbox("Out of memory");
1337 static void ssh2_pkt_adddata(void *data, int len)
1339 pktout.length += len;
1340 ssh2_pkt_ensure(pktout.length);
1341 memcpy(pktout.data + pktout.length - len, data, len);
1343 static void ssh2_pkt_addbyte(unsigned char byte)
1345 ssh2_pkt_adddata(&byte, 1);
1347 static void ssh2_pkt_init(int pkt_type)
1350 ssh2_pkt_addbyte((unsigned char) pkt_type);
1352 static void ssh2_pkt_addbool(unsigned char value)
1354 ssh2_pkt_adddata(&value, 1);
1356 static void ssh2_pkt_adduint32(unsigned long value)
1359 PUT_32BIT(x, value);
1360 ssh2_pkt_adddata(x, 4);
1362 static void ssh2_pkt_addstring_start(void)
1364 ssh2_pkt_adduint32(0);
1365 pktout.savedpos = pktout.length;
1367 static void ssh2_pkt_addstring_str(char *data)
1369 ssh2_pkt_adddata(data, strlen(data));
1370 PUT_32BIT(pktout.data + pktout.savedpos - 4,
1371 pktout.length - pktout.savedpos);
1373 static void ssh2_pkt_addstring_data(char *data, int len)
1375 ssh2_pkt_adddata(data, len);
1376 PUT_32BIT(pktout.data + pktout.savedpos - 4,
1377 pktout.length - pktout.savedpos);
1379 static void ssh2_pkt_addstring(char *data)
1381 ssh2_pkt_addstring_start();
1382 ssh2_pkt_addstring_str(data);
1384 static char *ssh2_mpint_fmt(Bignum b, int *len)
1387 int i, n = (bignum_bitcount(b) + 7) / 8;
1390 fatalbox("out of memory");
1392 for (i = 1; i <= n; i++)
1393 p[i] = bignum_byte(b, n - i);
1395 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1397 memmove(p, p + i, n + 1 - i);
1401 static void ssh2_pkt_addmp(Bignum b)
1405 p = ssh2_mpint_fmt(b, &len);
1406 ssh2_pkt_addstring_start();
1407 ssh2_pkt_addstring_data(p, len);
1412 * Construct an SSH2 final-form packet: compress it, encrypt it,
1413 * put the MAC on it. Final packet, ready to be sent, is stored in
1414 * pktout.data. Total length is returned.
1416 static int ssh2_pkt_construct(void)
1418 int cipherblk, maclen, padding, i;
1419 static unsigned long outgoing_sequence = 0;
1421 log_packet(PKT_OUTGOING, pktout.data[5], ssh2_pkt_type(pktout.data[5]),
1422 pktout.data + 6, pktout.length - 6);
1425 * Compress packet payload.
1428 unsigned char *newpayload;
1430 if (cscomp && cscomp->compress(pktout.data + 5, pktout.length - 5,
1431 &newpayload, &newlen)) {
1433 ssh2_pkt_adddata(newpayload, newlen);
1439 * Add padding. At least four bytes, and must also bring total
1440 * length (minus MAC) up to a multiple of the block size.
1442 cipherblk = cscipher ? cscipher->blksize : 8; /* block size */
1443 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1446 (cipherblk - (pktout.length + padding) % cipherblk) % cipherblk;
1447 maclen = csmac ? csmac->len : 0;
1448 ssh2_pkt_ensure(pktout.length + padding + maclen);
1449 pktout.data[4] = padding;
1450 for (i = 0; i < padding; i++)
1451 pktout.data[pktout.length + i] = random_byte();
1452 PUT_32BIT(pktout.data, pktout.length + padding - 4);
1454 csmac->generate(pktout.data, pktout.length + padding,
1456 outgoing_sequence++; /* whether or not we MACed */
1459 cscipher->encrypt(pktout.data, pktout.length + padding);
1461 /* Ready-to-send packet starts at pktout.data. We return length. */
1462 return pktout.length + padding + maclen;
1466 * Construct and send an SSH2 packet immediately.
1468 static void ssh2_pkt_send(void)
1472 len = ssh2_pkt_construct();
1473 backlog = sk_write(s, pktout.data, len);
1474 if (backlog > SSH_MAX_BACKLOG)
1475 ssh_throttle_all(1, backlog);
1479 * Construct an SSH2 packet and add it to a deferred data block.
1480 * Useful for sending multiple packets in a single sk_write() call,
1481 * to prevent a traffic-analysing listener from being able to work
1482 * out the length of any particular packet (such as the password
1485 * Note that because SSH2 sequence-numbers its packets, this can
1486 * NOT be used as an m4-style `defer' allowing packets to be
1487 * constructed in one order and sent in another.
1489 static void ssh2_pkt_defer(void)
1491 int len = ssh2_pkt_construct();
1492 if (deferred_len + len > deferred_size) {
1493 deferred_size = deferred_len + len + 128;
1494 deferred_send_data = srealloc(deferred_send_data, deferred_size);
1496 memcpy(deferred_send_data + deferred_len, pktout.data, len);
1497 deferred_len += len;
1501 * Send the whole deferred data block constructed by
1502 * ssh2_pkt_defer() or SSH1's defer_packet().
1504 static void ssh_pkt_defersend(void)
1507 backlog = sk_write(s, deferred_send_data, deferred_len);
1508 deferred_len = deferred_size = 0;
1509 sfree(deferred_send_data);
1510 deferred_send_data = NULL;
1511 if (backlog > SSH_MAX_BACKLOG)
1512 ssh_throttle_all(1, backlog);
1516 void bndebug(char *string, Bignum b)
1520 p = ssh2_mpint_fmt(b, &len);
1521 debug(("%s", string));
1522 for (i = 0; i < len; i++)
1523 debug((" %02x", p[i]));
1529 static void sha_mpint(SHA_State * s, Bignum b)
1533 p = ssh2_mpint_fmt(b, &len);
1534 sha_string(s, p, len);
1539 * SSH2 packet decode functions.
1541 static unsigned long ssh2_pkt_getuint32(void)
1543 unsigned long value;
1544 if (pktin.length - pktin.savedpos < 4)
1545 return 0; /* arrgh, no way to decline (FIXME?) */
1546 value = GET_32BIT(pktin.data + pktin.savedpos);
1547 pktin.savedpos += 4;
1550 static int ssh2_pkt_getbool(void)
1552 unsigned long value;
1553 if (pktin.length - pktin.savedpos < 1)
1554 return 0; /* arrgh, no way to decline (FIXME?) */
1555 value = pktin.data[pktin.savedpos] != 0;
1559 static void ssh2_pkt_getstring(char **p, int *length)
1563 if (pktin.length - pktin.savedpos < 4)
1565 *length = GET_32BIT(pktin.data + pktin.savedpos);
1566 pktin.savedpos += 4;
1567 if (pktin.length - pktin.savedpos < *length)
1569 *p = pktin.data + pktin.savedpos;
1570 pktin.savedpos += *length;
1572 static Bignum ssh2_pkt_getmp(void)
1578 ssh2_pkt_getstring(&p, &length);
1582 bombout(("internal error: Can't handle negative mpints"));
1585 b = bignum_from_bytes(p, length);
1590 * Helper function to add an SSH2 signature blob to a packet.
1591 * Expects to be shown the public key blob as well as the signature
1592 * blob. Normally works just like ssh2_pkt_addstring, but will
1593 * fiddle with the signature packet if necessary for
1594 * BUG_SSH2_RSA_PADDING.
1596 static void ssh2_add_sigblob(void *pkblob_v, int pkblob_len,
1597 void *sigblob_v, int sigblob_len)
1599 unsigned char *pkblob = (unsigned char *)pkblob_v;
1600 unsigned char *sigblob = (unsigned char *)sigblob_v;
1602 /* dmemdump(pkblob, pkblob_len); */
1603 /* dmemdump(sigblob, sigblob_len); */
1606 * See if this is in fact an ssh-rsa signature and a buggy
1607 * server; otherwise we can just do this the easy way.
1609 if ((ssh_remote_bugs & BUG_SSH2_RSA_PADDING) &&
1610 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
1611 int pos, len, siglen;
1614 * Find the byte length of the modulus.
1617 pos = 4+7; /* skip over "ssh-rsa" */
1618 pos += 4 + GET_32BIT(pkblob+pos); /* skip over exponent */
1619 len = GET_32BIT(pkblob+pos); /* find length of modulus */
1620 pos += 4; /* find modulus itself */
1621 while (len > 0 && pkblob[pos] == 0)
1623 /* debug(("modulus length is %d\n", len)); */
1626 * Now find the signature integer.
1628 pos = 4+7; /* skip over "ssh-rsa" */
1629 siglen = GET_32BIT(sigblob+pos);
1630 /* debug(("signature length is %d\n", siglen)); */
1632 if (len != siglen) {
1633 unsigned char newlen[4];
1634 ssh2_pkt_addstring_start();
1635 ssh2_pkt_addstring_data(sigblob, pos);
1636 /* dmemdump(sigblob, pos); */
1637 pos += 4; /* point to start of actual sig */
1638 PUT_32BIT(newlen, len);
1639 ssh2_pkt_addstring_data(newlen, 4);
1640 /* dmemdump(newlen, 4); */
1642 while (len-- > siglen) {
1643 ssh2_pkt_addstring_data(newlen, 1);
1644 /* dmemdump(newlen, 1); */
1646 ssh2_pkt_addstring_data(sigblob+pos, siglen);
1647 /* dmemdump(sigblob+pos, siglen); */
1651 /* Otherwise fall through and do it the easy way. */
1654 ssh2_pkt_addstring_start();
1655 ssh2_pkt_addstring_data(sigblob, sigblob_len);
1659 * Examine the remote side's version string and compare it against
1660 * a list of known buggy implementations.
1662 static void ssh_detect_bugs(char *vstring)
1664 char *imp; /* pointer to implementation part */
1666 imp += strcspn(imp, "-");
1668 imp += strcspn(imp, "-");
1671 ssh_remote_bugs = 0;
1673 if (cfg.sshbug_ignore1 == BUG_ON ||
1674 (cfg.sshbug_ignore1 == BUG_AUTO &&
1675 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
1676 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
1677 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25")))) {
1679 * These versions don't support SSH1_MSG_IGNORE, so we have
1680 * to use a different defence against password length
1683 ssh_remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
1684 logevent("We believe remote version has SSH1 ignore bug");
1687 if (cfg.sshbug_plainpw1 == BUG_ON ||
1688 (cfg.sshbug_plainpw1 == BUG_AUTO &&
1689 (!strcmp(imp, "Cisco-1.25")))) {
1691 * These versions need a plain password sent; they can't
1692 * handle having a null and a random length of data after
1695 ssh_remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
1696 logevent("We believe remote version needs a plain SSH1 password");
1699 if (cfg.sshbug_rsa1 == BUG_ON ||
1700 (cfg.sshbug_rsa1 == BUG_AUTO &&
1701 (!strcmp(imp, "Cisco-1.25")))) {
1703 * These versions apparently have no clue whatever about
1704 * RSA authentication and will panic and die if they see
1705 * an AUTH_RSA message.
1707 ssh_remote_bugs |= BUG_CHOKES_ON_RSA;
1708 logevent("We believe remote version can't handle RSA authentication");
1711 if (cfg.sshbug_hmac2 == BUG_ON ||
1712 (cfg.sshbug_hmac2 == BUG_AUTO &&
1713 (!strncmp(imp, "2.1.0", 5) || !strncmp(imp, "2.0.", 4) ||
1714 !strncmp(imp, "2.2.0", 5) || !strncmp(imp, "2.3.0", 5) ||
1715 !strncmp(imp, "2.1 ", 4)))) {
1717 * These versions have the HMAC bug.
1719 ssh_remote_bugs |= BUG_SSH2_HMAC;
1720 logevent("We believe remote version has SSH2 HMAC bug");
1723 if (cfg.sshbug_derivekey2 == BUG_ON ||
1724 (cfg.sshbug_derivekey2 == BUG_AUTO &&
1725 (!strncmp(imp, "2.0.", 4)))) {
1727 * These versions have the key-derivation bug (failing to
1728 * include the literal shared secret in the hashes that
1729 * generate the keys).
1731 ssh_remote_bugs |= BUG_SSH2_DERIVEKEY;
1732 logevent("We believe remote version has SSH2 key-derivation bug");
1735 if (cfg.sshbug_rsapad2 == BUG_ON ||
1736 (cfg.sshbug_rsapad2 == BUG_AUTO &&
1737 ((!strncmp(imp, "OpenSSH_2.", 10) && imp[10]>='5' && imp[10]<='9') ||
1738 (!strncmp(imp, "OpenSSH_3.", 10) && imp[10]>='0' && imp[10]<='2')))){
1740 * These versions have the SSH2 RSA padding bug.
1742 ssh_remote_bugs |= BUG_SSH2_RSA_PADDING;
1743 logevent("We believe remote version has SSH2 RSA padding bug");
1747 static int do_ssh_init(unsigned char c)
1750 static char version[10];
1751 static char *vstring;
1752 static int vstrsize;
1755 static int proto1, proto2;
1759 /* Search for the string "SSH-" in the input. */
1762 static const int transS[] = { 1, 2, 2, 1 };
1763 static const int transH[] = { 0, 0, 3, 0 };
1764 static const int transminus[] = { 0, 0, 0, -1 };
1775 crReturn(1); /* get another character */
1779 vstring = smalloc(vstrsize);
1780 strcpy(vstring, "SSH-");
1784 crReturn(1); /* get another char */
1785 if (vslen >= vstrsize - 1) {
1787 vstring = srealloc(vstring, vstrsize);
1789 vstring[vslen++] = c;
1794 } else if (i < sizeof(version) - 1)
1796 } else if (c == '\n')
1800 ssh_agentfwd_enabled = FALSE;
1801 rdpkt2_state.incoming_sequence = 0;
1804 vlog = smalloc(20 + vslen);
1805 vstring[strcspn (vstring, "\r\n")] = '\0'; /* remove end-of-line chars */
1806 sprintf(vlog, "Server version: %s", vstring);
1808 ssh_detect_bugs(vstring);
1812 * Decide which SSH protocol version to support.
1815 /* Anything strictly below "2.0" means protocol 1 is supported. */
1816 proto1 = ssh_versioncmp(version, "2.0") < 0;
1817 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
1818 proto2 = ssh_versioncmp(version, "1.99") >= 0;
1820 if (cfg.sshprot == 0 && !proto1) {
1821 bombout(("SSH protocol version 1 required by user but not provided by server"));
1824 if (cfg.sshprot == 3 && !proto2) {
1825 bombout(("SSH protocol version 2 required by user but not provided by server"));
1829 if (proto2 && (cfg.sshprot >= 2 || !proto1)) {
1833 char verstring[80], vlog[100];
1834 sprintf(verstring, "SSH-2.0-%s", sshver);
1835 SHA_Init(&exhashbase);
1837 * Hash our version string and their version string.
1839 sha_string(&exhashbase, verstring, strlen(verstring));
1840 sha_string(&exhashbase, vstring, strcspn(vstring, "\r\n"));
1841 sprintf(vlog, "We claim version: %s", verstring);
1843 strcat(verstring, "\n");
1844 logevent("Using SSH protocol version 2");
1845 sk_write(s, verstring, strlen(verstring));
1846 ssh_protocol = ssh2_protocol;
1848 s_rdpkt = ssh2_rdpkt;
1853 char verstring[80], vlog[100];
1854 sprintf(verstring, "SSH-%s-%s",
1855 (ssh_versioncmp(version, "1.5") <= 0 ? version : "1.5"),
1857 sprintf(vlog, "We claim version: %s", verstring);
1859 strcat(verstring, "\n");
1861 logevent("Using SSH protocol version 1");
1862 sk_write(s, verstring, strlen(verstring));
1863 ssh_protocol = ssh1_protocol;
1865 s_rdpkt = ssh1_rdpkt;
1867 ssh_state = SSH_STATE_BEFORE_SIZE;
1874 static void ssh_gotdata(unsigned char *data, int datalen)
1879 * To begin with, feed the characters one by one to the
1880 * protocol initialisation / selection function do_ssh_init().
1881 * When that returns 0, we're done with the initial greeting
1882 * exchange and can move on to packet discipline.
1887 crReturnV; /* more data please */
1888 ret = do_ssh_init(*data);
1896 * We emerge from that loop when the initial negotiation is
1897 * over and we have selected an s_rdpkt function. Now pass
1898 * everything to s_rdpkt, and then pass the resulting packets
1899 * to the proper protocol handler.
1904 while (datalen > 0) {
1905 if (s_rdpkt(&data, &datalen) == 0) {
1906 if (ssh_state == SSH_STATE_CLOSED) {
1909 ssh_protocol(NULL, 0, 1);
1910 if (ssh_state == SSH_STATE_CLOSED) {
1920 static int ssh_closing(Plug plug, char *error_msg, int error_code,
1923 ssh_state = SSH_STATE_CLOSED;
1929 /* A socket error has occurred. */
1930 logevent(error_msg);
1931 connection_fatal(error_msg);
1933 /* Otherwise, the remote side closed the connection normally. */
1938 static int ssh_receive(Plug plug, int urgent, char *data, int len)
1940 ssh_gotdata(data, len);
1941 if (ssh_state == SSH_STATE_CLOSED) {
1951 static void ssh_sent(Plug plug, int bufsize)
1954 * If the send backlog on the SSH socket itself clears, we
1955 * should unthrottle the whole world if it was throttled.
1957 if (bufsize < SSH_MAX_BACKLOG)
1958 ssh_throttle_all(0, bufsize);
1962 * Connect to specified host and port.
1963 * Returns an error message, or NULL on success.
1964 * Also places the canonical host name into `realhost'. It must be
1965 * freed by the caller.
1967 static char *connect_to_host(char *host, int port, char **realhost, int nodelay)
1969 static struct plug_function_table fn_table = {
1974 }, *fn_table_ptr = &fn_table;
1983 savedhost = smalloc(1 + strlen(host));
1985 fatalbox("Out of memory");
1986 strcpy(savedhost, host);
1989 port = 22; /* default ssh port */
2004 sprintf(buf, "Looking up host \"%.170s\"", host);
2007 addr = sk_namelookup(host, realhost);
2008 if ((err = sk_addr_error(addr)))
2012 *realhost = strdup(FWhost);
2019 char buf[200], addrbuf[100];
2020 sk_getaddr(addr, addrbuf, 100);
2021 sprintf(buf, "Connecting to %.100s port %d", addrbuf, port);
2024 s = new_connection(addr, *realhost, port, 0, 1, nodelay, &fn_table_ptr);
2025 if ((err = sk_socket_error(s))) {
2031 sk_write(s, "connect ", 8);
2032 sk_write(s, FWhost, strlen(FWhost));
2035 sprintf(buf, " %d\n", FWport);
2036 sk_write(s, buf, strlen(buf));
2044 * Throttle or unthrottle the SSH connection.
2046 static void ssh1_throttle(int adjust)
2048 int old_count = ssh1_throttle_count;
2049 ssh1_throttle_count += adjust;
2050 assert(ssh1_throttle_count >= 0);
2051 if (ssh1_throttle_count && !old_count) {
2052 sk_set_frozen(s, 1);
2053 } else if (!ssh1_throttle_count && old_count) {
2054 sk_set_frozen(s, 0);
2059 * Throttle or unthrottle _all_ local data streams (for when sends
2060 * on the SSH connection itself back up).
2062 static void ssh_throttle_all(int enable, int bufsize)
2065 struct ssh_channel *c;
2067 if (enable == ssh_throttled_all)
2069 ssh_throttled_all = enable;
2070 ssh_overall_bufsize = bufsize;
2073 for (i = 0; NULL != (c = index234(ssh_channels, i)); i++) {
2075 case CHAN_MAINSESSION:
2077 * This is treated separately, outside the switch.
2081 x11_override_throttle(c->u.x11.s, enable);
2084 /* Agent channels require no buffer management. */
2087 pfd_override_throttle(c->u.x11.s, enable);
2094 * Username and password input, abstracted off into reusable
2095 * routines (hopefully even reusable between SSH1 and SSH2!).
2097 static char *ssh_userpass_input_buffer;
2098 static int ssh_userpass_input_buflen;
2099 static int ssh_userpass_input_bufpos;
2100 static int ssh_userpass_input_echo;
2102 /* Set up a username or password input loop on a given buffer. */
2103 void setup_userpass_input(char *buffer, int buflen, int echo)
2105 ssh_userpass_input_buffer = buffer;
2106 ssh_userpass_input_buflen = buflen;
2107 ssh_userpass_input_bufpos = 0;
2108 ssh_userpass_input_echo = echo;
2112 * Process some terminal data in the course of username/password
2113 * input. Returns >0 for success (line of input returned in
2114 * buffer), <0 for failure (user hit ^C/^D, bomb out and exit), 0
2115 * for inconclusive (keep waiting for more input please).
2117 int process_userpass_input(unsigned char *in, int inlen)
2122 switch (c = *in++) {
2125 ssh_userpass_input_buffer[ssh_userpass_input_bufpos] = 0;
2126 ssh_userpass_input_buffer[ssh_userpass_input_buflen-1] = 0;
2131 if (ssh_userpass_input_bufpos > 0) {
2132 if (ssh_userpass_input_echo)
2133 c_write_str("\b \b");
2134 ssh_userpass_input_bufpos--;
2139 while (ssh_userpass_input_bufpos > 0) {
2140 if (ssh_userpass_input_echo)
2141 c_write_str("\b \b");
2142 ssh_userpass_input_bufpos--;
2150 if (((c >= ' ' && c <= '~') ||
2151 ((unsigned char) c >= 160))
2152 && ssh_userpass_input_bufpos < ssh_userpass_input_buflen-1) {
2153 ssh_userpass_input_buffer[ssh_userpass_input_bufpos++] = c;
2154 if (ssh_userpass_input_echo)
2164 * Handle the key exchange and user authentication phases.
2166 static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
2170 static unsigned char *rsabuf, *keystr1, *keystr2;
2171 unsigned char cookie[8];
2172 struct RSAKey servkey, hostkey;
2173 struct MD5Context md5c;
2174 static unsigned long supported_ciphers_mask, supported_auths_mask;
2175 static int tried_publickey, tried_agent;
2176 static int tis_auth_refused, ccard_auth_refused;
2177 static unsigned char session_id[16];
2178 static int cipher_type;
2179 static char username[100];
2180 static void *publickey_blob;
2181 int publickey_bloblen;
2188 if (pktin.type != SSH1_SMSG_PUBLIC_KEY) {
2189 bombout(("Public key packet not received"));
2193 logevent("Received public keys");
2195 memcpy(cookie, pktin.body, 8);
2197 i = makekey(pktin.body + 8, &servkey, &keystr1, 0);
2198 j = makekey(pktin.body + 8 + i, &hostkey, &keystr2, 0);
2201 * Log the host key fingerprint.
2205 logevent("Host key fingerprint is:");
2206 strcpy(logmsg, " ");
2207 hostkey.comment = NULL;
2208 rsa_fingerprint(logmsg + strlen(logmsg),
2209 sizeof(logmsg) - strlen(logmsg), &hostkey);
2213 ssh1_remote_protoflags = GET_32BIT(pktin.body + 8 + i + j);
2214 supported_ciphers_mask = GET_32BIT(pktin.body + 12 + i + j);
2215 supported_auths_mask = GET_32BIT(pktin.body + 16 + i + j);
2217 ssh1_local_protoflags =
2218 ssh1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
2219 ssh1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
2222 MD5Update(&md5c, keystr2, hostkey.bytes);
2223 MD5Update(&md5c, keystr1, servkey.bytes);
2224 MD5Update(&md5c, pktin.body, 8);
2225 MD5Final(session_id, &md5c);
2227 for (i = 0; i < 32; i++)
2228 session_key[i] = random_byte();
2230 len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
2232 rsabuf = smalloc(len);
2234 fatalbox("Out of memory");
2237 * Verify the host key.
2241 * First format the key into a string.
2243 int len = rsastr_len(&hostkey);
2244 char fingerprint[100];
2245 char *keystr = smalloc(len);
2247 fatalbox("Out of memory");
2248 rsastr_fmt(keystr, &hostkey);
2249 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
2250 verify_ssh_host_key(savedhost, savedport, "rsa", keystr,
2255 for (i = 0; i < 32; i++) {
2256 rsabuf[i] = session_key[i];
2258 rsabuf[i] ^= session_id[i];
2261 if (hostkey.bytes > servkey.bytes) {
2262 rsaencrypt(rsabuf, 32, &servkey);
2263 rsaencrypt(rsabuf, servkey.bytes, &hostkey);
2265 rsaencrypt(rsabuf, 32, &hostkey);
2266 rsaencrypt(rsabuf, hostkey.bytes, &servkey);
2269 logevent("Encrypted session key");
2272 int cipher_chosen = 0, warn = 0;
2273 char *cipher_string = NULL;
2274 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
2275 int next_cipher = cfg.ssh_cipherlist[i];
2276 if (next_cipher == CIPHER_WARN) {
2277 /* If/when we choose a cipher, warn about it */
2279 } else if (next_cipher == CIPHER_AES) {
2280 /* XXX Probably don't need to mention this. */
2281 logevent("AES not supported in SSH1, skipping");
2283 switch (next_cipher) {
2284 case CIPHER_3DES: cipher_type = SSH_CIPHER_3DES;
2285 cipher_string = "3DES"; break;
2286 case CIPHER_BLOWFISH: cipher_type = SSH_CIPHER_BLOWFISH;
2287 cipher_string = "Blowfish"; break;
2288 case CIPHER_DES: cipher_type = SSH_CIPHER_DES;
2289 cipher_string = "single-DES"; break;
2291 if (supported_ciphers_mask & (1 << cipher_type))
2295 if (!cipher_chosen) {
2296 if ((supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
2297 bombout(("Server violates SSH 1 protocol by not "
2298 "supporting 3DES encryption"));
2300 /* shouldn't happen */
2301 bombout(("No supported ciphers found"));
2305 /* Warn about chosen cipher if necessary. */
2307 askcipher(cipher_string, 0);
2310 switch (cipher_type) {
2311 case SSH_CIPHER_3DES:
2312 logevent("Using 3DES encryption");
2314 case SSH_CIPHER_DES:
2315 logevent("Using single-DES encryption");
2317 case SSH_CIPHER_BLOWFISH:
2318 logevent("Using Blowfish encryption");
2322 send_packet(SSH1_CMSG_SESSION_KEY,
2323 PKT_CHAR, cipher_type,
2324 PKT_DATA, cookie, 8,
2325 PKT_CHAR, (len * 8) >> 8, PKT_CHAR, (len * 8) & 0xFF,
2326 PKT_DATA, rsabuf, len,
2327 PKT_INT, ssh1_local_protoflags, PKT_END);
2329 logevent("Trying to enable encryption...");
2333 cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
2334 cipher_type == SSH_CIPHER_DES ? &ssh_des : &ssh_3des;
2335 cipher->sesskey(session_key);
2339 if (pktin.type != SSH1_SMSG_SUCCESS) {
2340 bombout(("Encryption not successfully enabled"));
2344 logevent("Successfully started encryption");
2348 if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
2349 if (ssh_get_line && !ssh_getline_pw_only) {
2350 if (!ssh_get_line("login as: ",
2351 username, sizeof(username), FALSE)) {
2353 * get_line failed to get a username.
2356 logevent("No username provided. Abandoning session.");
2357 ssh_state = SSH_STATE_CLOSED;
2362 c_write_str("login as: ");
2365 setup_userpass_input(username, sizeof(username), 1);
2367 crWaitUntil(!ispkt);
2368 ret = process_userpass_input(in, inlen);
2372 c_write_str("\r\n");
2375 strncpy(username, cfg.username, sizeof(username));
2376 username[sizeof(username)-1] = '\0';
2379 send_packet(SSH1_CMSG_USER, PKT_STR, username, PKT_END);
2381 char userlog[22 + sizeof(username)];
2382 sprintf(userlog, "Sent username \"%s\"", username);
2384 if (flags & FLAG_INTERACTIVE &&
2385 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
2386 strcat(userlog, "\r\n");
2387 c_write_str(userlog);
2394 if ((ssh_remote_bugs & BUG_CHOKES_ON_RSA)) {
2395 /* We must not attempt PK auth. Pretend we've already tried it. */
2396 tried_publickey = tried_agent = 1;
2398 tried_publickey = tried_agent = 0;
2400 tis_auth_refused = ccard_auth_refused = 0;
2401 /* Load the public half of cfg.keyfile so we notice if it's in Pageant */
2403 if (!rsakey_pubblob(cfg.keyfile, &publickey_blob, &publickey_bloblen))
2404 publickey_blob = NULL;
2406 publickey_blob = NULL;
2408 while (pktin.type == SSH1_SMSG_FAILURE) {
2409 static char password[100];
2410 static char prompt[200];
2413 static int pwpkt_type;
2414 pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
2416 if (agent_exists() && !tried_agent) {
2418 * Attempt RSA authentication using Pageant.
2420 static unsigned char request[5], *response, *p;
2421 static int responselen;
2422 static int i, nkeys;
2423 static int authed = FALSE;
2427 logevent("Pageant is running. Requesting keys.");
2429 /* Request the keys held by the agent. */
2430 PUT_32BIT(request, 1);
2431 request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
2432 agent_query(request, 5, &r, &responselen);
2433 response = (unsigned char *) r;
2434 if (response && responselen >= 5 &&
2435 response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
2437 nkeys = GET_32BIT(p);
2441 sprintf(buf, "Pageant has %d SSH1 keys", nkeys);
2444 for (i = 0; i < nkeys; i++) {
2445 static struct RSAKey key;
2446 static Bignum challenge;
2447 static char *commentp;
2448 static int commentlen;
2452 sprintf(buf, "Trying Pageant key #%d", i);
2455 if (publickey_blob &&
2456 !memcmp(p, publickey_blob, publickey_bloblen)) {
2457 logevent("This key matches configured key file");
2458 tried_publickey = 1;
2461 p += ssh1_read_bignum(p, &key.exponent);
2462 p += ssh1_read_bignum(p, &key.modulus);
2463 commentlen = GET_32BIT(p);
2467 send_packet(SSH1_CMSG_AUTH_RSA,
2468 PKT_BIGNUM, key.modulus, PKT_END);
2470 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
2471 logevent("Key refused");
2474 logevent("Received RSA challenge");
2475 ssh1_read_bignum(pktin.body, &challenge);
2477 char *agentreq, *q, *ret;
2480 len = 1 + 4; /* message type, bit count */
2481 len += ssh1_bignum_length(key.exponent);
2482 len += ssh1_bignum_length(key.modulus);
2483 len += ssh1_bignum_length(challenge);
2484 len += 16; /* session id */
2485 len += 4; /* response format */
2486 agentreq = smalloc(4 + len);
2487 PUT_32BIT(agentreq, len);
2489 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
2490 PUT_32BIT(q, bignum_bitcount(key.modulus));
2492 q += ssh1_write_bignum(q, key.exponent);
2493 q += ssh1_write_bignum(q, key.modulus);
2494 q += ssh1_write_bignum(q, challenge);
2495 memcpy(q, session_id, 16);
2497 PUT_32BIT(q, 1); /* response format */
2498 agent_query(agentreq, len + 4, &vret, &retlen);
2502 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
2503 logevent("Sending Pageant's response");
2504 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
2505 PKT_DATA, ret + 5, 16,
2509 if (pktin.type == SSH1_SMSG_SUCCESS) {
2511 ("Pageant's response accepted");
2512 if (flags & FLAG_VERBOSE) {
2514 ("Authenticated using RSA key \"");
2515 c_write(commentp, commentlen);
2516 c_write_str("\" from agent\r\n");
2521 ("Pageant's response not accepted");
2524 ("Pageant failed to answer challenge");
2528 logevent("No reply received from Pageant");
2531 freebn(key.exponent);
2532 freebn(key.modulus);
2541 if (*cfg.keyfile && !tried_publickey)
2542 pwpkt_type = SSH1_CMSG_AUTH_RSA;
2544 if (cfg.try_tis_auth &&
2545 (supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
2546 !tis_auth_refused) {
2547 pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
2548 logevent("Requested TIS authentication");
2549 send_packet(SSH1_CMSG_AUTH_TIS, PKT_END);
2551 if (pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
2552 logevent("TIS authentication declined");
2553 if (flags & FLAG_INTERACTIVE)
2554 c_write_str("TIS authentication refused.\r\n");
2555 tis_auth_refused = 1;
2558 int challengelen = ((pktin.body[0] << 24) |
2559 (pktin.body[1] << 16) |
2560 (pktin.body[2] << 8) |
2562 logevent("Received TIS challenge");
2563 if (challengelen > sizeof(prompt) - 1)
2564 challengelen = sizeof(prompt) - 1; /* prevent overrun */
2565 memcpy(prompt, pktin.body + 4, challengelen);
2566 /* Prompt heuristic comes from OpenSSH */
2567 strncpy(prompt + challengelen,
2568 memchr(prompt, '\n', challengelen) ?
2569 "": "\r\nResponse: ",
2570 (sizeof prompt) - challengelen);
2571 prompt[(sizeof prompt) - 1] = '\0';
2574 if (cfg.try_tis_auth &&
2575 (supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
2576 !ccard_auth_refused) {
2577 pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
2578 logevent("Requested CryptoCard authentication");
2579 send_packet(SSH1_CMSG_AUTH_CCARD, PKT_END);
2581 if (pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
2582 logevent("CryptoCard authentication declined");
2583 c_write_str("CryptoCard authentication refused.\r\n");
2584 ccard_auth_refused = 1;
2587 int challengelen = ((pktin.body[0] << 24) |
2588 (pktin.body[1] << 16) |
2589 (pktin.body[2] << 8) |
2591 logevent("Received CryptoCard challenge");
2592 if (challengelen > sizeof(prompt) - 1)
2593 challengelen = sizeof(prompt) - 1; /* prevent overrun */
2594 memcpy(prompt, pktin.body + 4, challengelen);
2595 strncpy(prompt + challengelen,
2596 memchr(prompt, '\n', challengelen) ?
2597 "" : "\r\nResponse: ",
2598 sizeof(prompt) - challengelen);
2599 prompt[sizeof(prompt) - 1] = '\0';
2602 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
2603 sprintf(prompt, "%.90s@%.90s's password: ",
2604 username, savedhost);
2606 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
2607 char *comment = NULL;
2610 if (flags & FLAG_VERBOSE)
2611 c_write_str("Trying public key authentication.\r\n");
2612 sprintf(msgbuf, "Trying public key \"%.200s\"", cfg.keyfile);
2614 type = key_type(cfg.keyfile);
2615 if (type != SSH_KEYTYPE_SSH1) {
2616 sprintf(msgbuf, "Key is of wrong type (%s)",
2617 key_type_to_str(type));
2619 c_write_str(msgbuf);
2620 c_write_str("\r\n");
2621 tried_publickey = 1;
2624 if (!rsakey_encrypted(cfg.keyfile, &comment)) {
2625 if (flags & FLAG_VERBOSE)
2626 c_write_str("No passphrase required.\r\n");
2629 sprintf(prompt, "Passphrase for key \"%.100s\": ", comment);
2634 * Show password prompt, having first obtained it via a TIS
2635 * or CryptoCard exchange if we're doing TIS or CryptoCard
2639 if (!ssh_get_line(prompt, password, sizeof(password), TRUE)) {
2641 * get_line failed to get a password (for example
2642 * because one was supplied on the command line
2643 * which has already failed to work). Terminate.
2645 send_packet(SSH1_MSG_DISCONNECT,
2646 PKT_STR, "No more passwords available to try",
2648 logevent("Unable to authenticate");
2649 connection_fatal("Unable to authenticate");
2650 ssh_state = SSH_STATE_CLOSED;
2654 /* Prompt may have come from server. We've munged it a bit, so
2655 * we know it to be zero-terminated at least once. */
2657 c_write_untrusted(prompt, strlen(prompt));
2660 setup_userpass_input(password, sizeof(password), 0);
2662 crWaitUntil(!ispkt);
2663 ret = process_userpass_input(in, inlen);
2667 c_write_str("\r\n");
2671 if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
2673 * Try public key authentication with the specified
2676 static struct RSAKey pubkey;
2677 static Bignum challenge, response;
2679 static unsigned char buffer[32];
2681 tried_publickey = 1;
2682 i = loadrsakey(cfg.keyfile, &pubkey, password);
2684 c_write_str("Couldn't load private key from ");
2685 c_write_str(cfg.keyfile);
2686 c_write_str(".\r\n");
2687 continue; /* go and try password */
2690 c_write_str("Wrong passphrase.\r\n");
2691 tried_publickey = 0;
2692 continue; /* try again */
2696 * Send a public key attempt.
2698 send_packet(SSH1_CMSG_AUTH_RSA,
2699 PKT_BIGNUM, pubkey.modulus, PKT_END);
2702 if (pktin.type == SSH1_SMSG_FAILURE) {
2703 c_write_str("Server refused our public key.\r\n");
2704 continue; /* go and try password */
2706 if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
2707 bombout(("Bizarre response to offer of public key"));
2710 ssh1_read_bignum(pktin.body, &challenge);
2711 response = rsadecrypt(challenge, &pubkey);
2712 freebn(pubkey.private_exponent); /* burn the evidence */
2714 for (i = 0; i < 32; i++) {
2715 buffer[i] = bignum_byte(response, 31 - i);
2719 MD5Update(&md5c, buffer, 32);
2720 MD5Update(&md5c, session_id, 16);
2721 MD5Final(buffer, &md5c);
2723 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
2724 PKT_DATA, buffer, 16, PKT_END);
2727 if (pktin.type == SSH1_SMSG_FAILURE) {
2728 if (flags & FLAG_VERBOSE)
2730 ("Failed to authenticate with our public key.\r\n");
2731 continue; /* go and try password */
2732 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
2734 ("Bizarre response to RSA authentication response"));
2738 break; /* we're through! */
2740 if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
2742 * Defence against traffic analysis: we send a
2743 * whole bunch of packets containing strings of
2744 * different lengths. One of these strings is the
2745 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
2746 * The others are all random data in
2747 * SSH1_MSG_IGNORE packets. This way a passive
2748 * listener can't tell which is the password, and
2749 * hence can't deduce the password length.
2751 * Anybody with a password length greater than 16
2752 * bytes is going to have enough entropy in their
2753 * password that a listener won't find it _that_
2754 * much help to know how long it is. So what we'll
2757 * - if password length < 16, we send 15 packets
2758 * containing string lengths 1 through 15
2760 * - otherwise, we let N be the nearest multiple
2761 * of 8 below the password length, and send 8
2762 * packets containing string lengths N through
2763 * N+7. This won't obscure the order of
2764 * magnitude of the password length, but it will
2765 * introduce a bit of extra uncertainty.
2767 * A few servers (the old 1.2.18 through 1.2.22)
2768 * can't deal with SSH1_MSG_IGNORE. For these
2769 * servers, we need an alternative defence. We make
2770 * use of the fact that the password is interpreted
2771 * as a C string: so we can append a NUL, then some
2774 * One server (a Cisco one) can deal with neither
2775 * SSH1_MSG_IGNORE _nor_ a padded password string.
2776 * For this server we are left with no defences
2777 * against password length sniffing.
2779 if (!(ssh_remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE)) {
2781 * The server can deal with SSH1_MSG_IGNORE, so
2782 * we can use the primary defence.
2784 int bottom, top, pwlen, i;
2787 pwlen = strlen(password);
2789 bottom = 0; /* zero length passwords are OK! :-) */
2792 bottom = pwlen & ~7;
2796 assert(pwlen >= bottom && pwlen <= top);
2798 randomstr = smalloc(top + 1);
2800 for (i = bottom; i <= top; i++) {
2802 defer_packet(pwpkt_type, PKT_STR, password,
2805 for (j = 0; j < i; j++) {
2807 randomstr[j] = random_byte();
2808 } while (randomstr[j] == '\0');
2810 randomstr[i] = '\0';
2811 defer_packet(SSH1_MSG_IGNORE,
2812 PKT_STR, randomstr, PKT_END);
2815 logevent("Sending password with camouflage packets");
2816 ssh_pkt_defersend();
2818 else if (!(ssh_remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
2820 * The server can't deal with SSH1_MSG_IGNORE
2821 * but can deal with padded passwords, so we
2822 * can use the secondary defence.
2828 len = strlen(password);
2829 if (len < sizeof(string)) {
2831 strcpy(string, password);
2832 len++; /* cover the zero byte */
2833 while (len < sizeof(string)) {
2834 string[len++] = (char) random_byte();
2839 logevent("Sending length-padded password");
2840 send_packet(pwpkt_type, PKT_INT, len,
2841 PKT_DATA, s, len, PKT_END);
2844 * The server has _both_
2845 * BUG_CHOKES_ON_SSH1_IGNORE and
2846 * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
2847 * therefore nothing we can do.
2850 len = strlen(password);
2851 logevent("Sending unpadded password");
2852 send_packet(pwpkt_type, PKT_INT, len,
2853 PKT_DATA, password, len, PKT_END);
2856 send_packet(pwpkt_type, PKT_STR, password, PKT_END);
2859 logevent("Sent password");
2860 memset(password, 0, strlen(password));
2862 if (pktin.type == SSH1_SMSG_FAILURE) {
2863 if (flags & FLAG_VERBOSE)
2864 c_write_str("Access denied\r\n");
2865 logevent("Authentication refused");
2866 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
2867 logevent("Received disconnect request");
2868 ssh_state = SSH_STATE_CLOSED;
2870 } else if (pktin.type != SSH1_SMSG_SUCCESS) {
2871 bombout(("Strange packet received, type %d", pktin.type));
2876 logevent("Authentication successful");
2881 void sshfwd_close(struct ssh_channel *c)
2883 if (c && !c->closes) {
2885 * If the channel's remoteid is -1, we have sent
2886 * CHANNEL_OPEN for this channel, but it hasn't even been
2887 * acknowledged by the server. So we must set a close flag
2888 * on it now, and then when the server acks the channel
2889 * open, we can close it then.
2891 if (((int)c->remoteid) != -1) {
2892 if (ssh_version == 1) {
2893 send_packet(SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
2896 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
2897 ssh2_pkt_adduint32(c->remoteid);
2901 c->closes = 1; /* sent MSG_CLOSE */
2902 if (c->type == CHAN_X11) {
2904 logevent("Forwarded X11 connection terminated");
2905 } else if (c->type == CHAN_SOCKDATA ||
2906 c->type == CHAN_SOCKDATA_DORMANT) {
2908 logevent("Forwarded port closed");
2913 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
2915 if (ssh_version == 1) {
2916 send_packet(SSH1_MSG_CHANNEL_DATA,
2917 PKT_INT, c->remoteid,
2918 PKT_INT, len, PKT_DATA, buf, len, PKT_END);
2920 * In SSH1 we can return 0 here - implying that forwarded
2921 * connections are never individually throttled - because
2922 * the only circumstance that can cause throttling will be
2923 * the whole SSH connection backing up, in which case
2924 * _everything_ will be throttled as a whole.
2928 ssh2_add_channel_data(c, buf, len);
2929 return ssh2_try_send(c);
2933 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
2935 if (ssh_version == 1) {
2936 if (c->v.v1.throttling && bufsize < SSH1_BUFFER_LIMIT) {
2937 c->v.v1.throttling = 0;
2941 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
2945 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt)
2951 while (!do_ssh1_login(in, inlen, ispkt)) {
2954 if (ssh_state == SSH_STATE_CLOSED)
2957 if (cfg.agentfwd && agent_exists()) {
2958 logevent("Requesting agent forwarding");
2959 send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
2963 if (pktin.type != SSH1_SMSG_SUCCESS
2964 && pktin.type != SSH1_SMSG_FAILURE) {
2965 bombout(("Protocol confusion"));
2967 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2968 logevent("Agent forwarding refused");
2970 logevent("Agent forwarding enabled");
2971 ssh_agentfwd_enabled = TRUE;
2975 if (cfg.x11_forward) {
2976 char proto[20], data[64];
2977 logevent("Requesting X11 forwarding");
2978 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
2979 if (ssh1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
2980 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING,
2981 PKT_STR, proto, PKT_STR, data,
2982 PKT_INT, 0, PKT_END);
2984 send_packet(SSH1_CMSG_X11_REQUEST_FORWARDING,
2985 PKT_STR, proto, PKT_STR, data, PKT_END);
2990 if (pktin.type != SSH1_SMSG_SUCCESS
2991 && pktin.type != SSH1_SMSG_FAILURE) {
2992 bombout(("Protocol confusion"));
2994 } else if (pktin.type == SSH1_SMSG_FAILURE) {
2995 logevent("X11 forwarding refused");
2997 logevent("X11 forwarding enabled");
2998 ssh_X11_fwd_enabled = TRUE;
3006 int sport,dport,sserv,dserv;
3007 char sports[256], dports[256], host[256];
3011 ssh_rportfwds = newtree234(ssh_rportcmp_ssh1);
3012 /* Add port forwardings. */
3017 while (*e && *e != '\t')
3023 while (*e && *e != ':')
3033 dport = atoi(dports);
3037 se = getservbyname(dports, NULL);
3039 dport = ntohs(se->s_port);
3042 "Service lookup failed for destination port \"%s\"",
3047 sport = atoi(sports);
3051 se = getservbyname(sports, NULL);
3053 sport = ntohs(se->s_port);
3056 "Service lookup failed for source port \"%s\"",
3061 if (sport && dport) {
3063 pfd_addforward(host, dport, sport);
3064 sprintf(buf, "Local port %.*s%.*s%d%.*s forwarding to"
3065 " %s:%.*s%.*s%d%.*s",
3066 sserv ? strlen(sports) : 0, sports,
3067 sserv, "(", sport, sserv, ")",
3069 dserv ? strlen(dports) : 0, dports,
3070 dserv, "(", dport, dserv, ")");
3073 struct ssh_rportfwd *pf;
3074 pf = smalloc(sizeof(*pf));
3075 strcpy(pf->dhost, host);
3077 if (add234(ssh_rportfwds, pf) != pf) {
3079 "Duplicate remote port forwarding to %s:%d",
3084 sprintf(buf, "Requesting remote port %.*s%.*s%d%.*s"
3085 " forward to %s:%.*s%.*s%d%.*s",
3086 sserv ? strlen(sports) : 0, sports,
3087 sserv, "(", sport, sserv, ")",
3089 dserv ? strlen(dports) : 0, dports,
3090 dserv, "(", dport, dserv, ")");
3092 send_packet(SSH1_CMSG_PORT_FORWARD_REQUEST,
3100 if (pktin.type != SSH1_SMSG_SUCCESS
3101 && pktin.type != SSH1_SMSG_FAILURE) {
3102 bombout(("Protocol confusion"));
3104 } else if (pktin.type == SSH1_SMSG_FAILURE) {
3105 c_write_str("Server refused port forwarding\r\n");
3106 ssh_editing = ssh_echoing = 1;
3108 logevent("Remote port forwarding enabled");
3116 send_packet(SSH1_CMSG_REQUEST_PTY,
3117 PKT_STR, cfg.termtype,
3118 PKT_INT, rows, PKT_INT, cols,
3119 PKT_INT, 0, PKT_INT, 0, PKT_CHAR, 0, PKT_END);
3120 ssh_state = SSH_STATE_INTERMED;
3124 if (pktin.type != SSH1_SMSG_SUCCESS
3125 && pktin.type != SSH1_SMSG_FAILURE) {
3126 bombout(("Protocol confusion"));
3128 } else if (pktin.type == SSH1_SMSG_FAILURE) {
3129 c_write_str("Server refused to allocate pty\r\n");
3130 ssh_editing = ssh_echoing = 1;
3132 logevent("Allocated pty");
3134 ssh_editing = ssh_echoing = 1;
3137 if (cfg.compression) {
3138 send_packet(SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
3142 if (pktin.type != SSH1_SMSG_SUCCESS
3143 && pktin.type != SSH1_SMSG_FAILURE) {
3144 bombout(("Protocol confusion"));
3146 } else if (pktin.type == SSH1_SMSG_FAILURE) {
3147 c_write_str("Server refused to compress\r\n");
3149 logevent("Started compression");
3150 ssh1_compressing = TRUE;
3151 zlib_compress_init();
3152 zlib_decompress_init();
3156 * Start the shell or command.
3158 * Special case: if the first-choice command is an SSH2
3159 * subsystem (hence not usable here) and the second choice
3160 * exists, we fall straight back to that.
3163 char *cmd = cfg.remote_cmd_ptr;
3165 if (cfg.ssh_subsys && cfg.remote_cmd_ptr2) {
3166 cmd = cfg.remote_cmd_ptr2;
3167 ssh_fallback_cmd = TRUE;
3170 send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
3172 send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
3173 logevent("Started session");
3176 ssh_state = SSH_STATE_SESSION;
3180 ssh_special(TS_EOF);
3182 ldisc_send(NULL, 0, 0); /* cause ldisc to notice changes */
3184 ssh_channels = newtree234(ssh_channelcmp);
3188 if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
3189 pktin.type == SSH1_SMSG_STDERR_DATA) {
3190 long len = GET_32BIT(pktin.body);
3192 from_backend(pktin.type == SSH1_SMSG_STDERR_DATA,
3193 pktin.body + 4, len);
3194 if (!ssh1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
3195 ssh1_stdout_throttling = 1;
3198 } else if (pktin.type == SSH1_MSG_DISCONNECT) {
3199 ssh_state = SSH_STATE_CLOSED;
3200 logevent("Received disconnect request");
3202 } else if (pktin.type == SSH1_SMSG_X11_OPEN) {
3203 /* Remote side is trying to open a channel to talk to our
3204 * X-Server. Give them back a local channel number. */
3205 struct ssh_channel *c;
3207 logevent("Received X11 connect request");
3208 /* Refuse if X11 forwarding is disabled. */
3209 if (!ssh_X11_fwd_enabled) {
3210 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
3211 PKT_INT, GET_32BIT(pktin.body), PKT_END);
3212 logevent("Rejected X11 connect request");
3214 c = smalloc(sizeof(struct ssh_channel));
3216 if (x11_init(&c->u.x11.s, cfg.x11_display, c) != NULL) {
3217 logevent("opening X11 forward connection failed");
3219 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
3220 PKT_INT, GET_32BIT(pktin.body),
3224 ("opening X11 forward connection succeeded");
3225 c->remoteid = GET_32BIT(pktin.body);
3226 c->localid = alloc_channel_id();
3228 c->v.v1.throttling = 0;
3229 c->type = CHAN_X11; /* identify channel type */
3230 add234(ssh_channels, c);
3231 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3232 PKT_INT, c->remoteid, PKT_INT,
3233 c->localid, PKT_END);
3234 logevent("Opened X11 forward channel");
3237 } else if (pktin.type == SSH1_SMSG_AGENT_OPEN) {
3238 /* Remote side is trying to open a channel to talk to our
3239 * agent. Give them back a local channel number. */
3240 struct ssh_channel *c;
3242 /* Refuse if agent forwarding is disabled. */
3243 if (!ssh_agentfwd_enabled) {
3244 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
3245 PKT_INT, GET_32BIT(pktin.body), PKT_END);
3247 c = smalloc(sizeof(struct ssh_channel));
3248 c->remoteid = GET_32BIT(pktin.body);
3249 c->localid = alloc_channel_id();
3251 c->v.v1.throttling = 0;
3252 c->type = CHAN_AGENT; /* identify channel type */
3253 c->u.a.lensofar = 0;
3254 add234(ssh_channels, c);
3255 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3256 PKT_INT, c->remoteid, PKT_INT, c->localid,
3259 } else if (pktin.type == SSH1_MSG_PORT_OPEN) {
3260 /* Remote side is trying to open a channel to talk to a
3261 * forwarded port. Give them back a local channel number. */
3262 struct ssh_channel *c;
3263 struct ssh_rportfwd pf;
3265 char host[256], buf[1024];
3267 c = smalloc(sizeof(struct ssh_channel));
3269 hostsize = GET_32BIT(pktin.body+4);
3270 for(h = host, p = pktin.body+8; hostsize != 0; hostsize--) {
3271 if (h+1 < host+sizeof(host))
3276 port = GET_32BIT(p);
3278 strcpy(pf.dhost, host);
3281 if (find234(ssh_rportfwds, &pf, NULL) == NULL) {
3282 sprintf(buf, "Rejected remote port open request for %s:%d",
3285 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
3286 PKT_INT, GET_32BIT(pktin.body), PKT_END);
3288 sprintf(buf, "Received remote port open request for %s:%d",
3291 e = pfd_newconnect(&c->u.pfd.s, host, port, c);
3294 sprintf(buf, "Port open failed: %s", e);
3297 send_packet(SSH1_MSG_CHANNEL_OPEN_FAILURE,
3298 PKT_INT, GET_32BIT(pktin.body),
3301 c->remoteid = GET_32BIT(pktin.body);
3302 c->localid = alloc_channel_id();
3304 c->v.v1.throttling = 0;
3305 c->type = CHAN_SOCKDATA; /* identify channel type */
3306 add234(ssh_channels, c);
3307 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
3308 PKT_INT, c->remoteid, PKT_INT,
3309 c->localid, PKT_END);
3310 logevent("Forwarded port opened successfully");
3314 } else if (pktin.type == SSH1_MSG_CHANNEL_OPEN_CONFIRMATION) {
3315 unsigned int remoteid = GET_32BIT(pktin.body);
3316 unsigned int localid = GET_32BIT(pktin.body+4);
3317 struct ssh_channel *c;
3319 c = find234(ssh_channels, &remoteid, ssh_channelfind);
3320 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
3321 c->remoteid = localid;
3322 c->type = CHAN_SOCKDATA;
3323 c->v.v1.throttling = 0;
3324 pfd_confirm(c->u.pfd.s);
3327 if (c && c->closes) {
3329 * We have a pending close on this channel,
3330 * which we decided on before the server acked
3331 * the channel open. So now we know the
3332 * remoteid, we can close it again.
3334 send_packet(SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
3338 } else if (pktin.type == SSH1_MSG_CHANNEL_OPEN_FAILURE) {
3339 unsigned int remoteid = GET_32BIT(pktin.body);
3340 unsigned int localid = GET_32BIT(pktin.body+4);
3341 struct ssh_channel *c;
3343 c = find234(ssh_channels, &remoteid, ssh_channelfind);
3344 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
3345 logevent("Forwarded connection refused by server");
3346 pfd_close(c->u.pfd.s);
3347 del234(ssh_channels, c);
3351 } else if (pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
3352 pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
3353 /* Remote side closes a channel. */
3354 unsigned i = GET_32BIT(pktin.body);
3355 struct ssh_channel *c;
3356 c = find234(ssh_channels, &i, ssh_channelfind);
3357 if (c && ((int)c->remoteid) != -1) {
3360 (pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
3362 if ((c->closes == 0) && (c->type == CHAN_X11)) {
3363 logevent("Forwarded X11 connection terminated");
3364 assert(c->u.x11.s != NULL);
3365 x11_close(c->u.x11.s);
3368 if ((c->closes == 0) && (c->type == CHAN_SOCKDATA)) {
3369 logevent("Forwarded port closed");
3370 assert(c->u.pfd.s != NULL);
3371 pfd_close(c->u.pfd.s);
3375 c->closes |= (closetype << 2); /* seen this message */
3376 if (!(c->closes & closetype)) {
3377 send_packet(pktin.type, PKT_INT, c->remoteid,
3379 c->closes |= closetype; /* sent it too */
3382 if (c->closes == 15) {
3383 del234(ssh_channels, c);
3387 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
3388 pktin.type == SSH1_MSG_CHANNEL_CLOSE ? "" :
3389 "_CONFIRMATION", c ? "half-open" : "nonexistent",
3392 } else if (pktin.type == SSH1_MSG_CHANNEL_DATA) {
3393 /* Data sent down one of our channels. */
3394 int i = GET_32BIT(pktin.body);
3395 int len = GET_32BIT(pktin.body + 4);
3396 unsigned char *p = pktin.body + 8;
3397 struct ssh_channel *c;
3398 c = find234(ssh_channels, &i, ssh_channelfind);
3403 bufsize = x11_send(c->u.x11.s, p, len);
3406 bufsize = pfd_send(c->u.pfd.s, p, len);
3409 /* Data for an agent message. Buffer it. */
3411 if (c->u.a.lensofar < 4) {
3412 int l = min(4 - c->u.a.lensofar, len);
3413 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
3417 c->u.a.lensofar += l;
3419 if (c->u.a.lensofar == 4) {
3421 4 + GET_32BIT(c->u.a.msglen);
3422 c->u.a.message = smalloc(c->u.a.totallen);
3423 memcpy(c->u.a.message, c->u.a.msglen, 4);
3425 if (c->u.a.lensofar >= 4 && len > 0) {
3427 min(c->u.a.totallen - c->u.a.lensofar,
3429 memcpy(c->u.a.message + c->u.a.lensofar, p,
3433 c->u.a.lensofar += l;
3435 if (c->u.a.lensofar == c->u.a.totallen) {
3436 void *reply, *sentreply;
3438 agent_query(c->u.a.message,
3439 c->u.a.totallen, &reply,
3444 /* Fake SSH_AGENT_FAILURE. */
3445 sentreply = "\0\0\0\1\5";
3448 send_packet(SSH1_MSG_CHANNEL_DATA,
3449 PKT_INT, c->remoteid,
3451 PKT_DATA, sentreply, replylen,
3455 sfree(c->u.a.message);
3456 c->u.a.lensofar = 0;
3459 bufsize = 0; /* agent channels never back up */
3462 if (!c->v.v1.throttling && bufsize > SSH1_BUFFER_LIMIT) {
3463 c->v.v1.throttling = 1;
3467 } else if (pktin.type == SSH1_SMSG_SUCCESS) {
3468 /* may be from EXEC_SHELL on some servers */
3469 } else if (pktin.type == SSH1_SMSG_FAILURE) {
3470 /* may be from EXEC_SHELL on some servers
3471 * if no pty is available or in other odd cases. Ignore */
3472 } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
3474 ssh_exitcode = GET_32BIT(pktin.body);
3475 sprintf(buf, "Server sent command exit status %d",
3478 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
3480 * In case `helpful' firewalls or proxies tack
3481 * extra human-readable text on the end of the
3482 * session which we might mistake for another
3483 * encrypted packet, we close the session once
3484 * we've sent EXIT_CONFIRMATION.
3486 ssh_state = SSH_STATE_CLOSED;
3489 bombout(("Strange packet received: type %d", pktin.type));
3494 int len = min(inlen, 512);
3495 send_packet(SSH1_CMSG_STDIN_DATA,
3496 PKT_INT, len, PKT_DATA, in, len, PKT_END);
3507 * Utility routine for decoding comma-separated strings in KEXINIT.
3509 static int in_commasep_string(char *needle, char *haystack, int haylen)
3511 int needlen = strlen(needle);
3514 * Is it at the start of the string?
3516 if (haylen >= needlen && /* haystack is long enough */
3517 !memcmp(needle, haystack, needlen) && /* initial match */
3518 (haylen == needlen || haystack[needlen] == ',')
3519 /* either , or EOS follows */
3523 * If not, search for the next comma and resume after that.
3524 * If no comma found, terminate.
3526 while (haylen > 0 && *haystack != ',')
3527 haylen--, haystack++;
3530 haylen--, haystack++; /* skip over comma itself */
3535 * SSH2 key creation method.
3537 static void ssh2_mkkey(Bignum K, char *H, char *sessid, char chr,
3541 /* First 20 bytes. */
3543 if (!(ssh_remote_bugs & BUG_SSH2_DERIVEKEY))
3545 SHA_Bytes(&s, H, 20);
3546 SHA_Bytes(&s, &chr, 1);
3547 SHA_Bytes(&s, sessid, 20);
3548 SHA_Final(&s, keyspace);
3549 /* Next 20 bytes. */
3551 if (!(ssh_remote_bugs & BUG_SSH2_DERIVEKEY))
3553 SHA_Bytes(&s, H, 20);
3554 SHA_Bytes(&s, keyspace, 20);
3555 SHA_Final(&s, keyspace + 20);
3559 * Handle the SSH2 transport layer.
3561 static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
3563 static int i, j, len, nbits, pbits, warn;
3565 static Bignum p, g, e, f, K;
3566 static int kex_init_value, kex_reply_value;
3567 static const struct ssh_mac **maclist;
3569 static const struct ssh2_cipher *cscipher_tobe = NULL;
3570 static const struct ssh2_cipher *sccipher_tobe = NULL;
3571 static const struct ssh_mac *csmac_tobe = NULL;
3572 static const struct ssh_mac *scmac_tobe = NULL;
3573 static const struct ssh_compress *cscomp_tobe = NULL;
3574 static const struct ssh_compress *sccomp_tobe = NULL;
3575 static char *hostkeydata, *sigdata, *keystr, *fingerprint;
3576 static int hostkeylen, siglen;
3577 static void *hkey; /* actual host key */
3578 static unsigned char exchange_hash[20];
3579 static unsigned char keyspace[40];
3580 static int n_preferred_ciphers;
3581 static const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
3582 static const struct ssh_compress *preferred_comp;
3583 static int cipherstr_started;
3584 static int first_kex;
3591 * Set up the preferred ciphers. (NULL => warn below here)
3593 n_preferred_ciphers = 0;
3594 for (i = 0; i < CIPHER_MAX; i++) {
3595 switch (cfg.ssh_cipherlist[i]) {
3596 case CIPHER_BLOWFISH:
3597 preferred_ciphers[n_preferred_ciphers] = &ssh2_blowfish;
3598 n_preferred_ciphers++;
3601 if (cfg.ssh2_des_cbc) {
3602 preferred_ciphers[n_preferred_ciphers] = &ssh2_des;
3603 n_preferred_ciphers++;
3607 preferred_ciphers[n_preferred_ciphers] = &ssh2_3des;
3608 n_preferred_ciphers++;
3611 preferred_ciphers[n_preferred_ciphers] = &ssh2_aes;
3612 n_preferred_ciphers++;
3615 /* Flag for later. Don't bother if it's the last in
3617 if (i < CIPHER_MAX - 1) {
3618 preferred_ciphers[n_preferred_ciphers] = NULL;
3619 n_preferred_ciphers++;
3626 * Set up preferred compression.
3628 if (cfg.compression)
3629 preferred_comp = &ssh_zlib;
3631 preferred_comp = &ssh_comp_none;
3634 * Be prepared to work around the buggy MAC problem.
3636 if (cfg.buggymac || (ssh_remote_bugs & BUG_SSH2_HMAC))
3637 maclist = buggymacs, nmacs = lenof(buggymacs);
3639 maclist = macs, nmacs = lenof(macs);
3643 * Construct and send our key exchange packet.
3645 ssh2_pkt_init(SSH2_MSG_KEXINIT);
3646 for (i = 0; i < 16; i++)
3647 ssh2_pkt_addbyte((unsigned char) random_byte());
3648 /* List key exchange algorithms. */
3649 ssh2_pkt_addstring_start();
3650 for (i = 0; i < lenof(kex_algs); i++) {
3651 ssh2_pkt_addstring_str(kex_algs[i]->name);
3652 if (i < lenof(kex_algs) - 1)
3653 ssh2_pkt_addstring_str(",");
3655 /* List server host key algorithms. */
3656 ssh2_pkt_addstring_start();
3657 for (i = 0; i < lenof(hostkey_algs); i++) {
3658 ssh2_pkt_addstring_str(hostkey_algs[i]->name);
3659 if (i < lenof(hostkey_algs) - 1)
3660 ssh2_pkt_addstring_str(",");
3662 /* List client->server encryption algorithms. */
3663 ssh2_pkt_addstring_start();
3664 cipherstr_started = 0;
3665 for (i = 0; i < n_preferred_ciphers; i++) {
3666 const struct ssh2_ciphers *c = preferred_ciphers[i];
3667 if (!c) continue; /* warning flag */
3668 for (j = 0; j < c->nciphers; j++) {
3669 if (cipherstr_started)
3670 ssh2_pkt_addstring_str(",");
3671 ssh2_pkt_addstring_str(c->list[j]->name);
3672 cipherstr_started = 1;
3675 /* List server->client encryption algorithms. */
3676 ssh2_pkt_addstring_start();
3677 cipherstr_started = 0;
3678 for (i = 0; i < n_preferred_ciphers; i++) {
3679 const struct ssh2_ciphers *c = preferred_ciphers[i];
3680 if (!c) continue; /* warning flag */
3681 for (j = 0; j < c->nciphers; j++) {
3682 if (cipherstr_started)
3683 ssh2_pkt_addstring_str(",");
3684 ssh2_pkt_addstring_str(c->list[j]->name);
3685 cipherstr_started = 1;
3688 /* List client->server MAC algorithms. */
3689 ssh2_pkt_addstring_start();
3690 for (i = 0; i < nmacs; i++) {
3691 ssh2_pkt_addstring_str(maclist[i]->name);
3693 ssh2_pkt_addstring_str(",");
3695 /* List server->client MAC algorithms. */
3696 ssh2_pkt_addstring_start();
3697 for (i = 0; i < nmacs; i++) {
3698 ssh2_pkt_addstring_str(maclist[i]->name);
3700 ssh2_pkt_addstring_str(",");
3702 /* List client->server compression algorithms. */
3703 ssh2_pkt_addstring_start();
3704 for (i = 0; i < lenof(compressions) + 1; i++) {
3705 const struct ssh_compress *c =
3706 i == 0 ? preferred_comp : compressions[i - 1];
3707 ssh2_pkt_addstring_str(c->name);
3708 if (i < lenof(compressions))
3709 ssh2_pkt_addstring_str(",");
3711 /* List server->client compression algorithms. */
3712 ssh2_pkt_addstring_start();
3713 for (i = 0; i < lenof(compressions) + 1; i++) {
3714 const struct ssh_compress *c =
3715 i == 0 ? preferred_comp : compressions[i - 1];
3716 ssh2_pkt_addstring_str(c->name);
3717 if (i < lenof(compressions))
3718 ssh2_pkt_addstring_str(",");
3720 /* List client->server languages. Empty list. */
3721 ssh2_pkt_addstring_start();
3722 /* List server->client languages. Empty list. */
3723 ssh2_pkt_addstring_start();
3724 /* First KEX packet does _not_ follow, because we're not that brave. */
3725 ssh2_pkt_addbool(FALSE);
3727 ssh2_pkt_adduint32(0);
3729 exhash = exhashbase;
3730 sha_string(&exhash, pktout.data + 5, pktout.length - 5);
3736 sha_string(&exhash, pktin.data + 5, pktin.length - 5);
3739 * Now examine the other side's KEXINIT to see what we're up
3742 if (pktin.type != SSH2_MSG_KEXINIT) {
3743 bombout(("expected key exchange packet from server"));
3748 cscipher_tobe = NULL;
3749 sccipher_tobe = NULL;
3754 pktin.savedpos += 16; /* skip garbage cookie */
3755 ssh2_pkt_getstring(&str, &len); /* key exchange algorithms */
3756 for (i = 0; i < lenof(kex_algs); i++) {
3757 if (in_commasep_string(kex_algs[i]->name, str, len)) {
3762 ssh2_pkt_getstring(&str, &len); /* host key algorithms */
3763 for (i = 0; i < lenof(hostkey_algs); i++) {
3764 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
3765 hostkey = hostkey_algs[i];
3769 ssh2_pkt_getstring(&str, &len); /* client->server cipher */
3771 for (i = 0; i < n_preferred_ciphers; i++) {
3772 const struct ssh2_ciphers *c = preferred_ciphers[i];
3776 for (j = 0; j < c->nciphers; j++) {
3777 if (in_commasep_string(c->list[j]->name, str, len)) {
3778 cscipher_tobe = c->list[j];
3783 if (cscipher_tobe) {
3785 askcipher(cscipher_tobe->name, 1);
3789 if (!cscipher_tobe) {
3790 bombout(("Couldn't agree a client-to-server cipher (available: %s)", str));
3794 ssh2_pkt_getstring(&str, &len); /* server->client cipher */
3796 for (i = 0; i < n_preferred_ciphers; i++) {
3797 const struct ssh2_ciphers *c = preferred_ciphers[i];
3801 for (j = 0; j < c->nciphers; j++) {
3802 if (in_commasep_string(c->list[j]->name, str, len)) {
3803 sccipher_tobe = c->list[j];
3808 if (sccipher_tobe) {
3810 askcipher(sccipher_tobe->name, 2);
3814 if (!sccipher_tobe) {
3815 bombout(("Couldn't agree a server-to-client cipher (available: %s)", str));
3819 ssh2_pkt_getstring(&str, &len); /* client->server mac */
3820 for (i = 0; i < nmacs; i++) {
3821 if (in_commasep_string(maclist[i]->name, str, len)) {
3822 csmac_tobe = maclist[i];
3826 ssh2_pkt_getstring(&str, &len); /* server->client mac */
3827 for (i = 0; i < nmacs; i++) {
3828 if (in_commasep_string(maclist[i]->name, str, len)) {
3829 scmac_tobe = maclist[i];
3833 ssh2_pkt_getstring(&str, &len); /* client->server compression */
3834 for (i = 0; i < lenof(compressions) + 1; i++) {
3835 const struct ssh_compress *c =
3836 i == 0 ? preferred_comp : compressions[i - 1];
3837 if (in_commasep_string(c->name, str, len)) {
3842 ssh2_pkt_getstring(&str, &len); /* server->client compression */
3843 for (i = 0; i < lenof(compressions) + 1; i++) {
3844 const struct ssh_compress *c =
3845 i == 0 ? preferred_comp : compressions[i - 1];
3846 if (in_commasep_string(c->name, str, len)) {
3853 * Work out the number of bits of key we will need from the key
3854 * exchange. We start with the maximum key length of either
3860 csbits = cscipher_tobe->keylen;
3861 scbits = sccipher_tobe->keylen;
3862 nbits = (csbits > scbits ? csbits : scbits);
3864 /* The keys only have 160-bit entropy, since they're based on
3865 * a SHA-1 hash. So cap the key size at 160 bits. */
3870 * If we're doing Diffie-Hellman group exchange, start by
3871 * requesting a group.
3873 if (kex == &ssh_diffiehellman_gex) {
3874 logevent("Doing Diffie-Hellman group exchange");
3875 ssh_pkt_ctx |= SSH2_PKTCTX_DHGEX;
3877 * Work out how big a DH group we will need to allow that
3880 pbits = 512 << ((nbits - 1) / 64);
3881 ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
3882 ssh2_pkt_adduint32(pbits);
3886 if (pktin.type != SSH2_MSG_KEX_DH_GEX_GROUP) {
3887 bombout(("expected key exchange group packet from server"));
3890 p = ssh2_pkt_getmp();
3891 g = ssh2_pkt_getmp();
3892 dh_setup_group(p, g);
3893 kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
3894 kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
3896 ssh_pkt_ctx |= SSH2_PKTCTX_DHGROUP1;
3898 kex_init_value = SSH2_MSG_KEXDH_INIT;
3899 kex_reply_value = SSH2_MSG_KEXDH_REPLY;
3902 logevent("Doing Diffie-Hellman key exchange");
3904 * Now generate and send e for Diffie-Hellman.
3906 e = dh_create_e(nbits * 2);
3907 ssh2_pkt_init(kex_init_value);
3912 if (pktin.type != kex_reply_value) {
3913 bombout(("expected key exchange reply packet from server"));
3916 ssh2_pkt_getstring(&hostkeydata, &hostkeylen);
3917 f = ssh2_pkt_getmp();
3918 ssh2_pkt_getstring(&sigdata, &siglen);
3922 sha_string(&exhash, hostkeydata, hostkeylen);
3923 if (kex == &ssh_diffiehellman_gex) {
3924 sha_uint32(&exhash, pbits);
3925 sha_mpint(&exhash, p);
3926 sha_mpint(&exhash, g);
3928 sha_mpint(&exhash, e);
3929 sha_mpint(&exhash, f);
3930 sha_mpint(&exhash, K);
3931 SHA_Final(&exhash, exchange_hash);
3936 debug(("Exchange hash is:\n"));
3937 dmemdump(exchange_hash, 20);
3940 hkey = hostkey->newkey(hostkeydata, hostkeylen);
3942 !hostkey->verifysig(hkey, sigdata, siglen, exchange_hash, 20)) {
3943 bombout(("Server's host key did not match the signature supplied"));
3948 * Authenticate remote host: verify host key. (We've already
3949 * checked the signature of the exchange hash.)
3951 keystr = hostkey->fmtkey(hkey);
3952 fingerprint = hostkey->fingerprint(hkey);
3953 verify_ssh_host_key(savedhost, savedport, hostkey->keytype,
3954 keystr, fingerprint);
3955 if (first_kex) { /* don't bother logging this in rekeys */
3956 logevent("Host key fingerprint is:");
3957 logevent(fingerprint);
3961 hostkey->freekey(hkey);
3964 * Send SSH2_MSG_NEWKEYS.
3966 ssh2_pkt_init(SSH2_MSG_NEWKEYS);
3970 * Expect SSH2_MSG_NEWKEYS from server.
3973 if (pktin.type != SSH2_MSG_NEWKEYS) {
3974 bombout(("expected new-keys packet from server"));
3979 * Create and initialise session keys.
3981 cscipher = cscipher_tobe;
3982 sccipher = sccipher_tobe;
3985 cscomp = cscomp_tobe;
3986 sccomp = sccomp_tobe;
3987 cscomp->compress_init();
3988 sccomp->decompress_init();
3990 * Set IVs after keys. Here we use the exchange hash from the
3991 * _first_ key exchange.
3994 memcpy(ssh2_session_id, exchange_hash, sizeof(exchange_hash));
3995 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'C', keyspace);
3996 cscipher->setcskey(keyspace);
3997 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'D', keyspace);
3998 sccipher->setsckey(keyspace);
3999 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'A', keyspace);
4000 cscipher->setcsiv(keyspace);
4001 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'B', keyspace);
4002 sccipher->setsciv(keyspace);
4003 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'E', keyspace);
4004 csmac->setcskey(keyspace);
4005 ssh2_mkkey(K, exchange_hash, ssh2_session_id, 'F', keyspace);
4006 scmac->setsckey(keyspace);
4009 * If this is the first key exchange phase, we must pass the
4010 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
4011 * wants to see it but because it will need time to initialise
4012 * itself before it sees an actual packet. In subsequent key
4013 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
4014 * it would only confuse the layer above.
4022 * Now we're encrypting. Begin returning 1 to the protocol main
4023 * function so that other things can run on top of the
4024 * transport. If we ever see a KEXINIT, we must go back to the
4027 while (!(ispkt && pktin.type == SSH2_MSG_KEXINIT)) {
4030 logevent("Server initiated key re-exchange");
4031 goto begin_key_exchange;
4037 * Add data to an SSH2 channel output buffer.
4039 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
4042 bufchain_add(&c->v.v2.outbuffer, buf, len);
4046 * Attempt to send data on an SSH2 channel.
4048 static int ssh2_try_send(struct ssh_channel *c)
4050 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
4053 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
4054 if ((unsigned)len > c->v.v2.remwindow)
4055 len = c->v.v2.remwindow;
4056 if ((unsigned)len > c->v.v2.remmaxpkt)
4057 len = c->v.v2.remmaxpkt;
4058 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
4059 ssh2_pkt_adduint32(c->remoteid);
4060 ssh2_pkt_addstring_start();
4061 ssh2_pkt_addstring_data(data, len);
4063 bufchain_consume(&c->v.v2.outbuffer, len);
4064 c->v.v2.remwindow -= len;
4068 * After having sent as much data as we can, return the amount
4071 return bufchain_size(&c->v.v2.outbuffer);
4075 * Potentially enlarge the window on an SSH2 channel.
4077 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin)
4080 * Never send WINDOW_ADJUST for a channel that the remote side
4081 * already thinks it's closed; there's no point, since it won't
4082 * be sending any more data anyway.
4087 if (newwin > c->v.v2.locwindow) {
4088 ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4089 ssh2_pkt_adduint32(c->remoteid);
4090 ssh2_pkt_adduint32(newwin - c->v.v2.locwindow);
4092 c->v.v2.locwindow = newwin;
4097 * Handle the SSH2 userauth and connection layers.
4099 static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
4102 AUTH_INVALID, AUTH_PUBLICKEY_AGENT, AUTH_PUBLICKEY_FILE,
4104 AUTH_KEYBOARD_INTERACTIVE
4108 AUTH_TYPE_PUBLICKEY,
4109 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
4110 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
4112 AUTH_TYPE_KEYBOARD_INTERACTIVE,
4113 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
4115 static int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
4116 static int tried_pubkey_config, tried_agent, tried_keyb_inter;
4117 static int kbd_inter_running;
4118 static int we_are_in;
4119 static int num_prompts, curr_prompt, echo;
4120 static char username[100];
4121 static int got_username;
4122 static char pwprompt[200];
4123 static char password[100];
4124 static void *publickey_blob;
4125 static int publickey_bloblen;
4130 * Request userauth protocol, and await a response to it.
4132 ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
4133 ssh2_pkt_addstring("ssh-userauth");
4135 crWaitUntilV(ispkt);
4136 if (pktin.type != SSH2_MSG_SERVICE_ACCEPT) {
4137 bombout(("Server refused user authentication protocol"));
4142 * We repeat this whole loop, including the username prompt,
4143 * until we manage a successful authentication. If the user
4144 * types the wrong _password_, they are sent back to the
4145 * beginning to try another username. (If they specify a
4146 * username in the config, they are never asked, even if they
4147 * do give a wrong password.)
4149 * I think this best serves the needs of
4151 * - the people who have no configuration, no keys, and just
4152 * want to try repeated (username,password) pairs until they
4153 * type both correctly
4155 * - people who have keys and configuration but occasionally
4156 * need to fall back to passwords
4158 * - people with a key held in Pageant, who might not have
4159 * logged in to a particular machine before; so they want to
4160 * type a username, and then _either_ their key will be
4161 * accepted, _or_ they will type a password. If they mistype
4162 * the username they will want to be able to get back and
4166 got_username = FALSE;
4171 if (got_username && !cfg.change_username) {
4173 * We got a username last time round this loop, and
4174 * with change_username turned off we don't try to get
4177 } else if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
4178 if (ssh_get_line && !ssh_getline_pw_only) {
4179 if (!ssh_get_line("login as: ",
4180 username, sizeof(username), FALSE)) {
4182 * get_line failed to get a username.
4185 logevent("No username provided. Abandoning session.");
4186 ssh_state = SSH_STATE_CLOSED;
4191 c_write_str("login as: ");
4193 setup_userpass_input(username, sizeof(username), 1);
4195 crWaitUntilV(!ispkt);
4196 ret = process_userpass_input(in, inlen);
4201 c_write_str("\r\n");
4202 username[strcspn(username, "\n\r")] = '\0';
4205 strncpy(username, cfg.username, sizeof(username));
4206 username[sizeof(username)-1] = '\0';
4207 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
4208 sprintf(stuff, "Using username \"%s\".\r\n", username);
4212 got_username = TRUE;
4215 * Send an authentication request using method "none": (a)
4216 * just in case it succeeds, and (b) so that we know what
4217 * authentication methods we can usefully try next.
4219 ssh_pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4221 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4222 ssh2_pkt_addstring(username);
4223 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4224 ssh2_pkt_addstring("none"); /* method */
4226 type = AUTH_TYPE_NONE;
4230 tried_pubkey_config = FALSE;
4231 tried_agent = FALSE;
4232 tried_keyb_inter = FALSE;
4233 kbd_inter_running = FALSE;
4234 /* Load the pub half of cfg.keyfile so we notice if it's in Pageant */
4237 logeventf("Reading private key file \"%.150s\"", cfg.keyfile);
4238 keytype = key_type(cfg.keyfile);
4239 if (keytype == SSH_KEYTYPE_SSH2)
4240 publickey_blob = ssh2_userkey_loadpub(cfg.keyfile, NULL,
4241 &publickey_bloblen);
4244 logeventf("Unable to use this key file (%s)",
4245 key_type_to_str(keytype));
4246 sprintf(msgbuf, "Unable to use key file \"%.150s\" (%s)\r\n",
4247 cfg.keyfile, key_type_to_str(keytype));
4248 c_write_str(msgbuf);
4249 publickey_blob = NULL;
4252 publickey_blob = NULL;
4256 * Wait for the result of the last authentication request.
4259 crWaitUntilV(ispkt);
4260 while (pktin.type == SSH2_MSG_USERAUTH_BANNER) {
4264 * Don't show the banner if we're operating in
4265 * non-verbose non-interactive mode. (It's probably
4266 * a script, which means nobody will read the
4267 * banner _anyway_, and moreover the printing of
4268 * the banner will screw up processing on the
4269 * output of (say) plink.)
4271 if (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE)) {
4272 ssh2_pkt_getstring(&banner, &size);
4274 c_write_untrusted(banner, size);
4276 crWaitUntilV(ispkt);
4278 if (pktin.type == SSH2_MSG_USERAUTH_SUCCESS) {
4279 logevent("Access granted");
4284 if (kbd_inter_running &&
4285 pktin.type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
4287 * This is either a further set-of-prompts packet
4288 * in keyboard-interactive authentication, or it's
4289 * the same one and we came back here with `gotit'
4290 * set. In the former case, we must reset the
4291 * curr_prompt variable.
4295 } else if (pktin.type != SSH2_MSG_USERAUTH_FAILURE) {
4296 bombout(("Strange packet received during authentication: type %d",
4304 * OK, we're now sitting on a USERAUTH_FAILURE message, so
4305 * we can look at the string in it and know what we can
4306 * helpfully try next.
4308 if (pktin.type == SSH2_MSG_USERAUTH_FAILURE) {
4311 ssh2_pkt_getstring(&methods, &methlen);
4312 kbd_inter_running = FALSE;
4313 if (!ssh2_pkt_getbool()) {
4315 * We have received an unequivocal Access
4316 * Denied. This can translate to a variety of
4319 * - if we'd just tried "none" authentication,
4320 * it's not worth printing anything at all
4322 * - if we'd just tried a public key _offer_,
4323 * the message should be "Server refused our
4324 * key" (or no message at all if the key
4325 * came from Pageant)
4327 * - if we'd just tried anything else, the
4328 * message really should be "Access denied".
4330 * Additionally, if we'd just tried password
4331 * authentication, we should break out of this
4332 * whole loop so as to go back to the username
4335 if (type == AUTH_TYPE_NONE) {
4337 } else if (type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
4338 type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
4339 if (type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
4340 c_write_str("Server refused our key\r\n");
4341 logevent("Server refused public key");
4342 } else if (type == AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
4343 /* server declined keyboard-interactive; ignore */
4345 c_write_str("Access denied\r\n");
4346 logevent("Access denied");
4347 if (type == AUTH_TYPE_PASSWORD) {
4353 c_write_str("Further authentication required\r\n");
4354 logevent("Further authentication required");
4358 in_commasep_string("publickey", methods, methlen);
4360 in_commasep_string("password", methods, methlen);
4361 can_keyb_inter = cfg.try_ki_auth &&
4362 in_commasep_string("keyboard-interactive", methods, methlen);
4366 ssh_pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4369 * Most password/passphrase prompts will be
4370 * non-echoing, so we set this to 0 by default.
4371 * Exception is that some keyboard-interactive prompts
4372 * can be echoing, in which case we'll set this to 1.
4376 if (!method && can_pubkey && agent_exists() && !tried_agent) {
4378 * Attempt public-key authentication using Pageant.
4380 static unsigned char request[5], *response, *p;
4381 static int responselen;
4382 static int i, nkeys;
4383 static int authed = FALSE;
4386 ssh_pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4387 ssh_pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
4391 logevent("Pageant is running. Requesting keys.");
4393 /* Request the keys held by the agent. */
4394 PUT_32BIT(request, 1);
4395 request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
4396 agent_query(request, 5, &r, &responselen);
4397 response = (unsigned char *) r;
4398 if (response && responselen >= 5 &&
4399 response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
4401 nkeys = GET_32BIT(p);
4405 sprintf(buf, "Pageant has %d SSH2 keys", nkeys);
4408 for (i = 0; i < nkeys; i++) {
4409 static char *pkblob, *alg, *commentp;
4410 static int pklen, alglen, commentlen;
4411 static int siglen, retlen, len;
4412 static char *q, *agentreq, *ret;
4417 sprintf(buf, "Trying Pageant key #%d", i);
4420 pklen = GET_32BIT(p);
4422 if (publickey_blob &&
4423 pklen == publickey_bloblen &&
4424 !memcmp(p, publickey_blob, publickey_bloblen)) {
4425 logevent("This key matches configured key file");
4426 tried_pubkey_config = 1;
4430 alglen = GET_32BIT(pkblob);
4432 commentlen = GET_32BIT(p);
4436 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4437 ssh2_pkt_addstring(username);
4438 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4439 ssh2_pkt_addstring("publickey"); /* method */
4440 ssh2_pkt_addbool(FALSE); /* no signature included */
4441 ssh2_pkt_addstring_start();
4442 ssh2_pkt_addstring_data(alg, alglen);
4443 ssh2_pkt_addstring_start();
4444 ssh2_pkt_addstring_data(pkblob, pklen);
4447 crWaitUntilV(ispkt);
4448 if (pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
4449 logevent("Key refused");
4453 if (flags & FLAG_VERBOSE) {
4455 ("Authenticating with public key \"");
4456 c_write(commentp, commentlen);
4457 c_write_str("\" from agent\r\n");
4461 * Server is willing to accept the key.
4462 * Construct a SIGN_REQUEST.
4464 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4465 ssh2_pkt_addstring(username);
4466 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4467 ssh2_pkt_addstring("publickey"); /* method */
4468 ssh2_pkt_addbool(TRUE);
4469 ssh2_pkt_addstring_start();
4470 ssh2_pkt_addstring_data(alg, alglen);
4471 ssh2_pkt_addstring_start();
4472 ssh2_pkt_addstring_data(pkblob, pklen);
4474 siglen = pktout.length - 5 + 4 + 20;
4475 len = 1; /* message type */
4476 len += 4 + pklen; /* key blob */
4477 len += 4 + siglen; /* data to sign */
4478 len += 4; /* flags */
4479 agentreq = smalloc(4 + len);
4480 PUT_32BIT(agentreq, len);
4482 *q++ = SSH2_AGENTC_SIGN_REQUEST;
4483 PUT_32BIT(q, pklen);
4485 memcpy(q, pkblob, pklen);
4487 PUT_32BIT(q, siglen);
4489 /* Now the data to be signed... */
4492 memcpy(q, ssh2_session_id, 20);
4494 memcpy(q, pktout.data + 5, pktout.length - 5);
4495 q += pktout.length - 5;
4496 /* And finally the (zero) flags word. */
4498 agent_query(agentreq, len + 4, &vret, &retlen);
4502 if (ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
4503 logevent("Sending Pageant's response");
4504 ssh2_add_sigblob(pkblob, pklen,
4505 ret + 9, GET_32BIT(ret + 5));
4511 ("Pageant failed to answer challenge");
4521 if (!method && can_pubkey && publickey_blob
4522 && !tried_pubkey_config) {
4523 unsigned char *pub_blob;
4524 char *algorithm, *comment;
4527 tried_pubkey_config = TRUE;
4529 ssh_pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4530 ssh_pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
4533 * Try the public key supplied in the configuration.
4535 * First, offer the public blob to see if the server is
4536 * willing to accept it.
4538 pub_blob = ssh2_userkey_loadpub(cfg.keyfile, &algorithm,
4541 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4542 ssh2_pkt_addstring(username);
4543 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4544 ssh2_pkt_addstring("publickey"); /* method */
4545 ssh2_pkt_addbool(FALSE); /* no signature included */
4546 ssh2_pkt_addstring(algorithm);
4547 ssh2_pkt_addstring_start();
4548 ssh2_pkt_addstring_data(pub_blob, pub_blob_len);
4550 logevent("Offered public key"); /* FIXME */
4552 crWaitUntilV(ispkt);
4553 if (pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
4555 type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
4556 continue; /* key refused; give up on it */
4559 logevent("Offer of public key accepted");
4561 * Actually attempt a serious authentication using
4564 if (ssh2_userkey_encrypted(cfg.keyfile, &comment)) {
4566 "Passphrase for key \"%.100s\": ",
4572 c_write_str("Authenticating with public key \"");
4573 c_write_str(comment);
4574 c_write_str("\"\r\n");
4575 method = AUTH_PUBLICKEY_FILE;
4579 if (!method && can_keyb_inter && !tried_keyb_inter) {
4580 method = AUTH_KEYBOARD_INTERACTIVE;
4581 type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4582 tried_keyb_inter = TRUE;
4584 ssh_pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4585 ssh_pkt_ctx |= SSH2_PKTCTX_KBDINTER;
4587 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4588 ssh2_pkt_addstring(username);
4589 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4590 ssh2_pkt_addstring("keyboard-interactive"); /* method */
4591 ssh2_pkt_addstring(""); /* lang */
4592 ssh2_pkt_addstring("");
4595 crWaitUntilV(ispkt);
4596 if (pktin.type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
4597 if (pktin.type == SSH2_MSG_USERAUTH_FAILURE)
4599 logevent("Keyboard-interactive authentication refused");
4600 type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
4604 kbd_inter_running = TRUE;
4608 if (kbd_inter_running) {
4609 method = AUTH_KEYBOARD_INTERACTIVE;
4610 type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4611 tried_keyb_inter = TRUE;
4613 ssh_pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4614 ssh_pkt_ctx |= SSH2_PKTCTX_KBDINTER;
4616 if (curr_prompt == 0) {
4618 * We've got a fresh USERAUTH_INFO_REQUEST.
4619 * Display header data, and start going through
4622 char *name, *inst, *lang;
4623 int name_len, inst_len, lang_len;
4625 ssh2_pkt_getstring(&name, &name_len);
4626 ssh2_pkt_getstring(&inst, &inst_len);
4627 ssh2_pkt_getstring(&lang, &lang_len);
4629 c_write_untrusted(name, name_len);
4630 c_write_str("\r\n");
4633 c_write_untrusted(inst, inst_len);
4634 c_write_str("\r\n");
4636 num_prompts = ssh2_pkt_getuint32();
4640 * If there are prompts remaining in the packet,
4641 * display one and get a response.
4643 if (curr_prompt < num_prompts) {
4647 ssh2_pkt_getstring(&prompt, &prompt_len);
4648 if (prompt_len > 0) {
4649 strncpy(pwprompt, prompt, sizeof(pwprompt));
4650 pwprompt[prompt_len < sizeof(pwprompt) ?
4651 prompt_len : sizeof(pwprompt)-1] = '\0';
4654 "<server failed to send prompt>: ");
4656 echo = ssh2_pkt_getbool();
4662 if (!method && can_passwd) {
4663 method = AUTH_PASSWORD;
4664 ssh_pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4665 ssh_pkt_ctx |= SSH2_PKTCTX_PASSWORD;
4666 sprintf(pwprompt, "%.90s@%.90s's password: ", username,
4673 if (!ssh_get_line(pwprompt, password,
4674 sizeof(password), TRUE)) {
4676 * get_line failed to get a password (for
4677 * example because one was supplied on the
4678 * command line which has already failed to
4681 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
4682 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
4684 ("No more passwords available to try");
4685 ssh2_pkt_addstring("en"); /* language tag */
4687 logevent("Unable to authenticate");
4688 connection_fatal("Unable to authenticate");
4689 ssh_state = SSH_STATE_CLOSED;
4694 c_write_untrusted(pwprompt, strlen(pwprompt));
4697 setup_userpass_input(password, sizeof(password), echo);
4699 crWaitUntilV(!ispkt);
4700 ret = process_userpass_input(in, inlen);
4704 c_write_str("\r\n");
4708 if (method == AUTH_PUBLICKEY_FILE) {
4710 * We have our passphrase. Now try the actual authentication.
4712 struct ssh2_userkey *key;
4714 key = ssh2_load_userkey(cfg.keyfile, password);
4715 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
4716 if (key == SSH2_WRONG_PASSPHRASE) {
4717 c_write_str("Wrong passphrase\r\n");
4718 tried_pubkey_config = FALSE;
4720 c_write_str("Unable to load private key\r\n");
4721 tried_pubkey_config = TRUE;
4723 /* Send a spurious AUTH_NONE to return to the top. */
4724 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4725 ssh2_pkt_addstring(username);
4726 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4727 ssh2_pkt_addstring("none"); /* method */
4729 type = AUTH_TYPE_NONE;
4731 unsigned char *pkblob, *sigblob, *sigdata;
4732 int pkblob_len, sigblob_len, sigdata_len;
4735 * We have loaded the private key and the server
4736 * has announced that it's willing to accept it.
4737 * Hallelujah. Generate a signature and send it.
4739 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4740 ssh2_pkt_addstring(username);
4741 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4742 ssh2_pkt_addstring("publickey"); /* method */
4743 ssh2_pkt_addbool(TRUE);
4744 ssh2_pkt_addstring(key->alg->name);
4745 pkblob = key->alg->public_blob(key->data, &pkblob_len);
4746 ssh2_pkt_addstring_start();
4747 ssh2_pkt_addstring_data(pkblob, pkblob_len);
4750 * The data to be signed is:
4754 * followed by everything so far placed in the
4757 sigdata_len = pktout.length - 5 + 4 + 20;
4758 sigdata = smalloc(sigdata_len);
4759 PUT_32BIT(sigdata, 20);
4760 memcpy(sigdata + 4, ssh2_session_id, 20);
4761 memcpy(sigdata + 24, pktout.data + 5,
4763 sigblob = key->alg->sign(key->data, sigdata,
4764 sigdata_len, &sigblob_len);
4765 ssh2_add_sigblob(pkblob, pkblob_len,
4766 sigblob, sigblob_len);
4772 type = AUTH_TYPE_PUBLICKEY;
4774 } else if (method == AUTH_PASSWORD) {
4776 * We send the password packet lumped tightly together with
4777 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
4778 * string long enough to make the total length of the two
4779 * packets constant. This should ensure that a passive
4780 * listener doing traffic analyis can't work out the length
4783 * For this to work, we need an assumption about the
4784 * maximum length of the password packet. I think 256 is
4785 * pretty conservative. Anyone using a password longer than
4786 * that probably doesn't have much to worry about from
4787 * people who find out how long their password is!
4789 ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4790 ssh2_pkt_addstring(username);
4791 ssh2_pkt_addstring("ssh-connection"); /* service requested */
4792 ssh2_pkt_addstring("password");
4793 ssh2_pkt_addbool(FALSE);
4794 ssh2_pkt_addstring(password);
4797 * We'll include a string that's an exact multiple of the
4798 * cipher block size. If the cipher is NULL for some
4799 * reason, we don't do this trick at all because we gain
4805 stringlen = (256 - deferred_len);
4806 stringlen += cscipher->blksize - 1;
4807 stringlen -= (stringlen % cscipher->blksize);
4810 * Temporarily disable actual compression,
4811 * so we can guarantee to get this string
4812 * exactly the length we want it. The
4813 * compression-disabling routine should
4814 * return an integer indicating how many
4815 * bytes we should adjust our string length
4818 stringlen -= cscomp->disable_compression();
4820 ssh2_pkt_init(SSH2_MSG_IGNORE);
4821 ssh2_pkt_addstring_start();
4822 for (i = 0; i < stringlen; i++) {
4823 char c = (char) random_byte();
4824 ssh2_pkt_addstring_data(&c, 1);
4828 ssh_pkt_defersend();
4829 logevent("Sent password");
4830 type = AUTH_TYPE_PASSWORD;
4831 } else if (method == AUTH_KEYBOARD_INTERACTIVE) {
4832 if (curr_prompt == 0) {
4833 ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
4834 ssh2_pkt_adduint32(num_prompts);
4836 if (need_pw) { /* only add pw if we just got one! */
4837 ssh2_pkt_addstring(password);
4838 memset(password, 0, sizeof(password));
4841 if (curr_prompt >= num_prompts) {
4845 * If there are prompts remaining, we set
4846 * `gotit' so that we won't attempt to get
4847 * another packet. Then we go back round the
4848 * loop and will end up retrieving another
4849 * prompt out of the existing packet. Funky or
4854 type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4857 ("No supported authentication methods left to try!\r\n");
4859 ("No supported authentications offered. Disconnecting");
4860 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
4861 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
4863 ("No supported authentication methods available");
4864 ssh2_pkt_addstring("en"); /* language tag */
4866 ssh_state = SSH_STATE_CLOSED;
4870 } while (!we_are_in);
4873 * Now we're authenticated for the connection protocol. The
4874 * connection protocol will automatically have started at this
4875 * point; there's no need to send SERVICE_REQUEST.
4879 * So now create a channel with a session in it.
4881 ssh_channels = newtree234(ssh_channelcmp);
4882 mainchan = smalloc(sizeof(struct ssh_channel));
4883 mainchan->localid = alloc_channel_id();
4884 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
4885 ssh2_pkt_addstring("session");
4886 ssh2_pkt_adduint32(mainchan->localid);
4887 mainchan->v.v2.locwindow = OUR_V2_WINSIZE;
4888 ssh2_pkt_adduint32(mainchan->v.v2.locwindow); /* our window size */
4889 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
4891 crWaitUntilV(ispkt);
4892 if (pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
4893 bombout(("Server refused to open a session"));
4895 /* FIXME: error data comes back in FAILURE packet */
4897 if (ssh2_pkt_getuint32() != mainchan->localid) {
4898 bombout(("Server's channel confirmation cited wrong channel"));
4901 mainchan->remoteid = ssh2_pkt_getuint32();
4902 mainchan->type = CHAN_MAINSESSION;
4903 mainchan->closes = 0;
4904 mainchan->v.v2.remwindow = ssh2_pkt_getuint32();
4905 mainchan->v.v2.remmaxpkt = ssh2_pkt_getuint32();
4906 bufchain_init(&mainchan->v.v2.outbuffer);
4907 add234(ssh_channels, mainchan);
4908 logevent("Opened channel for session");
4911 * Potentially enable X11 forwarding.
4913 if (cfg.x11_forward) {
4914 char proto[20], data[64];
4915 logevent("Requesting X11 forwarding");
4916 x11_invent_auth(proto, sizeof(proto), data, sizeof(data));
4917 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
4918 ssh2_pkt_adduint32(mainchan->remoteid);
4919 ssh2_pkt_addstring("x11-req");
4920 ssh2_pkt_addbool(1); /* want reply */
4921 ssh2_pkt_addbool(0); /* many connections */
4922 ssh2_pkt_addstring(proto);
4923 ssh2_pkt_addstring(data);
4924 ssh2_pkt_adduint32(0); /* screen number */
4928 crWaitUntilV(ispkt);
4929 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
4930 unsigned i = ssh2_pkt_getuint32();
4931 struct ssh_channel *c;
4932 c = find234(ssh_channels, &i, ssh_channelfind);
4934 continue; /* nonexistent channel */
4935 c->v.v2.remwindow += ssh2_pkt_getuint32();
4937 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4939 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
4940 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
4941 bombout(("Unexpected response to X11 forwarding request:"
4942 " packet type %d", pktin.type));
4945 logevent("X11 forwarding refused");
4947 logevent("X11 forwarding enabled");
4948 ssh_X11_fwd_enabled = TRUE;
4953 * Enable port forwardings.
4956 static char *e; /* preserve across crReturn */
4959 int sport,dport,sserv,dserv;
4960 char sports[256], dports[256], host[256];
4964 ssh_rportfwds = newtree234(ssh_rportcmp_ssh2);
4965 /* Add port forwardings. */
4970 while (*e && *e != '\t')
4976 while (*e && *e != ':')
4986 dport = atoi(dports);
4990 se = getservbyname(dports, NULL);
4992 dport = ntohs(se->s_port);
4995 "Service lookup failed for destination port \"%s\"",
5000 sport = atoi(sports);
5004 se = getservbyname(sports, NULL);
5006 sport = ntohs(se->s_port);
5009 "Service lookup failed for source port \"%s\"",
5014 if (sport && dport) {
5016 pfd_addforward(host, dport, sport);
5017 sprintf(buf, "Local port %.*s%.*s%d%.*s forwarding to"
5018 " %s:%.*s%.*s%d%.*s",
5019 sserv ? strlen(sports) : 0, sports,
5020 sserv, "(", sport, sserv, ")",
5022 dserv ? strlen(dports) : 0, dports,
5023 dserv, "(", dport, dserv, ")");
5026 struct ssh_rportfwd *pf;
5027 pf = smalloc(sizeof(*pf));
5028 strcpy(pf->dhost, host);
5031 if (add234(ssh_rportfwds, pf) != pf) {
5033 "Duplicate remote port forwarding to %s:%d",
5038 sprintf(buf, "Requesting remote port %.*s%.*s%d%.*s"
5039 " forward to %s:%.*s%.*s%d%.*s",
5040 sserv ? strlen(sports) : 0, sports,
5041 sserv, "(", sport, sserv, ")",
5043 dserv ? strlen(dports) : 0, dports,
5044 dserv, "(", dport, dserv, ")");
5046 ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5047 ssh2_pkt_addstring("tcpip-forward");
5048 ssh2_pkt_addbool(1);/* want reply */
5049 if (cfg.rport_acceptall)
5050 ssh2_pkt_addstring("0.0.0.0");
5052 ssh2_pkt_addstring("127.0.0.1");
5053 ssh2_pkt_adduint32(sport);
5057 crWaitUntilV(ispkt);
5058 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5059 unsigned i = ssh2_pkt_getuint32();
5060 struct ssh_channel *c;
5061 c = find234(ssh_channels, &i, ssh_channelfind);
5063 continue;/* nonexistent channel */
5064 c->v.v2.remwindow += ssh2_pkt_getuint32();
5066 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5068 if (pktin.type != SSH2_MSG_REQUEST_SUCCESS) {
5069 if (pktin.type != SSH2_MSG_REQUEST_FAILURE) {
5070 bombout(("Unexpected response to port "
5071 "forwarding request: packet type %d",
5075 logevent("Server refused this port forwarding");
5077 logevent("Remote port forwarding enabled");
5086 * Potentially enable agent forwarding.
5088 if (cfg.agentfwd && agent_exists()) {
5089 logevent("Requesting OpenSSH-style agent forwarding");
5090 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
5091 ssh2_pkt_adduint32(mainchan->remoteid);
5092 ssh2_pkt_addstring("auth-agent-req@openssh.com");
5093 ssh2_pkt_addbool(1); /* want reply */
5097 crWaitUntilV(ispkt);
5098 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5099 unsigned i = ssh2_pkt_getuint32();
5100 struct ssh_channel *c;
5101 c = find234(ssh_channels, &i, ssh_channelfind);
5103 continue; /* nonexistent channel */
5104 c->v.v2.remwindow += ssh2_pkt_getuint32();
5106 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5108 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5109 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5110 bombout(("Unexpected response to agent forwarding request:"
5111 " packet type %d", pktin.type));
5114 logevent("Agent forwarding refused");
5116 logevent("Agent forwarding enabled");
5117 ssh_agentfwd_enabled = TRUE;
5122 * Now allocate a pty for the session.
5125 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
5126 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
5127 ssh2_pkt_addstring("pty-req");
5128 ssh2_pkt_addbool(1); /* want reply */
5129 ssh2_pkt_addstring(cfg.termtype);
5130 ssh2_pkt_adduint32(cols);
5131 ssh2_pkt_adduint32(rows);
5132 ssh2_pkt_adduint32(0); /* pixel width */
5133 ssh2_pkt_adduint32(0); /* pixel height */
5134 ssh2_pkt_addstring_start();
5135 ssh2_pkt_addstring_data("\0", 1); /* TTY_OP_END, no special options */
5137 ssh_state = SSH_STATE_INTERMED;
5140 crWaitUntilV(ispkt);
5141 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5142 unsigned i = ssh2_pkt_getuint32();
5143 struct ssh_channel *c;
5144 c = find234(ssh_channels, &i, ssh_channelfind);
5146 continue; /* nonexistent channel */
5147 c->v.v2.remwindow += ssh2_pkt_getuint32();
5149 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5151 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5152 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5153 bombout(("Unexpected response to pty request:"
5154 " packet type %d", pktin.type));
5157 c_write_str("Server refused to allocate pty\r\n");
5158 ssh_editing = ssh_echoing = 1;
5160 logevent("Allocated pty");
5163 ssh_editing = ssh_echoing = 1;
5167 * Start a shell or a remote command. We may have to attempt
5168 * this twice if the config data has provided a second choice
5175 if (ssh_fallback_cmd) {
5176 subsys = cfg.ssh_subsys2;
5177 cmd = cfg.remote_cmd_ptr2;
5179 subsys = cfg.ssh_subsys;
5180 cmd = cfg.remote_cmd_ptr;
5183 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
5184 ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
5186 ssh2_pkt_addstring("subsystem");
5187 ssh2_pkt_addbool(1); /* want reply */
5188 ssh2_pkt_addstring(cmd);
5190 ssh2_pkt_addstring("exec");
5191 ssh2_pkt_addbool(1); /* want reply */
5192 ssh2_pkt_addstring(cmd);
5194 ssh2_pkt_addstring("shell");
5195 ssh2_pkt_addbool(1); /* want reply */
5199 crWaitUntilV(ispkt);
5200 if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5201 unsigned i = ssh2_pkt_getuint32();
5202 struct ssh_channel *c;
5203 c = find234(ssh_channels, &i, ssh_channelfind);
5205 continue; /* nonexistent channel */
5206 c->v.v2.remwindow += ssh2_pkt_getuint32();
5208 } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5209 if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5210 if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
5211 bombout(("Unexpected response to shell/command request:"
5212 " packet type %d", pktin.type));
5216 * We failed to start the command. If this is the
5217 * fallback command, we really are finished; if it's
5218 * not, and if the fallback command exists, try falling
5219 * back to it before complaining.
5221 if (!ssh_fallback_cmd && cfg.remote_cmd_ptr2 != NULL) {
5222 logevent("Primary command failed; attempting fallback");
5223 ssh_fallback_cmd = TRUE;
5226 bombout(("Server refused to start a shell/command"));
5229 logevent("Started a shell/command");
5234 ssh_state = SSH_STATE_SESSION;
5238 ssh_special(TS_EOF);
5243 ldisc_send(NULL, 0, 0); /* cause ldisc to notice changes */
5246 static int try_send;
5250 if (pktin.type == SSH2_MSG_CHANNEL_DATA ||
5251 pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
5254 unsigned i = ssh2_pkt_getuint32();
5255 struct ssh_channel *c;
5256 c = find234(ssh_channels, &i, ssh_channelfind);
5258 continue; /* nonexistent channel */
5259 if (pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
5260 ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR)
5261 continue; /* extended but not stderr */
5262 ssh2_pkt_getstring(&data, &length);
5265 c->v.v2.locwindow -= length;
5267 case CHAN_MAINSESSION:
5269 from_backend(pktin.type ==
5270 SSH2_MSG_CHANNEL_EXTENDED_DATA,
5274 bufsize = x11_send(c->u.x11.s, data, length);
5277 bufsize = pfd_send(c->u.pfd.s, data, length);
5280 while (length > 0) {
5281 if (c->u.a.lensofar < 4) {
5282 int l = min(4 - c->u.a.lensofar, length);
5283 memcpy(c->u.a.msglen + c->u.a.lensofar,
5287 c->u.a.lensofar += l;
5289 if (c->u.a.lensofar == 4) {
5291 4 + GET_32BIT(c->u.a.msglen);
5292 c->u.a.message = smalloc(c->u.a.totallen);
5293 memcpy(c->u.a.message, c->u.a.msglen, 4);
5295 if (c->u.a.lensofar >= 4 && length > 0) {
5297 min(c->u.a.totallen - c->u.a.lensofar,
5299 memcpy(c->u.a.message + c->u.a.lensofar,
5303 c->u.a.lensofar += l;
5305 if (c->u.a.lensofar == c->u.a.totallen) {
5306 void *reply, *sentreply;
5308 agent_query(c->u.a.message,
5309 c->u.a.totallen, &reply,
5314 /* Fake SSH_AGENT_FAILURE. */
5315 sentreply = "\0\0\0\1\5";
5318 ssh2_add_channel_data(c, sentreply,
5323 sfree(c->u.a.message);
5324 c->u.a.lensofar = 0;
5331 * If we are not buffering too much data,
5332 * enlarge the window again at the remote side.
5334 if (bufsize < OUR_V2_WINSIZE)
5335 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
5337 } else if (pktin.type == SSH2_MSG_DISCONNECT) {
5338 ssh_state = SSH_STATE_CLOSED;
5339 logevent("Received disconnect message");
5341 } else if (pktin.type == SSH2_MSG_CHANNEL_EOF) {
5342 unsigned i = ssh2_pkt_getuint32();
5343 struct ssh_channel *c;
5345 c = find234(ssh_channels, &i, ssh_channelfind);
5347 continue; /* nonexistent channel */
5349 if (c->type == CHAN_X11) {
5351 * Remote EOF on an X11 channel means we should
5352 * wrap up and close the channel ourselves.
5354 x11_close(c->u.x11.s);
5356 } else if (c->type == CHAN_AGENT) {
5358 } else if (c->type == CHAN_SOCKDATA) {
5359 pfd_close(c->u.pfd.s);
5362 } else if (pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
5363 unsigned i = ssh2_pkt_getuint32();
5364 struct ssh_channel *c;
5366 c = find234(ssh_channels, &i, ssh_channelfind);
5367 if (!c || ((int)c->remoteid) == -1) {
5368 bombout(("Received CHANNEL_CLOSE for %s channel %d\n",
5369 c ? "half-open" : "nonexistent", i));
5371 /* Do pre-close processing on the channel. */
5373 case CHAN_MAINSESSION:
5374 break; /* nothing to see here, move along */
5376 if (c->u.x11.s != NULL)
5377 x11_close(c->u.x11.s);
5384 if (c->u.pfd.s != NULL)
5385 pfd_close(c->u.pfd.s);
5389 if (c->closes == 0) {
5390 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
5391 ssh2_pkt_adduint32(c->remoteid);
5394 del234(ssh_channels, c);
5395 bufchain_clear(&c->v.v2.outbuffer);
5399 * See if that was the last channel left open.
5401 if (count234(ssh_channels) == 0) {
5404 * We used to send SSH_MSG_DISCONNECT here,
5405 * because I'd believed that _every_ conforming
5406 * SSH2 connection had to end with a disconnect
5407 * being sent by at least one side; apparently
5408 * I was wrong and it's perfectly OK to
5409 * unceremoniously slam the connection shut
5410 * when you're done, and indeed OpenSSH feels
5411 * this is more polite than sending a
5412 * DISCONNECT. So now we don't.
5414 logevent("All channels closed. Disconnecting");
5415 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
5416 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
5417 ssh2_pkt_addstring("All open channels closed");
5418 ssh2_pkt_addstring("en"); /* language tag */
5421 ssh_state = SSH_STATE_CLOSED;
5424 continue; /* remote sends close; ignore (FIXME) */
5425 } else if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5426 unsigned i = ssh2_pkt_getuint32();
5427 struct ssh_channel *c;
5428 c = find234(ssh_channels, &i, ssh_channelfind);
5430 continue; /* nonexistent channel */
5431 c->v.v2.remwindow += ssh2_pkt_getuint32();
5433 } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
5434 unsigned i = ssh2_pkt_getuint32();
5435 struct ssh_channel *c;
5436 c = find234(ssh_channels, &i, ssh_channelfind);
5438 continue; /* nonexistent channel */
5439 if (c->type != CHAN_SOCKDATA_DORMANT)
5440 continue; /* dunno why they're confirming this */
5441 c->remoteid = ssh2_pkt_getuint32();
5442 c->type = CHAN_SOCKDATA;
5443 c->v.v2.remwindow = ssh2_pkt_getuint32();
5444 c->v.v2.remmaxpkt = ssh2_pkt_getuint32();
5446 pfd_confirm(c->u.pfd.s);
5449 * We have a pending close on this channel,
5450 * which we decided on before the server acked
5451 * the channel open. So now we know the
5452 * remoteid, we can close it again.
5454 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
5455 ssh2_pkt_adduint32(c->remoteid);
5458 } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN_FAILURE) {
5459 unsigned i = ssh2_pkt_getuint32();
5460 struct ssh_channel *c;
5461 c = find234(ssh_channels, &i, ssh_channelfind);
5463 continue; /* nonexistent channel */
5464 if (c->type != CHAN_SOCKDATA_DORMANT)
5465 continue; /* dunno why they're failing this */
5467 logevent("Forwarded connection refused by server");
5469 pfd_close(c->u.pfd.s);
5471 del234(ssh_channels, c);
5473 } else if (pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
5476 int typelen, want_reply;
5477 struct ssh_channel *c;
5479 localid = ssh2_pkt_getuint32();
5480 ssh2_pkt_getstring(&type, &typelen);
5481 want_reply = ssh2_pkt_getbool();
5484 * First, check that the channel exists. Otherwise,
5485 * we can instantly disconnect with a rude message.
5487 c = find234(ssh_channels, &localid, ssh_channelfind);
5490 sprintf(buf, "Received channel request for nonexistent"
5491 " channel %d", localid);
5493 ssh2_pkt_init(SSH2_MSG_DISCONNECT);
5494 ssh2_pkt_adduint32(SSH2_DISCONNECT_BY_APPLICATION);
5495 ssh2_pkt_addstring(buf);
5496 ssh2_pkt_addstring("en"); /* language tag */
5498 connection_fatal("%s", buf);
5499 ssh_state = SSH_STATE_CLOSED;
5504 * Having got the channel number, we now look at
5505 * the request type string to see if it's something
5508 if (typelen == 11 && !memcmp(type, "exit-status", 11) &&
5510 /* We recognise "exit-status" on the primary channel. */
5512 ssh_exitcode = ssh2_pkt_getuint32();
5513 sprintf(buf, "Server sent command exit status %d",
5517 ssh2_pkt_init(SSH2_MSG_CHANNEL_SUCCESS);
5518 ssh2_pkt_adduint32(c->remoteid);
5523 * This is a channel request we don't know
5524 * about, so we now either ignore the request
5525 * or respond with CHANNEL_FAILURE, depending
5529 ssh2_pkt_init(SSH2_MSG_CHANNEL_FAILURE);
5530 ssh2_pkt_adduint32(c->remoteid);
5534 } else if (pktin.type == SSH2_MSG_GLOBAL_REQUEST) {
5536 int typelen, want_reply;
5538 ssh2_pkt_getstring(&type, &typelen);
5539 want_reply = ssh2_pkt_getbool();
5542 * We currently don't support any global requests
5543 * at all, so we either ignore the request or
5544 * respond with REQUEST_FAILURE, depending on
5548 ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
5551 } else if (pktin.type == SSH2_MSG_CHANNEL_OPEN) {
5555 struct ssh_channel *c;
5556 unsigned remid, winsize, pktsize;
5557 ssh2_pkt_getstring(&type, &typelen);
5558 c = smalloc(sizeof(struct ssh_channel));
5560 remid = ssh2_pkt_getuint32();
5561 winsize = ssh2_pkt_getuint32();
5562 pktsize = ssh2_pkt_getuint32();
5564 if (typelen == 3 && !memcmp(type, "x11", 3)) {
5565 if (!ssh_X11_fwd_enabled)
5566 error = "X11 forwarding is not enabled";
5567 else if (x11_init(&c->u.x11.s, cfg.x11_display, c) !=
5569 error = "Unable to open an X11 connection";
5573 } else if (typelen == 15 &&
5574 !memcmp(type, "forwarded-tcpip", 15)) {
5575 struct ssh_rportfwd pf, *realpf;
5578 ssh2_pkt_getstring(&dummy, &dummylen);/* skip address */
5579 pf.sport = ssh2_pkt_getuint32();
5580 realpf = find234(ssh_rportfwds, &pf, NULL);
5581 if (realpf == NULL) {
5582 error = "Remote port is not recognised";
5584 char *e = pfd_newconnect(&c->u.pfd.s, realpf->dhost,
5587 sprintf(buf, "Received remote port open request for %s:%d",
5588 realpf->dhost, realpf->dport);
5591 sprintf(buf, "Port open failed: %s", e);
5593 error = "Port open failed";
5595 logevent("Forwarded port opened successfully");
5596 c->type = CHAN_SOCKDATA;
5599 } else if (typelen == 22 &&
5600 !memcmp(type, "auth-agent@openssh.com", 3)) {
5601 if (!ssh_agentfwd_enabled)
5602 error = "Agent forwarding is not enabled";
5604 c->type = CHAN_AGENT; /* identify channel type */
5605 c->u.a.lensofar = 0;
5608 error = "Unsupported channel type requested";
5611 c->remoteid = remid;
5613 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
5614 ssh2_pkt_adduint32(c->remoteid);
5615 ssh2_pkt_adduint32(SSH2_OPEN_CONNECT_FAILED);
5616 ssh2_pkt_addstring(error);
5617 ssh2_pkt_addstring("en"); /* language tag */
5621 c->localid = alloc_channel_id();
5623 c->v.v2.locwindow = OUR_V2_WINSIZE;
5624 c->v.v2.remwindow = winsize;
5625 c->v.v2.remmaxpkt = pktsize;
5626 bufchain_init(&c->v.v2.outbuffer);
5627 add234(ssh_channels, c);
5628 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
5629 ssh2_pkt_adduint32(c->remoteid);
5630 ssh2_pkt_adduint32(c->localid);
5631 ssh2_pkt_adduint32(c->v.v2.locwindow);
5632 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
5636 bombout(("Strange packet received: type %d", pktin.type));
5641 * We have spare data. Add it to the channel buffer.
5643 ssh2_add_channel_data(mainchan, in, inlen);
5648 struct ssh_channel *c;
5650 * Try to send data on all channels if we can.
5652 for (i = 0; NULL != (c = index234(ssh_channels, i)); i++) {
5653 int bufsize = ssh2_try_send(c);
5656 case CHAN_MAINSESSION:
5657 /* stdin need not receive an unthrottle
5658 * notification since it will be polled */
5661 x11_unthrottle(c->u.x11.s);
5664 /* agent sockets are request/response and need no
5665 * buffer management */
5668 pfd_unthrottle(c->u.pfd.s);
5680 * Handle the top-level SSH2 protocol.
5682 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt)
5684 if (do_ssh2_transport(in, inlen, ispkt) == 0)
5686 do_ssh2_authconn(in, inlen, ispkt);
5690 * Called to set up the connection.
5692 * Returns an error message, or NULL on success.
5694 static char *ssh_init(char *host, int port, char **realhost, int nodelay)
5699 if (crypto_startup() == 0)
5700 return "Microsoft high encryption pack not installed!";
5706 ssh1_throttle_count = 0;
5707 ssh_overall_bufsize = 0;
5708 ssh_fallback_cmd = 0;
5710 p = connect_to_host(host, port, realhost, nodelay);
5718 * Called to send data down the Telnet connection.
5720 static int ssh_send(char *buf, int len)
5722 if (s == NULL || ssh_protocol == NULL)
5725 ssh_protocol(buf, len, 0);
5727 return ssh_sendbuffer();
5731 * Called to query the current amount of buffered stdin data.
5733 static int ssh_sendbuffer(void)
5737 if (s == NULL || ssh_protocol == NULL)
5741 * If the SSH socket itself has backed up, add the total backup
5742 * size on that to any individual buffer on the stdin channel.
5745 if (ssh_throttled_all)
5746 override_value = ssh_overall_bufsize;
5748 if (ssh_version == 1) {
5749 return override_value;
5750 } else if (ssh_version == 2) {
5751 if (!mainchan || mainchan->closes > 0)
5752 return override_value;
5754 return override_value + bufchain_size(&mainchan->v.v2.outbuffer);
5761 * Called to set the size of the window from SSH's POV.
5763 static void ssh_size(void)
5765 switch (ssh_state) {
5766 case SSH_STATE_BEFORE_SIZE:
5767 case SSH_STATE_PREPACKET:
5768 case SSH_STATE_CLOSED:
5769 break; /* do nothing */
5770 case SSH_STATE_INTERMED:
5771 size_needed = TRUE; /* buffer for later */
5773 case SSH_STATE_SESSION:
5775 if (ssh_version == 1) {
5776 send_packet(SSH1_CMSG_WINDOW_SIZE,
5777 PKT_INT, rows, PKT_INT, cols,
5778 PKT_INT, 0, PKT_INT, 0, PKT_END);
5780 ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
5781 ssh2_pkt_adduint32(mainchan->remoteid);
5782 ssh2_pkt_addstring("window-change");
5783 ssh2_pkt_addbool(0);
5784 ssh2_pkt_adduint32(cols);
5785 ssh2_pkt_adduint32(rows);
5786 ssh2_pkt_adduint32(0);
5787 ssh2_pkt_adduint32(0);
5796 * Send Telnet special codes. TS_EOF is useful for `plink', so you
5797 * can send an EOF and collect resulting output (e.g. `plink
5800 static void ssh_special(Telnet_Special code)
5802 if (code == TS_EOF) {
5803 if (ssh_state != SSH_STATE_SESSION) {
5805 * Buffer the EOF in case we are pre-SESSION, so we can
5806 * send it as soon as we reach SESSION.
5812 if (ssh_version == 1) {
5813 send_packet(SSH1_CMSG_EOF, PKT_END);
5815 ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
5816 ssh2_pkt_adduint32(mainchan->remoteid);
5819 logevent("Sent EOF message");
5820 } else if (code == TS_PING) {
5821 if (ssh_state == SSH_STATE_CLOSED
5822 || ssh_state == SSH_STATE_PREPACKET) return;
5823 if (ssh_version == 1) {
5824 if (!(ssh_remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
5825 send_packet(SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
5827 ssh2_pkt_init(SSH2_MSG_IGNORE);
5828 ssh2_pkt_addstring_start();
5836 void *new_sock_channel(Socket s)
5838 struct ssh_channel *c;
5839 c = smalloc(sizeof(struct ssh_channel));
5842 c->remoteid = -1; /* to be set when open confirmed */
5843 c->localid = alloc_channel_id();
5845 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
5847 bufchain_init(&c->v.v2.outbuffer);
5848 add234(ssh_channels, c);
5854 * This is called when stdout/stderr (the entity to which
5855 * from_backend sends data) manages to clear some backlog.
5857 void ssh_unthrottle(int bufsize)
5859 if (ssh_version == 1) {
5860 if (ssh1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
5861 ssh1_stdout_throttling = 0;
5865 if (mainchan && mainchan->closes == 0)
5866 ssh2_set_window(mainchan, OUR_V2_WINSIZE - bufsize);
5870 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
5872 struct ssh_channel *c = (struct ssh_channel *)channel;
5875 sprintf(buf, "Opening forwarded connection to %.512s:%d", hostname, port);
5878 if (ssh_version == 1) {
5879 send_packet(SSH1_MSG_PORT_OPEN,
5880 PKT_INT, c->localid,
5883 //PKT_STR, <org:orgport>,
5886 ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
5887 ssh2_pkt_addstring("direct-tcpip");
5888 ssh2_pkt_adduint32(c->localid);
5889 c->v.v2.locwindow = OUR_V2_WINSIZE;
5890 ssh2_pkt_adduint32(c->v.v2.locwindow);/* our window size */
5891 ssh2_pkt_adduint32(0x4000UL); /* our max pkt size */
5892 ssh2_pkt_addstring(hostname);
5893 ssh2_pkt_adduint32(port);
5895 * We make up values for the originator data; partly it's
5896 * too much hassle to keep track, and partly I'm not
5897 * convinced the server should be told details like that
5898 * about my local network configuration.
5900 ssh2_pkt_addstring("client-side-connection");
5901 ssh2_pkt_adduint32(0);
5907 static Socket ssh_socket(void)
5912 static int ssh_sendok(void)
5917 static int ssh_ldisc(int option)
5919 if (option == LD_ECHO)
5921 if (option == LD_EDIT)
5926 static int ssh_return_exitcode(void)
5928 return ssh_exitcode;
5931 Backend ssh_backend = {
5938 ssh_return_exitcode,