23 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
24 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
25 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
26 #define SSH1_CMSG_USER 4 /* 0x4 */
27 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
28 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
29 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
30 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
31 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
32 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
33 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
34 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
35 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
36 #define SSH1_SMSG_FAILURE 15 /* 0xf */
37 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
38 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
39 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
40 #define SSH1_CMSG_EOF 19 /* 0x13 */
41 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
42 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
43 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
44 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
45 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
46 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
47 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
48 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
49 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
50 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
51 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
52 #define SSH1_MSG_IGNORE 32 /* 0x20 */
53 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
54 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
55 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
56 #define SSH1_MSG_DEBUG 36 /* 0x24 */
57 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
58 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
59 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
60 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
61 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
62 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
63 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
65 #define SSH1_AUTH_TIS 5 /* 0x5 */
66 #define SSH1_AUTH_CCARD 16 /* 0x10 */
68 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
69 /* Mask for protoflags we will echo back to server if seen */
70 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
72 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
73 #define SSH2_MSG_IGNORE 2 /* 0x2 */
74 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
75 #define SSH2_MSG_DEBUG 4 /* 0x4 */
76 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
77 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
78 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
79 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
80 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
81 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
82 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
83 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
84 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
85 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
86 #define SSH2_MSG_KEXRSA_PUBKEY 30 /* 0x1e */
87 #define SSH2_MSG_KEXRSA_SECRET 31 /* 0x1f */
88 #define SSH2_MSG_KEXRSA_DONE 32 /* 0x20 */
89 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
90 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
91 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
92 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
93 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
94 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
95 #define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */
96 #define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */
97 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
98 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
99 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
100 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
101 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
102 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
103 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
104 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
105 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
106 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
107 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
108 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
109 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
110 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
113 * Packet type contexts, so that ssh2_pkt_type can correctly decode
114 * the ambiguous type numbers back into the correct type strings.
116 #define SSH2_PKTCTX_DHGROUP 0x0001
117 #define SSH2_PKTCTX_DHGEX 0x0002
118 #define SSH2_PKTCTX_RSAKEX 0x0004
119 #define SSH2_PKTCTX_KEX_MASK 0x000F
120 #define SSH2_PKTCTX_PUBLICKEY 0x0010
121 #define SSH2_PKTCTX_PASSWORD 0x0020
122 #define SSH2_PKTCTX_KBDINTER 0x0040
123 #define SSH2_PKTCTX_AUTH_MASK 0x00F0
125 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
126 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
127 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
128 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
129 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
130 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
131 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
132 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
133 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
134 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
135 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
136 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
137 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
138 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
139 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
141 static const char *const ssh2_disconnect_reasons[] = {
143 "host not allowed to connect",
145 "key exchange failed",
146 "host authentication failed",
149 "service not available",
150 "protocol version not supported",
151 "host key not verifiable",
154 "too many connections",
155 "auth cancelled by user",
156 "no more auth methods available",
160 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
161 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
162 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
163 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
165 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
168 * Various remote-bug flags.
170 #define BUG_CHOKES_ON_SSH1_IGNORE 1
171 #define BUG_SSH2_HMAC 2
172 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
173 #define BUG_CHOKES_ON_RSA 8
174 #define BUG_SSH2_RSA_PADDING 16
175 #define BUG_SSH2_DERIVEKEY 32
176 #define BUG_SSH2_REKEY 64
177 #define BUG_SSH2_PK_SESSIONID 128
180 * Codes for terminal modes.
181 * Most of these are the same in SSH-1 and SSH-2.
182 * This list is derived from draft-ietf-secsh-connect-25 and
185 static const struct {
186 const char* const mode;
188 enum { TTY_OP_CHAR, TTY_OP_BOOL } type;
190 /* "V" prefix discarded for special characters relative to SSH specs */
191 { "INTR", 1, TTY_OP_CHAR },
192 { "QUIT", 2, TTY_OP_CHAR },
193 { "ERASE", 3, TTY_OP_CHAR },
194 { "KILL", 4, TTY_OP_CHAR },
195 { "EOF", 5, TTY_OP_CHAR },
196 { "EOL", 6, TTY_OP_CHAR },
197 { "EOL2", 7, TTY_OP_CHAR },
198 { "START", 8, TTY_OP_CHAR },
199 { "STOP", 9, TTY_OP_CHAR },
200 { "SUSP", 10, TTY_OP_CHAR },
201 { "DSUSP", 11, TTY_OP_CHAR },
202 { "REPRINT", 12, TTY_OP_CHAR },
203 { "WERASE", 13, TTY_OP_CHAR },
204 { "LNEXT", 14, TTY_OP_CHAR },
205 { "FLUSH", 15, TTY_OP_CHAR },
206 { "SWTCH", 16, TTY_OP_CHAR },
207 { "STATUS", 17, TTY_OP_CHAR },
208 { "DISCARD", 18, TTY_OP_CHAR },
209 { "IGNPAR", 30, TTY_OP_BOOL },
210 { "PARMRK", 31, TTY_OP_BOOL },
211 { "INPCK", 32, TTY_OP_BOOL },
212 { "ISTRIP", 33, TTY_OP_BOOL },
213 { "INLCR", 34, TTY_OP_BOOL },
214 { "IGNCR", 35, TTY_OP_BOOL },
215 { "ICRNL", 36, TTY_OP_BOOL },
216 { "IUCLC", 37, TTY_OP_BOOL },
217 { "IXON", 38, TTY_OP_BOOL },
218 { "IXANY", 39, TTY_OP_BOOL },
219 { "IXOFF", 40, TTY_OP_BOOL },
220 { "IMAXBEL", 41, TTY_OP_BOOL },
221 { "ISIG", 50, TTY_OP_BOOL },
222 { "ICANON", 51, TTY_OP_BOOL },
223 { "XCASE", 52, TTY_OP_BOOL },
224 { "ECHO", 53, TTY_OP_BOOL },
225 { "ECHOE", 54, TTY_OP_BOOL },
226 { "ECHOK", 55, TTY_OP_BOOL },
227 { "ECHONL", 56, TTY_OP_BOOL },
228 { "NOFLSH", 57, TTY_OP_BOOL },
229 { "TOSTOP", 58, TTY_OP_BOOL },
230 { "IEXTEN", 59, TTY_OP_BOOL },
231 { "ECHOCTL", 60, TTY_OP_BOOL },
232 { "ECHOKE", 61, TTY_OP_BOOL },
233 { "PENDIN", 62, TTY_OP_BOOL }, /* XXX is this a real mode? */
234 { "OPOST", 70, TTY_OP_BOOL },
235 { "OLCUC", 71, TTY_OP_BOOL },
236 { "ONLCR", 72, TTY_OP_BOOL },
237 { "OCRNL", 73, TTY_OP_BOOL },
238 { "ONOCR", 74, TTY_OP_BOOL },
239 { "ONLRET", 75, TTY_OP_BOOL },
240 { "CS7", 90, TTY_OP_BOOL },
241 { "CS8", 91, TTY_OP_BOOL },
242 { "PARENB", 92, TTY_OP_BOOL },
243 { "PARODD", 93, TTY_OP_BOOL }
246 /* Miscellaneous other tty-related constants. */
247 #define SSH_TTY_OP_END 0
248 /* The opcodes for ISPEED/OSPEED differ between SSH-1 and SSH-2. */
249 #define SSH1_TTY_OP_ISPEED 192
250 #define SSH1_TTY_OP_OSPEED 193
251 #define SSH2_TTY_OP_ISPEED 128
252 #define SSH2_TTY_OP_OSPEED 129
254 /* Helper functions for parsing tty-related config. */
255 static unsigned int ssh_tty_parse_specchar(char *s)
260 ret = ctrlparse(s, &next);
261 if (!next) ret = s[0];
263 ret = 255; /* special value meaning "don't set" */
267 static unsigned int ssh_tty_parse_boolean(char *s)
269 if (stricmp(s, "yes") == 0 ||
270 stricmp(s, "on") == 0 ||
271 stricmp(s, "true") == 0 ||
272 stricmp(s, "+") == 0)
274 else if (stricmp(s, "no") == 0 ||
275 stricmp(s, "off") == 0 ||
276 stricmp(s, "false") == 0 ||
277 stricmp(s, "-") == 0)
278 return 0; /* false */
280 return (atoi(s) != 0);
283 #define translate(x) if (type == x) return #x
284 #define translatec(x,ctx) if (type == x && (pkt_ctx & ctx)) return #x
285 static char *ssh1_pkt_type(int type)
287 translate(SSH1_MSG_DISCONNECT);
288 translate(SSH1_SMSG_PUBLIC_KEY);
289 translate(SSH1_CMSG_SESSION_KEY);
290 translate(SSH1_CMSG_USER);
291 translate(SSH1_CMSG_AUTH_RSA);
292 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
293 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
294 translate(SSH1_CMSG_AUTH_PASSWORD);
295 translate(SSH1_CMSG_REQUEST_PTY);
296 translate(SSH1_CMSG_WINDOW_SIZE);
297 translate(SSH1_CMSG_EXEC_SHELL);
298 translate(SSH1_CMSG_EXEC_CMD);
299 translate(SSH1_SMSG_SUCCESS);
300 translate(SSH1_SMSG_FAILURE);
301 translate(SSH1_CMSG_STDIN_DATA);
302 translate(SSH1_SMSG_STDOUT_DATA);
303 translate(SSH1_SMSG_STDERR_DATA);
304 translate(SSH1_CMSG_EOF);
305 translate(SSH1_SMSG_EXIT_STATUS);
306 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
307 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
308 translate(SSH1_MSG_CHANNEL_DATA);
309 translate(SSH1_MSG_CHANNEL_CLOSE);
310 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
311 translate(SSH1_SMSG_X11_OPEN);
312 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
313 translate(SSH1_MSG_PORT_OPEN);
314 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
315 translate(SSH1_SMSG_AGENT_OPEN);
316 translate(SSH1_MSG_IGNORE);
317 translate(SSH1_CMSG_EXIT_CONFIRMATION);
318 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
319 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
320 translate(SSH1_MSG_DEBUG);
321 translate(SSH1_CMSG_REQUEST_COMPRESSION);
322 translate(SSH1_CMSG_AUTH_TIS);
323 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
324 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
325 translate(SSH1_CMSG_AUTH_CCARD);
326 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
327 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
330 static char *ssh2_pkt_type(int pkt_ctx, int type)
332 translate(SSH2_MSG_DISCONNECT);
333 translate(SSH2_MSG_IGNORE);
334 translate(SSH2_MSG_UNIMPLEMENTED);
335 translate(SSH2_MSG_DEBUG);
336 translate(SSH2_MSG_SERVICE_REQUEST);
337 translate(SSH2_MSG_SERVICE_ACCEPT);
338 translate(SSH2_MSG_KEXINIT);
339 translate(SSH2_MSG_NEWKEYS);
340 translatec(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP);
341 translatec(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP);
342 translatec(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
343 translatec(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
344 translatec(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
345 translatec(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
346 translatec(SSH2_MSG_KEXRSA_PUBKEY, SSH2_PKTCTX_RSAKEX);
347 translatec(SSH2_MSG_KEXRSA_SECRET, SSH2_PKTCTX_RSAKEX);
348 translatec(SSH2_MSG_KEXRSA_DONE, SSH2_PKTCTX_RSAKEX);
349 translate(SSH2_MSG_USERAUTH_REQUEST);
350 translate(SSH2_MSG_USERAUTH_FAILURE);
351 translate(SSH2_MSG_USERAUTH_SUCCESS);
352 translate(SSH2_MSG_USERAUTH_BANNER);
353 translatec(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
354 translatec(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
355 translatec(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
356 translatec(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
357 translate(SSH2_MSG_GLOBAL_REQUEST);
358 translate(SSH2_MSG_REQUEST_SUCCESS);
359 translate(SSH2_MSG_REQUEST_FAILURE);
360 translate(SSH2_MSG_CHANNEL_OPEN);
361 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
362 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
363 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
364 translate(SSH2_MSG_CHANNEL_DATA);
365 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
366 translate(SSH2_MSG_CHANNEL_EOF);
367 translate(SSH2_MSG_CHANNEL_CLOSE);
368 translate(SSH2_MSG_CHANNEL_REQUEST);
369 translate(SSH2_MSG_CHANNEL_SUCCESS);
370 translate(SSH2_MSG_CHANNEL_FAILURE);
376 /* Enumeration values for fields in SSH-1 packets */
378 PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
379 /* These values are for communicating relevant semantics of
380 * fields to the packet logging code. */
381 PKTT_OTHER, PKTT_PASSWORD, PKTT_DATA
385 * Coroutine mechanics for the sillier bits of the code. If these
386 * macros look impenetrable to you, you might find it helpful to
389 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
391 * which explains the theory behind these macros.
393 * In particular, if you are getting `case expression not constant'
394 * errors when building with MS Visual Studio, this is because MS's
395 * Edit and Continue debugging feature causes their compiler to
396 * violate ANSI C. To disable Edit and Continue debugging:
398 * - right-click ssh.c in the FileView
400 * - select the C/C++ tab and the General category
401 * - under `Debug info:', select anything _other_ than `Program
402 * Database for Edit and Continue'.
404 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
407 if (!ssh->t) ssh->t = snew(struct t); \
409 #define crFinish(z) } *crLine = 0; return (z); }
410 #define crFinishV } *crLine = 0; return; }
411 #define crReturn(z) \
413 *crLine =__LINE__; return (z); case __LINE__:;\
417 *crLine=__LINE__; return; case __LINE__:;\
419 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
420 #define crStopV do{ *crLine = 0; return; }while(0)
421 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
422 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
424 typedef struct ssh_tag *Ssh;
427 static struct Packet *ssh1_pkt_init(int pkt_type);
428 static struct Packet *ssh2_pkt_init(int pkt_type);
429 static void ssh_pkt_ensure(struct Packet *, int length);
430 static void ssh_pkt_adddata(struct Packet *, void *data, int len);
431 static void ssh_pkt_addbyte(struct Packet *, unsigned char value);
432 static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
433 static void ssh_pkt_adduint32(struct Packet *, unsigned long value);
434 static void ssh_pkt_addstring_start(struct Packet *);
435 static void ssh_pkt_addstring_str(struct Packet *, char *data);
436 static void ssh_pkt_addstring_data(struct Packet *, char *data, int len);
437 static void ssh_pkt_addstring(struct Packet *, char *data);
438 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
439 static void ssh1_pkt_addmp(struct Packet *, Bignum b);
440 static void ssh2_pkt_addmp(struct Packet *, Bignum b);
441 static int ssh2_pkt_construct(Ssh, struct Packet *);
442 static void ssh2_pkt_send(Ssh, struct Packet *);
443 static void ssh2_pkt_send_noqueue(Ssh, struct Packet *);
444 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
445 struct Packet *pktin);
446 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
447 struct Packet *pktin);
450 * Buffer management constants. There are several of these for
451 * various different purposes:
453 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
454 * on a local data stream before we throttle the whole SSH
455 * connection (in SSH-1 only). Throttling the whole connection is
456 * pretty drastic so we set this high in the hope it won't
459 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
460 * on the SSH connection itself before we defensively throttle
461 * _all_ local data streams. This is pretty drastic too (though
462 * thankfully unlikely in SSH-2 since the window mechanism should
463 * ensure that the server never has any need to throttle its end
464 * of the connection), so we set this high as well.
466 * - OUR_V2_WINSIZE is the maximum window size we present on SSH-2
470 #define SSH1_BUFFER_LIMIT 32768
471 #define SSH_MAX_BACKLOG 32768
472 #define OUR_V2_WINSIZE 16384
473 #define OUR_V2_MAXPKT 0x4000UL
475 /* Maximum length of passwords/passphrases (arbitrary) */
476 #define SSH_MAX_PASSWORD_LEN 100
478 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
480 const static struct ssh_mac *macs[] = {
481 &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
483 const static struct ssh_mac *buggymacs[] = {
484 &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
487 static void *ssh_comp_none_init(void)
491 static void ssh_comp_none_cleanup(void *handle)
494 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
495 unsigned char **outblock, int *outlen)
499 static int ssh_comp_none_disable(void *handle)
503 const static struct ssh_compress ssh_comp_none = {
505 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
506 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
507 ssh_comp_none_disable, NULL
509 extern const struct ssh_compress ssh_zlib;
510 const static struct ssh_compress *compressions[] = {
511 &ssh_zlib, &ssh_comp_none
514 enum { /* channel types */
519 CHAN_SOCKDATA_DORMANT /* one the remote hasn't confirmed */
523 * 2-3-4 tree storing channels.
526 Ssh ssh; /* pointer back to main context */
527 unsigned remoteid, localid;
529 /* True if we opened this channel but server hasn't confirmed. */
532 * In SSH-1, this value contains four bits:
534 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
535 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
536 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
537 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
539 * A channel is completely finished with when all four bits are set.
543 struct ssh1_data_channel {
546 struct ssh2_data_channel {
548 unsigned remwindow, remmaxpkt;
553 struct ssh_agent_channel {
554 unsigned char *message;
555 unsigned char msglen[4];
556 unsigned lensofar, totallen;
558 struct ssh_x11_channel {
561 struct ssh_pfd_channel {
568 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
569 * use this structure in different ways, reflecting SSH-2's
570 * altogether saner approach to port forwarding.
572 * In SSH-1, you arrange a remote forwarding by sending the server
573 * the remote port number, and the local destination host:port.
574 * When a connection comes in, the server sends you back that
575 * host:port pair, and you connect to it. This is a ready-made
576 * security hole if you're not on the ball: a malicious server
577 * could send you back _any_ host:port pair, so if you trustingly
578 * connect to the address it gives you then you've just opened the
579 * entire inside of your corporate network just by connecting
580 * through it to a dodgy SSH server. Hence, we must store a list of
581 * host:port pairs we _are_ trying to forward to, and reject a
582 * connection request from the server if it's not in the list.
584 * In SSH-2, each side of the connection minds its own business and
585 * doesn't send unnecessary information to the other. You arrange a
586 * remote forwarding by sending the server just the remote port
587 * number. When a connection comes in, the server tells you which
588 * of its ports was connected to; and _you_ have to remember what
589 * local host:port pair went with that port number.
591 * Hence, in SSH-1 this structure is indexed by destination
592 * host:port pair, whereas in SSH-2 it is indexed by source port.
594 struct ssh_portfwd; /* forward declaration */
596 struct ssh_rportfwd {
597 unsigned sport, dport;
600 struct ssh_portfwd *pfrec;
602 #define free_rportfwd(pf) ( \
603 ((pf) ? (sfree((pf)->sportdesc)) : (void)0 ), sfree(pf) )
606 * Separately to the rportfwd tree (which is for looking up port
607 * open requests from the server), a tree of _these_ structures is
608 * used to keep track of all the currently open port forwardings,
609 * so that we can reconfigure in mid-session if the user requests
613 enum { DESTROY, KEEP, CREATE } status;
615 unsigned sport, dport;
618 struct ssh_rportfwd *remote;
622 #define free_portfwd(pf) ( \
623 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
624 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
627 long length; /* length of `data' actually used */
628 long forcepad; /* SSH-2: force padding to at least this length */
629 int type; /* only used for incoming packets */
630 unsigned long sequence; /* SSH-2 incoming sequence number */
631 unsigned char *data; /* allocated storage */
632 unsigned char *body; /* offset of payload within `data' */
633 long savedpos; /* temporary index into `data' (for strings) */
634 long maxlen; /* amount of storage allocated for `data' */
635 long encrypted_len; /* for SSH-2 total-size counting */
638 * State associated with packet logging
642 struct logblank_t *blanks;
645 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
646 struct Packet *pktin);
647 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
648 struct Packet *pktin);
649 static void ssh1_protocol_setup(Ssh ssh);
650 static void ssh2_protocol_setup(Ssh ssh);
651 static void ssh_size(void *handle, int width, int height);
652 static void ssh_special(void *handle, Telnet_Special);
653 static int ssh2_try_send(struct ssh_channel *c);
654 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
655 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
656 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin);
657 static int ssh_sendbuffer(void *handle);
658 static int ssh_do_close(Ssh ssh, int notify_exit);
659 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
660 static int ssh2_pkt_getbool(struct Packet *pkt);
661 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
662 static void ssh2_timer(void *ctx, long now);
663 static int do_ssh2_transport(Ssh ssh, void *vin, int inlen,
664 struct Packet *pktin);
666 struct rdpkt1_state_tag {
667 long len, pad, biglen, to_read;
668 unsigned long realcrc, gotcrc;
672 struct Packet *pktin;
675 struct rdpkt2_state_tag {
676 long len, pad, payload, packetlen, maclen;
679 unsigned long incoming_sequence;
680 struct Packet *pktin;
683 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
684 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
686 struct queued_handler;
687 struct queued_handler {
689 chandler_fn_t handler;
691 struct queued_handler *next;
695 const struct plug_function_table *fn;
696 /* the above field _must_ be first in the structure */
706 unsigned char session_key[32];
708 int v1_remote_protoflags;
709 int v1_local_protoflags;
710 int agentfwd_enabled;
713 const struct ssh_cipher *cipher;
716 const struct ssh2_cipher *cscipher, *sccipher;
717 void *cs_cipher_ctx, *sc_cipher_ctx;
718 const struct ssh_mac *csmac, *scmac;
719 void *cs_mac_ctx, *sc_mac_ctx;
720 const struct ssh_compress *cscomp, *sccomp;
721 void *cs_comp_ctx, *sc_comp_ctx;
722 const struct ssh_kex *kex;
723 const struct ssh_signkey *hostkey;
724 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
725 int v2_session_id_len;
731 int echoing, editing;
735 int ospeed, ispeed; /* temporaries */
736 int term_width, term_height;
738 tree234 *channels; /* indexed by local id */
739 struct ssh_channel *mainchan; /* primary session channel */
740 int ncmode; /* is primary channel direct-tcpip? */
745 tree234 *rportfwds, *portfwds;
749 SSH_STATE_BEFORE_SIZE,
755 int size_needed, eof_needed;
757 struct Packet **queue;
758 int queuelen, queuesize;
760 unsigned char *deferred_send_data;
761 int deferred_len, deferred_size;
764 * Gross hack: pscp will try to start SFTP but fall back to
765 * scp1 if that fails. This variable is the means by which
766 * scp.c can reach into the SSH code and find out which one it
771 bufchain banner; /* accumulates banners during do_ssh2_authconn */
778 int v1_throttle_count;
781 int v1_stdout_throttling;
782 unsigned long v2_outgoing_sequence;
784 int ssh1_rdpkt_crstate;
785 int ssh2_rdpkt_crstate;
786 int do_ssh_init_crstate;
787 int ssh_gotdata_crstate;
788 int do_ssh1_login_crstate;
789 int do_ssh1_connection_crstate;
790 int do_ssh2_transport_crstate;
791 int do_ssh2_authconn_crstate;
793 void *do_ssh_init_state;
794 void *do_ssh1_login_state;
795 void *do_ssh2_transport_state;
796 void *do_ssh2_authconn_state;
798 struct rdpkt1_state_tag rdpkt1_state;
799 struct rdpkt2_state_tag rdpkt2_state;
801 /* SSH-1 and SSH-2 use this for different things, but both use it */
802 int protocol_initial_phase_done;
804 void (*protocol) (Ssh ssh, void *vin, int inlen,
806 struct Packet *(*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
809 * We maintain a full _copy_ of a Config structure here, not
810 * merely a pointer to it. That way, when we're passed a new
811 * one for reconfiguration, we can check the differences and
812 * potentially reconfigure port forwardings etc in mid-session.
817 * Used to transfer data back from async callbacks.
819 void *agent_response;
820 int agent_response_len;
824 * The SSH connection can be set as `frozen', meaning we are
825 * not currently accepting incoming data from the network. This
826 * is slightly more serious than setting the _socket_ as
827 * frozen, because we may already have had data passed to us
828 * from the network which we need to delay processing until
829 * after the freeze is lifted, so we also need a bufchain to
833 bufchain queued_incoming_data;
836 * Dispatch table for packet types that we may have to deal
839 handler_fn_t packet_dispatch[256];
842 * Queues of one-off handler functions for success/failure
843 * indications from a request.
845 struct queued_handler *qhead, *qtail;
848 * This module deals with sending keepalives.
853 * Track incoming and outgoing data sizes and time, for
856 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
857 unsigned long max_data_size;
859 long next_rekey, last_rekey;
860 char *deferred_rekey_reason; /* points to STATIC string; don't free */
863 #define logevent(s) logevent(ssh->frontend, s)
865 /* logevent, only printf-formatted. */
866 static void logeventf(Ssh ssh, const char *fmt, ...)
872 buf = dupvprintf(fmt, ap);
878 #define bombout(msg) \
880 char *text = dupprintf msg; \
881 ssh_do_close(ssh, FALSE); \
883 connection_fatal(ssh->frontend, "%s", text); \
887 /* Functions to leave bits out of the SSH packet log file. */
889 static void dont_log_password(Ssh ssh, struct Packet *pkt, int blanktype)
891 if (ssh->cfg.logomitpass)
892 pkt->logmode = blanktype;
895 static void dont_log_data(Ssh ssh, struct Packet *pkt, int blanktype)
897 if (ssh->cfg.logomitdata)
898 pkt->logmode = blanktype;
901 static void end_log_omission(Ssh ssh, struct Packet *pkt)
903 pkt->logmode = PKTLOG_EMIT;
906 /* Helper function for common bits of parsing cfg.ttymodes. */
907 static void parse_ttymodes(Ssh ssh, char *modes,
908 void (*do_mode)(void *data, char *mode, char *val),
912 char *t = strchr(modes, '\t');
913 char *m = snewn(t-modes+1, char);
915 strncpy(m, modes, t-modes);
918 val = get_ttymode(ssh->frontend, m);
922 do_mode(data, m, val);
925 modes += strlen(modes) + 1;
929 static int ssh_channelcmp(void *av, void *bv)
931 struct ssh_channel *a = (struct ssh_channel *) av;
932 struct ssh_channel *b = (struct ssh_channel *) bv;
933 if (a->localid < b->localid)
935 if (a->localid > b->localid)
939 static int ssh_channelfind(void *av, void *bv)
941 unsigned *a = (unsigned *) av;
942 struct ssh_channel *b = (struct ssh_channel *) bv;
950 static int ssh_rportcmp_ssh1(void *av, void *bv)
952 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
953 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
955 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
956 return i < 0 ? -1 : +1;
957 if (a->dport > b->dport)
959 if (a->dport < b->dport)
964 static int ssh_rportcmp_ssh2(void *av, void *bv)
966 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
967 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
969 if (a->sport > b->sport)
971 if (a->sport < b->sport)
977 * Special form of strcmp which can cope with NULL inputs. NULL is
978 * defined to sort before even the empty string.
980 static int nullstrcmp(const char *a, const char *b)
982 if (a == NULL && b == NULL)
991 static int ssh_portcmp(void *av, void *bv)
993 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
994 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
996 if (a->type > b->type)
998 if (a->type < b->type)
1000 if (a->addressfamily > b->addressfamily)
1002 if (a->addressfamily < b->addressfamily)
1004 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1005 return i < 0 ? -1 : +1;
1006 if (a->sport > b->sport)
1008 if (a->sport < b->sport)
1010 if (a->type != 'D') {
1011 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1012 return i < 0 ? -1 : +1;
1013 if (a->dport > b->dport)
1015 if (a->dport < b->dport)
1021 static int alloc_channel_id(Ssh ssh)
1023 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1024 unsigned low, high, mid;
1026 struct ssh_channel *c;
1029 * First-fit allocation of channel numbers: always pick the
1030 * lowest unused one. To do this, binary-search using the
1031 * counted B-tree to find the largest channel ID which is in a
1032 * contiguous sequence from the beginning. (Precisely
1033 * everything in that sequence must have ID equal to its tree
1034 * index plus CHANNEL_NUMBER_OFFSET.)
1036 tsize = count234(ssh->channels);
1040 while (high - low > 1) {
1041 mid = (high + low) / 2;
1042 c = index234(ssh->channels, mid);
1043 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1044 low = mid; /* this one is fine */
1046 high = mid; /* this one is past it */
1049 * Now low points to either -1, or the tree index of the
1050 * largest ID in the initial sequence.
1053 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1054 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1056 return low + 1 + CHANNEL_NUMBER_OFFSET;
1059 static void c_write_stderr(int trusted, const char *buf, int len)
1062 for (i = 0; i < len; i++)
1063 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1064 fputc(buf[i], stderr);
1067 static void c_write(Ssh ssh, const char *buf, int len)
1069 if (flags & FLAG_STDERR)
1070 c_write_stderr(1, buf, len);
1072 from_backend(ssh->frontend, 1, buf, len);
1075 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1077 if (flags & FLAG_STDERR)
1078 c_write_stderr(0, buf, len);
1080 from_backend_untrusted(ssh->frontend, buf, len);
1083 static void c_write_str(Ssh ssh, const char *buf)
1085 c_write(ssh, buf, strlen(buf));
1088 static void ssh_free_packet(struct Packet *pkt)
1093 static struct Packet *ssh_new_packet(void)
1095 struct Packet *pkt = snew(struct Packet);
1097 pkt->body = pkt->data = NULL;
1099 pkt->logmode = PKTLOG_EMIT;
1107 * Collect incoming data in the incoming packet buffer.
1108 * Decipher and verify the packet when it is completely read.
1109 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1110 * Update the *data and *datalen variables.
1111 * Return a Packet structure when a packet is completed.
1113 static struct Packet *ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1115 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1117 crBegin(ssh->ssh1_rdpkt_crstate);
1119 st->pktin = ssh_new_packet();
1121 st->pktin->type = 0;
1122 st->pktin->length = 0;
1124 for (st->i = st->len = 0; st->i < 4; st->i++) {
1125 while ((*datalen) == 0)
1127 st->len = (st->len << 8) + **data;
1128 (*data)++, (*datalen)--;
1131 st->pad = 8 - (st->len % 8);
1132 st->biglen = st->len + st->pad;
1133 st->pktin->length = st->len - 5;
1135 if (st->biglen < 0) {
1136 bombout(("Extremely large packet length from server suggests"
1137 " data stream corruption"));
1138 ssh_free_packet(st->pktin);
1142 st->pktin->maxlen = st->biglen;
1143 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1145 st->to_read = st->biglen;
1146 st->p = st->pktin->data;
1147 while (st->to_read > 0) {
1148 st->chunk = st->to_read;
1149 while ((*datalen) == 0)
1151 if (st->chunk > (*datalen))
1152 st->chunk = (*datalen);
1153 memcpy(st->p, *data, st->chunk);
1155 *datalen -= st->chunk;
1157 st->to_read -= st->chunk;
1160 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1161 st->biglen, NULL)) {
1162 bombout(("Network attack (CRC compensation) detected!"));
1163 ssh_free_packet(st->pktin);
1168 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1170 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1171 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1172 if (st->gotcrc != st->realcrc) {
1173 bombout(("Incorrect CRC received on packet"));
1174 ssh_free_packet(st->pktin);
1178 st->pktin->body = st->pktin->data + st->pad + 1;
1179 st->pktin->savedpos = 0;
1181 if (ssh->v1_compressing) {
1182 unsigned char *decompblk;
1184 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1185 st->pktin->body - 1, st->pktin->length + 1,
1186 &decompblk, &decomplen)) {
1187 bombout(("Zlib decompression encountered invalid data"));
1188 ssh_free_packet(st->pktin);
1192 if (st->pktin->maxlen < st->pad + decomplen) {
1193 st->pktin->maxlen = st->pad + decomplen;
1194 st->pktin->data = sresize(st->pktin->data,
1195 st->pktin->maxlen + APIEXTRA,
1197 st->pktin->body = st->pktin->data + st->pad + 1;
1200 memcpy(st->pktin->body - 1, decompblk, decomplen);
1202 st->pktin->length = decomplen - 1;
1205 st->pktin->type = st->pktin->body[-1];
1208 * Log incoming packet, possibly omitting sensitive fields.
1212 struct logblank_t blank;
1213 if (ssh->cfg.logomitdata) {
1214 int do_blank = FALSE, blank_prefix = 0;
1215 /* "Session data" packets - omit the data field */
1216 if ((st->pktin->type == SSH1_SMSG_STDOUT_DATA) ||
1217 (st->pktin->type == SSH1_SMSG_STDERR_DATA)) {
1218 do_blank = TRUE; blank_prefix = 0;
1219 } else if (st->pktin->type == SSH1_MSG_CHANNEL_DATA) {
1220 do_blank = TRUE; blank_prefix = 4;
1223 blank.offset = blank_prefix;
1224 blank.len = st->pktin->length;
1225 blank.type = PKTLOG_OMIT;
1229 log_packet(ssh->logctx,
1230 PKT_INCOMING, st->pktin->type,
1231 ssh1_pkt_type(st->pktin->type),
1232 st->pktin->body, st->pktin->length,
1236 crFinish(st->pktin);
1239 static struct Packet *ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1241 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1243 crBegin(ssh->ssh2_rdpkt_crstate);
1245 st->pktin = ssh_new_packet();
1247 st->pktin->type = 0;
1248 st->pktin->length = 0;
1250 st->cipherblk = ssh->sccipher->blksize;
1253 if (st->cipherblk < 8)
1256 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1259 * Acquire and decrypt the first block of the packet. This will
1260 * contain the length and padding details.
1262 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1263 while ((*datalen) == 0)
1265 st->pktin->data[st->i] = *(*data)++;
1270 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1271 st->pktin->data, st->cipherblk);
1274 * Now get the length and padding figures.
1276 st->len = GET_32BIT(st->pktin->data);
1277 st->pad = st->pktin->data[4];
1280 * _Completely_ silly lengths should be stomped on before they
1281 * do us any more damage.
1283 if (st->len < 0 || st->len > 35000 || st->pad < 4 ||
1284 st->len - st->pad < 1 || (st->len + 4) % st->cipherblk != 0) {
1285 bombout(("Incoming packet was garbled on decryption"));
1286 ssh_free_packet(st->pktin);
1291 * This enables us to deduce the payload length.
1293 st->payload = st->len - st->pad - 1;
1295 st->pktin->length = st->payload + 5;
1298 * So now we can work out the total packet length.
1300 st->packetlen = st->len + 4;
1301 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1304 * Allocate memory for the rest of the packet.
1306 st->pktin->maxlen = st->packetlen + st->maclen;
1307 st->pktin->data = sresize(st->pktin->data,
1308 st->pktin->maxlen + APIEXTRA,
1312 * Read and decrypt the remainder of the packet.
1314 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1316 while ((*datalen) == 0)
1318 st->pktin->data[st->i] = *(*data)++;
1321 /* Decrypt everything _except_ the MAC. */
1323 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1324 st->pktin->data + st->cipherblk,
1325 st->packetlen - st->cipherblk);
1327 st->pktin->encrypted_len = st->packetlen;
1333 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data, st->len + 4,
1334 st->incoming_sequence)) {
1335 bombout(("Incorrect MAC received on packet"));
1336 ssh_free_packet(st->pktin);
1340 st->pktin->sequence = st->incoming_sequence++;
1343 * Decompress packet payload.
1346 unsigned char *newpayload;
1349 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1350 st->pktin->data + 5, st->pktin->length - 5,
1351 &newpayload, &newlen)) {
1352 if (st->pktin->maxlen < newlen + 5) {
1353 st->pktin->maxlen = newlen + 5;
1354 st->pktin->data = sresize(st->pktin->data,
1355 st->pktin->maxlen + APIEXTRA,
1358 st->pktin->length = 5 + newlen;
1359 memcpy(st->pktin->data + 5, newpayload, newlen);
1364 st->pktin->savedpos = 6;
1365 st->pktin->body = st->pktin->data;
1366 st->pktin->type = st->pktin->data[5];
1369 * Log incoming packet, possibly omitting sensitive fields.
1373 struct logblank_t blank;
1374 if (ssh->cfg.logomitdata) {
1375 int do_blank = FALSE, blank_prefix = 0;
1376 /* "Session data" packets - omit the data field */
1377 if (st->pktin->type == SSH2_MSG_CHANNEL_DATA) {
1378 do_blank = TRUE; blank_prefix = 4;
1379 } else if (st->pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
1380 do_blank = TRUE; blank_prefix = 8;
1383 blank.offset = blank_prefix;
1384 blank.len = (st->pktin->length-6) - blank_prefix;
1385 blank.type = PKTLOG_OMIT;
1389 log_packet(ssh->logctx, PKT_INCOMING, st->pktin->type,
1390 ssh2_pkt_type(ssh->pkt_ctx, st->pktin->type),
1391 st->pktin->data+6, st->pktin->length-6,
1395 crFinish(st->pktin);
1398 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1400 int pad, biglen, i, pktoffs;
1404 * XXX various versions of SC (including 8.8.4) screw up the
1405 * register allocation in this function and use the same register
1406 * (D6) for len and as a temporary, with predictable results. The
1407 * following sledgehammer prevents this.
1414 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1415 ssh1_pkt_type(pkt->data[12]),
1416 pkt->body, pkt->length - (pkt->body - pkt->data),
1417 pkt->nblanks, pkt->blanks);
1418 sfree(pkt->blanks); pkt->blanks = NULL;
1421 if (ssh->v1_compressing) {
1422 unsigned char *compblk;
1424 zlib_compress_block(ssh->cs_comp_ctx,
1425 pkt->data + 12, pkt->length - 12,
1426 &compblk, &complen);
1427 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1428 memcpy(pkt->data + 12, compblk, complen);
1430 pkt->length = complen + 12;
1433 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1435 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1436 pad = 8 - (len % 8);
1438 biglen = len + pad; /* len(padding+type+data+CRC) */
1440 for (i = pktoffs; i < 4+8; i++)
1441 pkt->data[i] = random_byte();
1442 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
1443 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
1444 PUT_32BIT(pkt->data + pktoffs, len);
1447 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
1448 pkt->data + pktoffs + 4, biglen);
1450 if (offset_p) *offset_p = pktoffs;
1451 return biglen + 4; /* len(length+padding+type+data+CRC) */
1454 static int s_write(Ssh ssh, void *data, int len)
1457 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len, 0, NULL);
1458 return sk_write(ssh->s, (char *)data, len);
1461 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1463 int len, backlog, offset;
1464 len = s_wrpkt_prepare(ssh, pkt, &offset);
1465 backlog = s_write(ssh, pkt->data + offset, len);
1466 if (backlog > SSH_MAX_BACKLOG)
1467 ssh_throttle_all(ssh, 1, backlog);
1468 ssh_free_packet(pkt);
1471 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1474 len = s_wrpkt_prepare(ssh, pkt, &offset);
1475 if (ssh->deferred_len + len > ssh->deferred_size) {
1476 ssh->deferred_size = ssh->deferred_len + len + 128;
1477 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1481 memcpy(ssh->deferred_send_data + ssh->deferred_len,
1482 pkt->data + offset, len);
1483 ssh->deferred_len += len;
1484 ssh_free_packet(pkt);
1488 * Construct a SSH-1 packet with the specified contents.
1489 * (This all-at-once interface used to be the only one, but now SSH-1
1490 * packets can also be constructed incrementally.)
1492 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
1498 pkt = ssh1_pkt_init(pkttype);
1500 while ((argtype = va_arg(ap, int)) != PKT_END) {
1501 unsigned char *argp, argchar;
1503 unsigned long argint;
1506 /* Actual fields in the packet */
1508 argint = va_arg(ap, int);
1509 ssh_pkt_adduint32(pkt, argint);
1512 argchar = (unsigned char) va_arg(ap, int);
1513 ssh_pkt_addbyte(pkt, argchar);
1516 argp = va_arg(ap, unsigned char *);
1517 arglen = va_arg(ap, int);
1518 ssh_pkt_adddata(pkt, argp, arglen);
1521 sargp = va_arg(ap, char *);
1522 ssh_pkt_addstring(pkt, sargp);
1525 bn = va_arg(ap, Bignum);
1526 ssh1_pkt_addmp(pkt, bn);
1528 /* Tokens for modifications to packet logging */
1530 dont_log_password(ssh, pkt, PKTLOG_BLANK);
1533 dont_log_data(ssh, pkt, PKTLOG_OMIT);
1536 end_log_omission(ssh, pkt);
1544 static void send_packet(Ssh ssh, int pkttype, ...)
1548 va_start(ap, pkttype);
1549 pkt = construct_packet(ssh, pkttype, ap);
1554 static void defer_packet(Ssh ssh, int pkttype, ...)
1558 va_start(ap, pkttype);
1559 pkt = construct_packet(ssh, pkttype, ap);
1561 s_wrpkt_defer(ssh, pkt);
1564 static int ssh_versioncmp(char *a, char *b)
1567 unsigned long av, bv;
1569 av = strtoul(a, &ae, 10);
1570 bv = strtoul(b, &be, 10);
1572 return (av < bv ? -1 : +1);
1577 av = strtoul(ae, &ae, 10);
1578 bv = strtoul(be, &be, 10);
1580 return (av < bv ? -1 : +1);
1585 * Utility routines for putting an SSH-protocol `string' and
1586 * `uint32' into a hash state.
1588 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
1590 unsigned char lenblk[4];
1591 PUT_32BIT(lenblk, len);
1592 h->bytes(s, lenblk, 4);
1593 h->bytes(s, str, len);
1596 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
1598 unsigned char intblk[4];
1599 PUT_32BIT(intblk, i);
1600 h->bytes(s, intblk, 4);
1604 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
1606 static void ssh_pkt_ensure(struct Packet *pkt, int length)
1608 if (pkt->maxlen < length) {
1609 unsigned char *body = pkt->body;
1610 int offset = body ? body - pkt->data : 0;
1611 pkt->maxlen = length + 256;
1612 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
1613 if (body) pkt->body = pkt->data + offset;
1616 static void ssh_pkt_adddata(struct Packet *pkt, void *data, int len)
1618 if (pkt->logmode != PKTLOG_EMIT) {
1620 pkt->blanks = sresize(pkt->blanks, pkt->nblanks, struct logblank_t);
1622 pkt->blanks[pkt->nblanks-1].offset = pkt->length -
1623 (pkt->body - pkt->data);
1624 pkt->blanks[pkt->nblanks-1].len = len;
1625 pkt->blanks[pkt->nblanks-1].type = pkt->logmode;
1628 ssh_pkt_ensure(pkt, pkt->length);
1629 memcpy(pkt->data + pkt->length - len, data, len);
1631 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
1633 ssh_pkt_adddata(pkt, &byte, 1);
1635 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
1637 ssh_pkt_adddata(pkt, &value, 1);
1639 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
1642 PUT_32BIT(x, value);
1643 ssh_pkt_adddata(pkt, x, 4);
1645 static void ssh_pkt_addstring_start(struct Packet *pkt)
1647 ssh_pkt_adduint32(pkt, 0);
1648 pkt->savedpos = pkt->length;
1650 static void ssh_pkt_addstring_str(struct Packet *pkt, char *data)
1652 ssh_pkt_adddata(pkt, data, strlen(data));
1653 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1655 static void ssh_pkt_addstring_data(struct Packet *pkt, char *data, int len)
1657 ssh_pkt_adddata(pkt, data, len);
1658 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1660 static void ssh_pkt_addstring(struct Packet *pkt, char *data)
1662 ssh_pkt_addstring_start(pkt);
1663 ssh_pkt_addstring_str(pkt, data);
1665 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
1667 int len = ssh1_bignum_length(b);
1668 unsigned char *data = snewn(len, unsigned char);
1669 (void) ssh1_write_bignum(data, b);
1670 ssh_pkt_adddata(pkt, data, len);
1673 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
1676 int i, n = (bignum_bitcount(b) + 7) / 8;
1677 p = snewn(n + 1, unsigned char);
1679 for (i = 1; i <= n; i++)
1680 p[i] = bignum_byte(b, n - i);
1682 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1684 memmove(p, p + i, n + 1 - i);
1688 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
1692 p = ssh2_mpint_fmt(b, &len);
1693 ssh_pkt_addstring_start(pkt);
1694 ssh_pkt_addstring_data(pkt, (char *)p, len);
1698 static struct Packet *ssh1_pkt_init(int pkt_type)
1700 struct Packet *pkt = ssh_new_packet();
1701 pkt->length = 4 + 8; /* space for length + max padding */
1702 ssh_pkt_addbyte(pkt, pkt_type);
1703 pkt->body = pkt->data + pkt->length;
1707 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
1708 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
1709 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
1710 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
1711 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
1712 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
1713 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
1714 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
1715 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
1717 static struct Packet *ssh2_pkt_init(int pkt_type)
1719 struct Packet *pkt = ssh_new_packet();
1720 pkt->length = 5; /* space for packet length + padding length */
1722 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
1723 pkt->body = pkt->data + pkt->length; /* after packet type */
1728 * Construct an SSH-2 final-form packet: compress it, encrypt it,
1729 * put the MAC on it. Final packet, ready to be sent, is stored in
1730 * pkt->data. Total length is returned.
1732 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
1734 int cipherblk, maclen, padding, i;
1737 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1738 ssh2_pkt_type(ssh->pkt_ctx, pkt->data[5]),
1739 pkt->body, pkt->length - (pkt->body - pkt->data),
1740 pkt->nblanks, pkt->blanks);
1741 sfree(pkt->blanks); pkt->blanks = NULL;
1745 * Compress packet payload.
1748 unsigned char *newpayload;
1751 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
1753 &newpayload, &newlen)) {
1755 ssh2_pkt_adddata(pkt, newpayload, newlen);
1761 * Add padding. At least four bytes, and must also bring total
1762 * length (minus MAC) up to a multiple of the block size.
1763 * If pkt->forcepad is set, make sure the packet is at least that size
1766 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
1767 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1769 if (pkt->length + padding < pkt->forcepad)
1770 padding = pkt->forcepad - pkt->length;
1772 (cipherblk - (pkt->length + padding) % cipherblk) % cipherblk;
1773 assert(padding <= 255);
1774 maclen = ssh->csmac ? ssh->csmac->len : 0;
1775 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
1776 pkt->data[4] = padding;
1777 for (i = 0; i < padding; i++)
1778 pkt->data[pkt->length + i] = random_byte();
1779 PUT_32BIT(pkt->data, pkt->length + padding - 4);
1781 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
1782 pkt->length + padding,
1783 ssh->v2_outgoing_sequence);
1784 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
1787 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
1788 pkt->data, pkt->length + padding);
1790 pkt->encrypted_len = pkt->length + padding;
1792 /* Ready-to-send packet starts at pkt->data. We return length. */
1793 return pkt->length + padding + maclen;
1797 * Routines called from the main SSH code to send packets. There
1798 * are quite a few of these, because we have two separate
1799 * mechanisms for delaying the sending of packets:
1801 * - In order to send an IGNORE message and a password message in
1802 * a single fixed-length blob, we require the ability to
1803 * concatenate the encrypted forms of those two packets _into_ a
1804 * single blob and then pass it to our <network.h> transport
1805 * layer in one go. Hence, there's a deferment mechanism which
1806 * works after packet encryption.
1808 * - In order to avoid sending any connection-layer messages
1809 * during repeat key exchange, we have to queue up any such
1810 * outgoing messages _before_ they are encrypted (and in
1811 * particular before they're allocated sequence numbers), and
1812 * then send them once we've finished.
1814 * I call these mechanisms `defer' and `queue' respectively, so as
1815 * to distinguish them reasonably easily.
1817 * The functions send_noqueue() and defer_noqueue() free the packet
1818 * structure they are passed. Every outgoing packet goes through
1819 * precisely one of these functions in its life; packets passed to
1820 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
1821 * these or get queued, and then when the queue is later emptied
1822 * the packets are all passed to defer_noqueue().
1824 * When using a CBC-mode cipher, it's necessary to ensure that an
1825 * attacker can't provide data to be encrypted using an IV that they
1826 * know. We ensure this by prefixing each packet that might contain
1827 * user data with an SSH_MSG_IGNORE. This is done using the deferral
1828 * mechanism, so in this case send_noqueue() ends up redirecting to
1829 * defer_noqueue(). If you don't like this inefficiency, don't use
1833 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
1834 static void ssh_pkt_defersend(Ssh);
1837 * Send an SSH-2 packet immediately, without queuing or deferring.
1839 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
1843 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
1844 /* We need to send two packets, so use the deferral mechanism. */
1845 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
1846 ssh_pkt_defersend(ssh);
1849 len = ssh2_pkt_construct(ssh, pkt);
1850 backlog = s_write(ssh, pkt->data, len);
1851 if (backlog > SSH_MAX_BACKLOG)
1852 ssh_throttle_all(ssh, 1, backlog);
1854 ssh->outgoing_data_size += pkt->encrypted_len;
1855 if (!ssh->kex_in_progress &&
1856 ssh->max_data_size != 0 &&
1857 ssh->outgoing_data_size > ssh->max_data_size)
1858 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
1860 ssh_free_packet(pkt);
1864 * Defer an SSH-2 packet.
1866 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
1869 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
1870 ssh->deferred_len == 0 && !noignore) {
1872 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
1873 * get encrypted with a known IV.
1875 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
1876 ssh2_pkt_addstring_start(ipkt);
1877 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
1879 len = ssh2_pkt_construct(ssh, pkt);
1880 if (ssh->deferred_len + len > ssh->deferred_size) {
1881 ssh->deferred_size = ssh->deferred_len + len + 128;
1882 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1886 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->data, len);
1887 ssh->deferred_len += len;
1888 ssh->deferred_data_size += pkt->encrypted_len;
1889 ssh_free_packet(pkt);
1893 * Queue an SSH-2 packet.
1895 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
1897 assert(ssh->queueing);
1899 if (ssh->queuelen >= ssh->queuesize) {
1900 ssh->queuesize = ssh->queuelen + 32;
1901 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
1904 ssh->queue[ssh->queuelen++] = pkt;
1908 * Either queue or send a packet, depending on whether queueing is
1911 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
1914 ssh2_pkt_queue(ssh, pkt);
1916 ssh2_pkt_send_noqueue(ssh, pkt);
1920 * Either queue or defer a packet, depending on whether queueing is
1923 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
1926 ssh2_pkt_queue(ssh, pkt);
1928 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
1932 * Send the whole deferred data block constructed by
1933 * ssh2_pkt_defer() or SSH-1's defer_packet().
1935 * The expected use of the defer mechanism is that you call
1936 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
1937 * not currently queueing, this simply sets up deferred_send_data
1938 * and then sends it. If we _are_ currently queueing, the calls to
1939 * ssh2_pkt_defer() put the deferred packets on to the queue
1940 * instead, and therefore ssh_pkt_defersend() has no deferred data
1941 * to send. Hence, there's no need to make it conditional on
1944 static void ssh_pkt_defersend(Ssh ssh)
1947 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
1948 ssh->deferred_len = ssh->deferred_size = 0;
1949 sfree(ssh->deferred_send_data);
1950 ssh->deferred_send_data = NULL;
1951 if (backlog > SSH_MAX_BACKLOG)
1952 ssh_throttle_all(ssh, 1, backlog);
1954 ssh->outgoing_data_size += ssh->deferred_data_size;
1955 if (!ssh->kex_in_progress &&
1956 ssh->max_data_size != 0 &&
1957 ssh->outgoing_data_size > ssh->max_data_size)
1958 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
1959 ssh->deferred_data_size = 0;
1963 * Send a packet whose length needs to be disguised (typically
1964 * passwords or keyboard-interactive responses).
1966 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
1972 * The simplest way to do this is to adjust the
1973 * variable-length padding field in the outgoing packet.
1975 * Currently compiled out, because some Cisco SSH servers
1976 * don't like excessively padded packets (bah, why's it
1979 pkt->forcepad = padsize;
1980 ssh2_pkt_send(ssh, pkt);
1985 * If we can't do that, however, an alternative approach is
1986 * to use the pkt_defer mechanism to bundle the packet
1987 * tightly together with an SSH_MSG_IGNORE such that their
1988 * combined length is a constant. So first we construct the
1989 * final form of this packet and defer its sending.
1991 ssh2_pkt_defer(ssh, pkt);
1994 * Now construct an SSH_MSG_IGNORE which includes a string
1995 * that's an exact multiple of the cipher block size. (If
1996 * the cipher is NULL so that the block size is
1997 * unavailable, we don't do this trick at all, because we
1998 * gain nothing by it.)
2000 if (ssh->cscipher) {
2003 stringlen = (256 - ssh->deferred_len);
2004 stringlen += ssh->cscipher->blksize - 1;
2005 stringlen -= (stringlen % ssh->cscipher->blksize);
2008 * Temporarily disable actual compression, so we
2009 * can guarantee to get this string exactly the
2010 * length we want it. The compression-disabling
2011 * routine should return an integer indicating how
2012 * many bytes we should adjust our string length
2016 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2018 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2019 ssh2_pkt_addstring_start(pkt);
2020 for (i = 0; i < stringlen; i++) {
2021 char c = (char) random_byte();
2022 ssh2_pkt_addstring_data(pkt, &c, 1);
2024 ssh2_pkt_defer(ssh, pkt);
2026 ssh_pkt_defersend(ssh);
2031 * Send all queued SSH-2 packets. We send them by means of
2032 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2033 * packets that needed to be lumped together.
2035 static void ssh2_pkt_queuesend(Ssh ssh)
2039 assert(!ssh->queueing);
2041 for (i = 0; i < ssh->queuelen; i++)
2042 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2045 ssh_pkt_defersend(ssh);
2049 void bndebug(char *string, Bignum b)
2053 p = ssh2_mpint_fmt(b, &len);
2054 debug(("%s", string));
2055 for (i = 0; i < len; i++)
2056 debug((" %02x", p[i]));
2062 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2066 p = ssh2_mpint_fmt(b, &len);
2067 hash_string(h, s, p, len);
2072 * Packet decode functions for both SSH-1 and SSH-2.
2074 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2076 unsigned long value;
2077 if (pkt->length - pkt->savedpos < 4)
2078 return 0; /* arrgh, no way to decline (FIXME?) */
2079 value = GET_32BIT(pkt->body + pkt->savedpos);
2083 static int ssh2_pkt_getbool(struct Packet *pkt)
2085 unsigned long value;
2086 if (pkt->length - pkt->savedpos < 1)
2087 return 0; /* arrgh, no way to decline (FIXME?) */
2088 value = pkt->body[pkt->savedpos] != 0;
2092 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2097 if (pkt->length - pkt->savedpos < 4)
2099 len = GET_32BIT(pkt->body + pkt->savedpos);
2104 if (pkt->length - pkt->savedpos < *length)
2106 *p = (char *)(pkt->body + pkt->savedpos);
2107 pkt->savedpos += *length;
2109 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2111 if (pkt->length - pkt->savedpos < length)
2113 pkt->savedpos += length;
2114 return pkt->body + (pkt->savedpos - length);
2116 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2117 unsigned char **keystr)
2121 j = makekey(pkt->body + pkt->savedpos,
2122 pkt->length - pkt->savedpos,
2129 assert(pkt->savedpos < pkt->length);
2133 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2138 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2139 pkt->length - pkt->savedpos, &b);
2147 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2153 ssh_pkt_getstring(pkt, &p, &length);
2158 b = bignum_from_bytes((unsigned char *)p, length);
2163 * Helper function to add an SSH-2 signature blob to a packet.
2164 * Expects to be shown the public key blob as well as the signature
2165 * blob. Normally works just like ssh2_pkt_addstring, but will
2166 * fiddle with the signature packet if necessary for
2167 * BUG_SSH2_RSA_PADDING.
2169 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2170 void *pkblob_v, int pkblob_len,
2171 void *sigblob_v, int sigblob_len)
2173 unsigned char *pkblob = (unsigned char *)pkblob_v;
2174 unsigned char *sigblob = (unsigned char *)sigblob_v;
2176 /* dmemdump(pkblob, pkblob_len); */
2177 /* dmemdump(sigblob, sigblob_len); */
2180 * See if this is in fact an ssh-rsa signature and a buggy
2181 * server; otherwise we can just do this the easy way.
2183 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) &&
2184 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2185 int pos, len, siglen;
2188 * Find the byte length of the modulus.
2191 pos = 4+7; /* skip over "ssh-rsa" */
2192 pos += 4 + GET_32BIT(pkblob+pos); /* skip over exponent */
2193 len = GET_32BIT(pkblob+pos); /* find length of modulus */
2194 pos += 4; /* find modulus itself */
2195 while (len > 0 && pkblob[pos] == 0)
2197 /* debug(("modulus length is %d\n", len)); */
2200 * Now find the signature integer.
2202 pos = 4+7; /* skip over "ssh-rsa" */
2203 siglen = GET_32BIT(sigblob+pos);
2204 /* debug(("signature length is %d\n", siglen)); */
2206 if (len != siglen) {
2207 unsigned char newlen[4];
2208 ssh2_pkt_addstring_start(pkt);
2209 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2210 /* dmemdump(sigblob, pos); */
2211 pos += 4; /* point to start of actual sig */
2212 PUT_32BIT(newlen, len);
2213 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2214 /* dmemdump(newlen, 4); */
2216 while (len-- > siglen) {
2217 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2218 /* dmemdump(newlen, 1); */
2220 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2221 /* dmemdump(sigblob+pos, siglen); */
2225 /* Otherwise fall through and do it the easy way. */
2228 ssh2_pkt_addstring_start(pkt);
2229 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2233 * Examine the remote side's version string and compare it against
2234 * a list of known buggy implementations.
2236 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2238 char *imp; /* pointer to implementation part */
2240 imp += strcspn(imp, "-");
2242 imp += strcspn(imp, "-");
2245 ssh->remote_bugs = 0;
2248 * General notes on server version strings:
2249 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2250 * here -- in particular, we've heard of one that's perfectly happy
2251 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2252 * so we can't distinguish them.
2254 if (ssh->cfg.sshbug_ignore1 == FORCE_ON ||
2255 (ssh->cfg.sshbug_ignore1 == AUTO &&
2256 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2257 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2258 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2259 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2261 * These versions don't support SSH1_MSG_IGNORE, so we have
2262 * to use a different defence against password length
2265 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2266 logevent("We believe remote version has SSH-1 ignore bug");
2269 if (ssh->cfg.sshbug_plainpw1 == FORCE_ON ||
2270 (ssh->cfg.sshbug_plainpw1 == AUTO &&
2271 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2273 * These versions need a plain password sent; they can't
2274 * handle having a null and a random length of data after
2277 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2278 logevent("We believe remote version needs a plain SSH-1 password");
2281 if (ssh->cfg.sshbug_rsa1 == FORCE_ON ||
2282 (ssh->cfg.sshbug_rsa1 == AUTO &&
2283 (!strcmp(imp, "Cisco-1.25")))) {
2285 * These versions apparently have no clue whatever about
2286 * RSA authentication and will panic and die if they see
2287 * an AUTH_RSA message.
2289 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2290 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2293 if (ssh->cfg.sshbug_hmac2 == FORCE_ON ||
2294 (ssh->cfg.sshbug_hmac2 == AUTO &&
2295 !wc_match("* VShell", imp) &&
2296 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2297 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2298 wc_match("2.1 *", imp)))) {
2300 * These versions have the HMAC bug.
2302 ssh->remote_bugs |= BUG_SSH2_HMAC;
2303 logevent("We believe remote version has SSH-2 HMAC bug");
2306 if (ssh->cfg.sshbug_derivekey2 == FORCE_ON ||
2307 (ssh->cfg.sshbug_derivekey2 == AUTO &&
2308 !wc_match("* VShell", imp) &&
2309 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2311 * These versions have the key-derivation bug (failing to
2312 * include the literal shared secret in the hashes that
2313 * generate the keys).
2315 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2316 logevent("We believe remote version has SSH-2 key-derivation bug");
2319 if (ssh->cfg.sshbug_rsapad2 == FORCE_ON ||
2320 (ssh->cfg.sshbug_rsapad2 == AUTO &&
2321 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2322 wc_match("OpenSSH_3.[0-2]*", imp)))) {
2324 * These versions have the SSH-2 RSA padding bug.
2326 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2327 logevent("We believe remote version has SSH-2 RSA padding bug");
2330 if (ssh->cfg.sshbug_pksessid2 == FORCE_ON ||
2331 (ssh->cfg.sshbug_pksessid2 == AUTO &&
2332 wc_match("OpenSSH_2.[0-2]*", imp))) {
2334 * These versions have the SSH-2 session-ID bug in
2335 * public-key authentication.
2337 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2338 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2341 if (ssh->cfg.sshbug_rekey2 == FORCE_ON ||
2342 (ssh->cfg.sshbug_rekey2 == AUTO &&
2343 (wc_match("DigiSSH_2.0", imp) ||
2344 wc_match("OpenSSH_2.[0-4]*", imp) ||
2345 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2346 wc_match("Sun_SSH_1.0", imp) ||
2347 wc_match("Sun_SSH_1.0.1", imp) ||
2348 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2349 wc_match("WeOnlyDo-*", imp)))) {
2351 * These versions have the SSH-2 rekey bug.
2353 ssh->remote_bugs |= BUG_SSH2_REKEY;
2354 logevent("We believe remote version has SSH-2 rekey bug");
2359 * The `software version' part of an SSH version string is required
2360 * to contain no spaces or minus signs.
2362 static void ssh_fix_verstring(char *str)
2364 /* Eat "SSH-<protoversion>-". */
2365 assert(*str == 'S'); str++;
2366 assert(*str == 'S'); str++;
2367 assert(*str == 'H'); str++;
2368 assert(*str == '-'); str++;
2369 while (*str && *str != '-') str++;
2370 assert(*str == '-'); str++;
2372 /* Convert minus signs and spaces in the remaining string into
2375 if (*str == '-' || *str == ' ')
2382 * Send an appropriate SSH version string.
2384 static void ssh_send_verstring(Ssh ssh, char *svers)
2388 if (ssh->version == 2) {
2390 * Construct a v2 version string.
2392 verstring = dupprintf("SSH-2.0-%s\015\012", sshver);
2395 * Construct a v1 version string.
2397 verstring = dupprintf("SSH-%s-%s\012",
2398 (ssh_versioncmp(svers, "1.5") <= 0 ?
2403 ssh_fix_verstring(verstring);
2405 if (ssh->version == 2) {
2408 * Record our version string.
2410 len = strcspn(verstring, "\015\012");
2411 ssh->v_c = snewn(len + 1, char);
2412 memcpy(ssh->v_c, verstring, len);
2416 logeventf(ssh, "We claim version: %.*s",
2417 strcspn(verstring, "\015\012"), verstring);
2418 s_write(ssh, verstring, strlen(verstring));
2422 static int do_ssh_init(Ssh ssh, unsigned char c)
2424 struct do_ssh_init_state {
2432 crState(do_ssh_init_state);
2434 crBegin(ssh->do_ssh_init_crstate);
2436 /* Search for a line beginning with the string "SSH-" in the input. */
2438 if (c != 'S') goto no;
2440 if (c != 'S') goto no;
2442 if (c != 'H') goto no;
2444 if (c != '-') goto no;
2453 s->vstring = snewn(s->vstrsize, char);
2454 strcpy(s->vstring, "SSH-");
2458 crReturn(1); /* get another char */
2459 if (s->vslen >= s->vstrsize - 1) {
2461 s->vstring = sresize(s->vstring, s->vstrsize, char);
2463 s->vstring[s->vslen++] = c;
2466 s->version[s->i] = '\0';
2468 } else if (s->i < sizeof(s->version) - 1)
2469 s->version[s->i++] = c;
2470 } else if (c == '\012')
2474 ssh->agentfwd_enabled = FALSE;
2475 ssh->rdpkt2_state.incoming_sequence = 0;
2477 s->vstring[s->vslen] = 0;
2478 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
2479 logeventf(ssh, "Server version: %s", s->vstring);
2480 ssh_detect_bugs(ssh, s->vstring);
2483 * Decide which SSH protocol version to support.
2486 /* Anything strictly below "2.0" means protocol 1 is supported. */
2487 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
2488 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2489 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
2491 if (ssh->cfg.sshprot == 0 && !s->proto1) {
2492 bombout(("SSH protocol version 1 required by user but not provided by server"));
2495 if (ssh->cfg.sshprot == 3 && !s->proto2) {
2496 bombout(("SSH protocol version 2 required by user but not provided by server"));
2500 if (s->proto2 && (ssh->cfg.sshprot >= 2 || !s->proto1))
2505 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
2507 /* Send the version string, if we haven't already */
2508 if (ssh->cfg.sshprot != 3)
2509 ssh_send_verstring(ssh, s->version);
2511 if (ssh->version == 2) {
2514 * Record their version string.
2516 len = strcspn(s->vstring, "\015\012");
2517 ssh->v_s = snewn(len + 1, char);
2518 memcpy(ssh->v_s, s->vstring, len);
2522 * Initialise SSH-2 protocol.
2524 ssh->protocol = ssh2_protocol;
2525 ssh2_protocol_setup(ssh);
2526 ssh->s_rdpkt = ssh2_rdpkt;
2529 * Initialise SSH-1 protocol.
2531 ssh->protocol = ssh1_protocol;
2532 ssh1_protocol_setup(ssh);
2533 ssh->s_rdpkt = ssh1_rdpkt;
2535 if (ssh->version == 2)
2536 do_ssh2_transport(ssh, NULL, -1, NULL);
2538 update_specials_menu(ssh->frontend);
2539 ssh->state = SSH_STATE_BEFORE_SIZE;
2540 ssh->pinger = pinger_new(&ssh->cfg, &ssh_backend, ssh);
2547 static void ssh_process_incoming_data(Ssh ssh,
2548 unsigned char **data, int *datalen)
2550 struct Packet *pktin;
2552 pktin = ssh->s_rdpkt(ssh, data, datalen);
2554 ssh->protocol(ssh, NULL, 0, pktin);
2555 ssh_free_packet(pktin);
2559 static void ssh_queue_incoming_data(Ssh ssh,
2560 unsigned char **data, int *datalen)
2562 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
2567 static void ssh_process_queued_incoming_data(Ssh ssh)
2570 unsigned char *data;
2573 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
2574 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
2578 while (!ssh->frozen && len > 0)
2579 ssh_process_incoming_data(ssh, &data, &len);
2582 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
2586 static void ssh_set_frozen(Ssh ssh, int frozen)
2589 sk_set_frozen(ssh->s, frozen);
2590 ssh->frozen = frozen;
2593 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
2595 /* Log raw data, if we're in that mode. */
2597 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
2600 crBegin(ssh->ssh_gotdata_crstate);
2603 * To begin with, feed the characters one by one to the
2604 * protocol initialisation / selection function do_ssh_init().
2605 * When that returns 0, we're done with the initial greeting
2606 * exchange and can move on to packet discipline.
2609 int ret; /* need not be kept across crReturn */
2611 crReturnV; /* more data please */
2612 ret = do_ssh_init(ssh, *data);
2620 * We emerge from that loop when the initial negotiation is
2621 * over and we have selected an s_rdpkt function. Now pass
2622 * everything to s_rdpkt, and then pass the resulting packets
2623 * to the proper protocol handler.
2627 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
2629 ssh_queue_incoming_data(ssh, &data, &datalen);
2630 /* This uses up all data and cannot cause anything interesting
2631 * to happen; indeed, for anything to happen at all, we must
2632 * return, so break out. */
2634 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
2635 /* This uses up some or all data, and may freeze the
2637 ssh_process_queued_incoming_data(ssh);
2639 /* This uses up some or all data, and may freeze the
2641 ssh_process_incoming_data(ssh, &data, &datalen);
2643 /* FIXME this is probably EBW. */
2644 if (ssh->state == SSH_STATE_CLOSED)
2647 /* We're out of data. Go and get some more. */
2653 static int ssh_do_close(Ssh ssh, int notify_exit)
2656 struct ssh_channel *c;
2658 ssh->state = SSH_STATE_CLOSED;
2659 expire_timer_context(ssh);
2664 notify_remote_exit(ssh->frontend);
2669 * Now we must shut down any port- and X-forwarded channels going
2670 * through this connection.
2672 if (ssh->channels) {
2673 while (NULL != (c = index234(ssh->channels, 0))) {
2676 x11_close(c->u.x11.s);
2679 pfd_close(c->u.pfd.s);
2682 del234(ssh->channels, c); /* moving next one to index 0 */
2683 if (ssh->version == 2)
2684 bufchain_clear(&c->v.v2.outbuffer);
2689 * Go through port-forwardings, and close any associated
2690 * listening sockets.
2692 if (ssh->portfwds) {
2693 struct ssh_portfwd *pf;
2694 while (NULL != (pf = index234(ssh->portfwds, 0))) {
2695 /* Dispose of any listening socket. */
2697 pfd_terminate(pf->local);
2698 del234(ssh->portfwds, pf); /* moving next one to index 0 */
2706 static void ssh_log(Plug plug, int type, SockAddr addr, int port,
2707 const char *error_msg, int error_code)
2709 Ssh ssh = (Ssh) plug;
2710 char addrbuf[256], *msg;
2712 sk_getaddr(addr, addrbuf, lenof(addrbuf));
2715 msg = dupprintf("Connecting to %s port %d", addrbuf, port);
2717 msg = dupprintf("Failed to connect to %s: %s", addrbuf, error_msg);
2723 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
2726 Ssh ssh = (Ssh) plug;
2727 int need_notify = ssh_do_close(ssh, FALSE);
2730 if (!ssh->close_expected)
2731 error_msg = "Server unexpectedly closed network connection";
2733 error_msg = "Server closed network connection";
2736 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
2740 notify_remote_exit(ssh->frontend);
2743 logevent(error_msg);
2744 if (!ssh->close_expected || !ssh->clean_exit)
2745 connection_fatal(ssh->frontend, "%s", error_msg);
2749 static int ssh_receive(Plug plug, int urgent, char *data, int len)
2751 Ssh ssh = (Ssh) plug;
2752 ssh_gotdata(ssh, (unsigned char *)data, len);
2753 if (ssh->state == SSH_STATE_CLOSED) {
2754 ssh_do_close(ssh, TRUE);
2760 static void ssh_sent(Plug plug, int bufsize)
2762 Ssh ssh = (Ssh) plug;
2764 * If the send backlog on the SSH socket itself clears, we
2765 * should unthrottle the whole world if it was throttled.
2767 if (bufsize < SSH_MAX_BACKLOG)
2768 ssh_throttle_all(ssh, 0, bufsize);
2772 * Connect to specified host and port.
2773 * Returns an error message, or NULL on success.
2774 * Also places the canonical host name into `realhost'. It must be
2775 * freed by the caller.
2777 static const char *connect_to_host(Ssh ssh, char *host, int port,
2778 char **realhost, int nodelay, int keepalive)
2780 static const struct plug_function_table fn_table = {
2791 ssh->savedhost = snewn(1 + strlen(host), char);
2792 strcpy(ssh->savedhost, host);
2795 port = 22; /* default ssh port */
2796 ssh->savedport = port;
2801 logeventf(ssh, "Looking up host \"%s\"%s", host,
2802 (ssh->cfg.addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
2803 (ssh->cfg.addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" : "")));
2804 addr = name_lookup(host, port, realhost, &ssh->cfg,
2805 ssh->cfg.addressfamily);
2806 if ((err = sk_addr_error(addr)) != NULL) {
2814 ssh->fn = &fn_table;
2815 ssh->s = new_connection(addr, *realhost, port,
2816 0, 1, nodelay, keepalive, (Plug) ssh, &ssh->cfg);
2817 if ((err = sk_socket_error(ssh->s)) != NULL) {
2819 notify_remote_exit(ssh->frontend);
2824 * If the SSH version number's fixed, set it now, and if it's SSH-2,
2825 * send the version string too.
2827 if (ssh->cfg.sshprot == 0)
2829 if (ssh->cfg.sshprot == 3) {
2831 ssh_send_verstring(ssh, NULL);
2838 * Throttle or unthrottle the SSH connection.
2840 static void ssh1_throttle(Ssh ssh, int adjust)
2842 int old_count = ssh->v1_throttle_count;
2843 ssh->v1_throttle_count += adjust;
2844 assert(ssh->v1_throttle_count >= 0);
2845 if (ssh->v1_throttle_count && !old_count) {
2846 ssh_set_frozen(ssh, 1);
2847 } else if (!ssh->v1_throttle_count && old_count) {
2848 ssh_set_frozen(ssh, 0);
2853 * Throttle or unthrottle _all_ local data streams (for when sends
2854 * on the SSH connection itself back up).
2856 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
2859 struct ssh_channel *c;
2861 if (enable == ssh->throttled_all)
2863 ssh->throttled_all = enable;
2864 ssh->overall_bufsize = bufsize;
2867 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
2869 case CHAN_MAINSESSION:
2871 * This is treated separately, outside the switch.
2875 x11_override_throttle(c->u.x11.s, enable);
2878 /* Agent channels require no buffer management. */
2881 pfd_override_throttle(c->u.pfd.s, enable);
2887 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
2889 Ssh ssh = (Ssh) sshv;
2891 ssh->agent_response = reply;
2892 ssh->agent_response_len = replylen;
2894 if (ssh->version == 1)
2895 do_ssh1_login(ssh, NULL, -1, NULL);
2897 do_ssh2_authconn(ssh, NULL, -1, NULL);
2900 static void ssh_dialog_callback(void *sshv, int ret)
2902 Ssh ssh = (Ssh) sshv;
2904 ssh->user_response = ret;
2906 if (ssh->version == 1)
2907 do_ssh1_login(ssh, NULL, -1, NULL);
2909 do_ssh2_transport(ssh, NULL, -1, NULL);
2912 * This may have unfrozen the SSH connection, so do a
2915 ssh_process_queued_incoming_data(ssh);
2918 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
2920 struct ssh_channel *c = (struct ssh_channel *)cv;
2922 void *sentreply = reply;
2925 /* Fake SSH_AGENT_FAILURE. */
2926 sentreply = "\0\0\0\1\5";
2929 if (ssh->version == 2) {
2930 ssh2_add_channel_data(c, sentreply, replylen);
2933 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
2934 PKT_INT, c->remoteid,
2937 PKT_DATA, sentreply, replylen,
2946 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
2947 * non-NULL, otherwise just close the connection. `client_reason' == NULL
2948 * => log `wire_reason'.
2950 static void ssh_disconnect(Ssh ssh, char *client_reason, char *wire_reason,
2951 int code, int clean_exit)
2955 client_reason = wire_reason;
2957 error = dupprintf("Disconnected: %s", client_reason);
2959 error = dupstr("Disconnected");
2961 if (ssh->version == 1) {
2962 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
2964 } else if (ssh->version == 2) {
2965 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
2966 ssh2_pkt_adduint32(pktout, code);
2967 ssh2_pkt_addstring(pktout, wire_reason);
2968 ssh2_pkt_addstring(pktout, "en"); /* language tag */
2969 ssh2_pkt_send_noqueue(ssh, pktout);
2972 ssh->close_expected = TRUE;
2973 ssh->clean_exit = clean_exit;
2974 ssh_closing((Plug)ssh, error, 0, 0);
2979 * Handle the key exchange and user authentication phases.
2981 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
2982 struct Packet *pktin)
2985 unsigned char cookie[8], *ptr;
2986 struct RSAKey servkey, hostkey;
2987 struct MD5Context md5c;
2988 struct do_ssh1_login_state {
2990 unsigned char *rsabuf, *keystr1, *keystr2;
2991 unsigned long supported_ciphers_mask, supported_auths_mask;
2992 int tried_publickey, tried_agent;
2993 int tis_auth_refused, ccard_auth_refused;
2994 unsigned char session_id[16];
2997 void *publickey_blob;
2998 int publickey_bloblen;
2999 char *publickey_comment;
3000 int publickey_encrypted;
3001 prompts_t *cur_prompt;
3004 unsigned char request[5], *response, *p;
3014 crState(do_ssh1_login_state);
3016 crBegin(ssh->do_ssh1_login_crstate);
3021 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3022 bombout(("Public key packet not received"));
3026 logevent("Received public keys");
3028 ptr = ssh_pkt_getdata(pktin, 8);
3030 bombout(("SSH-1 public key packet stopped before random cookie"));
3033 memcpy(cookie, ptr, 8);
3035 if (!ssh1_pkt_getrsakey(pktin, &servkey, &s->keystr1) ||
3036 !ssh1_pkt_getrsakey(pktin, &hostkey, &s->keystr2)) {
3037 bombout(("Failed to read SSH-1 public keys from public key packet"));
3042 * Log the host key fingerprint.
3046 logevent("Host key fingerprint is:");
3047 strcpy(logmsg, " ");
3048 hostkey.comment = NULL;
3049 rsa_fingerprint(logmsg + strlen(logmsg),
3050 sizeof(logmsg) - strlen(logmsg), &hostkey);
3054 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
3055 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
3056 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
3058 ssh->v1_local_protoflags =
3059 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
3060 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
3063 MD5Update(&md5c, s->keystr2, hostkey.bytes);
3064 MD5Update(&md5c, s->keystr1, servkey.bytes);
3065 MD5Update(&md5c, cookie, 8);
3066 MD5Final(s->session_id, &md5c);
3068 for (i = 0; i < 32; i++)
3069 ssh->session_key[i] = random_byte();
3072 * Verify that the `bits' and `bytes' parameters match.
3074 if (hostkey.bits > hostkey.bytes * 8 ||
3075 servkey.bits > servkey.bytes * 8) {
3076 bombout(("SSH-1 public keys were badly formatted"));
3080 s->len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
3082 s->rsabuf = snewn(s->len, unsigned char);
3085 * Verify the host key.
3089 * First format the key into a string.
3091 int len = rsastr_len(&hostkey);
3092 char fingerprint[100];
3093 char *keystr = snewn(len, char);
3094 rsastr_fmt(keystr, &hostkey);
3095 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
3097 ssh_set_frozen(ssh, 1);
3098 s->dlgret = verify_ssh_host_key(ssh->frontend,
3099 ssh->savedhost, ssh->savedport,
3100 "rsa", keystr, fingerprint,
3101 ssh_dialog_callback, ssh);
3103 if (s->dlgret < 0) {
3107 bombout(("Unexpected data from server while waiting"
3108 " for user host key response"));
3111 } while (pktin || inlen > 0);
3112 s->dlgret = ssh->user_response;
3114 ssh_set_frozen(ssh, 0);
3116 if (s->dlgret == 0) {
3117 ssh_disconnect(ssh, "User aborted at host key verification",
3123 for (i = 0; i < 32; i++) {
3124 s->rsabuf[i] = ssh->session_key[i];
3126 s->rsabuf[i] ^= s->session_id[i];
3129 if (hostkey.bytes > servkey.bytes) {
3130 ret = rsaencrypt(s->rsabuf, 32, &servkey);
3132 ret = rsaencrypt(s->rsabuf, servkey.bytes, &hostkey);
3134 ret = rsaencrypt(s->rsabuf, 32, &hostkey);
3136 ret = rsaencrypt(s->rsabuf, hostkey.bytes, &servkey);
3139 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
3143 logevent("Encrypted session key");
3146 int cipher_chosen = 0, warn = 0;
3147 char *cipher_string = NULL;
3149 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
3150 int next_cipher = ssh->cfg.ssh_cipherlist[i];
3151 if (next_cipher == CIPHER_WARN) {
3152 /* If/when we choose a cipher, warn about it */
3154 } else if (next_cipher == CIPHER_AES) {
3155 /* XXX Probably don't need to mention this. */
3156 logevent("AES not supported in SSH-1, skipping");
3158 switch (next_cipher) {
3159 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
3160 cipher_string = "3DES"; break;
3161 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
3162 cipher_string = "Blowfish"; break;
3163 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
3164 cipher_string = "single-DES"; break;
3166 if (s->supported_ciphers_mask & (1 << s->cipher_type))
3170 if (!cipher_chosen) {
3171 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
3172 bombout(("Server violates SSH-1 protocol by not "
3173 "supporting 3DES encryption"));
3175 /* shouldn't happen */
3176 bombout(("No supported ciphers found"));
3180 /* Warn about chosen cipher if necessary. */
3182 ssh_set_frozen(ssh, 1);
3183 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
3184 ssh_dialog_callback, ssh);
3185 if (s->dlgret < 0) {
3189 bombout(("Unexpected data from server while waiting"
3190 " for user response"));
3193 } while (pktin || inlen > 0);
3194 s->dlgret = ssh->user_response;
3196 ssh_set_frozen(ssh, 0);
3197 if (s->dlgret == 0) {
3198 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
3205 switch (s->cipher_type) {
3206 case SSH_CIPHER_3DES:
3207 logevent("Using 3DES encryption");
3209 case SSH_CIPHER_DES:
3210 logevent("Using single-DES encryption");
3212 case SSH_CIPHER_BLOWFISH:
3213 logevent("Using Blowfish encryption");
3217 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
3218 PKT_CHAR, s->cipher_type,
3219 PKT_DATA, cookie, 8,
3220 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
3221 PKT_DATA, s->rsabuf, s->len,
3222 PKT_INT, ssh->v1_local_protoflags, PKT_END);
3224 logevent("Trying to enable encryption...");
3228 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
3229 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
3231 ssh->v1_cipher_ctx = ssh->cipher->make_context();
3232 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
3233 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
3235 ssh->crcda_ctx = crcda_make_context();
3236 logevent("Installing CRC compensation attack detector");
3238 if (servkey.modulus) {
3239 sfree(servkey.modulus);
3240 servkey.modulus = NULL;
3242 if (servkey.exponent) {
3243 sfree(servkey.exponent);
3244 servkey.exponent = NULL;
3246 if (hostkey.modulus) {
3247 sfree(hostkey.modulus);
3248 hostkey.modulus = NULL;
3250 if (hostkey.exponent) {
3251 sfree(hostkey.exponent);
3252 hostkey.exponent = NULL;
3256 if (pktin->type != SSH1_SMSG_SUCCESS) {
3257 bombout(("Encryption not successfully enabled"));
3261 logevent("Successfully started encryption");
3263 fflush(stdout); /* FIXME eh? */
3265 if (!*ssh->cfg.username) {
3266 int ret; /* need not be kept over crReturn */
3267 s->cur_prompt = new_prompts(ssh->frontend);
3268 s->cur_prompt->to_server = TRUE;
3269 s->cur_prompt->name = dupstr("SSH login name");
3270 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE,
3271 lenof(s->username));
3272 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3275 crWaitUntil(!pktin);
3276 ret = get_userpass_input(s->cur_prompt, in, inlen);
3281 * Failed to get a username. Terminate.
3283 free_prompts(s->cur_prompt);
3284 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
3287 memcpy(s->username, s->cur_prompt->prompts[0]->result,
3288 lenof(s->username));
3289 free_prompts(s->cur_prompt);
3291 strncpy(s->username, ssh->cfg.username, sizeof(s->username));
3292 s->username[sizeof(s->username)-1] = '\0';
3295 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, s->username, PKT_END);
3297 char *userlog = dupprintf("Sent username \"%s\"", s->username);
3299 if (flags & FLAG_INTERACTIVE &&
3300 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
3301 c_write_str(ssh, userlog);
3302 c_write_str(ssh, "\r\n");
3310 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA)) {
3311 /* We must not attempt PK auth. Pretend we've already tried it. */
3312 s->tried_publickey = s->tried_agent = 1;
3314 s->tried_publickey = s->tried_agent = 0;
3316 s->tis_auth_refused = s->ccard_auth_refused = 0;
3318 * Load the public half of any configured keyfile for later use.
3320 if (!filename_is_null(ssh->cfg.keyfile)) {
3322 logeventf(ssh, "Reading private key file \"%.150s\"",
3323 filename_to_str(&ssh->cfg.keyfile));
3324 keytype = key_type(&ssh->cfg.keyfile);
3325 if (keytype == SSH_KEYTYPE_SSH1) {
3327 if (rsakey_pubblob(&ssh->cfg.keyfile,
3328 &s->publickey_blob, &s->publickey_bloblen,
3329 &s->publickey_comment, &error)) {
3330 s->publickey_encrypted = rsakey_encrypted(&ssh->cfg.keyfile,
3334 logeventf(ssh, "Unable to load private key (%s)", error);
3335 msgbuf = dupprintf("Unable to load private key file "
3336 "\"%.150s\" (%s)\r\n",
3337 filename_to_str(&ssh->cfg.keyfile),
3339 c_write_str(ssh, msgbuf);
3341 s->publickey_blob = NULL;
3345 logeventf(ssh, "Unable to use this key file (%s)",
3346 key_type_to_str(keytype));
3347 msgbuf = dupprintf("Unable to use key file \"%.150s\""
3349 filename_to_str(&ssh->cfg.keyfile),
3350 key_type_to_str(keytype));
3351 c_write_str(ssh, msgbuf);
3353 s->publickey_blob = NULL;
3356 s->publickey_blob = NULL;
3358 while (pktin->type == SSH1_SMSG_FAILURE) {
3359 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
3361 if (ssh->cfg.tryagent && agent_exists() && !s->tried_agent) {
3363 * Attempt RSA authentication using Pageant.
3369 logevent("Pageant is running. Requesting keys.");
3371 /* Request the keys held by the agent. */
3372 PUT_32BIT(s->request, 1);
3373 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
3374 if (!agent_query(s->request, 5, &r, &s->responselen,
3375 ssh_agent_callback, ssh)) {
3379 bombout(("Unexpected data from server while waiting"
3380 " for agent response"));
3383 } while (pktin || inlen > 0);
3384 r = ssh->agent_response;
3385 s->responselen = ssh->agent_response_len;
3387 s->response = (unsigned char *) r;
3388 if (s->response && s->responselen >= 5 &&
3389 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
3390 s->p = s->response + 5;
3391 s->nkeys = GET_32BIT(s->p);
3393 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
3394 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
3395 unsigned char *pkblob = s->p;
3399 do { /* do while (0) to make breaking easy */
3400 n = ssh1_read_bignum
3401 (s->p, s->responselen-(s->p-s->response),
3406 n = ssh1_read_bignum
3407 (s->p, s->responselen-(s->p-s->response),
3412 if (s->responselen - (s->p-s->response) < 4)
3414 s->commentlen = GET_32BIT(s->p);
3416 if (s->responselen - (s->p-s->response) <
3419 s->commentp = (char *)s->p;
3420 s->p += s->commentlen;
3424 logevent("Pageant key list packet was truncated");
3428 if (s->publickey_blob) {
3429 if (!memcmp(pkblob, s->publickey_blob,
3430 s->publickey_bloblen)) {
3431 logeventf(ssh, "Pageant key #%d matches "
3432 "configured key file", s->keyi);
3433 s->tried_publickey = 1;
3435 /* Skip non-configured key */
3438 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
3439 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3440 PKT_BIGNUM, s->key.modulus, PKT_END);
3442 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3443 logevent("Key refused");
3446 logevent("Received RSA challenge");
3447 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3448 bombout(("Server's RSA challenge was badly formatted"));
3453 char *agentreq, *q, *ret;
3456 len = 1 + 4; /* message type, bit count */
3457 len += ssh1_bignum_length(s->key.exponent);
3458 len += ssh1_bignum_length(s->key.modulus);
3459 len += ssh1_bignum_length(s->challenge);
3460 len += 16; /* session id */
3461 len += 4; /* response format */
3462 agentreq = snewn(4 + len, char);
3463 PUT_32BIT(agentreq, len);
3465 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
3466 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
3468 q += ssh1_write_bignum(q, s->key.exponent);
3469 q += ssh1_write_bignum(q, s->key.modulus);
3470 q += ssh1_write_bignum(q, s->challenge);
3471 memcpy(q, s->session_id, 16);
3473 PUT_32BIT(q, 1); /* response format */
3474 if (!agent_query(agentreq, len + 4, &vret, &retlen,
3475 ssh_agent_callback, ssh)) {
3480 bombout(("Unexpected data from server"
3481 " while waiting for agent"
3485 } while (pktin || inlen > 0);
3486 vret = ssh->agent_response;
3487 retlen = ssh->agent_response_len;
3492 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
3493 logevent("Sending Pageant's response");
3494 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3495 PKT_DATA, ret + 5, 16,
3499 if (pktin->type == SSH1_SMSG_SUCCESS) {
3501 ("Pageant's response accepted");
3502 if (flags & FLAG_VERBOSE) {
3503 c_write_str(ssh, "Authenticated using"
3505 c_write(ssh, s->commentp,
3507 c_write_str(ssh, "\" from agent\r\n");
3512 ("Pageant's response not accepted");
3515 ("Pageant failed to answer challenge");
3519 logevent("No reply received from Pageant");
3522 freebn(s->key.exponent);
3523 freebn(s->key.modulus);
3524 freebn(s->challenge);
3529 if (s->publickey_blob && !s->tried_publickey)
3530 logevent("Configured key file not in Pageant");
3535 if (s->publickey_blob && !s->tried_publickey) {
3537 * Try public key authentication with the specified
3540 int got_passphrase; /* need not be kept over crReturn */
3541 if (flags & FLAG_VERBOSE)
3542 c_write_str(ssh, "Trying public key authentication.\r\n");
3543 logeventf(ssh, "Trying public key \"%s\"",
3544 filename_to_str(&ssh->cfg.keyfile));
3545 s->tried_publickey = 1;
3546 got_passphrase = FALSE;
3547 while (!got_passphrase) {
3549 * Get a passphrase, if necessary.
3551 char *passphrase = NULL; /* only written after crReturn */
3553 if (!s->publickey_encrypted) {
3554 if (flags & FLAG_VERBOSE)
3555 c_write_str(ssh, "No passphrase required.\r\n");
3558 int ret; /* need not be kept over crReturn */
3559 s->cur_prompt = new_prompts(ssh->frontend);
3560 s->cur_prompt->to_server = FALSE;
3561 s->cur_prompt->name = dupstr("SSH key passphrase");
3562 add_prompt(s->cur_prompt,
3563 dupprintf("Passphrase for key \"%.100s\": ",
3564 s->publickey_comment),
3565 FALSE, SSH_MAX_PASSWORD_LEN);
3566 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3569 crWaitUntil(!pktin);
3570 ret = get_userpass_input(s->cur_prompt, in, inlen);
3574 /* Failed to get a passphrase. Terminate. */
3575 free_prompts(s->cur_prompt);
3576 ssh_disconnect(ssh, NULL, "Unable to authenticate",
3580 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
3581 free_prompts(s->cur_prompt);
3584 * Try decrypting key with passphrase.
3586 ret = loadrsakey(&ssh->cfg.keyfile, &s->key, passphrase,
3589 memset(passphrase, 0, strlen(passphrase));
3593 /* Correct passphrase. */
3594 got_passphrase = TRUE;
3595 } else if (ret == 0) {
3596 c_write_str(ssh, "Couldn't load private key from ");
3597 c_write_str(ssh, filename_to_str(&ssh->cfg.keyfile));
3598 c_write_str(ssh, " (");
3599 c_write_str(ssh, error);
3600 c_write_str(ssh, ").\r\n");
3601 got_passphrase = FALSE;
3602 break; /* go and try something else */
3603 } else if (ret == -1) {
3604 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
3605 got_passphrase = FALSE;
3608 assert(0 && "unexpected return from loadrsakey()");
3609 got_passphrase = FALSE; /* placate optimisers */
3613 if (got_passphrase) {
3616 * Send a public key attempt.
3618 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3619 PKT_BIGNUM, s->key.modulus, PKT_END);
3622 if (pktin->type == SSH1_SMSG_FAILURE) {
3623 c_write_str(ssh, "Server refused our public key.\r\n");
3624 continue; /* go and try something else */
3626 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3627 bombout(("Bizarre response to offer of public key"));
3633 unsigned char buffer[32];
3634 Bignum challenge, response;
3636 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3637 bombout(("Server's RSA challenge was badly formatted"));
3640 response = rsadecrypt(challenge, &s->key);
3641 freebn(s->key.private_exponent);/* burn the evidence */
3643 for (i = 0; i < 32; i++) {
3644 buffer[i] = bignum_byte(response, 31 - i);
3648 MD5Update(&md5c, buffer, 32);
3649 MD5Update(&md5c, s->session_id, 16);
3650 MD5Final(buffer, &md5c);
3652 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3653 PKT_DATA, buffer, 16, PKT_END);
3660 if (pktin->type == SSH1_SMSG_FAILURE) {
3661 if (flags & FLAG_VERBOSE)
3662 c_write_str(ssh, "Failed to authenticate with"
3663 " our public key.\r\n");
3664 continue; /* go and try something else */
3665 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
3666 bombout(("Bizarre response to RSA authentication response"));
3670 break; /* we're through! */
3676 * Otherwise, try various forms of password-like authentication.
3678 s->cur_prompt = new_prompts(ssh->frontend);
3680 if (ssh->cfg.try_tis_auth &&
3681 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
3682 !s->tis_auth_refused) {
3683 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
3684 logevent("Requested TIS authentication");
3685 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
3687 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
3688 logevent("TIS authentication declined");
3689 if (flags & FLAG_INTERACTIVE)
3690 c_write_str(ssh, "TIS authentication refused.\r\n");
3691 s->tis_auth_refused = 1;
3696 char *instr_suf, *prompt;
3698 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3700 bombout(("TIS challenge packet was badly formed"));
3703 logevent("Received TIS challenge");
3704 s->cur_prompt->to_server = TRUE;
3705 s->cur_prompt->name = dupstr("SSH TIS authentication");
3706 /* Prompt heuristic comes from OpenSSH */
3707 if (memchr(challenge, '\n', challengelen)) {
3708 instr_suf = dupstr("");
3709 prompt = dupprintf("%.*s", challengelen, challenge);
3711 instr_suf = dupprintf("%.*s", challengelen, challenge);
3712 prompt = dupstr("Response: ");
3714 s->cur_prompt->instruction =
3715 dupprintf("Using TIS authentication.%s%s",
3716 (*instr_suf) ? "\n" : "",
3718 s->cur_prompt->instr_reqd = TRUE;
3719 add_prompt(s->cur_prompt, prompt, FALSE, SSH_MAX_PASSWORD_LEN);
3723 if (ssh->cfg.try_tis_auth &&
3724 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
3725 !s->ccard_auth_refused) {
3726 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
3727 logevent("Requested CryptoCard authentication");
3728 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
3730 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
3731 logevent("CryptoCard authentication declined");
3732 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
3733 s->ccard_auth_refused = 1;
3738 char *instr_suf, *prompt;
3740 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3742 bombout(("CryptoCard challenge packet was badly formed"));
3745 logevent("Received CryptoCard challenge");
3746 s->cur_prompt->to_server = TRUE;
3747 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
3748 s->cur_prompt->name_reqd = FALSE;
3749 /* Prompt heuristic comes from OpenSSH */
3750 if (memchr(challenge, '\n', challengelen)) {
3751 instr_suf = dupstr("");
3752 prompt = dupprintf("%.*s", challengelen, challenge);
3754 instr_suf = dupprintf("%.*s", challengelen, challenge);
3755 prompt = dupstr("Response: ");
3757 s->cur_prompt->instruction =
3758 dupprintf("Using CryptoCard authentication.%s%s",
3759 (*instr_suf) ? "\n" : "",
3761 s->cur_prompt->instr_reqd = TRUE;
3762 add_prompt(s->cur_prompt, prompt, FALSE, SSH_MAX_PASSWORD_LEN);
3766 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
3767 s->cur_prompt->to_server = TRUE;
3768 s->cur_prompt->name = dupstr("SSH password");
3769 add_prompt(s->cur_prompt, dupprintf("%.90s@%.90s's password: ",
3770 s->username, ssh->savedhost),
3771 FALSE, SSH_MAX_PASSWORD_LEN);
3775 * Show password prompt, having first obtained it via a TIS
3776 * or CryptoCard exchange if we're doing TIS or CryptoCard
3780 int ret; /* need not be kept over crReturn */
3781 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3784 crWaitUntil(!pktin);
3785 ret = get_userpass_input(s->cur_prompt, in, inlen);
3790 * Failed to get a password (for example
3791 * because one was supplied on the command line
3792 * which has already failed to work). Terminate.
3794 free_prompts(s->cur_prompt);
3795 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
3800 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
3802 * Defence against traffic analysis: we send a
3803 * whole bunch of packets containing strings of
3804 * different lengths. One of these strings is the
3805 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
3806 * The others are all random data in
3807 * SSH1_MSG_IGNORE packets. This way a passive
3808 * listener can't tell which is the password, and
3809 * hence can't deduce the password length.
3811 * Anybody with a password length greater than 16
3812 * bytes is going to have enough entropy in their
3813 * password that a listener won't find it _that_
3814 * much help to know how long it is. So what we'll
3817 * - if password length < 16, we send 15 packets
3818 * containing string lengths 1 through 15
3820 * - otherwise, we let N be the nearest multiple
3821 * of 8 below the password length, and send 8
3822 * packets containing string lengths N through
3823 * N+7. This won't obscure the order of
3824 * magnitude of the password length, but it will
3825 * introduce a bit of extra uncertainty.
3827 * A few servers can't deal with SSH1_MSG_IGNORE, at
3828 * least in this context. For these servers, we need
3829 * an alternative defence. We make use of the fact
3830 * that the password is interpreted as a C string:
3831 * so we can append a NUL, then some random data.
3833 * A few servers can deal with neither SSH1_MSG_IGNORE
3834 * here _nor_ a padded password string.
3835 * For these servers we are left with no defences
3836 * against password length sniffing.
3838 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
3839 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
3841 * The server can deal with SSH1_MSG_IGNORE, so
3842 * we can use the primary defence.
3844 int bottom, top, pwlen, i;
3847 pwlen = strlen(s->cur_prompt->prompts[0]->result);
3849 bottom = 0; /* zero length passwords are OK! :-) */
3852 bottom = pwlen & ~7;
3856 assert(pwlen >= bottom && pwlen <= top);
3858 randomstr = snewn(top + 1, char);
3860 for (i = bottom; i <= top; i++) {
3862 defer_packet(ssh, s->pwpkt_type,
3863 PKTT_PASSWORD, PKT_STR,
3864 s->cur_prompt->prompts[0]->result,
3865 PKTT_OTHER, PKT_END);
3867 for (j = 0; j < i; j++) {
3869 randomstr[j] = random_byte();
3870 } while (randomstr[j] == '\0');
3872 randomstr[i] = '\0';
3873 defer_packet(ssh, SSH1_MSG_IGNORE,
3874 PKT_STR, randomstr, PKT_END);
3877 logevent("Sending password with camouflage packets");
3878 ssh_pkt_defersend(ssh);
3881 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
3883 * The server can't deal with SSH1_MSG_IGNORE
3884 * but can deal with padded passwords, so we
3885 * can use the secondary defence.
3891 len = strlen(s->cur_prompt->prompts[0]->result);
3892 if (len < sizeof(string)) {
3894 strcpy(string, s->cur_prompt->prompts[0]->result);
3895 len++; /* cover the zero byte */
3896 while (len < sizeof(string)) {
3897 string[len++] = (char) random_byte();
3900 ss = s->cur_prompt->prompts[0]->result;
3902 logevent("Sending length-padded password");
3903 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
3904 PKT_INT, len, PKT_DATA, ss, len,
3905 PKTT_OTHER, PKT_END);
3908 * The server is believed unable to cope with
3909 * any of our password camouflage methods.
3912 len = strlen(s->cur_prompt->prompts[0]->result);
3913 logevent("Sending unpadded password");
3914 send_packet(ssh, s->pwpkt_type,
3915 PKTT_PASSWORD, PKT_INT, len,
3916 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
3917 PKTT_OTHER, PKT_END);
3920 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
3921 PKT_STR, s->cur_prompt->prompts[0]->result,
3922 PKTT_OTHER, PKT_END);
3924 logevent("Sent password");
3925 free_prompts(s->cur_prompt);
3927 if (pktin->type == SSH1_SMSG_FAILURE) {
3928 if (flags & FLAG_VERBOSE)
3929 c_write_str(ssh, "Access denied\r\n");
3930 logevent("Authentication refused");
3931 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
3932 bombout(("Strange packet received, type %d", pktin->type));
3938 if (s->publickey_blob) {
3939 sfree(s->publickey_blob);
3940 sfree(s->publickey_comment);
3943 logevent("Authentication successful");
3948 void sshfwd_close(struct ssh_channel *c)
3952 if (ssh->state == SSH_STATE_CLOSED)
3955 if (c && !c->closes) {
3957 * If halfopen is true, we have sent
3958 * CHANNEL_OPEN for this channel, but it hasn't even been
3959 * acknowledged by the server. So we must set a close flag
3960 * on it now, and then when the server acks the channel
3961 * open, we can close it then.
3964 if (ssh->version == 1) {
3965 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
3968 struct Packet *pktout;
3969 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
3970 ssh2_pkt_adduint32(pktout, c->remoteid);
3971 ssh2_pkt_send(ssh, pktout);
3974 c->closes = 1; /* sent MSG_CLOSE */
3975 if (c->type == CHAN_X11) {
3977 logevent("Forwarded X11 connection terminated");
3978 } else if (c->type == CHAN_SOCKDATA ||
3979 c->type == CHAN_SOCKDATA_DORMANT) {
3981 logevent("Forwarded port closed");
3986 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
3990 if (ssh->state == SSH_STATE_CLOSED)
3993 if (ssh->version == 1) {
3994 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3995 PKT_INT, c->remoteid,
3997 PKT_INT, len, PKT_DATA, buf, len,
3998 PKTT_OTHER, PKT_END);
4000 * In SSH-1 we can return 0 here - implying that forwarded
4001 * connections are never individually throttled - because
4002 * the only circumstance that can cause throttling will be
4003 * the whole SSH connection backing up, in which case
4004 * _everything_ will be throttled as a whole.
4008 ssh2_add_channel_data(c, buf, len);
4009 return ssh2_try_send(c);
4013 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
4017 if (ssh->state == SSH_STATE_CLOSED)
4020 if (ssh->version == 1) {
4021 if (c->v.v1.throttling && bufsize < SSH1_BUFFER_LIMIT) {
4022 c->v.v1.throttling = 0;
4023 ssh1_throttle(ssh, -1);
4026 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
4030 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
4032 struct queued_handler *qh = ssh->qhead;
4036 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
4039 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
4040 ssh->packet_dispatch[qh->msg1] = NULL;
4043 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
4044 ssh->packet_dispatch[qh->msg2] = NULL;
4048 ssh->qhead = qh->next;
4050 if (ssh->qhead->msg1 > 0) {
4051 assert(ssh->packet_dispatch[ssh->qhead->msg1] == NULL);
4052 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
4054 if (ssh->qhead->msg2 > 0) {
4055 assert(ssh->packet_dispatch[ssh->qhead->msg2] == NULL);
4056 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
4059 ssh->qhead = ssh->qtail = NULL;
4060 ssh->packet_dispatch[pktin->type] = NULL;
4063 qh->handler(ssh, pktin, qh->ctx);
4068 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
4069 chandler_fn_t handler, void *ctx)
4071 struct queued_handler *qh;
4073 qh = snew(struct queued_handler);
4076 qh->handler = handler;
4080 if (ssh->qtail == NULL) {
4084 assert(ssh->packet_dispatch[qh->msg1] == NULL);
4085 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
4088 assert(ssh->packet_dispatch[qh->msg2] == NULL);
4089 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
4092 ssh->qtail->next = qh;
4097 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
4099 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
4101 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
4102 SSH2_MSG_REQUEST_SUCCESS)) {
4103 logeventf(ssh, "Remote port forwarding from %s enabled",
4106 logeventf(ssh, "Remote port forwarding from %s refused",
4109 rpf = del234(ssh->rportfwds, pf);
4115 static void ssh_setup_portfwd(Ssh ssh, const Config *cfg)
4117 const char *portfwd_strptr = cfg->portfwd;
4118 struct ssh_portfwd *epf;
4121 if (!ssh->portfwds) {
4122 ssh->portfwds = newtree234(ssh_portcmp);
4125 * Go through the existing port forwardings and tag them
4126 * with status==DESTROY. Any that we want to keep will be
4127 * re-enabled (status==KEEP) as we go through the
4128 * configuration and find out which bits are the same as
4131 struct ssh_portfwd *epf;
4133 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4134 epf->status = DESTROY;
4137 while (*portfwd_strptr) {
4138 char address_family, type;
4139 int sport,dport,sserv,dserv;
4140 char sports[256], dports[256], saddr[256], host[256];
4143 address_family = 'A';
4145 if (*portfwd_strptr == 'A' ||
4146 *portfwd_strptr == '4' ||
4147 *portfwd_strptr == '6')
4148 address_family = *portfwd_strptr++;
4149 if (*portfwd_strptr == 'L' ||
4150 *portfwd_strptr == 'R' ||
4151 *portfwd_strptr == 'D')
4152 type = *portfwd_strptr++;
4157 while (*portfwd_strptr && *portfwd_strptr != '\t') {
4158 if (*portfwd_strptr == ':') {
4160 * We've seen a colon in the middle of the
4161 * source port number. This means that
4162 * everything we've seen until now is the
4163 * source _address_, so we'll move it into
4164 * saddr and start sports from the beginning
4169 if (ssh->version == 1 && type == 'R') {
4170 logeventf(ssh, "SSH-1 cannot handle remote source address "
4171 "spec \"%s\"; ignoring", sports);
4173 strcpy(saddr, sports);
4176 if (n < lenof(sports)-1) sports[n++] = *portfwd_strptr++;
4180 if (*portfwd_strptr == '\t')
4183 while (*portfwd_strptr && *portfwd_strptr != ':') {
4184 if (n < lenof(host)-1) host[n++] = *portfwd_strptr++;
4187 if (*portfwd_strptr == ':')
4190 while (*portfwd_strptr) {
4191 if (n < lenof(dports)-1) dports[n++] = *portfwd_strptr++;
4195 dport = atoi(dports);
4199 dport = net_service_lookup(dports);
4201 logeventf(ssh, "Service lookup failed for destination"
4202 " port \"%s\"", dports);
4206 while (*portfwd_strptr) portfwd_strptr++;
4210 portfwd_strptr++; /* eat the NUL and move to next one */
4212 sport = atoi(sports);
4216 sport = net_service_lookup(sports);
4218 logeventf(ssh, "Service lookup failed for source"
4219 " port \"%s\"", sports);
4222 if (sport && dport) {
4223 /* Set up a description of the source port. */
4224 struct ssh_portfwd *pfrec, *epfrec;
4226 pfrec = snew(struct ssh_portfwd);
4228 pfrec->saddr = *saddr ? dupstr(saddr) : NULL;
4229 pfrec->sserv = sserv ? dupstr(sports) : NULL;
4230 pfrec->sport = sport;
4231 pfrec->daddr = *host ? dupstr(host) : NULL;
4232 pfrec->dserv = dserv ? dupstr(dports) : NULL;
4233 pfrec->dport = dport;
4234 pfrec->local = NULL;
4235 pfrec->remote = NULL;
4236 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
4237 address_family == '6' ? ADDRTYPE_IPV6 :
4240 epfrec = add234(ssh->portfwds, pfrec);
4241 if (epfrec != pfrec) {
4243 * We already have a port forwarding with precisely
4244 * these parameters. Hence, no need to do anything;
4245 * simply tag the existing one as KEEP.
4247 epfrec->status = KEEP;
4248 free_portfwd(pfrec);
4250 pfrec->status = CREATE;
4256 * Now go through and destroy any port forwardings which were
4259 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4260 if (epf->status == DESTROY) {
4263 message = dupprintf("%s port forwarding from %s%s%d",
4264 epf->type == 'L' ? "local" :
4265 epf->type == 'R' ? "remote" : "dynamic",
4266 epf->saddr ? epf->saddr : "",
4267 epf->saddr ? ":" : "",
4270 if (epf->type != 'D') {
4271 char *msg2 = dupprintf("%s to %s:%d", message,
4272 epf->daddr, epf->dport);
4277 logeventf(ssh, "Cancelling %s", message);
4281 struct ssh_rportfwd *rpf = epf->remote;
4282 struct Packet *pktout;
4285 * Cancel the port forwarding at the server
4288 if (ssh->version == 1) {
4290 * We cannot cancel listening ports on the
4291 * server side in SSH-1! There's no message
4292 * to support it. Instead, we simply remove
4293 * the rportfwd record from the local end
4294 * so that any connections the server tries
4295 * to make on it are rejected.
4298 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4299 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
4300 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
4302 ssh2_pkt_addstring(pktout, epf->saddr);
4303 } else if (ssh->cfg.rport_acceptall) {
4304 /* XXX: ssh->cfg.rport_acceptall may not represent
4305 * what was used to open the original connection,
4306 * since it's reconfigurable. */
4307 ssh2_pkt_addstring(pktout, "0.0.0.0");
4309 ssh2_pkt_addstring(pktout, "127.0.0.1");
4311 ssh2_pkt_adduint32(pktout, epf->sport);
4312 ssh2_pkt_send(ssh, pktout);
4315 del234(ssh->rportfwds, rpf);
4317 } else if (epf->local) {
4318 pfd_terminate(epf->local);
4321 delpos234(ssh->portfwds, i);
4323 i--; /* so we don't skip one in the list */
4327 * And finally, set up any new port forwardings (status==CREATE).
4329 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4330 if (epf->status == CREATE) {
4331 char *sportdesc, *dportdesc;
4332 sportdesc = dupprintf("%s%s%s%s%d%s",
4333 epf->saddr ? epf->saddr : "",
4334 epf->saddr ? ":" : "",
4335 epf->sserv ? epf->sserv : "",
4336 epf->sserv ? "(" : "",
4338 epf->sserv ? ")" : "");
4339 if (epf->type == 'D') {
4342 dportdesc = dupprintf("%s:%s%s%d%s",
4344 epf->dserv ? epf->dserv : "",
4345 epf->dserv ? "(" : "",
4347 epf->dserv ? ")" : "");
4350 if (epf->type == 'L') {
4351 const char *err = pfd_addforward(epf->daddr, epf->dport,
4352 epf->saddr, epf->sport,
4355 epf->addressfamily);
4357 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
4358 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4359 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4360 sportdesc, dportdesc,
4361 err ? " failed: " : "", err ? err : "");
4362 } else if (epf->type == 'D') {
4363 const char *err = pfd_addforward(NULL, -1,
4364 epf->saddr, epf->sport,
4367 epf->addressfamily);
4369 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
4370 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4371 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4373 err ? " failed: " : "", err ? err : "");
4375 struct ssh_rportfwd *pf;
4378 * Ensure the remote port forwardings tree exists.
4380 if (!ssh->rportfwds) {
4381 if (ssh->version == 1)
4382 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
4384 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
4387 pf = snew(struct ssh_rportfwd);
4388 strncpy(pf->dhost, epf->daddr, lenof(pf->dhost)-1);
4389 pf->dhost[lenof(pf->dhost)-1] = '\0';
4390 pf->dport = epf->dport;
4391 pf->sport = epf->sport;
4392 if (add234(ssh->rportfwds, pf) != pf) {
4393 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
4394 epf->daddr, epf->dport);
4397 logeventf(ssh, "Requesting remote port %s"
4398 " forward to %s", sportdesc, dportdesc);
4400 pf->sportdesc = sportdesc;
4405 if (ssh->version == 1) {
4406 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
4407 PKT_INT, epf->sport,
4408 PKT_STR, epf->daddr,
4409 PKT_INT, epf->dport,
4411 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
4413 ssh_rportfwd_succfail, pf);
4415 struct Packet *pktout;
4416 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4417 ssh2_pkt_addstring(pktout, "tcpip-forward");
4418 ssh2_pkt_addbool(pktout, 1);/* want reply */
4420 ssh2_pkt_addstring(pktout, epf->saddr);
4421 } else if (cfg->rport_acceptall) {
4422 ssh2_pkt_addstring(pktout, "0.0.0.0");
4424 ssh2_pkt_addstring(pktout, "127.0.0.1");
4426 ssh2_pkt_adduint32(pktout, epf->sport);
4427 ssh2_pkt_send(ssh, pktout);
4429 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
4430 SSH2_MSG_REQUEST_FAILURE,
4431 ssh_rportfwd_succfail, pf);
4440 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
4443 int stringlen, bufsize;
4445 ssh_pkt_getstring(pktin, &string, &stringlen);
4446 if (string == NULL) {
4447 bombout(("Incoming terminal data packet was badly formed"));
4451 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
4453 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
4454 ssh->v1_stdout_throttling = 1;
4455 ssh1_throttle(ssh, +1);
4459 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
4461 /* Remote side is trying to open a channel to talk to our
4462 * X-Server. Give them back a local channel number. */
4463 struct ssh_channel *c;
4464 int remoteid = ssh_pkt_getuint32(pktin);
4466 logevent("Received X11 connect request");
4467 /* Refuse if X11 forwarding is disabled. */
4468 if (!ssh->X11_fwd_enabled) {
4469 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4470 PKT_INT, remoteid, PKT_END);
4471 logevent("Rejected X11 connect request");
4473 c = snew(struct ssh_channel);
4476 if (x11_init(&c->u.x11.s, ssh->cfg.x11_display, c,
4477 ssh->x11auth, NULL, -1, &ssh->cfg) != NULL) {
4478 logevent("Opening X11 forward connection failed");
4480 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4481 PKT_INT, remoteid, PKT_END);
4484 ("Opening X11 forward connection succeeded");
4485 c->remoteid = remoteid;
4486 c->halfopen = FALSE;
4487 c->localid = alloc_channel_id(ssh);
4489 c->v.v1.throttling = 0;
4490 c->type = CHAN_X11; /* identify channel type */
4491 add234(ssh->channels, c);
4492 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4493 PKT_INT, c->remoteid, PKT_INT,
4494 c->localid, PKT_END);
4495 logevent("Opened X11 forward channel");
4500 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
4502 /* Remote side is trying to open a channel to talk to our
4503 * agent. Give them back a local channel number. */
4504 struct ssh_channel *c;
4505 int remoteid = ssh_pkt_getuint32(pktin);
4507 /* Refuse if agent forwarding is disabled. */
4508 if (!ssh->agentfwd_enabled) {
4509 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4510 PKT_INT, remoteid, PKT_END);
4512 c = snew(struct ssh_channel);
4514 c->remoteid = remoteid;
4515 c->halfopen = FALSE;
4516 c->localid = alloc_channel_id(ssh);
4518 c->v.v1.throttling = 0;
4519 c->type = CHAN_AGENT; /* identify channel type */
4520 c->u.a.lensofar = 0;
4521 add234(ssh->channels, c);
4522 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4523 PKT_INT, c->remoteid, PKT_INT, c->localid,
4528 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
4530 /* Remote side is trying to open a channel to talk to a
4531 * forwarded port. Give them back a local channel number. */
4532 struct ssh_channel *c;
4533 struct ssh_rportfwd pf, *pfp;
4538 c = snew(struct ssh_channel);
4541 remoteid = ssh_pkt_getuint32(pktin);
4542 ssh_pkt_getstring(pktin, &host, &hostsize);
4543 port = ssh_pkt_getuint32(pktin);
4545 if (hostsize >= lenof(pf.dhost))
4546 hostsize = lenof(pf.dhost)-1;
4547 memcpy(pf.dhost, host, hostsize);
4548 pf.dhost[hostsize] = '\0';
4550 pfp = find234(ssh->rportfwds, &pf, NULL);
4553 logeventf(ssh, "Rejected remote port open request for %s:%d",
4555 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4556 PKT_INT, remoteid, PKT_END);
4558 logeventf(ssh, "Received remote port open request for %s:%d",
4560 e = pfd_newconnect(&c->u.pfd.s, pf.dhost, port,
4561 c, &ssh->cfg, pfp->pfrec->addressfamily);
4563 logeventf(ssh, "Port open failed: %s", e);
4565 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4566 PKT_INT, remoteid, PKT_END);
4568 c->remoteid = remoteid;
4569 c->halfopen = FALSE;
4570 c->localid = alloc_channel_id(ssh);
4572 c->v.v1.throttling = 0;
4573 c->type = CHAN_SOCKDATA; /* identify channel type */
4574 add234(ssh->channels, c);
4575 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4576 PKT_INT, c->remoteid, PKT_INT,
4577 c->localid, PKT_END);
4578 logevent("Forwarded port opened successfully");
4583 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
4585 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4586 unsigned int localid = ssh_pkt_getuint32(pktin);
4587 struct ssh_channel *c;
4589 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4590 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4591 c->remoteid = localid;
4592 c->halfopen = FALSE;
4593 c->type = CHAN_SOCKDATA;
4594 c->v.v1.throttling = 0;
4595 pfd_confirm(c->u.pfd.s);
4598 if (c && c->closes) {
4600 * We have a pending close on this channel,
4601 * which we decided on before the server acked
4602 * the channel open. So now we know the
4603 * remoteid, we can close it again.
4605 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE,
4606 PKT_INT, c->remoteid, PKT_END);
4610 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
4612 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4613 struct ssh_channel *c;
4615 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4616 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4617 logevent("Forwarded connection refused by server");
4618 pfd_close(c->u.pfd.s);
4619 del234(ssh->channels, c);
4624 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
4626 /* Remote side closes a channel. */
4627 unsigned i = ssh_pkt_getuint32(pktin);
4628 struct ssh_channel *c;
4629 c = find234(ssh->channels, &i, ssh_channelfind);
4630 if (c && !c->halfopen) {
4633 (pktin->type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
4635 if ((c->closes == 0) && (c->type == CHAN_X11)) {
4636 logevent("Forwarded X11 connection terminated");
4637 assert(c->u.x11.s != NULL);
4638 x11_close(c->u.x11.s);
4641 if ((c->closes == 0) && (c->type == CHAN_SOCKDATA)) {
4642 logevent("Forwarded port closed");
4643 assert(c->u.pfd.s != NULL);
4644 pfd_close(c->u.pfd.s);
4648 c->closes |= (closetype << 2); /* seen this message */
4649 if (!(c->closes & closetype)) {
4650 send_packet(ssh, pktin->type, PKT_INT, c->remoteid,
4652 c->closes |= closetype; /* sent it too */
4655 if (c->closes == 15) {
4656 del234(ssh->channels, c);
4660 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
4661 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
4662 "_CONFIRMATION", c ? "half-open" : "nonexistent",
4667 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
4669 /* Data sent down one of our channels. */
4670 int i = ssh_pkt_getuint32(pktin);
4673 struct ssh_channel *c;
4675 ssh_pkt_getstring(pktin, &p, &len);
4677 c = find234(ssh->channels, &i, ssh_channelfind);
4682 bufsize = x11_send(c->u.x11.s, p, len);
4685 bufsize = pfd_send(c->u.pfd.s, p, len);
4688 /* Data for an agent message. Buffer it. */
4690 if (c->u.a.lensofar < 4) {
4691 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)len);
4692 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
4696 c->u.a.lensofar += l;
4698 if (c->u.a.lensofar == 4) {
4700 4 + GET_32BIT(c->u.a.msglen);
4701 c->u.a.message = snewn(c->u.a.totallen,
4703 memcpy(c->u.a.message, c->u.a.msglen, 4);
4705 if (c->u.a.lensofar >= 4 && len > 0) {
4707 min(c->u.a.totallen - c->u.a.lensofar,
4709 memcpy(c->u.a.message + c->u.a.lensofar, p,
4713 c->u.a.lensofar += l;
4715 if (c->u.a.lensofar == c->u.a.totallen) {
4718 if (agent_query(c->u.a.message,
4721 ssh_agentf_callback, c))
4722 ssh_agentf_callback(c, reply, replylen);
4723 sfree(c->u.a.message);
4724 c->u.a.lensofar = 0;
4727 bufsize = 0; /* agent channels never back up */
4730 if (!c->v.v1.throttling && bufsize > SSH1_BUFFER_LIMIT) {
4731 c->v.v1.throttling = 1;
4732 ssh1_throttle(ssh, +1);
4737 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
4739 ssh->exitcode = ssh_pkt_getuint32(pktin);
4740 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
4741 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
4743 * In case `helpful' firewalls or proxies tack
4744 * extra human-readable text on the end of the
4745 * session which we might mistake for another
4746 * encrypted packet, we close the session once
4747 * we've sent EXIT_CONFIRMATION.
4749 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
4752 /* Helper function to deal with sending tty modes for REQUEST_PTY */
4753 static void ssh1_send_ttymode(void *data, char *mode, char *val)
4755 struct Packet *pktout = (struct Packet *)data;
4757 unsigned int arg = 0;
4758 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
4759 if (i == lenof(ssh_ttymodes)) return;
4760 switch (ssh_ttymodes[i].type) {
4762 arg = ssh_tty_parse_specchar(val);
4765 arg = ssh_tty_parse_boolean(val);
4768 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
4769 ssh2_pkt_addbyte(pktout, arg);
4773 static void do_ssh1_connection(Ssh ssh, unsigned char *in, int inlen,
4774 struct Packet *pktin)
4776 crBegin(ssh->do_ssh1_connection_crstate);
4778 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
4779 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
4780 ssh1_smsg_stdout_stderr_data;
4782 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
4783 ssh1_msg_channel_open_confirmation;
4784 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
4785 ssh1_msg_channel_open_failure;
4786 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
4787 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
4788 ssh1_msg_channel_close;
4789 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
4790 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
4792 if (ssh->cfg.agentfwd && agent_exists()) {
4793 logevent("Requesting agent forwarding");
4794 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
4798 if (pktin->type != SSH1_SMSG_SUCCESS
4799 && pktin->type != SSH1_SMSG_FAILURE) {
4800 bombout(("Protocol confusion"));
4802 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4803 logevent("Agent forwarding refused");
4805 logevent("Agent forwarding enabled");
4806 ssh->agentfwd_enabled = TRUE;
4807 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
4811 if (ssh->cfg.x11_forward) {
4812 char proto[20], data[64];
4813 logevent("Requesting X11 forwarding");
4814 ssh->x11auth = x11_invent_auth(proto, sizeof(proto),
4815 data, sizeof(data), ssh->cfg.x11_auth);
4816 x11_get_real_auth(ssh->x11auth, ssh->cfg.x11_display);
4818 * Note that while we blank the X authentication data here, we don't
4819 * take any special action to blank the start of an X11 channel,
4820 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
4821 * without having session blanking enabled is likely to leak your
4822 * cookie into the log.
4824 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
4825 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
4827 PKTT_PASSWORD, PKT_STR, data, PKTT_OTHER,
4828 PKT_INT, x11_get_screen_number(ssh->cfg.x11_display),
4831 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
4833 PKTT_PASSWORD, PKT_STR, data, PKTT_OTHER, PKT_END);
4838 if (pktin->type != SSH1_SMSG_SUCCESS
4839 && pktin->type != SSH1_SMSG_FAILURE) {
4840 bombout(("Protocol confusion"));
4842 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4843 logevent("X11 forwarding refused");
4845 logevent("X11 forwarding enabled");
4846 ssh->X11_fwd_enabled = TRUE;
4847 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
4851 ssh_setup_portfwd(ssh, &ssh->cfg);
4852 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
4854 if (!ssh->cfg.nopty) {
4856 /* Unpick the terminal-speed string. */
4857 /* XXX perhaps we should allow no speeds to be sent. */
4858 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
4859 sscanf(ssh->cfg.termspeed, "%d,%d", &ssh->ospeed, &ssh->ispeed);
4860 /* Send the pty request. */
4861 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
4862 ssh_pkt_addstring(pkt, ssh->cfg.termtype);
4863 ssh_pkt_adduint32(pkt, ssh->term_height);
4864 ssh_pkt_adduint32(pkt, ssh->term_width);
4865 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
4866 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
4867 parse_ttymodes(ssh, ssh->cfg.ttymodes,
4868 ssh1_send_ttymode, (void *)pkt);
4869 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
4870 ssh_pkt_adduint32(pkt, ssh->ispeed);
4871 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
4872 ssh_pkt_adduint32(pkt, ssh->ospeed);
4873 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
4875 ssh->state = SSH_STATE_INTERMED;
4879 if (pktin->type != SSH1_SMSG_SUCCESS
4880 && pktin->type != SSH1_SMSG_FAILURE) {
4881 bombout(("Protocol confusion"));
4883 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4884 c_write_str(ssh, "Server refused to allocate pty\r\n");
4885 ssh->editing = ssh->echoing = 1;
4887 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
4888 ssh->ospeed, ssh->ispeed);
4890 ssh->editing = ssh->echoing = 1;
4893 if (ssh->cfg.compression) {
4894 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
4898 if (pktin->type != SSH1_SMSG_SUCCESS
4899 && pktin->type != SSH1_SMSG_FAILURE) {
4900 bombout(("Protocol confusion"));
4902 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4903 c_write_str(ssh, "Server refused to compress\r\n");
4905 logevent("Started compression");
4906 ssh->v1_compressing = TRUE;
4907 ssh->cs_comp_ctx = zlib_compress_init();
4908 logevent("Initialised zlib (RFC1950) compression");
4909 ssh->sc_comp_ctx = zlib_decompress_init();
4910 logevent("Initialised zlib (RFC1950) decompression");
4914 * Start the shell or command.
4916 * Special case: if the first-choice command is an SSH-2
4917 * subsystem (hence not usable here) and the second choice
4918 * exists, we fall straight back to that.
4921 char *cmd = ssh->cfg.remote_cmd_ptr;
4923 if (!cmd) cmd = ssh->cfg.remote_cmd;
4925 if (ssh->cfg.ssh_subsys && ssh->cfg.remote_cmd_ptr2) {
4926 cmd = ssh->cfg.remote_cmd_ptr2;
4927 ssh->fallback_cmd = TRUE;
4930 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
4932 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
4933 logevent("Started session");
4936 ssh->state = SSH_STATE_SESSION;
4937 if (ssh->size_needed)
4938 ssh_size(ssh, ssh->term_width, ssh->term_height);
4939 if (ssh->eof_needed)
4940 ssh_special(ssh, TS_EOF);
4943 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
4945 ssh->channels = newtree234(ssh_channelcmp);
4949 * By this point, most incoming packets are already being
4950 * handled by the dispatch table, and we need only pay
4951 * attention to the unusual ones.
4956 if (pktin->type == SSH1_SMSG_SUCCESS) {
4957 /* may be from EXEC_SHELL on some servers */
4958 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4959 /* may be from EXEC_SHELL on some servers
4960 * if no pty is available or in other odd cases. Ignore */
4962 bombout(("Strange packet received: type %d", pktin->type));
4967 int len = min(inlen, 512);
4968 send_packet(ssh, SSH1_CMSG_STDIN_DATA, PKTT_DATA,
4969 PKT_INT, len, PKT_DATA, in, len,
4970 PKTT_OTHER, PKT_END);
4981 * Handle the top-level SSH-2 protocol.
4983 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
4988 ssh_pkt_getstring(pktin, &msg, &msglen);
4989 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
4992 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
4994 /* log reason code in disconnect message */
4998 ssh_pkt_getstring(pktin, &msg, &msglen);
4999 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
5002 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
5004 /* Do nothing, because we're ignoring it! Duhh. */
5007 static void ssh1_protocol_setup(Ssh ssh)
5012 * Most messages are handled by the coroutines.
5014 for (i = 0; i < 256; i++)
5015 ssh->packet_dispatch[i] = NULL;
5018 * These special message types we install handlers for.
5020 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
5021 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
5022 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
5025 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
5026 struct Packet *pktin)
5028 unsigned char *in=(unsigned char*)vin;
5029 if (ssh->state == SSH_STATE_CLOSED)
5032 if (pktin && ssh->packet_dispatch[pktin->type]) {
5033 ssh->packet_dispatch[pktin->type](ssh, pktin);
5037 if (!ssh->protocol_initial_phase_done) {
5038 if (do_ssh1_login(ssh, in, inlen, pktin))
5039 ssh->protocol_initial_phase_done = TRUE;
5044 do_ssh1_connection(ssh, in, inlen, pktin);
5048 * Utility routine for decoding comma-separated strings in KEXINIT.
5050 static int in_commasep_string(char *needle, char *haystack, int haylen)
5053 if (!needle || !haystack) /* protect against null pointers */
5055 needlen = strlen(needle);
5058 * Is it at the start of the string?
5060 if (haylen >= needlen && /* haystack is long enough */
5061 !memcmp(needle, haystack, needlen) && /* initial match */
5062 (haylen == needlen || haystack[needlen] == ',')
5063 /* either , or EOS follows */
5067 * If not, search for the next comma and resume after that.
5068 * If no comma found, terminate.
5070 while (haylen > 0 && *haystack != ',')
5071 haylen--, haystack++;
5074 haylen--, haystack++; /* skip over comma itself */
5079 * Similar routine for checking whether we have the first string in a list.
5081 static int first_in_commasep_string(char *needle, char *haystack, int haylen)
5084 if (!needle || !haystack) /* protect against null pointers */
5086 needlen = strlen(needle);
5088 * Is it at the start of the string?
5090 if (haylen >= needlen && /* haystack is long enough */
5091 !memcmp(needle, haystack, needlen) && /* initial match */
5092 (haylen == needlen || haystack[needlen] == ',')
5093 /* either , or EOS follows */
5101 * SSH-2 key creation method.
5102 * (Currently assumes 2 lots of any hash are sufficient to generate
5103 * keys/IVs for any cipher/MAC. SSH2_MKKEY_ITERS documents this assumption.)
5105 #define SSH2_MKKEY_ITERS (2)
5106 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H, char chr,
5107 unsigned char *keyspace)
5109 const struct ssh_hash *h = ssh->kex->hash;
5111 /* First hlen bytes. */
5113 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5114 hash_mpint(h, s, K);
5115 h->bytes(s, H, h->hlen);
5116 h->bytes(s, &chr, 1);
5117 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
5118 h->final(s, keyspace);
5119 /* Next hlen bytes. */
5121 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5122 hash_mpint(h, s, K);
5123 h->bytes(s, H, h->hlen);
5124 h->bytes(s, keyspace, h->hlen);
5125 h->final(s, keyspace + h->hlen);
5129 * Handle the SSH-2 transport layer.
5131 static int do_ssh2_transport(Ssh ssh, void *vin, int inlen,
5132 struct Packet *pktin)
5134 unsigned char *in = (unsigned char *)vin;
5135 struct do_ssh2_transport_state {
5136 int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
5137 Bignum p, g, e, f, K;
5140 int kex_init_value, kex_reply_value;
5141 const struct ssh_mac **maclist;
5143 const struct ssh2_cipher *cscipher_tobe;
5144 const struct ssh2_cipher *sccipher_tobe;
5145 const struct ssh_mac *csmac_tobe;
5146 const struct ssh_mac *scmac_tobe;
5147 const struct ssh_compress *cscomp_tobe;
5148 const struct ssh_compress *sccomp_tobe;
5149 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
5150 int hostkeylen, siglen, rsakeylen;
5151 void *hkey; /* actual host key */
5152 void *rsakey; /* for RSA kex */
5153 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
5154 int n_preferred_kex;
5155 const struct ssh_kexes *preferred_kex[KEX_MAX];
5156 int n_preferred_ciphers;
5157 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
5158 const struct ssh_compress *preferred_comp;
5159 int got_session_id, activated_authconn;
5160 struct Packet *pktout;
5165 crState(do_ssh2_transport_state);
5167 crBegin(ssh->do_ssh2_transport_crstate);
5169 s->cscipher_tobe = s->sccipher_tobe = NULL;
5170 s->csmac_tobe = s->scmac_tobe = NULL;
5171 s->cscomp_tobe = s->sccomp_tobe = NULL;
5173 s->got_session_id = s->activated_authconn = FALSE;
5176 * Be prepared to work around the buggy MAC problem.
5178 if (ssh->remote_bugs & BUG_SSH2_HMAC)
5179 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
5181 s->maclist = macs, s->nmacs = lenof(macs);
5184 ssh->pkt_ctx &= ~SSH2_PKTCTX_KEX_MASK;
5186 int i, j, commalist_started;
5189 * Set up the preferred key exchange. (NULL => warn below here)
5191 s->n_preferred_kex = 0;
5192 for (i = 0; i < KEX_MAX; i++) {
5193 switch (ssh->cfg.ssh_kexlist[i]) {
5195 s->preferred_kex[s->n_preferred_kex++] =
5196 &ssh_diffiehellman_gex;
5199 s->preferred_kex[s->n_preferred_kex++] =
5200 &ssh_diffiehellman_group14;
5203 s->preferred_kex[s->n_preferred_kex++] =
5204 &ssh_diffiehellman_group1;
5207 s->preferred_kex[s->n_preferred_kex++] =
5211 /* Flag for later. Don't bother if it's the last in
5213 if (i < KEX_MAX - 1) {
5214 s->preferred_kex[s->n_preferred_kex++] = NULL;
5221 * Set up the preferred ciphers. (NULL => warn below here)
5223 s->n_preferred_ciphers = 0;
5224 for (i = 0; i < CIPHER_MAX; i++) {
5225 switch (ssh->cfg.ssh_cipherlist[i]) {
5226 case CIPHER_BLOWFISH:
5227 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
5230 if (ssh->cfg.ssh2_des_cbc) {
5231 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
5235 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
5238 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
5240 case CIPHER_ARCFOUR:
5241 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
5244 /* Flag for later. Don't bother if it's the last in
5246 if (i < CIPHER_MAX - 1) {
5247 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
5254 * Set up preferred compression.
5256 if (ssh->cfg.compression)
5257 s->preferred_comp = &ssh_zlib;
5259 s->preferred_comp = &ssh_comp_none;
5262 * Enable queueing of outgoing auth- or connection-layer
5263 * packets while we are in the middle of a key exchange.
5265 ssh->queueing = TRUE;
5268 * Flag that KEX is in progress.
5270 ssh->kex_in_progress = TRUE;
5273 * Construct and send our key exchange packet.
5275 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
5276 for (i = 0; i < 16; i++)
5277 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
5278 /* List key exchange algorithms. */
5279 ssh2_pkt_addstring_start(s->pktout);
5280 commalist_started = 0;
5281 for (i = 0; i < s->n_preferred_kex; i++) {
5282 const struct ssh_kexes *k = s->preferred_kex[i];
5283 if (!k) continue; /* warning flag */
5284 for (j = 0; j < k->nkexes; j++) {
5285 if (commalist_started)
5286 ssh2_pkt_addstring_str(s->pktout, ",");
5287 ssh2_pkt_addstring_str(s->pktout, k->list[j]->name);
5288 commalist_started = 1;
5291 /* List server host key algorithms. */
5292 ssh2_pkt_addstring_start(s->pktout);
5293 for (i = 0; i < lenof(hostkey_algs); i++) {
5294 ssh2_pkt_addstring_str(s->pktout, hostkey_algs[i]->name);
5295 if (i < lenof(hostkey_algs) - 1)
5296 ssh2_pkt_addstring_str(s->pktout, ",");
5298 /* List client->server encryption algorithms. */
5299 ssh2_pkt_addstring_start(s->pktout);
5300 commalist_started = 0;
5301 for (i = 0; i < s->n_preferred_ciphers; i++) {
5302 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5303 if (!c) continue; /* warning flag */
5304 for (j = 0; j < c->nciphers; j++) {
5305 if (commalist_started)
5306 ssh2_pkt_addstring_str(s->pktout, ",");
5307 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
5308 commalist_started = 1;
5311 /* List server->client encryption algorithms. */
5312 ssh2_pkt_addstring_start(s->pktout);
5313 commalist_started = 0;
5314 for (i = 0; i < s->n_preferred_ciphers; i++) {
5315 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5316 if (!c) continue; /* warning flag */
5317 for (j = 0; j < c->nciphers; j++) {
5318 if (commalist_started)
5319 ssh2_pkt_addstring_str(s->pktout, ",");
5320 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
5321 commalist_started = 1;
5324 /* List client->server MAC algorithms. */
5325 ssh2_pkt_addstring_start(s->pktout);
5326 for (i = 0; i < s->nmacs; i++) {
5327 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5328 if (i < s->nmacs - 1)
5329 ssh2_pkt_addstring_str(s->pktout, ",");
5331 /* List server->client MAC algorithms. */
5332 ssh2_pkt_addstring_start(s->pktout);
5333 for (i = 0; i < s->nmacs; i++) {
5334 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5335 if (i < s->nmacs - 1)
5336 ssh2_pkt_addstring_str(s->pktout, ",");
5338 /* List client->server compression algorithms. */
5339 ssh2_pkt_addstring_start(s->pktout);
5340 assert(lenof(compressions) > 1);
5341 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
5342 for (i = 0; i < lenof(compressions); i++) {
5343 const struct ssh_compress *c = compressions[i];
5344 if (c != s->preferred_comp) {
5345 ssh2_pkt_addstring_str(s->pktout, ",");
5346 ssh2_pkt_addstring_str(s->pktout, c->name);
5349 /* List server->client compression algorithms. */
5350 ssh2_pkt_addstring_start(s->pktout);
5351 assert(lenof(compressions) > 1);
5352 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
5353 for (i = 0; i < lenof(compressions); i++) {
5354 const struct ssh_compress *c = compressions[i];
5355 if (c != s->preferred_comp) {
5356 ssh2_pkt_addstring_str(s->pktout, ",");
5357 ssh2_pkt_addstring_str(s->pktout, c->name);
5360 /* List client->server languages. Empty list. */
5361 ssh2_pkt_addstring_start(s->pktout);
5362 /* List server->client languages. Empty list. */
5363 ssh2_pkt_addstring_start(s->pktout);
5364 /* First KEX packet does _not_ follow, because we're not that brave. */
5365 ssh2_pkt_addbool(s->pktout, FALSE);
5367 ssh2_pkt_adduint32(s->pktout, 0);
5370 s->our_kexinitlen = s->pktout->length - 5;
5371 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
5372 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
5374 ssh2_pkt_send_noqueue(ssh, s->pktout);
5380 * Now examine the other side's KEXINIT to see what we're up
5384 char *str, *preferred;
5387 if (pktin->type != SSH2_MSG_KEXINIT) {
5388 bombout(("expected key exchange packet from server"));
5392 ssh->hostkey = NULL;
5393 s->cscipher_tobe = NULL;
5394 s->sccipher_tobe = NULL;
5395 s->csmac_tobe = NULL;
5396 s->scmac_tobe = NULL;
5397 s->cscomp_tobe = NULL;
5398 s->sccomp_tobe = NULL;
5399 s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
5401 pktin->savedpos += 16; /* skip garbage cookie */
5402 ssh_pkt_getstring(pktin, &str, &len); /* key exchange algorithms */
5405 for (i = 0; i < s->n_preferred_kex; i++) {
5406 const struct ssh_kexes *k = s->preferred_kex[i];
5410 for (j = 0; j < k->nkexes; j++) {
5411 if (!preferred) preferred = k->list[j]->name;
5412 if (in_commasep_string(k->list[j]->name, str, len)) {
5413 ssh->kex = k->list[j];
5422 bombout(("Couldn't agree a key exchange algorithm (available: %s)",
5423 str ? str : "(null)"));
5427 * Note that the server's guess is considered wrong if it doesn't match
5428 * the first algorithm in our list, even if it's still the algorithm
5431 s->guessok = first_in_commasep_string(preferred, str, len);
5432 ssh_pkt_getstring(pktin, &str, &len); /* host key algorithms */
5433 for (i = 0; i < lenof(hostkey_algs); i++) {
5434 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
5435 ssh->hostkey = hostkey_algs[i];
5439 s->guessok = s->guessok &&
5440 first_in_commasep_string(hostkey_algs[0]->name, str, len);
5441 ssh_pkt_getstring(pktin, &str, &len); /* client->server cipher */
5442 for (i = 0; i < s->n_preferred_ciphers; i++) {
5443 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5445 s->warn_cscipher = TRUE;
5447 for (j = 0; j < c->nciphers; j++) {
5448 if (in_commasep_string(c->list[j]->name, str, len)) {
5449 s->cscipher_tobe = c->list[j];
5454 if (s->cscipher_tobe)
5457 if (!s->cscipher_tobe) {
5458 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
5459 str ? str : "(null)"));
5463 ssh_pkt_getstring(pktin, &str, &len); /* server->client cipher */
5464 for (i = 0; i < s->n_preferred_ciphers; i++) {
5465 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5467 s->warn_sccipher = TRUE;
5469 for (j = 0; j < c->nciphers; j++) {
5470 if (in_commasep_string(c->list[j]->name, str, len)) {
5471 s->sccipher_tobe = c->list[j];
5476 if (s->sccipher_tobe)
5479 if (!s->sccipher_tobe) {
5480 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
5481 str ? str : "(null)"));
5485 ssh_pkt_getstring(pktin, &str, &len); /* client->server mac */
5486 for (i = 0; i < s->nmacs; i++) {
5487 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5488 s->csmac_tobe = s->maclist[i];
5492 ssh_pkt_getstring(pktin, &str, &len); /* server->client mac */
5493 for (i = 0; i < s->nmacs; i++) {
5494 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5495 s->scmac_tobe = s->maclist[i];
5499 ssh_pkt_getstring(pktin, &str, &len); /* client->server compression */
5500 for (i = 0; i < lenof(compressions) + 1; i++) {
5501 const struct ssh_compress *c =
5502 i == 0 ? s->preferred_comp : compressions[i - 1];
5503 if (in_commasep_string(c->name, str, len)) {
5508 ssh_pkt_getstring(pktin, &str, &len); /* server->client compression */
5509 for (i = 0; i < lenof(compressions) + 1; i++) {
5510 const struct ssh_compress *c =
5511 i == 0 ? s->preferred_comp : compressions[i - 1];
5512 if (in_commasep_string(c->name, str, len)) {
5517 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
5518 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
5519 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
5522 ssh_set_frozen(ssh, 1);
5523 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
5525 ssh_dialog_callback, ssh);
5526 if (s->dlgret < 0) {
5530 bombout(("Unexpected data from server while"
5531 " waiting for user response"));
5534 } while (pktin || inlen > 0);
5535 s->dlgret = ssh->user_response;
5537 ssh_set_frozen(ssh, 0);
5538 if (s->dlgret == 0) {
5539 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
5545 if (s->warn_cscipher) {
5546 ssh_set_frozen(ssh, 1);
5547 s->dlgret = askalg(ssh->frontend,
5548 "client-to-server cipher",
5549 s->cscipher_tobe->name,
5550 ssh_dialog_callback, ssh);
5551 if (s->dlgret < 0) {
5555 bombout(("Unexpected data from server while"
5556 " waiting for user response"));
5559 } while (pktin || inlen > 0);
5560 s->dlgret = ssh->user_response;
5562 ssh_set_frozen(ssh, 0);
5563 if (s->dlgret == 0) {
5564 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
5570 if (s->warn_sccipher) {
5571 ssh_set_frozen(ssh, 1);
5572 s->dlgret = askalg(ssh->frontend,
5573 "server-to-client cipher",
5574 s->sccipher_tobe->name,
5575 ssh_dialog_callback, ssh);
5576 if (s->dlgret < 0) {
5580 bombout(("Unexpected data from server while"
5581 " waiting for user response"));
5584 } while (pktin || inlen > 0);
5585 s->dlgret = ssh->user_response;
5587 ssh_set_frozen(ssh, 0);
5588 if (s->dlgret == 0) {
5589 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
5595 ssh->exhash = ssh->kex->hash->init();
5596 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
5597 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
5598 hash_string(ssh->kex->hash, ssh->exhash,
5599 s->our_kexinit, s->our_kexinitlen);
5600 sfree(s->our_kexinit);
5601 if (pktin->length > 5)
5602 hash_string(ssh->kex->hash, ssh->exhash,
5603 pktin->data + 5, pktin->length - 5);
5605 if (s->ignorepkt) /* first_kex_packet_follows */
5606 crWaitUntil(pktin); /* Ignore packet */
5609 if (ssh->kex->main_type == KEXTYPE_DH) {
5611 * Work out the number of bits of key we will need from the
5612 * key exchange. We start with the maximum key length of
5618 csbits = s->cscipher_tobe->keylen;
5619 scbits = s->sccipher_tobe->keylen;
5620 s->nbits = (csbits > scbits ? csbits : scbits);
5622 /* The keys only have hlen-bit entropy, since they're based on
5623 * a hash. So cap the key size at hlen bits. */
5624 if (s->nbits > ssh->kex->hash->hlen * 8)
5625 s->nbits = ssh->kex->hash->hlen * 8;
5628 * If we're doing Diffie-Hellman group exchange, start by
5629 * requesting a group.
5631 if (!ssh->kex->pdata) {
5632 logevent("Doing Diffie-Hellman group exchange");
5633 ssh->pkt_ctx |= SSH2_PKTCTX_DHGEX;
5635 * Work out how big a DH group we will need to allow that
5638 s->pbits = 512 << ((s->nbits - 1) / 64);
5639 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
5640 ssh2_pkt_adduint32(s->pktout, s->pbits);
5641 ssh2_pkt_send_noqueue(ssh, s->pktout);
5644 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
5645 bombout(("expected key exchange group packet from server"));
5648 s->p = ssh2_pkt_getmp(pktin);
5649 s->g = ssh2_pkt_getmp(pktin);
5650 if (!s->p || !s->g) {
5651 bombout(("unable to read mp-ints from incoming group packet"));
5654 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
5655 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
5656 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
5658 ssh->pkt_ctx |= SSH2_PKTCTX_DHGROUP;
5659 ssh->kex_ctx = dh_setup_group(ssh->kex);
5660 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
5661 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
5662 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
5663 ssh->kex->groupname);
5666 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
5667 ssh->kex->hash->text_name);
5669 * Now generate and send e for Diffie-Hellman.
5671 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
5672 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
5673 s->pktout = ssh2_pkt_init(s->kex_init_value);
5674 ssh2_pkt_addmp(s->pktout, s->e);
5675 ssh2_pkt_send_noqueue(ssh, s->pktout);
5677 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
5679 if (pktin->type != s->kex_reply_value) {
5680 bombout(("expected key exchange reply packet from server"));
5683 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
5684 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
5685 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
5686 s->f = ssh2_pkt_getmp(pktin);
5688 bombout(("unable to parse key exchange reply packet"));
5691 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
5693 s->K = dh_find_K(ssh->kex_ctx, s->f);
5695 /* We assume everything from now on will be quick, and it might
5696 * involve user interaction. */
5697 set_busy_status(ssh->frontend, BUSY_NOT);
5699 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
5700 if (!ssh->kex->pdata) {
5701 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
5702 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
5703 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
5705 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
5706 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
5708 dh_cleanup(ssh->kex_ctx);
5710 if (!ssh->kex->pdata) {
5715 logeventf(ssh, "Doing RSA key exchange with hash %s",
5716 ssh->kex->hash->text_name);
5717 ssh->pkt_ctx |= SSH2_PKTCTX_RSAKEX;
5719 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
5723 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
5724 bombout(("expected RSA public key packet from server"));
5728 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
5729 hash_string(ssh->kex->hash, ssh->exhash,
5730 s->hostkeydata, s->hostkeylen);
5731 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
5735 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
5736 s->rsakeydata = snewn(s->rsakeylen, char);
5737 memcpy(s->rsakeydata, keydata, s->rsakeylen);
5740 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
5742 sfree(s->rsakeydata);
5743 bombout(("unable to parse RSA public key from server"));
5747 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
5750 * Next, set up a shared secret K, of precisely KLEN -
5751 * 2*HLEN - 49 bits, where KLEN is the bit length of the
5752 * RSA key modulus and HLEN is the bit length of the hash
5756 int klen = ssh_rsakex_klen(s->rsakey);
5757 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
5759 unsigned char *kstr1, *kstr2, *outstr;
5760 int kstr1len, kstr2len, outstrlen;
5762 s->K = bn_power_2(nbits - 1);
5764 for (i = 0; i < nbits; i++) {
5766 byte = random_byte();
5768 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
5772 * Encode this as an mpint.
5774 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
5775 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
5776 PUT_32BIT(kstr2, kstr1len);
5777 memcpy(kstr2 + 4, kstr1, kstr1len);
5780 * Encrypt it with the given RSA key.
5782 outstrlen = (klen + 7) / 8;
5783 outstr = snewn(outstrlen, unsigned char);
5784 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
5785 outstr, outstrlen, s->rsakey);
5788 * And send it off in a return packet.
5790 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
5791 ssh2_pkt_addstring_start(s->pktout);
5792 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
5793 ssh2_pkt_send_noqueue(ssh, s->pktout);
5795 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
5802 ssh_rsakex_freekey(s->rsakey);
5805 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
5806 sfree(s->rsakeydata);
5807 bombout(("expected signature packet from server"));
5811 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
5813 sfree(s->rsakeydata);
5816 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
5817 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
5818 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
5820 ssh->kex_ctx = NULL;
5823 debug(("Exchange hash is:\n"));
5824 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
5828 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
5829 (char *)s->exchange_hash,
5830 ssh->kex->hash->hlen)) {
5831 bombout(("Server's host key did not match the signature supplied"));
5836 * Authenticate remote host: verify host key. (We've already
5837 * checked the signature of the exchange hash.)
5839 s->keystr = ssh->hostkey->fmtkey(s->hkey);
5840 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
5841 ssh_set_frozen(ssh, 1);
5842 s->dlgret = verify_ssh_host_key(ssh->frontend,
5843 ssh->savedhost, ssh->savedport,
5844 ssh->hostkey->keytype, s->keystr,
5846 ssh_dialog_callback, ssh);
5847 if (s->dlgret < 0) {
5851 bombout(("Unexpected data from server while waiting"
5852 " for user host key response"));
5855 } while (pktin || inlen > 0);
5856 s->dlgret = ssh->user_response;
5858 ssh_set_frozen(ssh, 0);
5859 if (s->dlgret == 0) {
5860 ssh_disconnect(ssh, "User aborted at host key verification", NULL,
5864 if (!s->got_session_id) { /* don't bother logging this in rekeys */
5865 logevent("Host key fingerprint is:");
5866 logevent(s->fingerprint);
5868 sfree(s->fingerprint);
5870 ssh->hostkey->freekey(s->hkey);
5873 * The exchange hash from the very first key exchange is also
5874 * the session id, used in session key construction and
5877 if (!s->got_session_id) {
5878 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
5879 memcpy(ssh->v2_session_id, s->exchange_hash,
5880 sizeof(s->exchange_hash));
5881 ssh->v2_session_id_len = ssh->kex->hash->hlen;
5882 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
5883 s->got_session_id = TRUE;
5887 * Send SSH2_MSG_NEWKEYS.
5889 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
5890 ssh2_pkt_send_noqueue(ssh, s->pktout);
5891 ssh->outgoing_data_size = 0; /* start counting from here */
5894 * We've sent client NEWKEYS, so create and initialise
5895 * client-to-server session keys.
5897 if (ssh->cs_cipher_ctx)
5898 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
5899 ssh->cscipher = s->cscipher_tobe;
5900 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
5902 if (ssh->cs_mac_ctx)
5903 ssh->csmac->free_context(ssh->cs_mac_ctx);
5904 ssh->csmac = s->csmac_tobe;
5905 ssh->cs_mac_ctx = ssh->csmac->make_context();
5907 if (ssh->cs_comp_ctx)
5908 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
5909 ssh->cscomp = s->cscomp_tobe;
5910 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
5913 * Set IVs on client-to-server keys. Here we use the exchange
5914 * hash from the _first_ key exchange.
5917 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
5918 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
5919 ssh2_mkkey(ssh,s->K,s->exchange_hash,'C',keyspace);
5920 assert((ssh->cscipher->keylen+7) / 8 <=
5921 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
5922 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
5923 ssh2_mkkey(ssh,s->K,s->exchange_hash,'A',keyspace);
5924 assert(ssh->cscipher->blksize <=
5925 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
5926 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
5927 ssh2_mkkey(ssh,s->K,s->exchange_hash,'E',keyspace);
5928 assert(ssh->csmac->len <=
5929 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
5930 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
5931 memset(keyspace, 0, sizeof(keyspace));
5934 logeventf(ssh, "Initialised %.200s client->server encryption",
5935 ssh->cscipher->text_name);
5936 logeventf(ssh, "Initialised %.200s client->server MAC algorithm",
5937 ssh->csmac->text_name);
5938 if (ssh->cscomp->text_name)
5939 logeventf(ssh, "Initialised %s compression",
5940 ssh->cscomp->text_name);
5943 * Now our end of the key exchange is complete, we can send all
5944 * our queued higher-layer packets.
5946 ssh->queueing = FALSE;
5947 ssh2_pkt_queuesend(ssh);
5950 * Expect SSH2_MSG_NEWKEYS from server.
5953 if (pktin->type != SSH2_MSG_NEWKEYS) {
5954 bombout(("expected new-keys packet from server"));
5957 ssh->incoming_data_size = 0; /* start counting from here */
5960 * We've seen server NEWKEYS, so create and initialise
5961 * server-to-client session keys.
5963 if (ssh->sc_cipher_ctx)
5964 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
5965 ssh->sccipher = s->sccipher_tobe;
5966 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
5968 if (ssh->sc_mac_ctx)
5969 ssh->scmac->free_context(ssh->sc_mac_ctx);
5970 ssh->scmac = s->scmac_tobe;
5971 ssh->sc_mac_ctx = ssh->scmac->make_context();
5973 if (ssh->sc_comp_ctx)
5974 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
5975 ssh->sccomp = s->sccomp_tobe;
5976 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
5979 * Set IVs on server-to-client keys. Here we use the exchange
5980 * hash from the _first_ key exchange.
5983 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
5984 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
5985 ssh2_mkkey(ssh,s->K,s->exchange_hash,'D',keyspace);
5986 assert((ssh->sccipher->keylen+7) / 8 <=
5987 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
5988 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
5989 ssh2_mkkey(ssh,s->K,s->exchange_hash,'B',keyspace);
5990 assert(ssh->sccipher->blksize <=
5991 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
5992 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
5993 ssh2_mkkey(ssh,s->K,s->exchange_hash,'F',keyspace);
5994 assert(ssh->scmac->len <=
5995 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
5996 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
5997 memset(keyspace, 0, sizeof(keyspace));
5999 logeventf(ssh, "Initialised %.200s server->client encryption",
6000 ssh->sccipher->text_name);
6001 logeventf(ssh, "Initialised %.200s server->client MAC algorithm",
6002 ssh->scmac->text_name);
6003 if (ssh->sccomp->text_name)
6004 logeventf(ssh, "Initialised %s decompression",
6005 ssh->sccomp->text_name);
6008 * Free shared secret.
6013 * Key exchange is over. Loop straight back round if we have a
6014 * deferred rekey reason.
6016 if (ssh->deferred_rekey_reason) {
6017 logevent(ssh->deferred_rekey_reason);
6019 ssh->deferred_rekey_reason = NULL;
6020 goto begin_key_exchange;
6024 * Otherwise, schedule a timer for our next rekey.
6026 ssh->kex_in_progress = FALSE;
6027 ssh->last_rekey = GETTICKCOUNT();
6028 if (ssh->cfg.ssh_rekey_time != 0)
6029 ssh->next_rekey = schedule_timer(ssh->cfg.ssh_rekey_time*60*TICKSPERSEC,
6033 * If this is the first key exchange phase, we must pass the
6034 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
6035 * wants to see it but because it will need time to initialise
6036 * itself before it sees an actual packet. In subsequent key
6037 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
6038 * it would only confuse the layer above.
6040 if (s->activated_authconn) {
6043 s->activated_authconn = TRUE;
6046 * Now we're encrypting. Begin returning 1 to the protocol main
6047 * function so that other things can run on top of the
6048 * transport. If we ever see a KEXINIT, we must go back to the
6051 * We _also_ go back to the start if we see pktin==NULL and
6052 * inlen==-1, because this is a special signal meaning
6053 * `initiate client-driven rekey', and `in' contains a message
6054 * giving the reason for the rekey.
6056 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
6057 (!pktin && inlen == -1))) {
6062 logevent("Server initiated key re-exchange");
6065 * Special case: if the server bug is set that doesn't
6066 * allow rekeying, we give a different log message and
6067 * continue waiting. (If such a server _initiates_ a rekey,
6068 * we process it anyway!)
6070 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
6071 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
6073 /* Reset the counters, so that at least this message doesn't
6074 * hit the event log _too_ often. */
6075 ssh->outgoing_data_size = 0;
6076 ssh->incoming_data_size = 0;
6077 if (ssh->cfg.ssh_rekey_time != 0) {
6079 schedule_timer(ssh->cfg.ssh_rekey_time*60*TICKSPERSEC,
6082 goto wait_for_rekey; /* this is utterly horrid */
6084 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
6087 goto begin_key_exchange;
6093 * Add data to an SSH-2 channel output buffer.
6095 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
6098 bufchain_add(&c->v.v2.outbuffer, buf, len);
6102 * Attempt to send data on an SSH-2 channel.
6104 static int ssh2_try_send(struct ssh_channel *c)
6107 struct Packet *pktout;
6109 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
6112 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
6113 if ((unsigned)len > c->v.v2.remwindow)
6114 len = c->v.v2.remwindow;
6115 if ((unsigned)len > c->v.v2.remmaxpkt)
6116 len = c->v.v2.remmaxpkt;
6117 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
6118 ssh2_pkt_adduint32(pktout, c->remoteid);
6119 dont_log_data(ssh, pktout, PKTLOG_OMIT);
6120 ssh2_pkt_addstring_start(pktout);
6121 ssh2_pkt_addstring_data(pktout, data, len);
6122 end_log_omission(ssh, pktout);
6123 ssh2_pkt_send(ssh, pktout);
6124 bufchain_consume(&c->v.v2.outbuffer, len);
6125 c->v.v2.remwindow -= len;
6129 * After having sent as much data as we can, return the amount
6132 return bufchain_size(&c->v.v2.outbuffer);
6135 static void ssh2_try_send_and_unthrottle(struct ssh_channel *c)
6139 return; /* don't send on closing channels */
6140 bufsize = ssh2_try_send(c);
6143 case CHAN_MAINSESSION:
6144 /* stdin need not receive an unthrottle
6145 * notification since it will be polled */
6148 x11_unthrottle(c->u.x11.s);
6151 /* agent sockets are request/response and need no
6152 * buffer management */
6155 pfd_unthrottle(c->u.pfd.s);
6162 * Potentially enlarge the window on an SSH-2 channel.
6164 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin)
6169 * Never send WINDOW_ADJUST for a channel that the remote side
6170 * already thinks it's closed; there's no point, since it won't
6171 * be sending any more data anyway.
6177 * Only send a WINDOW_ADJUST if there's significantly more window
6178 * available than the other end thinks there is. This saves us
6179 * sending a WINDOW_ADJUST for every character in a shell session.
6181 * "Significant" is arbitrarily defined as half the window size.
6183 if (newwin > c->v.v2.locwindow * 2) {
6184 struct Packet *pktout;
6186 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
6187 ssh2_pkt_adduint32(pktout, c->remoteid);
6188 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
6189 ssh2_pkt_send(ssh, pktout);
6190 c->v.v2.locwindow = newwin;
6194 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
6196 unsigned i = ssh_pkt_getuint32(pktin);
6197 struct ssh_channel *c;
6198 c = find234(ssh->channels, &i, ssh_channelfind);
6199 if (c && !c->closes) {
6200 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
6201 ssh2_try_send_and_unthrottle(c);
6205 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
6209 unsigned i = ssh_pkt_getuint32(pktin);
6210 struct ssh_channel *c;
6211 c = find234(ssh->channels, &i, ssh_channelfind);
6213 return; /* nonexistent channel */
6214 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
6215 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
6216 return; /* extended but not stderr */
6217 ssh_pkt_getstring(pktin, &data, &length);
6220 c->v.v2.locwindow -= length;
6222 case CHAN_MAINSESSION:
6224 from_backend(ssh->frontend, pktin->type ==
6225 SSH2_MSG_CHANNEL_EXTENDED_DATA,
6229 bufsize = x11_send(c->u.x11.s, data, length);
6232 bufsize = pfd_send(c->u.pfd.s, data, length);
6235 while (length > 0) {
6236 if (c->u.a.lensofar < 4) {
6237 unsigned int l = min(4 - c->u.a.lensofar,
6239 memcpy(c->u.a.msglen + c->u.a.lensofar,
6243 c->u.a.lensofar += l;
6245 if (c->u.a.lensofar == 4) {
6247 4 + GET_32BIT(c->u.a.msglen);
6248 c->u.a.message = snewn(c->u.a.totallen,
6250 memcpy(c->u.a.message, c->u.a.msglen, 4);
6252 if (c->u.a.lensofar >= 4 && length > 0) {
6254 min(c->u.a.totallen - c->u.a.lensofar,
6256 memcpy(c->u.a.message + c->u.a.lensofar,
6260 c->u.a.lensofar += l;
6262 if (c->u.a.lensofar == c->u.a.totallen) {
6265 if (agent_query(c->u.a.message,
6268 ssh_agentf_callback, c))
6269 ssh_agentf_callback(c, reply, replylen);
6270 sfree(c->u.a.message);
6271 c->u.a.lensofar = 0;
6278 * If we are not buffering too much data,
6279 * enlarge the window again at the remote side.
6281 if (bufsize < OUR_V2_WINSIZE)
6282 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
6286 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
6288 unsigned i = ssh_pkt_getuint32(pktin);
6289 struct ssh_channel *c;
6291 c = find234(ssh->channels, &i, ssh_channelfind);
6293 return; /* nonexistent channel */
6295 if (c->type == CHAN_X11) {
6297 * Remote EOF on an X11 channel means we should
6298 * wrap up and close the channel ourselves.
6300 x11_close(c->u.x11.s);
6302 } else if (c->type == CHAN_AGENT) {
6304 } else if (c->type == CHAN_SOCKDATA) {
6305 pfd_close(c->u.pfd.s);
6310 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
6312 unsigned i = ssh_pkt_getuint32(pktin);
6313 struct ssh_channel *c;
6314 struct Packet *pktout;
6316 c = find234(ssh->channels, &i, ssh_channelfind);
6317 if (!c || c->halfopen) {
6318 bombout(("Received CHANNEL_CLOSE for %s channel %d\n",
6319 c ? "half-open" : "nonexistent", i));
6322 /* Do pre-close processing on the channel. */
6324 case CHAN_MAINSESSION:
6325 ssh->mainchan = NULL;
6326 update_specials_menu(ssh->frontend);
6329 if (c->u.x11.s != NULL)
6330 x11_close(c->u.x11.s);
6337 if (c->u.pfd.s != NULL)
6338 pfd_close(c->u.pfd.s);
6342 if (c->closes == 0) {
6343 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
6344 ssh2_pkt_adduint32(pktout, c->remoteid);
6345 ssh2_pkt_send(ssh, pktout);
6347 del234(ssh->channels, c);
6348 bufchain_clear(&c->v.v2.outbuffer);
6352 * See if that was the last channel left open.
6353 * (This is only our termination condition if we're
6354 * not running in -N mode.)
6356 if (!ssh->cfg.ssh_no_shell && count234(ssh->channels) == 0) {
6358 * We used to send SSH_MSG_DISCONNECT here,
6359 * because I'd believed that _every_ conforming
6360 * SSH-2 connection had to end with a disconnect
6361 * being sent by at least one side; apparently
6362 * I was wrong and it's perfectly OK to
6363 * unceremoniously slam the connection shut
6364 * when you're done, and indeed OpenSSH feels
6365 * this is more polite than sending a
6366 * DISCONNECT. So now we don't.
6368 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
6372 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
6374 unsigned i = ssh_pkt_getuint32(pktin);
6375 struct ssh_channel *c;
6376 struct Packet *pktout;
6378 c = find234(ssh->channels, &i, ssh_channelfind);
6380 return; /* nonexistent channel */
6381 if (c->type != CHAN_SOCKDATA_DORMANT)
6382 return; /* dunno why they're confirming this */
6383 c->remoteid = ssh_pkt_getuint32(pktin);
6384 c->halfopen = FALSE;
6385 c->type = CHAN_SOCKDATA;
6386 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
6387 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
6389 pfd_confirm(c->u.pfd.s);
6392 * We have a pending close on this channel,
6393 * which we decided on before the server acked
6394 * the channel open. So now we know the
6395 * remoteid, we can close it again.
6397 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
6398 ssh2_pkt_adduint32(pktout, c->remoteid);
6399 ssh2_pkt_send(ssh, pktout);
6403 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
6405 static const char *const reasons[] = {
6406 "<unknown reason code>",
6407 "Administratively prohibited",
6409 "Unknown channel type",
6410 "Resource shortage",
6412 unsigned i = ssh_pkt_getuint32(pktin);
6413 unsigned reason_code;
6414 char *reason_string;
6416 struct ssh_channel *c;
6417 c = find234(ssh->channels, &i, ssh_channelfind);
6419 return; /* nonexistent channel */
6420 if (c->type != CHAN_SOCKDATA_DORMANT)
6421 return; /* dunno why they're failing this */
6423 reason_code = ssh_pkt_getuint32(pktin);
6424 if (reason_code >= lenof(reasons))
6425 reason_code = 0; /* ensure reasons[reason_code] in range */
6426 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
6427 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
6428 reasons[reason_code], reason_length, reason_string);
6430 pfd_close(c->u.pfd.s);
6432 del234(ssh->channels, c);
6436 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
6440 int typelen, want_reply;
6441 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
6442 struct ssh_channel *c;
6443 struct Packet *pktout;
6445 localid = ssh_pkt_getuint32(pktin);
6446 ssh_pkt_getstring(pktin, &type, &typelen);
6447 want_reply = ssh2_pkt_getbool(pktin);
6450 * First, check that the channel exists. Otherwise,
6451 * we can instantly disconnect with a rude message.
6453 c = find234(ssh->channels, &localid, ssh_channelfind);
6455 char *buf = dupprintf("Received channel request for nonexistent"
6456 " channel %d", localid);
6457 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6463 * Having got the channel number, we now look at
6464 * the request type string to see if it's something
6467 if (c == ssh->mainchan) {
6469 * We recognise "exit-status" and "exit-signal" on
6470 * the primary channel.
6472 if (typelen == 11 &&
6473 !memcmp(type, "exit-status", 11)) {
6475 ssh->exitcode = ssh_pkt_getuint32(pktin);
6476 logeventf(ssh, "Server sent command exit status %d",
6478 reply = SSH2_MSG_CHANNEL_SUCCESS;
6480 } else if (typelen == 11 &&
6481 !memcmp(type, "exit-signal", 11)) {
6483 int is_plausible = TRUE, is_int = FALSE;
6484 char *fmt_sig = "", *fmt_msg = "";
6486 int msglen = 0, core = FALSE;
6487 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
6488 * provide an `int' for the signal, despite its
6489 * having been a `string' in the drafts since at
6490 * least 2001. (Fixed in session.c 1.147.) Try to
6491 * infer which we can safely parse it as. */
6493 unsigned char *p = pktin->body +
6495 long len = pktin->length - pktin->savedpos;
6496 unsigned long num = GET_32BIT(p); /* what is it? */
6497 /* If it's 0, it hardly matters; assume string */
6501 int maybe_int = FALSE, maybe_str = FALSE;
6502 #define CHECK_HYPOTHESIS(offset, result) \
6505 if (q >= 0 && q+4 <= len) { \
6506 q = q + 4 + GET_32BIT(p+q); \
6507 if (q >= 0 && q+4 <= len && \
6508 ((q = q + 4 + GET_32BIT(p+q))!= 0) && q == len) \
6512 CHECK_HYPOTHESIS(4+1, maybe_int);
6513 CHECK_HYPOTHESIS(4+num+1, maybe_str);
6514 #undef CHECK_HYPOTHESIS
6515 if (maybe_int && !maybe_str)
6517 else if (!maybe_int && maybe_str)
6520 /* Crikey. Either or neither. Panic. */
6521 is_plausible = FALSE;
6524 ssh->exitcode = 128; /* means `unknown signal' */
6527 /* Old non-standard OpenSSH. */
6528 int signum = ssh_pkt_getuint32(pktin);
6529 fmt_sig = dupprintf(" %d", signum);
6530 ssh->exitcode = 128 + signum;
6532 /* As per the drafts. */
6535 ssh_pkt_getstring(pktin, &sig, &siglen);
6536 /* Signal name isn't supposed to be blank, but
6537 * let's cope gracefully if it is. */
6539 fmt_sig = dupprintf(" \"%.*s\"",
6544 * Really hideous method of translating the
6545 * signal description back into a locally
6546 * meaningful number.
6551 #define TRANSLATE_SIGNAL(s) \
6552 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
6553 ssh->exitcode = 128 + SIG ## s
6555 TRANSLATE_SIGNAL(ABRT);
6558 TRANSLATE_SIGNAL(ALRM);
6561 TRANSLATE_SIGNAL(FPE);
6564 TRANSLATE_SIGNAL(HUP);
6567 TRANSLATE_SIGNAL(ILL);
6570 TRANSLATE_SIGNAL(INT);
6573 TRANSLATE_SIGNAL(KILL);
6576 TRANSLATE_SIGNAL(PIPE);
6579 TRANSLATE_SIGNAL(QUIT);
6582 TRANSLATE_SIGNAL(SEGV);
6585 TRANSLATE_SIGNAL(TERM);
6588 TRANSLATE_SIGNAL(USR1);
6591 TRANSLATE_SIGNAL(USR2);
6593 #undef TRANSLATE_SIGNAL
6595 ssh->exitcode = 128;
6597 core = ssh2_pkt_getbool(pktin);
6598 ssh_pkt_getstring(pktin, &msg, &msglen);
6600 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
6602 /* ignore lang tag */
6603 } /* else don't attempt to parse */
6604 logeventf(ssh, "Server exited on signal%s%s%s",
6605 fmt_sig, core ? " (core dumped)" : "",
6607 if (*fmt_sig) sfree(fmt_sig);
6608 if (*fmt_msg) sfree(fmt_msg);
6609 reply = SSH2_MSG_CHANNEL_SUCCESS;
6614 * This is a channel request we don't know
6615 * about, so we now either ignore the request
6616 * or respond with CHANNEL_FAILURE, depending
6619 reply = SSH2_MSG_CHANNEL_FAILURE;
6622 pktout = ssh2_pkt_init(reply);
6623 ssh2_pkt_adduint32(pktout, c->remoteid);
6624 ssh2_pkt_send(ssh, pktout);
6628 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
6631 int typelen, want_reply;
6632 struct Packet *pktout;
6634 ssh_pkt_getstring(pktin, &type, &typelen);
6635 want_reply = ssh2_pkt_getbool(pktin);
6638 * We currently don't support any global requests
6639 * at all, so we either ignore the request or
6640 * respond with REQUEST_FAILURE, depending on
6644 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
6645 ssh2_pkt_send(ssh, pktout);
6649 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
6657 struct ssh_channel *c;
6658 unsigned remid, winsize, pktsize;
6659 struct Packet *pktout;
6661 ssh_pkt_getstring(pktin, &type, &typelen);
6662 c = snew(struct ssh_channel);
6665 remid = ssh_pkt_getuint32(pktin);
6666 winsize = ssh_pkt_getuint32(pktin);
6667 pktsize = ssh_pkt_getuint32(pktin);
6669 if (typelen == 3 && !memcmp(type, "x11", 3)) {
6672 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
6673 addrstr = snewn(peeraddrlen+1, char);
6674 memcpy(addrstr, peeraddr, peeraddrlen);
6675 addrstr[peeraddrlen] = '\0';
6676 peerport = ssh_pkt_getuint32(pktin);
6678 logeventf(ssh, "Received X11 connect request from %s:%d",
6681 if (!ssh->X11_fwd_enabled)
6682 error = "X11 forwarding is not enabled";
6683 else if (x11_init(&c->u.x11.s, ssh->cfg.x11_display, c,
6684 ssh->x11auth, addrstr, peerport,
6685 &ssh->cfg) != NULL) {
6686 error = "Unable to open an X11 connection";
6688 logevent("Opening X11 forward connection succeeded");
6693 } else if (typelen == 15 &&
6694 !memcmp(type, "forwarded-tcpip", 15)) {
6695 struct ssh_rportfwd pf, *realpf;
6698 ssh_pkt_getstring(pktin, &dummy, &dummylen);/* skip address */
6699 pf.sport = ssh_pkt_getuint32(pktin);
6700 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
6701 peerport = ssh_pkt_getuint32(pktin);
6702 realpf = find234(ssh->rportfwds, &pf, NULL);
6703 logeventf(ssh, "Received remote port %d open request "
6704 "from %s:%d", pf.sport, peeraddr, peerport);
6705 if (realpf == NULL) {
6706 error = "Remote port is not recognised";
6708 const char *e = pfd_newconnect(&c->u.pfd.s,
6712 realpf->pfrec->addressfamily);
6713 logeventf(ssh, "Attempting to forward remote port to "
6714 "%s:%d", realpf->dhost, realpf->dport);
6716 logeventf(ssh, "Port open failed: %s", e);
6717 error = "Port open failed";
6719 logevent("Forwarded port opened successfully");
6720 c->type = CHAN_SOCKDATA;
6723 } else if (typelen == 22 &&
6724 !memcmp(type, "auth-agent@openssh.com", 22)) {
6725 if (!ssh->agentfwd_enabled)
6726 error = "Agent forwarding is not enabled";
6728 c->type = CHAN_AGENT; /* identify channel type */
6729 c->u.a.lensofar = 0;
6732 error = "Unsupported channel type requested";
6735 c->remoteid = remid;
6736 c->halfopen = FALSE;
6738 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
6739 ssh2_pkt_adduint32(pktout, c->remoteid);
6740 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
6741 ssh2_pkt_addstring(pktout, error);
6742 ssh2_pkt_addstring(pktout, "en"); /* language tag */
6743 ssh2_pkt_send(ssh, pktout);
6744 logeventf(ssh, "Rejected channel open: %s", error);
6747 c->localid = alloc_channel_id(ssh);
6749 c->v.v2.locwindow = OUR_V2_WINSIZE;
6750 c->v.v2.remwindow = winsize;
6751 c->v.v2.remmaxpkt = pktsize;
6752 bufchain_init(&c->v.v2.outbuffer);
6753 add234(ssh->channels, c);
6754 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
6755 ssh2_pkt_adduint32(pktout, c->remoteid);
6756 ssh2_pkt_adduint32(pktout, c->localid);
6757 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
6758 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
6759 ssh2_pkt_send(ssh, pktout);
6764 * Buffer banner messages for later display at some convenient point.
6766 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
6768 /* Arbitrary limit to prevent unbounded inflation of buffer */
6769 if (bufchain_size(&ssh->banner) <= 131072) {
6770 char *banner = NULL;
6772 ssh_pkt_getstring(pktin, &banner, &size);
6774 bufchain_add(&ssh->banner, banner, size);
6778 /* Helper function to deal with sending tty modes for "pty-req" */
6779 static void ssh2_send_ttymode(void *data, char *mode, char *val)
6781 struct Packet *pktout = (struct Packet *)data;
6783 unsigned int arg = 0;
6784 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
6785 if (i == lenof(ssh_ttymodes)) return;
6786 switch (ssh_ttymodes[i].type) {
6788 arg = ssh_tty_parse_specchar(val);
6791 arg = ssh_tty_parse_boolean(val);
6794 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
6795 ssh2_pkt_adduint32(pktout, arg);
6799 * Handle the SSH-2 userauth and connection layers.
6801 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
6802 struct Packet *pktin)
6804 struct do_ssh2_authconn_state {
6807 AUTH_TYPE_PUBLICKEY,
6808 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
6809 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
6811 AUTH_TYPE_KEYBOARD_INTERACTIVE,
6812 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
6814 int done_service_req;
6815 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
6816 int tried_pubkey_config, done_agent;
6817 int kbd_inter_refused;
6819 prompts_t *cur_prompt;
6824 void *publickey_blob;
6825 int publickey_bloblen;
6826 int publickey_encrypted;
6827 char *publickey_algorithm;
6828 char *publickey_comment;
6829 unsigned char agent_request[5], *agent_response, *agentp;
6830 int agent_responselen;
6831 unsigned char *pkblob_in_agent;
6833 char *pkblob, *alg, *commentp;
6834 int pklen, alglen, commentlen;
6835 int siglen, retlen, len;
6836 char *q, *agentreq, *ret;
6838 int num_env, env_left, env_ok;
6839 struct Packet *pktout;
6841 crState(do_ssh2_authconn_state);
6843 crBegin(ssh->do_ssh2_authconn_crstate);
6845 s->done_service_req = FALSE;
6846 s->we_are_in = FALSE;
6847 if (!ssh->cfg.ssh_no_userauth) {
6849 * Request userauth protocol, and await a response to it.
6851 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
6852 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
6853 ssh2_pkt_send(ssh, s->pktout);
6854 crWaitUntilV(pktin);
6855 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
6856 s->done_service_req = TRUE;
6858 if (!s->done_service_req) {
6860 * Request connection protocol directly, without authentication.
6862 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
6863 ssh2_pkt_addstring(s->pktout, "ssh-connection");
6864 ssh2_pkt_send(ssh, s->pktout);
6865 crWaitUntilV(pktin);
6866 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
6867 s->we_are_in = TRUE; /* no auth required */
6869 bombout(("Server refused service request"));
6874 /* Arrange to be able to deal with any BANNERs that come in.
6875 * (We do this now as packets may come in during the next bit.) */
6876 bufchain_init(&ssh->banner);
6877 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
6878 ssh2_msg_userauth_banner;
6881 * Misc one-time setup for authentication.
6883 s->publickey_blob = NULL;
6884 if (!s->we_are_in) {
6887 * Load the public half of any configured public key file
6890 if (!filename_is_null(ssh->cfg.keyfile)) {
6892 logeventf(ssh, "Reading private key file \"%.150s\"",
6893 filename_to_str(&ssh->cfg.keyfile));
6894 keytype = key_type(&ssh->cfg.keyfile);
6895 if (keytype == SSH_KEYTYPE_SSH2) {
6898 ssh2_userkey_loadpub(&ssh->cfg.keyfile,
6899 &s->publickey_algorithm,
6900 &s->publickey_bloblen,
6901 &s->publickey_comment, &error);
6902 if (s->publickey_blob) {
6903 s->publickey_encrypted =
6904 ssh2_userkey_encrypted(&ssh->cfg.keyfile, NULL);
6907 logeventf(ssh, "Unable to load private key (%s)",
6909 msgbuf = dupprintf("Unable to load private key file "
6910 "\"%.150s\" (%s)\r\n",
6911 filename_to_str(&ssh->cfg.keyfile),
6913 c_write_str(ssh, msgbuf);
6918 logeventf(ssh, "Unable to use this key file (%s)",
6919 key_type_to_str(keytype));
6920 msgbuf = dupprintf("Unable to use key file \"%.150s\""
6922 filename_to_str(&ssh->cfg.keyfile),
6923 key_type_to_str(keytype));
6924 c_write_str(ssh, msgbuf);
6926 s->publickey_blob = NULL;
6931 * Find out about any keys Pageant has (but if there's a
6932 * public key configured, filter out all others).
6935 s->agent_response = NULL;
6936 s->pkblob_in_agent = NULL;
6937 if (ssh->cfg.tryagent && agent_exists()) {
6941 logevent("Pageant is running. Requesting keys.");
6943 /* Request the keys held by the agent. */
6944 PUT_32BIT(s->agent_request, 1);
6945 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
6946 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
6947 ssh_agent_callback, ssh)) {
6951 bombout(("Unexpected data from server while"
6952 " waiting for agent response"));
6955 } while (pktin || inlen > 0);
6956 r = ssh->agent_response;
6957 s->agent_responselen = ssh->agent_response_len;
6959 s->agent_response = (unsigned char *) r;
6960 if (s->agent_response && s->agent_responselen >= 5 &&
6961 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
6964 p = s->agent_response + 5;
6965 s->nkeys = GET_32BIT(p);
6967 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
6968 if (s->publickey_blob) {
6969 /* See if configured key is in agent. */
6970 for (keyi = 0; keyi < s->nkeys; keyi++) {
6971 s->pklen = GET_32BIT(p);
6972 if (s->pklen == s->publickey_bloblen &&
6973 !memcmp(p+4, s->publickey_blob,
6974 s->publickey_bloblen)) {
6975 logeventf(ssh, "Pageant key #%d matches "
6976 "configured key file", keyi);
6978 s->pkblob_in_agent = p;
6982 p += GET_32BIT(p) + 4; /* comment */
6984 if (!s->pkblob_in_agent) {
6985 logevent("Configured key file not in Pageant");
6995 * We repeat this whole loop, including the username prompt,
6996 * until we manage a successful authentication. If the user
6997 * types the wrong _password_, they can be sent back to the
6998 * beginning to try another username, if this is configured on.
6999 * (If they specify a username in the config, they are never
7000 * asked, even if they do give a wrong password.)
7002 * I think this best serves the needs of
7004 * - the people who have no configuration, no keys, and just
7005 * want to try repeated (username,password) pairs until they
7006 * type both correctly
7008 * - people who have keys and configuration but occasionally
7009 * need to fall back to passwords
7011 * - people with a key held in Pageant, who might not have
7012 * logged in to a particular machine before; so they want to
7013 * type a username, and then _either_ their key will be
7014 * accepted, _or_ they will type a password. If they mistype
7015 * the username they will want to be able to get back and
7018 s->username[0] = '\0';
7019 s->got_username = FALSE;
7020 while (!s->we_are_in) {
7024 if (s->got_username && !ssh->cfg.change_username) {
7026 * We got a username last time round this loop, and
7027 * with change_username turned off we don't try to get
7030 } else if (!*ssh->cfg.username) {
7031 int ret; /* need not be kept over crReturn */
7032 s->cur_prompt = new_prompts(ssh->frontend);
7033 s->cur_prompt->to_server = TRUE;
7034 s->cur_prompt->name = dupstr("SSH login name");
7035 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE,
7036 lenof(s->username));
7037 ret = get_userpass_input(s->cur_prompt, NULL, 0);
7040 crWaitUntilV(!pktin);
7041 ret = get_userpass_input(s->cur_prompt, in, inlen);
7046 * get_userpass_input() failed to get a username.
7049 free_prompts(s->cur_prompt);
7050 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
7053 memcpy(s->username, s->cur_prompt->prompts[0]->result,
7054 lenof(s->username));
7055 free_prompts(s->cur_prompt);
7058 strncpy(s->username, ssh->cfg.username, sizeof(s->username));
7059 s->username[sizeof(s->username)-1] = '\0';
7060 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
7061 stuff = dupprintf("Using username \"%s\".\r\n", s->username);
7062 c_write_str(ssh, stuff);
7066 s->got_username = TRUE;
7069 * Send an authentication request using method "none": (a)
7070 * just in case it succeeds, and (b) so that we know what
7071 * authentication methods we can usefully try next.
7073 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
7075 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7076 ssh2_pkt_addstring(s->pktout, s->username);
7077 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
7078 ssh2_pkt_addstring(s->pktout, "none"); /* method */
7079 ssh2_pkt_send(ssh, s->pktout);
7080 s->type = AUTH_TYPE_NONE;
7082 s->we_are_in = FALSE;
7084 s->tried_pubkey_config = FALSE;
7085 s->kbd_inter_refused = FALSE;
7087 /* Reset agent request state. */
7088 s->done_agent = FALSE;
7089 if (s->agent_response) {
7090 if (s->pkblob_in_agent) {
7091 s->agentp = s->pkblob_in_agent;
7093 s->agentp = s->agent_response + 5 + 4;
7100 * Wait for the result of the last authentication request.
7103 crWaitUntilV(pktin);
7105 * Now is a convenient point to spew any banner material
7106 * that we've accumulated. (This should ensure that when
7107 * we exit the auth loop, we haven't any left to deal
7111 int size = bufchain_size(&ssh->banner);
7113 * Don't show the banner if we're operating in
7114 * non-verbose non-interactive mode. (It's probably
7115 * a script, which means nobody will read the
7116 * banner _anyway_, and moreover the printing of
7117 * the banner will screw up processing on the
7118 * output of (say) plink.)
7120 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
7121 char *banner = snewn(size, char);
7122 bufchain_fetch(&ssh->banner, banner, size);
7123 c_write_untrusted(ssh, banner, size);
7126 bufchain_clear(&ssh->banner);
7128 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
7129 logevent("Access granted");
7130 s->we_are_in = TRUE;
7134 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE) {
7135 bombout(("Strange packet received during authentication: "
7136 "type %d", pktin->type));
7143 * OK, we're now sitting on a USERAUTH_FAILURE message, so
7144 * we can look at the string in it and know what we can
7145 * helpfully try next.
7147 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
7150 ssh_pkt_getstring(pktin, &methods, &methlen);
7151 if (!ssh2_pkt_getbool(pktin)) {
7153 * We have received an unequivocal Access
7154 * Denied. This can translate to a variety of
7157 * - if we'd just tried "none" authentication,
7158 * it's not worth printing anything at all
7160 * - if we'd just tried a public key _offer_,
7161 * the message should be "Server refused our
7162 * key" (or no message at all if the key
7163 * came from Pageant)
7165 * - if we'd just tried anything else, the
7166 * message really should be "Access denied".
7168 * Additionally, if we'd just tried password
7169 * authentication, we should break out of this
7170 * whole loop so as to go back to the username
7171 * prompt (iff we're configured to allow
7172 * username change attempts).
7174 if (s->type == AUTH_TYPE_NONE) {
7176 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
7177 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
7178 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
7179 c_write_str(ssh, "Server refused our key\r\n");
7180 logevent("Server refused public key");
7181 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
7182 /* server declined keyboard-interactive; ignore */
7184 c_write_str(ssh, "Access denied\r\n");
7185 logevent("Access denied");
7186 if (s->type == AUTH_TYPE_PASSWORD &&
7187 ssh->cfg.change_username) {
7188 /* XXX perhaps we should allow
7189 * keyboard-interactive to do this too? */
7190 s->we_are_in = FALSE;
7195 c_write_str(ssh, "Further authentication required\r\n");
7196 logevent("Further authentication required");
7200 in_commasep_string("publickey", methods, methlen);
7202 in_commasep_string("password", methods, methlen);
7203 s->can_keyb_inter = ssh->cfg.try_ki_auth &&
7204 in_commasep_string("keyboard-interactive", methods, methlen);
7207 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
7209 if (s->can_pubkey && !s->done_agent && s->nkeys) {
7212 * Attempt public-key authentication using a key from Pageant.
7215 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
7216 ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
7218 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
7220 /* Unpack key from agent response */
7221 s->pklen = GET_32BIT(s->agentp);
7223 s->pkblob = (char *)s->agentp;
7224 s->agentp += s->pklen;
7225 s->alglen = GET_32BIT(s->pkblob);
7226 s->alg = s->pkblob + 4;
7227 s->commentlen = GET_32BIT(s->agentp);
7229 s->commentp = (char *)s->agentp;
7230 s->agentp += s->commentlen;
7231 /* s->agentp now points at next key, if any */
7233 /* See if server will accept it */
7234 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7235 ssh2_pkt_addstring(s->pktout, s->username);
7236 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7237 /* service requested */
7238 ssh2_pkt_addstring(s->pktout, "publickey");
7240 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
7241 ssh2_pkt_addstring_start(s->pktout);
7242 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
7243 ssh2_pkt_addstring_start(s->pktout);
7244 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
7245 ssh2_pkt_send(ssh, s->pktout);
7246 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
7248 crWaitUntilV(pktin);
7249 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
7251 /* Offer of key refused. */
7258 if (flags & FLAG_VERBOSE) {
7259 c_write_str(ssh, "Authenticating with "
7261 c_write(ssh, s->commentp, s->commentlen);
7262 c_write_str(ssh, "\" from agent\r\n");
7266 * Server is willing to accept the key.
7267 * Construct a SIGN_REQUEST.
7269 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7270 ssh2_pkt_addstring(s->pktout, s->username);
7271 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7272 /* service requested */
7273 ssh2_pkt_addstring(s->pktout, "publickey");
7275 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
7276 ssh2_pkt_addstring_start(s->pktout);
7277 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
7278 ssh2_pkt_addstring_start(s->pktout);
7279 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
7281 /* Ask agent for signature. */
7282 s->siglen = s->pktout->length - 5 + 4 +
7283 ssh->v2_session_id_len;
7284 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
7286 s->len = 1; /* message type */
7287 s->len += 4 + s->pklen; /* key blob */
7288 s->len += 4 + s->siglen; /* data to sign */
7289 s->len += 4; /* flags */
7290 s->agentreq = snewn(4 + s->len, char);
7291 PUT_32BIT(s->agentreq, s->len);
7292 s->q = s->agentreq + 4;
7293 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
7294 PUT_32BIT(s->q, s->pklen);
7296 memcpy(s->q, s->pkblob, s->pklen);
7298 PUT_32BIT(s->q, s->siglen);
7300 /* Now the data to be signed... */
7301 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
7302 PUT_32BIT(s->q, ssh->v2_session_id_len);
7305 memcpy(s->q, ssh->v2_session_id,
7306 ssh->v2_session_id_len);
7307 s->q += ssh->v2_session_id_len;
7308 memcpy(s->q, s->pktout->data + 5,
7309 s->pktout->length - 5);
7310 s->q += s->pktout->length - 5;
7311 /* And finally the (zero) flags word. */
7313 if (!agent_query(s->agentreq, s->len + 4,
7315 ssh_agent_callback, ssh)) {
7319 bombout(("Unexpected data from server"
7320 " while waiting for agent"
7324 } while (pktin || inlen > 0);
7325 vret = ssh->agent_response;
7326 s->retlen = ssh->agent_response_len;
7331 if (s->ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
7332 logevent("Sending Pageant's response");
7333 ssh2_add_sigblob(ssh, s->pktout,
7334 s->pkblob, s->pklen,
7336 GET_32BIT(s->ret + 5));
7337 ssh2_pkt_send(ssh, s->pktout);
7338 s->type = AUTH_TYPE_PUBLICKEY;
7340 /* FIXME: less drastic response */
7341 bombout(("Pageant failed to answer challenge"));
7347 /* Do we have any keys left to try? */
7348 if (s->pkblob_in_agent) {
7349 s->done_agent = TRUE;
7350 s->tried_pubkey_config = TRUE;
7353 if (s->keyi >= s->nkeys)
7354 s->done_agent = TRUE;
7357 } else if (s->can_pubkey && s->publickey_blob &&
7358 !s->tried_pubkey_config) {
7360 struct ssh2_userkey *key; /* not live over crReturn */
7361 char *passphrase; /* not live over crReturn */
7363 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
7364 ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
7366 s->tried_pubkey_config = TRUE;
7369 * Try the public key supplied in the configuration.
7371 * First, offer the public blob to see if the server is
7372 * willing to accept it.
7374 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7375 ssh2_pkt_addstring(s->pktout, s->username);
7376 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7377 /* service requested */
7378 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
7379 ssh2_pkt_addbool(s->pktout, FALSE);
7380 /* no signature included */
7381 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
7382 ssh2_pkt_addstring_start(s->pktout);
7383 ssh2_pkt_addstring_data(s->pktout,
7384 (char *)s->publickey_blob,
7385 s->publickey_bloblen);
7386 ssh2_pkt_send(ssh, s->pktout);
7387 logevent("Offered public key");
7389 crWaitUntilV(pktin);
7390 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
7391 /* Key refused. Give up. */
7392 s->gotit = TRUE; /* reconsider message next loop */
7393 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
7394 continue; /* process this new message */
7396 logevent("Offer of public key accepted");
7399 * Actually attempt a serious authentication using
7402 if (flags & FLAG_VERBOSE) {
7403 c_write_str(ssh, "Authenticating with public key \"");
7404 c_write_str(ssh, s->publickey_comment);
7405 c_write_str(ssh, "\"\r\n");
7409 const char *error; /* not live over crReturn */
7410 if (s->publickey_encrypted) {
7412 * Get a passphrase from the user.
7414 int ret; /* need not be kept over crReturn */
7415 s->cur_prompt = new_prompts(ssh->frontend);
7416 s->cur_prompt->to_server = FALSE;
7417 s->cur_prompt->name = dupstr("SSH key passphrase");
7418 add_prompt(s->cur_prompt,
7419 dupprintf("Passphrase for key \"%.100s\": ",
7420 s->publickey_comment),
7421 FALSE, SSH_MAX_PASSWORD_LEN);
7422 ret = get_userpass_input(s->cur_prompt, NULL, 0);
7425 crWaitUntilV(!pktin);
7426 ret = get_userpass_input(s->cur_prompt,
7431 /* Failed to get a passphrase. Terminate. */
7432 free_prompts(s->cur_prompt);
7433 ssh_disconnect(ssh, NULL,
7434 "Unable to authenticate",
7435 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
7440 dupstr(s->cur_prompt->prompts[0]->result);
7441 free_prompts(s->cur_prompt);
7443 passphrase = NULL; /* no passphrase needed */
7447 * Try decrypting the key.
7449 key = ssh2_load_userkey(&ssh->cfg.keyfile, passphrase,
7452 /* burn the evidence */
7453 memset(passphrase, 0, strlen(passphrase));
7456 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
7458 (key == SSH2_WRONG_PASSPHRASE)) {
7459 c_write_str(ssh, "Wrong passphrase\r\n");
7461 /* and loop again */
7463 c_write_str(ssh, "Unable to load private key (");
7464 c_write_str(ssh, error);
7465 c_write_str(ssh, ")\r\n");
7467 break; /* try something else */
7473 unsigned char *pkblob, *sigblob, *sigdata;
7474 int pkblob_len, sigblob_len, sigdata_len;
7478 * We have loaded the private key and the server
7479 * has announced that it's willing to accept it.
7480 * Hallelujah. Generate a signature and send it.
7482 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7483 ssh2_pkt_addstring(s->pktout, s->username);
7484 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7485 /* service requested */
7486 ssh2_pkt_addstring(s->pktout, "publickey");
7488 ssh2_pkt_addbool(s->pktout, TRUE);
7489 /* signature follows */
7490 ssh2_pkt_addstring(s->pktout, key->alg->name);
7491 pkblob = key->alg->public_blob(key->data,
7493 ssh2_pkt_addstring_start(s->pktout);
7494 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
7498 * The data to be signed is:
7502 * followed by everything so far placed in the
7505 sigdata_len = s->pktout->length - 5 + 4 +
7506 ssh->v2_session_id_len;
7507 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
7509 sigdata = snewn(sigdata_len, unsigned char);
7511 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
7512 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
7515 memcpy(sigdata+p, ssh->v2_session_id,
7516 ssh->v2_session_id_len);
7517 p += ssh->v2_session_id_len;
7518 memcpy(sigdata+p, s->pktout->data + 5,
7519 s->pktout->length - 5);
7520 p += s->pktout->length - 5;
7521 assert(p == sigdata_len);
7522 sigblob = key->alg->sign(key->data, (char *)sigdata,
7523 sigdata_len, &sigblob_len);
7524 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
7525 sigblob, sigblob_len);
7530 ssh2_pkt_send(ssh, s->pktout);
7531 s->type = AUTH_TYPE_PUBLICKEY;
7532 key->alg->freekey(key->data);
7535 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
7538 * Keyboard-interactive authentication.
7541 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
7543 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
7544 ssh->pkt_ctx |= SSH2_PKTCTX_KBDINTER;
7546 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7547 ssh2_pkt_addstring(s->pktout, s->username);
7548 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7549 /* service requested */
7550 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
7552 ssh2_pkt_addstring(s->pktout, ""); /* lang */
7553 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
7554 ssh2_pkt_send(ssh, s->pktout);
7556 crWaitUntilV(pktin);
7557 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
7558 /* Server is not willing to do keyboard-interactive
7559 * at all (or, bizarrely but legally, accepts the
7560 * user without actually issuing any prompts).
7561 * Give up on it entirely. */
7563 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE)
7564 logevent("Keyboard-interactive authentication refused");
7565 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
7566 s->kbd_inter_refused = TRUE; /* don't try it again */
7571 * Loop while the server continues to send INFO_REQUESTs.
7573 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
7575 char *name, *inst, *lang;
7576 int name_len, inst_len, lang_len;
7580 * We've got a fresh USERAUTH_INFO_REQUEST.
7581 * Get the preamble and start building a prompt.
7583 ssh_pkt_getstring(pktin, &name, &name_len);
7584 ssh_pkt_getstring(pktin, &inst, &inst_len);
7585 ssh_pkt_getstring(pktin, &lang, &lang_len);
7586 s->cur_prompt = new_prompts(ssh->frontend);
7587 s->cur_prompt->to_server = TRUE;
7589 /* FIXME: better prefix to distinguish from
7591 s->cur_prompt->name =
7592 dupprintf("SSH server: %.*s", name_len, name);
7593 s->cur_prompt->name_reqd = TRUE;
7595 s->cur_prompt->name =
7596 dupstr("SSH server authentication");
7597 s->cur_prompt->name_reqd = FALSE;
7599 /* FIXME: ugly to print "Using..." in prompt _every_
7600 * time round. Can this be done more subtly? */
7601 s->cur_prompt->instruction =
7602 dupprintf("Using keyboard-interactive authentication.%s%.*s",
7603 inst_len ? "\n" : "", inst_len, inst);
7604 s->cur_prompt->instr_reqd = TRUE;
7607 * Get the prompts from the packet.
7609 s->num_prompts = ssh_pkt_getuint32(pktin);
7610 for (i = 0; i < s->num_prompts; i++) {
7614 static char noprompt[] =
7615 "<server failed to send prompt>: ";
7617 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
7618 echo = ssh2_pkt_getbool(pktin);
7621 prompt_len = lenof(noprompt)-1;
7623 add_prompt(s->cur_prompt,
7624 dupprintf("%.*s", prompt_len, prompt),
7625 echo, SSH_MAX_PASSWORD_LEN);
7629 * Get the user's responses.
7631 if (s->num_prompts) {
7632 int ret; /* not live over crReturn */
7633 ret = get_userpass_input(s->cur_prompt, NULL, 0);
7636 crWaitUntilV(!pktin);
7637 ret = get_userpass_input(s->cur_prompt, in, inlen);
7642 * Failed to get responses. Terminate.
7644 free_prompts(s->cur_prompt);
7645 ssh_disconnect(ssh, NULL, "Unable to authenticate",
7646 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
7653 * Send the responses to the server.
7655 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
7656 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
7657 for (i=0; i < s->num_prompts; i++) {
7658 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
7659 ssh2_pkt_addstring(s->pktout,
7660 s->cur_prompt->prompts[i]->result);
7661 end_log_omission(ssh, s->pktout);
7663 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
7666 * Get the next packet in case it's another
7669 crWaitUntilV(pktin);
7674 * We should have SUCCESS or FAILURE now.
7678 } else if (s->can_passwd) {
7681 * Plain old password authentication.
7683 int ret; /* not live over crReturn */
7684 int changereq_first_time; /* not live over crReturn */
7686 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
7687 ssh->pkt_ctx |= SSH2_PKTCTX_PASSWORD;
7689 s->cur_prompt = new_prompts(ssh->frontend);
7690 s->cur_prompt->to_server = TRUE;
7691 s->cur_prompt->name = dupstr("SSH password");
7692 add_prompt(s->cur_prompt, dupprintf("%.90s@%.90s's password: ",
7695 FALSE, SSH_MAX_PASSWORD_LEN);
7697 ret = get_userpass_input(s->cur_prompt, NULL, 0);
7700 crWaitUntilV(!pktin);
7701 ret = get_userpass_input(s->cur_prompt, in, inlen);
7706 * Failed to get responses. Terminate.
7708 free_prompts(s->cur_prompt);
7709 ssh_disconnect(ssh, NULL, "Unable to authenticate",
7710 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
7715 * Squirrel away the password. (We may need it later if
7716 * asked to change it.)
7718 s->password = dupstr(s->cur_prompt->prompts[0]->result);
7719 free_prompts(s->cur_prompt);
7722 * Send the password packet.
7724 * We pad out the password packet to 256 bytes to make
7725 * it harder for an attacker to find the length of the
7728 * Anyone using a password longer than 256 bytes
7729 * probably doesn't have much to worry about from
7730 * people who find out how long their password is!
7732 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7733 ssh2_pkt_addstring(s->pktout, s->username);
7734 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7735 /* service requested */
7736 ssh2_pkt_addstring(s->pktout, "password");
7737 ssh2_pkt_addbool(s->pktout, FALSE);
7738 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
7739 ssh2_pkt_addstring(s->pktout, s->password);
7740 end_log_omission(ssh, s->pktout);
7741 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
7742 logevent("Sent password");
7743 s->type = AUTH_TYPE_PASSWORD;
7746 * Wait for next packet, in case it's a password change
7749 crWaitUntilV(pktin);
7750 changereq_first_time = TRUE;
7752 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
7755 * We're being asked for a new password
7756 * (perhaps not for the first time).
7757 * Loop until the server accepts it.
7760 int got_new = FALSE; /* not live over crReturn */
7761 char *prompt; /* not live over crReturn */
7762 int prompt_len; /* not live over crReturn */
7766 if (changereq_first_time)
7767 msg = "Server requested password change";
7769 msg = "Server rejected new password";
7771 c_write_str(ssh, msg);
7772 c_write_str(ssh, "\r\n");
7775 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
7777 s->cur_prompt = new_prompts(ssh->frontend);
7778 s->cur_prompt->to_server = TRUE;
7779 s->cur_prompt->name = dupstr("New SSH password");
7780 s->cur_prompt->instruction =
7781 dupprintf("%.*s", prompt_len, prompt);
7782 s->cur_prompt->instr_reqd = TRUE;
7784 * There's no explicit requirement in the protocol
7785 * for the "old" passwords in the original and
7786 * password-change messages to be the same, and
7787 * apparently some Cisco kit supports password change
7788 * by the user entering a blank password originally
7789 * and the real password subsequently, so,
7790 * reluctantly, we prompt for the old password again.
7792 * (On the other hand, some servers don't even bother
7793 * to check this field.)
7795 add_prompt(s->cur_prompt,
7796 dupstr("Current password (blank for previously entered password): "),
7797 FALSE, SSH_MAX_PASSWORD_LEN);
7798 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
7799 FALSE, SSH_MAX_PASSWORD_LEN);
7800 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
7801 FALSE, SSH_MAX_PASSWORD_LEN);
7804 * Loop until the user manages to enter the same
7809 ret = get_userpass_input(s->cur_prompt, NULL, 0);
7812 crWaitUntilV(!pktin);
7813 ret = get_userpass_input(s->cur_prompt, in, inlen);
7818 * Failed to get responses. Terminate.
7820 /* burn the evidence */
7821 free_prompts(s->cur_prompt);
7822 memset(s->password, 0, strlen(s->password));
7824 ssh_disconnect(ssh, NULL, "Unable to authenticate",
7825 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
7831 * If the user specified a new original password
7832 * (IYSWIM), overwrite any previously specified
7834 * (A side effect is that the user doesn't have to
7835 * re-enter it if they louse up the new password.)
7837 if (s->cur_prompt->prompts[0]->result[0]) {
7838 memset(s->password, 0, strlen(s->password));
7839 /* burn the evidence */
7842 dupstr(s->cur_prompt->prompts[0]->result);
7846 * Check the two new passwords match.
7848 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
7849 s->cur_prompt->prompts[2]->result)
7852 /* They don't. Silly user. */
7853 c_write_str(ssh, "Passwords do not match\r\n");
7858 * Send the new password (along with the old one).
7859 * (see above for padding rationale)
7861 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7862 ssh2_pkt_addstring(s->pktout, s->username);
7863 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7864 /* service requested */
7865 ssh2_pkt_addstring(s->pktout, "password");
7866 ssh2_pkt_addbool(s->pktout, TRUE);
7867 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
7868 ssh2_pkt_addstring(s->pktout, s->password);
7869 ssh2_pkt_addstring(s->pktout,
7870 s->cur_prompt->prompts[1]->result);
7871 free_prompts(s->cur_prompt);
7872 end_log_omission(ssh, s->pktout);
7873 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
7874 logevent("Sent new password");
7877 * Now see what the server has to say about it.
7878 * (If it's CHANGEREQ again, it's not happy with the
7881 crWaitUntilV(pktin);
7882 changereq_first_time = FALSE;
7887 * We need to reexamine the current pktin at the top
7888 * of the loop. Either:
7889 * - we weren't asked to change password at all, in
7890 * which case it's a SUCCESS or FAILURE with the
7892 * - we sent a new password, and the server was
7893 * either OK with it (SUCCESS or FAILURE w/partial
7894 * success) or unhappy with the _old_ password
7895 * (FAILURE w/o partial success)
7896 * In any of these cases, we go back to the top of
7897 * the loop and start again.
7902 * We don't need the old password any more, in any
7903 * case. Burn the evidence.
7905 memset(s->password, 0, strlen(s->password));
7910 ssh_disconnect(ssh, NULL,
7911 "No supported authentication methods available",
7912 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
7920 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
7922 /* Clear up various bits and pieces from authentication. */
7923 if (s->publickey_blob) {
7924 sfree(s->publickey_blob);
7925 sfree(s->publickey_comment);
7927 if (s->agent_response)
7928 sfree(s->agent_response);
7931 * Now the connection protocol has started, one way or another.
7934 ssh->channels = newtree234(ssh_channelcmp);
7937 * Set up handlers for some connection protocol messages, so we
7938 * don't have to handle them repeatedly in this coroutine.
7940 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
7941 ssh2_msg_channel_window_adjust;
7942 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
7943 ssh2_msg_global_request;
7946 * Create the main session channel.
7948 if (ssh->cfg.ssh_no_shell) {
7949 ssh->mainchan = NULL;
7950 } else if (*ssh->cfg.ssh_nc_host) {
7952 * Just start a direct-tcpip channel and use it as the main
7955 ssh->mainchan = snew(struct ssh_channel);
7956 ssh->mainchan->ssh = ssh;
7957 ssh->mainchan->localid = alloc_channel_id(ssh);
7959 "Opening direct-tcpip channel to %s:%d in place of session",
7960 ssh->cfg.ssh_nc_host, ssh->cfg.ssh_nc_port);
7961 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7962 ssh2_pkt_addstring(s->pktout, "direct-tcpip");
7963 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
7964 ssh->mainchan->v.v2.locwindow = OUR_V2_WINSIZE;
7965 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
7966 ssh2_pkt_adduint32(s->pktout, OUR_V2_MAXPKT); /* our max pkt size */
7967 ssh2_pkt_addstring(s->pktout, ssh->cfg.ssh_nc_host);
7968 ssh2_pkt_adduint32(s->pktout, ssh->cfg.ssh_nc_port);
7970 * There's nothing meaningful to put in the originator
7971 * fields, but some servers insist on syntactically correct
7974 ssh2_pkt_addstring(s->pktout, "0.0.0.0");
7975 ssh2_pkt_adduint32(s->pktout, 0);
7976 ssh2_pkt_send(ssh, s->pktout);
7978 crWaitUntilV(pktin);
7979 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
7980 bombout(("Server refused to open a direct-tcpip channel"));
7982 /* FIXME: error data comes back in FAILURE packet */
7984 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
7985 bombout(("Server's channel confirmation cited wrong channel"));
7988 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
7989 ssh->mainchan->halfopen = FALSE;
7990 ssh->mainchan->type = CHAN_MAINSESSION;
7991 ssh->mainchan->closes = 0;
7992 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
7993 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
7994 bufchain_init(&ssh->mainchan->v.v2.outbuffer);
7995 add234(ssh->channels, ssh->mainchan);
7996 update_specials_menu(ssh->frontend);
7997 logevent("Opened direct-tcpip channel");
8000 ssh->mainchan = snew(struct ssh_channel);
8001 ssh->mainchan->ssh = ssh;
8002 ssh->mainchan->localid = alloc_channel_id(ssh);
8003 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
8004 ssh2_pkt_addstring(s->pktout, "session");
8005 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
8006 ssh->mainchan->v.v2.locwindow = OUR_V2_WINSIZE;
8007 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
8008 ssh2_pkt_adduint32(s->pktout, OUR_V2_MAXPKT); /* our max pkt size */
8009 ssh2_pkt_send(ssh, s->pktout);
8010 crWaitUntilV(pktin);
8011 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
8012 bombout(("Server refused to open a session"));
8014 /* FIXME: error data comes back in FAILURE packet */
8016 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
8017 bombout(("Server's channel confirmation cited wrong channel"));
8020 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
8021 ssh->mainchan->halfopen = FALSE;
8022 ssh->mainchan->type = CHAN_MAINSESSION;
8023 ssh->mainchan->closes = 0;
8024 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8025 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8026 bufchain_init(&ssh->mainchan->v.v2.outbuffer);
8027 add234(ssh->channels, ssh->mainchan);
8028 update_specials_menu(ssh->frontend);
8029 logevent("Opened channel for session");
8030 ssh->ncmode = FALSE;
8034 * Now we have a channel, make dispatch table entries for
8035 * general channel-based messages.
8037 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
8038 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
8039 ssh2_msg_channel_data;
8040 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
8041 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
8042 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
8043 ssh2_msg_channel_open_confirmation;
8044 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
8045 ssh2_msg_channel_open_failure;
8046 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
8047 ssh2_msg_channel_request;
8048 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
8049 ssh2_msg_channel_open;
8052 * Potentially enable X11 forwarding.
8054 if (ssh->mainchan && !ssh->ncmode && ssh->cfg.x11_forward) {
8055 char proto[20], data[64];
8056 logevent("Requesting X11 forwarding");
8057 ssh->x11auth = x11_invent_auth(proto, sizeof(proto),
8058 data, sizeof(data), ssh->cfg.x11_auth);
8059 x11_get_real_auth(ssh->x11auth, ssh->cfg.x11_display);
8060 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8061 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8062 ssh2_pkt_addstring(s->pktout, "x11-req");
8063 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8064 ssh2_pkt_addbool(s->pktout, 0); /* many connections */
8065 ssh2_pkt_addstring(s->pktout, proto);
8067 * Note that while we blank the X authentication data here, we don't
8068 * take any special action to blank the start of an X11 channel,
8069 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
8070 * without having session blanking enabled is likely to leak your
8071 * cookie into the log.
8073 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8074 ssh2_pkt_addstring(s->pktout, data);
8075 end_log_omission(ssh, s->pktout);
8076 ssh2_pkt_adduint32(s->pktout, x11_get_screen_number(ssh->cfg.x11_display));
8077 ssh2_pkt_send(ssh, s->pktout);
8079 crWaitUntilV(pktin);
8081 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8082 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8083 bombout(("Unexpected response to X11 forwarding request:"
8084 " packet type %d", pktin->type));
8087 logevent("X11 forwarding refused");
8089 logevent("X11 forwarding enabled");
8090 ssh->X11_fwd_enabled = TRUE;
8095 * Enable port forwardings.
8097 ssh_setup_portfwd(ssh, &ssh->cfg);
8100 * Potentially enable agent forwarding.
8102 if (ssh->mainchan && !ssh->ncmode && ssh->cfg.agentfwd && agent_exists()) {
8103 logevent("Requesting OpenSSH-style agent forwarding");
8104 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8105 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8106 ssh2_pkt_addstring(s->pktout, "auth-agent-req@openssh.com");
8107 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8108 ssh2_pkt_send(ssh, s->pktout);
8110 crWaitUntilV(pktin);
8112 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8113 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8114 bombout(("Unexpected response to agent forwarding request:"
8115 " packet type %d", pktin->type));
8118 logevent("Agent forwarding refused");
8120 logevent("Agent forwarding enabled");
8121 ssh->agentfwd_enabled = TRUE;
8126 * Now allocate a pty for the session.
8128 if (ssh->mainchan && !ssh->ncmode && !ssh->cfg.nopty) {
8129 /* Unpick the terminal-speed string. */
8130 /* XXX perhaps we should allow no speeds to be sent. */
8131 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
8132 sscanf(ssh->cfg.termspeed, "%d,%d", &ssh->ospeed, &ssh->ispeed);
8133 /* Build the pty request. */
8134 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8135 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
8136 ssh2_pkt_addstring(s->pktout, "pty-req");
8137 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8138 ssh2_pkt_addstring(s->pktout, ssh->cfg.termtype);
8139 ssh2_pkt_adduint32(s->pktout, ssh->term_width);
8140 ssh2_pkt_adduint32(s->pktout, ssh->term_height);
8141 ssh2_pkt_adduint32(s->pktout, 0); /* pixel width */
8142 ssh2_pkt_adduint32(s->pktout, 0); /* pixel height */
8143 ssh2_pkt_addstring_start(s->pktout);
8144 parse_ttymodes(ssh, ssh->cfg.ttymodes,
8145 ssh2_send_ttymode, (void *)s->pktout);
8146 ssh2_pkt_addbyte(s->pktout, SSH2_TTY_OP_ISPEED);
8147 ssh2_pkt_adduint32(s->pktout, ssh->ispeed);
8148 ssh2_pkt_addbyte(s->pktout, SSH2_TTY_OP_OSPEED);
8149 ssh2_pkt_adduint32(s->pktout, ssh->ospeed);
8150 ssh2_pkt_addstring_data(s->pktout, "\0", 1); /* TTY_OP_END */
8151 ssh2_pkt_send(ssh, s->pktout);
8152 ssh->state = SSH_STATE_INTERMED;
8154 crWaitUntilV(pktin);
8156 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8157 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8158 bombout(("Unexpected response to pty request:"
8159 " packet type %d", pktin->type));
8162 c_write_str(ssh, "Server refused to allocate pty\r\n");
8163 ssh->editing = ssh->echoing = 1;
8165 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
8166 ssh->ospeed, ssh->ispeed);
8169 ssh->editing = ssh->echoing = 1;
8173 * Send environment variables.
8175 * Simplest thing here is to send all the requests at once, and
8176 * then wait for a whole bunch of successes or failures.
8178 if (ssh->mainchan && !ssh->ncmode && *ssh->cfg.environmt) {
8179 char *e = ssh->cfg.environmt;
8180 char *var, *varend, *val;
8186 while (*e && *e != '\t') e++;
8188 if (*e == '\t') e++;
8193 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8194 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8195 ssh2_pkt_addstring(s->pktout, "env");
8196 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8197 ssh2_pkt_addstring_start(s->pktout);
8198 ssh2_pkt_addstring_data(s->pktout, var, varend-var);
8199 ssh2_pkt_addstring(s->pktout, val);
8200 ssh2_pkt_send(ssh, s->pktout);
8205 logeventf(ssh, "Sent %d environment variables", s->num_env);
8208 s->env_left = s->num_env;
8210 while (s->env_left > 0) {
8211 crWaitUntilV(pktin);
8213 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8214 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8215 bombout(("Unexpected response to environment request:"
8216 " packet type %d", pktin->type));
8226 if (s->env_ok == s->num_env) {
8227 logevent("All environment variables successfully set");
8228 } else if (s->env_ok == 0) {
8229 logevent("All environment variables refused");
8230 c_write_str(ssh, "Server refused to set environment variables\r\n");
8232 logeventf(ssh, "%d environment variables refused",
8233 s->num_env - s->env_ok);
8234 c_write_str(ssh, "Server refused to set all environment variables\r\n");
8239 * Start a shell or a remote command. We may have to attempt
8240 * this twice if the config data has provided a second choice
8243 if (ssh->mainchan && !ssh->ncmode) while (1) {
8247 if (ssh->fallback_cmd) {
8248 subsys = ssh->cfg.ssh_subsys2;
8249 cmd = ssh->cfg.remote_cmd_ptr2;
8251 subsys = ssh->cfg.ssh_subsys;
8252 cmd = ssh->cfg.remote_cmd_ptr;
8253 if (!cmd) cmd = ssh->cfg.remote_cmd;
8256 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8257 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
8259 ssh2_pkt_addstring(s->pktout, "subsystem");
8260 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8261 ssh2_pkt_addstring(s->pktout, cmd);
8263 ssh2_pkt_addstring(s->pktout, "exec");
8264 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8265 ssh2_pkt_addstring(s->pktout, cmd);
8267 ssh2_pkt_addstring(s->pktout, "shell");
8268 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8270 ssh2_pkt_send(ssh, s->pktout);
8272 crWaitUntilV(pktin);
8274 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8275 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8276 bombout(("Unexpected response to shell/command request:"
8277 " packet type %d", pktin->type));
8281 * We failed to start the command. If this is the
8282 * fallback command, we really are finished; if it's
8283 * not, and if the fallback command exists, try falling
8284 * back to it before complaining.
8286 if (!ssh->fallback_cmd && ssh->cfg.remote_cmd_ptr2 != NULL) {
8287 logevent("Primary command failed; attempting fallback");
8288 ssh->fallback_cmd = TRUE;
8291 bombout(("Server refused to start a shell/command"));
8294 logevent("Started a shell/command");
8299 ssh->state = SSH_STATE_SESSION;
8300 if (ssh->size_needed)
8301 ssh_size(ssh, ssh->term_width, ssh->term_height);
8302 if (ssh->eof_needed)
8303 ssh_special(ssh, TS_EOF);
8309 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
8314 s->try_send = FALSE;
8318 * _All_ the connection-layer packets we expect to
8319 * receive are now handled by the dispatch table.
8320 * Anything that reaches here must be bogus.
8323 bombout(("Strange packet received: type %d", pktin->type));
8325 } else if (ssh->mainchan) {
8327 * We have spare data. Add it to the channel buffer.
8329 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
8334 struct ssh_channel *c;
8336 * Try to send data on all channels if we can.
8338 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
8339 ssh2_try_send_and_unthrottle(c);
8347 * Handlers for SSH-2 messages that might arrive at any moment.
8349 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
8351 /* log reason code in disconnect message */
8353 int nowlen, reason, msglen;
8355 reason = ssh_pkt_getuint32(pktin);
8356 ssh_pkt_getstring(pktin, &msg, &msglen);
8358 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
8359 buf = dupprintf("Received disconnect message (%s)",
8360 ssh2_disconnect_reasons[reason]);
8362 buf = dupprintf("Received disconnect message (unknown"
8363 " type %d)", reason);
8367 buf = dupprintf("Disconnection message text: %n%.*s",
8368 &nowlen, msglen, msg);
8370 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
8372 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
8373 ssh2_disconnect_reasons[reason] : "unknown",
8378 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
8380 /* log the debug message */
8385 /* XXX maybe we should actually take notice of this */
8386 always_display = ssh2_pkt_getbool(pktin);
8387 ssh_pkt_getstring(pktin, &msg, &msglen);
8389 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
8392 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
8394 struct Packet *pktout;
8395 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
8396 ssh2_pkt_adduint32(pktout, pktin->sequence);
8398 * UNIMPLEMENTED messages MUST appear in the same order as the
8399 * messages they respond to. Hence, never queue them.
8401 ssh2_pkt_send_noqueue(ssh, pktout);
8405 * Handle the top-level SSH-2 protocol.
8407 static void ssh2_protocol_setup(Ssh ssh)
8412 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
8414 for (i = 0; i < 256; i++)
8415 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
8418 * Any message we actually understand, we set to NULL so that
8419 * the coroutines will get it.
8421 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = NULL;
8422 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = NULL;
8423 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = NULL;
8424 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = NULL;
8425 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = NULL;
8426 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = NULL;
8427 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = NULL;
8428 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = NULL; duplicate case value */
8429 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = NULL; duplicate case value */
8430 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = NULL;
8431 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = NULL;
8432 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = NULL;
8433 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = NULL;
8434 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = NULL;
8435 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
8436 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = NULL;
8437 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = NULL; duplicate case value */
8438 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = NULL; duplicate case value */
8439 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = NULL;
8440 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = NULL;
8441 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = NULL;
8442 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = NULL;
8443 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = NULL;
8444 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = NULL;
8445 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = NULL;
8446 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = NULL;
8447 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = NULL;
8448 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = NULL;
8449 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = NULL;
8450 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = NULL;
8451 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = NULL;
8452 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = NULL;
8453 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = NULL;
8456 * These special message types we install handlers for.
8458 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
8459 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
8460 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
8463 static void ssh2_timer(void *ctx, long now)
8467 if (ssh->state == SSH_STATE_CLOSED)
8470 if (!ssh->kex_in_progress && ssh->cfg.ssh_rekey_time != 0 &&
8471 now - ssh->next_rekey >= 0) {
8472 do_ssh2_transport(ssh, "timeout", -1, NULL);
8476 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
8477 struct Packet *pktin)
8479 unsigned char *in = (unsigned char *)vin;
8480 if (ssh->state == SSH_STATE_CLOSED)
8484 ssh->incoming_data_size += pktin->encrypted_len;
8485 if (!ssh->kex_in_progress &&
8486 ssh->max_data_size != 0 &&
8487 ssh->incoming_data_size > ssh->max_data_size)
8488 do_ssh2_transport(ssh, "too much data received", -1, NULL);
8491 if (pktin && ssh->packet_dispatch[pktin->type]) {
8492 ssh->packet_dispatch[pktin->type](ssh, pktin);
8496 if (!ssh->protocol_initial_phase_done ||
8497 (pktin && pktin->type >= 20 && pktin->type < 50)) {
8498 if (do_ssh2_transport(ssh, in, inlen, pktin) &&
8499 !ssh->protocol_initial_phase_done) {
8500 ssh->protocol_initial_phase_done = TRUE;
8502 * Allow authconn to initialise itself.
8504 do_ssh2_authconn(ssh, NULL, 0, NULL);
8507 do_ssh2_authconn(ssh, in, inlen, pktin);
8512 * Called to set up the connection.
8514 * Returns an error message, or NULL on success.
8516 static const char *ssh_init(void *frontend_handle, void **backend_handle,
8518 char *host, int port, char **realhost, int nodelay,
8524 ssh = snew(struct ssh_tag);
8525 ssh->cfg = *cfg; /* STRUCTURE COPY */
8526 ssh->version = 0; /* when not ready yet */
8529 ssh->v1_cipher_ctx = NULL;
8530 ssh->crcda_ctx = NULL;
8531 ssh->cscipher = NULL;
8532 ssh->cs_cipher_ctx = NULL;
8533 ssh->sccipher = NULL;
8534 ssh->sc_cipher_ctx = NULL;
8536 ssh->cs_mac_ctx = NULL;
8538 ssh->sc_mac_ctx = NULL;
8540 ssh->cs_comp_ctx = NULL;
8542 ssh->sc_comp_ctx = NULL;
8544 ssh->kex_ctx = NULL;
8545 ssh->hostkey = NULL;
8547 ssh->close_expected = FALSE;
8548 ssh->clean_exit = FALSE;
8549 ssh->state = SSH_STATE_PREPACKET;
8550 ssh->size_needed = FALSE;
8551 ssh->eof_needed = FALSE;
8554 ssh->deferred_send_data = NULL;
8555 ssh->deferred_len = 0;
8556 ssh->deferred_size = 0;
8557 ssh->fallback_cmd = 0;
8559 ssh->x11auth = NULL;
8560 ssh->v1_compressing = FALSE;
8561 ssh->v2_outgoing_sequence = 0;
8562 ssh->ssh1_rdpkt_crstate = 0;
8563 ssh->ssh2_rdpkt_crstate = 0;
8564 ssh->do_ssh_init_crstate = 0;
8565 ssh->ssh_gotdata_crstate = 0;
8566 ssh->do_ssh1_connection_crstate = 0;
8567 ssh->do_ssh1_login_crstate = 0;
8568 ssh->do_ssh2_transport_crstate = 0;
8569 ssh->do_ssh2_authconn_crstate = 0;
8570 ssh->do_ssh_init_state = NULL;
8571 ssh->do_ssh1_login_state = NULL;
8572 ssh->do_ssh2_transport_state = NULL;
8573 ssh->do_ssh2_authconn_state = NULL;
8576 ssh->mainchan = NULL;
8577 ssh->throttled_all = 0;
8578 ssh->v1_stdout_throttling = 0;
8580 ssh->queuelen = ssh->queuesize = 0;
8581 ssh->queueing = FALSE;
8582 ssh->qhead = ssh->qtail = NULL;
8583 ssh->deferred_rekey_reason = NULL;
8584 bufchain_init(&ssh->queued_incoming_data);
8585 ssh->frozen = FALSE;
8587 *backend_handle = ssh;
8590 if (crypto_startup() == 0)
8591 return "Microsoft high encryption pack not installed!";
8594 ssh->frontend = frontend_handle;
8595 ssh->term_width = ssh->cfg.width;
8596 ssh->term_height = ssh->cfg.height;
8598 ssh->channels = NULL;
8599 ssh->rportfwds = NULL;
8600 ssh->portfwds = NULL;
8605 ssh->v1_throttle_count = 0;
8606 ssh->overall_bufsize = 0;
8607 ssh->fallback_cmd = 0;
8609 ssh->protocol = NULL;
8611 ssh->protocol_initial_phase_done = FALSE;
8615 ssh->incoming_data_size = ssh->outgoing_data_size =
8616 ssh->deferred_data_size = 0L;
8617 ssh->max_data_size = parse_blocksize(ssh->cfg.ssh_rekey_data);
8618 ssh->kex_in_progress = FALSE;
8620 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
8629 static void ssh_free(void *handle)
8631 Ssh ssh = (Ssh) handle;
8632 struct ssh_channel *c;
8633 struct ssh_rportfwd *pf;
8635 if (ssh->v1_cipher_ctx)
8636 ssh->cipher->free_context(ssh->v1_cipher_ctx);
8637 if (ssh->cs_cipher_ctx)
8638 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
8639 if (ssh->sc_cipher_ctx)
8640 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
8641 if (ssh->cs_mac_ctx)
8642 ssh->csmac->free_context(ssh->cs_mac_ctx);
8643 if (ssh->sc_mac_ctx)
8644 ssh->scmac->free_context(ssh->sc_mac_ctx);
8645 if (ssh->cs_comp_ctx) {
8647 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
8649 zlib_compress_cleanup(ssh->cs_comp_ctx);
8651 if (ssh->sc_comp_ctx) {
8653 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
8655 zlib_decompress_cleanup(ssh->sc_comp_ctx);
8658 dh_cleanup(ssh->kex_ctx);
8659 sfree(ssh->savedhost);
8661 while (ssh->queuelen-- > 0)
8662 ssh_free_packet(ssh->queue[ssh->queuelen]);
8665 while (ssh->qhead) {
8666 struct queued_handler *qh = ssh->qhead;
8667 ssh->qhead = qh->next;
8670 ssh->qhead = ssh->qtail = NULL;
8672 if (ssh->channels) {
8673 while ((c = delpos234(ssh->channels, 0)) != NULL) {
8676 if (c->u.x11.s != NULL)
8677 x11_close(c->u.x11.s);
8680 if (c->u.pfd.s != NULL)
8681 pfd_close(c->u.pfd.s);
8686 freetree234(ssh->channels);
8687 ssh->channels = NULL;
8690 if (ssh->rportfwds) {
8691 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
8693 freetree234(ssh->rportfwds);
8694 ssh->rportfwds = NULL;
8696 sfree(ssh->deferred_send_data);
8698 x11_free_auth(ssh->x11auth);
8699 sfree(ssh->do_ssh_init_state);
8700 sfree(ssh->do_ssh1_login_state);
8701 sfree(ssh->do_ssh2_transport_state);
8702 sfree(ssh->do_ssh2_authconn_state);
8705 if (ssh->crcda_ctx) {
8706 crcda_free_context(ssh->crcda_ctx);
8707 ssh->crcda_ctx = NULL;
8710 ssh_do_close(ssh, TRUE);
8711 expire_timer_context(ssh);
8713 pinger_free(ssh->pinger);
8714 bufchain_clear(&ssh->queued_incoming_data);
8721 * Reconfigure the SSH backend.
8723 static void ssh_reconfig(void *handle, Config *cfg)
8725 Ssh ssh = (Ssh) handle;
8726 char *rekeying = NULL, rekey_mandatory = FALSE;
8727 unsigned long old_max_data_size;
8729 pinger_reconfig(ssh->pinger, &ssh->cfg, cfg);
8731 ssh_setup_portfwd(ssh, cfg);
8733 if (ssh->cfg.ssh_rekey_time != cfg->ssh_rekey_time &&
8734 cfg->ssh_rekey_time != 0) {
8735 long new_next = ssh->last_rekey + cfg->ssh_rekey_time*60*TICKSPERSEC;
8736 long now = GETTICKCOUNT();
8738 if (new_next - now < 0) {
8739 rekeying = "timeout shortened";
8741 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
8745 old_max_data_size = ssh->max_data_size;
8746 ssh->max_data_size = parse_blocksize(cfg->ssh_rekey_data);
8747 if (old_max_data_size != ssh->max_data_size &&
8748 ssh->max_data_size != 0) {
8749 if (ssh->outgoing_data_size > ssh->max_data_size ||
8750 ssh->incoming_data_size > ssh->max_data_size)
8751 rekeying = "data limit lowered";
8754 if (ssh->cfg.compression != cfg->compression) {
8755 rekeying = "compression setting changed";
8756 rekey_mandatory = TRUE;
8759 if (ssh->cfg.ssh2_des_cbc != cfg->ssh2_des_cbc ||
8760 memcmp(ssh->cfg.ssh_cipherlist, cfg->ssh_cipherlist,
8761 sizeof(ssh->cfg.ssh_cipherlist))) {
8762 rekeying = "cipher settings changed";
8763 rekey_mandatory = TRUE;
8766 ssh->cfg = *cfg; /* STRUCTURE COPY */
8769 if (!ssh->kex_in_progress) {
8770 do_ssh2_transport(ssh, rekeying, -1, NULL);
8771 } else if (rekey_mandatory) {
8772 ssh->deferred_rekey_reason = rekeying;
8778 * Called to send data down the SSH connection.
8780 static int ssh_send(void *handle, char *buf, int len)
8782 Ssh ssh = (Ssh) handle;
8784 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
8787 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
8789 return ssh_sendbuffer(ssh);
8793 * Called to query the current amount of buffered stdin data.
8795 static int ssh_sendbuffer(void *handle)
8797 Ssh ssh = (Ssh) handle;
8800 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
8804 * If the SSH socket itself has backed up, add the total backup
8805 * size on that to any individual buffer on the stdin channel.
8808 if (ssh->throttled_all)
8809 override_value = ssh->overall_bufsize;
8811 if (ssh->version == 1) {
8812 return override_value;
8813 } else if (ssh->version == 2) {
8814 if (!ssh->mainchan || ssh->mainchan->closes > 0)
8815 return override_value;
8817 return (override_value +
8818 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
8825 * Called to set the size of the window from SSH's POV.
8827 static void ssh_size(void *handle, int width, int height)
8829 Ssh ssh = (Ssh) handle;
8830 struct Packet *pktout;
8832 ssh->term_width = width;
8833 ssh->term_height = height;
8835 switch (ssh->state) {
8836 case SSH_STATE_BEFORE_SIZE:
8837 case SSH_STATE_PREPACKET:
8838 case SSH_STATE_CLOSED:
8839 break; /* do nothing */
8840 case SSH_STATE_INTERMED:
8841 ssh->size_needed = TRUE; /* buffer for later */
8843 case SSH_STATE_SESSION:
8844 if (!ssh->cfg.nopty) {
8845 if (ssh->version == 1) {
8846 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
8847 PKT_INT, ssh->term_height,
8848 PKT_INT, ssh->term_width,
8849 PKT_INT, 0, PKT_INT, 0, PKT_END);
8850 } else if (ssh->mainchan) {
8851 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8852 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
8853 ssh2_pkt_addstring(pktout, "window-change");
8854 ssh2_pkt_addbool(pktout, 0);
8855 ssh2_pkt_adduint32(pktout, ssh->term_width);
8856 ssh2_pkt_adduint32(pktout, ssh->term_height);
8857 ssh2_pkt_adduint32(pktout, 0);
8858 ssh2_pkt_adduint32(pktout, 0);
8859 ssh2_pkt_send(ssh, pktout);
8867 * Return a list of the special codes that make sense in this
8870 static const struct telnet_special *ssh_get_specials(void *handle)
8872 static const struct telnet_special ssh1_ignore_special[] = {
8873 {"IGNORE message", TS_NOP}
8875 static const struct telnet_special ssh2_transport_specials[] = {
8876 {"IGNORE message", TS_NOP},
8877 {"Repeat key exchange", TS_REKEY},
8879 static const struct telnet_special ssh2_session_specials[] = {
8882 /* These are the signal names defined by draft-ietf-secsh-connect-23.
8883 * They include all the ISO C signals, but are a subset of the POSIX
8884 * required signals. */
8885 {"SIGINT (Interrupt)", TS_SIGINT},
8886 {"SIGTERM (Terminate)", TS_SIGTERM},
8887 {"SIGKILL (Kill)", TS_SIGKILL},
8888 {"SIGQUIT (Quit)", TS_SIGQUIT},
8889 {"SIGHUP (Hangup)", TS_SIGHUP},
8890 {"More signals", TS_SUBMENU},
8891 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
8892 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
8893 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
8894 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
8897 static const struct telnet_special specials_end[] = {
8900 /* XXX review this length for any changes: */
8901 static struct telnet_special ssh_specials[lenof(ssh2_transport_specials) +
8902 lenof(ssh2_session_specials) +
8903 lenof(specials_end)];
8904 Ssh ssh = (Ssh) handle;
8906 #define ADD_SPECIALS(name) \
8908 assert((i + lenof(name)) <= lenof(ssh_specials)); \
8909 memcpy(&ssh_specials[i], name, sizeof name); \
8913 if (ssh->version == 1) {
8914 /* Don't bother offering IGNORE if we've decided the remote
8915 * won't cope with it, since we wouldn't bother sending it if
8917 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
8918 ADD_SPECIALS(ssh1_ignore_special);
8919 } else if (ssh->version == 2) {
8920 ADD_SPECIALS(ssh2_transport_specials);
8922 ADD_SPECIALS(ssh2_session_specials);
8923 } /* else we're not ready yet */
8926 ADD_SPECIALS(specials_end);
8927 return ssh_specials;
8935 * Send special codes. TS_EOF is useful for `plink', so you
8936 * can send an EOF and collect resulting output (e.g. `plink
8939 static void ssh_special(void *handle, Telnet_Special code)
8941 Ssh ssh = (Ssh) handle;
8942 struct Packet *pktout;
8944 if (code == TS_EOF) {
8945 if (ssh->state != SSH_STATE_SESSION) {
8947 * Buffer the EOF in case we are pre-SESSION, so we can
8948 * send it as soon as we reach SESSION.
8951 ssh->eof_needed = TRUE;
8954 if (ssh->version == 1) {
8955 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
8956 } else if (ssh->mainchan) {
8957 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
8958 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
8959 ssh2_pkt_send(ssh, pktout);
8960 ssh->send_ok = 0; /* now stop trying to read from stdin */
8962 logevent("Sent EOF message");
8963 } else if (code == TS_PING || code == TS_NOP) {
8964 if (ssh->state == SSH_STATE_CLOSED
8965 || ssh->state == SSH_STATE_PREPACKET) return;
8966 if (ssh->version == 1) {
8967 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
8968 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
8970 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
8971 ssh2_pkt_addstring_start(pktout);
8972 ssh2_pkt_send_noqueue(ssh, pktout);
8974 } else if (code == TS_REKEY) {
8975 if (!ssh->kex_in_progress && ssh->version == 2) {
8976 do_ssh2_transport(ssh, "at user request", -1, NULL);
8978 } else if (code == TS_BRK) {
8979 if (ssh->state == SSH_STATE_CLOSED
8980 || ssh->state == SSH_STATE_PREPACKET) return;
8981 if (ssh->version == 1) {
8982 logevent("Unable to send BREAK signal in SSH-1");
8983 } else if (ssh->mainchan) {
8984 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8985 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
8986 ssh2_pkt_addstring(pktout, "break");
8987 ssh2_pkt_addbool(pktout, 0);
8988 ssh2_pkt_adduint32(pktout, 0); /* default break length */
8989 ssh2_pkt_send(ssh, pktout);
8992 /* Is is a POSIX signal? */
8993 char *signame = NULL;
8994 if (code == TS_SIGABRT) signame = "ABRT";
8995 if (code == TS_SIGALRM) signame = "ALRM";
8996 if (code == TS_SIGFPE) signame = "FPE";
8997 if (code == TS_SIGHUP) signame = "HUP";
8998 if (code == TS_SIGILL) signame = "ILL";
8999 if (code == TS_SIGINT) signame = "INT";
9000 if (code == TS_SIGKILL) signame = "KILL";
9001 if (code == TS_SIGPIPE) signame = "PIPE";
9002 if (code == TS_SIGQUIT) signame = "QUIT";
9003 if (code == TS_SIGSEGV) signame = "SEGV";
9004 if (code == TS_SIGTERM) signame = "TERM";
9005 if (code == TS_SIGUSR1) signame = "USR1";
9006 if (code == TS_SIGUSR2) signame = "USR2";
9007 /* The SSH-2 protocol does in principle support arbitrary named
9008 * signals, including signame@domain, but we don't support those. */
9010 /* It's a signal. */
9011 if (ssh->version == 2 && ssh->mainchan) {
9012 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9013 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9014 ssh2_pkt_addstring(pktout, "signal");
9015 ssh2_pkt_addbool(pktout, 0);
9016 ssh2_pkt_addstring(pktout, signame);
9017 ssh2_pkt_send(ssh, pktout);
9018 logeventf(ssh, "Sent signal SIG%s", signame);
9021 /* Never heard of it. Do nothing */
9026 void *new_sock_channel(void *handle, Socket s)
9028 Ssh ssh = (Ssh) handle;
9029 struct ssh_channel *c;
9030 c = snew(struct ssh_channel);
9035 c->localid = alloc_channel_id(ssh);
9037 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
9039 bufchain_init(&c->v.v2.outbuffer);
9040 add234(ssh->channels, c);
9046 * This is called when stdout/stderr (the entity to which
9047 * from_backend sends data) manages to clear some backlog.
9049 static void ssh_unthrottle(void *handle, int bufsize)
9051 Ssh ssh = (Ssh) handle;
9052 if (ssh->version == 1) {
9053 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
9054 ssh->v1_stdout_throttling = 0;
9055 ssh1_throttle(ssh, -1);
9058 ssh2_set_window(ssh->mainchan, OUR_V2_WINSIZE - bufsize);
9062 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
9064 struct ssh_channel *c = (struct ssh_channel *)channel;
9066 struct Packet *pktout;
9068 logeventf(ssh, "Opening forwarded connection to %s:%d", hostname, port);
9070 if (ssh->version == 1) {
9071 send_packet(ssh, SSH1_MSG_PORT_OPEN,
9072 PKT_INT, c->localid,
9075 /* PKT_STR, <org:orgport>, */
9078 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
9079 ssh2_pkt_addstring(pktout, "direct-tcpip");
9080 ssh2_pkt_adduint32(pktout, c->localid);
9081 c->v.v2.locwindow = OUR_V2_WINSIZE;
9082 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
9083 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
9084 ssh2_pkt_addstring(pktout, hostname);
9085 ssh2_pkt_adduint32(pktout, port);
9087 * We make up values for the originator data; partly it's
9088 * too much hassle to keep track, and partly I'm not
9089 * convinced the server should be told details like that
9090 * about my local network configuration.
9091 * The "originator IP address" is syntactically a numeric
9092 * IP address, and some servers (e.g., Tectia) get upset
9093 * if it doesn't match this syntax.
9095 ssh2_pkt_addstring(pktout, "0.0.0.0");
9096 ssh2_pkt_adduint32(pktout, 0);
9097 ssh2_pkt_send(ssh, pktout);
9101 static int ssh_connected(void *handle)
9103 Ssh ssh = (Ssh) handle;
9104 return ssh->s != NULL;
9107 static int ssh_sendok(void *handle)
9109 Ssh ssh = (Ssh) handle;
9110 return ssh->send_ok;
9113 static int ssh_ldisc(void *handle, int option)
9115 Ssh ssh = (Ssh) handle;
9116 if (option == LD_ECHO)
9117 return ssh->echoing;
9118 if (option == LD_EDIT)
9119 return ssh->editing;
9123 static void ssh_provide_ldisc(void *handle, void *ldisc)
9125 Ssh ssh = (Ssh) handle;
9129 static void ssh_provide_logctx(void *handle, void *logctx)
9131 Ssh ssh = (Ssh) handle;
9132 ssh->logctx = logctx;
9135 static int ssh_return_exitcode(void *handle)
9137 Ssh ssh = (Ssh) handle;
9141 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
9145 * cfg_info for SSH is the currently running version of the
9146 * protocol. (1 for 1; 2 for 2; 0 for not-decided-yet.)
9148 static int ssh_cfg_info(void *handle)
9150 Ssh ssh = (Ssh) handle;
9151 return ssh->version;
9155 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
9156 * that fails. This variable is the means by which scp.c can reach
9157 * into the SSH code and find out which one it got.
9159 extern int ssh_fallback_cmd(void *handle)
9161 Ssh ssh = (Ssh) handle;
9162 return ssh->fallback_cmd;
9165 Backend ssh_backend = {
9175 ssh_return_exitcode,