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.
124 SSH2_PKTCTX_PUBLICKEY,
125 SSH2_PKTCTX_PASSWORD,
129 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
130 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
131 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
132 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
133 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
134 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
135 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
136 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
137 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
138 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
139 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
140 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
141 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
142 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
143 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
145 static const char *const ssh2_disconnect_reasons[] = {
147 "host not allowed to connect",
149 "key exchange failed",
150 "host authentication failed",
153 "service not available",
154 "protocol version not supported",
155 "host key not verifiable",
158 "too many connections",
159 "auth cancelled by user",
160 "no more auth methods available",
164 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
165 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
166 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
167 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
169 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
172 * Various remote-bug flags.
174 #define BUG_CHOKES_ON_SSH1_IGNORE 1
175 #define BUG_SSH2_HMAC 2
176 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
177 #define BUG_CHOKES_ON_RSA 8
178 #define BUG_SSH2_RSA_PADDING 16
179 #define BUG_SSH2_DERIVEKEY 32
180 #define BUG_SSH2_REKEY 64
181 #define BUG_SSH2_PK_SESSIONID 128
184 * Codes for terminal modes.
185 * Most of these are the same in SSH-1 and SSH-2.
186 * This list is derived from draft-ietf-secsh-connect-25 and
189 static const struct {
190 const char* const mode;
192 enum { TTY_OP_CHAR, TTY_OP_BOOL } type;
194 /* "V" prefix discarded for special characters relative to SSH specs */
195 { "INTR", 1, TTY_OP_CHAR },
196 { "QUIT", 2, TTY_OP_CHAR },
197 { "ERASE", 3, TTY_OP_CHAR },
198 { "KILL", 4, TTY_OP_CHAR },
199 { "EOF", 5, TTY_OP_CHAR },
200 { "EOL", 6, TTY_OP_CHAR },
201 { "EOL2", 7, TTY_OP_CHAR },
202 { "START", 8, TTY_OP_CHAR },
203 { "STOP", 9, TTY_OP_CHAR },
204 { "SUSP", 10, TTY_OP_CHAR },
205 { "DSUSP", 11, TTY_OP_CHAR },
206 { "REPRINT", 12, TTY_OP_CHAR },
207 { "WERASE", 13, TTY_OP_CHAR },
208 { "LNEXT", 14, TTY_OP_CHAR },
209 { "FLUSH", 15, TTY_OP_CHAR },
210 { "SWTCH", 16, TTY_OP_CHAR },
211 { "STATUS", 17, TTY_OP_CHAR },
212 { "DISCARD", 18, TTY_OP_CHAR },
213 { "IGNPAR", 30, TTY_OP_BOOL },
214 { "PARMRK", 31, TTY_OP_BOOL },
215 { "INPCK", 32, TTY_OP_BOOL },
216 { "ISTRIP", 33, TTY_OP_BOOL },
217 { "INLCR", 34, TTY_OP_BOOL },
218 { "IGNCR", 35, TTY_OP_BOOL },
219 { "ICRNL", 36, TTY_OP_BOOL },
220 { "IUCLC", 37, TTY_OP_BOOL },
221 { "IXON", 38, TTY_OP_BOOL },
222 { "IXANY", 39, TTY_OP_BOOL },
223 { "IXOFF", 40, TTY_OP_BOOL },
224 { "IMAXBEL", 41, TTY_OP_BOOL },
225 { "ISIG", 50, TTY_OP_BOOL },
226 { "ICANON", 51, TTY_OP_BOOL },
227 { "XCASE", 52, TTY_OP_BOOL },
228 { "ECHO", 53, TTY_OP_BOOL },
229 { "ECHOE", 54, TTY_OP_BOOL },
230 { "ECHOK", 55, TTY_OP_BOOL },
231 { "ECHONL", 56, TTY_OP_BOOL },
232 { "NOFLSH", 57, TTY_OP_BOOL },
233 { "TOSTOP", 58, TTY_OP_BOOL },
234 { "IEXTEN", 59, TTY_OP_BOOL },
235 { "ECHOCTL", 60, TTY_OP_BOOL },
236 { "ECHOKE", 61, TTY_OP_BOOL },
237 { "PENDIN", 62, TTY_OP_BOOL }, /* XXX is this a real mode? */
238 { "OPOST", 70, TTY_OP_BOOL },
239 { "OLCUC", 71, TTY_OP_BOOL },
240 { "ONLCR", 72, TTY_OP_BOOL },
241 { "OCRNL", 73, TTY_OP_BOOL },
242 { "ONOCR", 74, TTY_OP_BOOL },
243 { "ONLRET", 75, TTY_OP_BOOL },
244 { "CS7", 90, TTY_OP_BOOL },
245 { "CS8", 91, TTY_OP_BOOL },
246 { "PARENB", 92, TTY_OP_BOOL },
247 { "PARODD", 93, TTY_OP_BOOL }
250 /* Miscellaneous other tty-related constants. */
251 #define SSH_TTY_OP_END 0
252 /* The opcodes for ISPEED/OSPEED differ between SSH-1 and SSH-2. */
253 #define SSH1_TTY_OP_ISPEED 192
254 #define SSH1_TTY_OP_OSPEED 193
255 #define SSH2_TTY_OP_ISPEED 128
256 #define SSH2_TTY_OP_OSPEED 129
258 /* Helper functions for parsing tty-related config. */
259 static unsigned int ssh_tty_parse_specchar(char *s)
264 ret = ctrlparse(s, &next);
265 if (!next) ret = s[0];
267 ret = 255; /* special value meaning "don't set" */
271 static unsigned int ssh_tty_parse_boolean(char *s)
273 if (stricmp(s, "yes") == 0 ||
274 stricmp(s, "on") == 0 ||
275 stricmp(s, "true") == 0 ||
276 stricmp(s, "+") == 0)
278 else if (stricmp(s, "no") == 0 ||
279 stricmp(s, "off") == 0 ||
280 stricmp(s, "false") == 0 ||
281 stricmp(s, "-") == 0)
282 return 0; /* false */
284 return (atoi(s) != 0);
287 #define translate(x) if (type == x) return #x
288 #define translatek(x,ctx) if (type == x && (pkt_kctx == ctx)) return #x
289 #define translatea(x,ctx) if (type == x && (pkt_actx == ctx)) return #x
290 static char *ssh1_pkt_type(int type)
292 translate(SSH1_MSG_DISCONNECT);
293 translate(SSH1_SMSG_PUBLIC_KEY);
294 translate(SSH1_CMSG_SESSION_KEY);
295 translate(SSH1_CMSG_USER);
296 translate(SSH1_CMSG_AUTH_RSA);
297 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
298 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
299 translate(SSH1_CMSG_AUTH_PASSWORD);
300 translate(SSH1_CMSG_REQUEST_PTY);
301 translate(SSH1_CMSG_WINDOW_SIZE);
302 translate(SSH1_CMSG_EXEC_SHELL);
303 translate(SSH1_CMSG_EXEC_CMD);
304 translate(SSH1_SMSG_SUCCESS);
305 translate(SSH1_SMSG_FAILURE);
306 translate(SSH1_CMSG_STDIN_DATA);
307 translate(SSH1_SMSG_STDOUT_DATA);
308 translate(SSH1_SMSG_STDERR_DATA);
309 translate(SSH1_CMSG_EOF);
310 translate(SSH1_SMSG_EXIT_STATUS);
311 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
312 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
313 translate(SSH1_MSG_CHANNEL_DATA);
314 translate(SSH1_MSG_CHANNEL_CLOSE);
315 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
316 translate(SSH1_SMSG_X11_OPEN);
317 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
318 translate(SSH1_MSG_PORT_OPEN);
319 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
320 translate(SSH1_SMSG_AGENT_OPEN);
321 translate(SSH1_MSG_IGNORE);
322 translate(SSH1_CMSG_EXIT_CONFIRMATION);
323 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
324 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
325 translate(SSH1_MSG_DEBUG);
326 translate(SSH1_CMSG_REQUEST_COMPRESSION);
327 translate(SSH1_CMSG_AUTH_TIS);
328 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
329 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
330 translate(SSH1_CMSG_AUTH_CCARD);
331 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
332 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
335 static char *ssh2_pkt_type(Pkt_KCtx pkt_kctx, Pkt_ACtx pkt_actx, int type)
337 translate(SSH2_MSG_DISCONNECT);
338 translate(SSH2_MSG_IGNORE);
339 translate(SSH2_MSG_UNIMPLEMENTED);
340 translate(SSH2_MSG_DEBUG);
341 translate(SSH2_MSG_SERVICE_REQUEST);
342 translate(SSH2_MSG_SERVICE_ACCEPT);
343 translate(SSH2_MSG_KEXINIT);
344 translate(SSH2_MSG_NEWKEYS);
345 translatek(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP);
346 translatek(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP);
347 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
348 translatek(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
349 translatek(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
350 translatek(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
351 translatek(SSH2_MSG_KEXRSA_PUBKEY, SSH2_PKTCTX_RSAKEX);
352 translatek(SSH2_MSG_KEXRSA_SECRET, SSH2_PKTCTX_RSAKEX);
353 translatek(SSH2_MSG_KEXRSA_DONE, SSH2_PKTCTX_RSAKEX);
354 translate(SSH2_MSG_USERAUTH_REQUEST);
355 translate(SSH2_MSG_USERAUTH_FAILURE);
356 translate(SSH2_MSG_USERAUTH_SUCCESS);
357 translate(SSH2_MSG_USERAUTH_BANNER);
358 translatea(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
359 translatea(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
360 translatea(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
361 translatea(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
362 translate(SSH2_MSG_GLOBAL_REQUEST);
363 translate(SSH2_MSG_REQUEST_SUCCESS);
364 translate(SSH2_MSG_REQUEST_FAILURE);
365 translate(SSH2_MSG_CHANNEL_OPEN);
366 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
367 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
368 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
369 translate(SSH2_MSG_CHANNEL_DATA);
370 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
371 translate(SSH2_MSG_CHANNEL_EOF);
372 translate(SSH2_MSG_CHANNEL_CLOSE);
373 translate(SSH2_MSG_CHANNEL_REQUEST);
374 translate(SSH2_MSG_CHANNEL_SUCCESS);
375 translate(SSH2_MSG_CHANNEL_FAILURE);
381 /* Enumeration values for fields in SSH-1 packets */
383 PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
384 /* These values are for communicating relevant semantics of
385 * fields to the packet logging code. */
386 PKTT_OTHER, PKTT_PASSWORD, PKTT_DATA
390 * Coroutine mechanics for the sillier bits of the code. If these
391 * macros look impenetrable to you, you might find it helpful to
394 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
396 * which explains the theory behind these macros.
398 * In particular, if you are getting `case expression not constant'
399 * errors when building with MS Visual Studio, this is because MS's
400 * Edit and Continue debugging feature causes their compiler to
401 * violate ANSI C. To disable Edit and Continue debugging:
403 * - right-click ssh.c in the FileView
405 * - select the C/C++ tab and the General category
406 * - under `Debug info:', select anything _other_ than `Program
407 * Database for Edit and Continue'.
409 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
412 if (!ssh->t) ssh->t = snew(struct t); \
414 #define crFinish(z) } *crLine = 0; return (z); }
415 #define crFinishV } *crLine = 0; return; }
416 #define crReturn(z) \
418 *crLine =__LINE__; return (z); case __LINE__:;\
422 *crLine=__LINE__; return; case __LINE__:;\
424 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
425 #define crStopV do{ *crLine = 0; return; }while(0)
426 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
427 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
429 typedef struct ssh_tag *Ssh;
432 static struct Packet *ssh1_pkt_init(int pkt_type);
433 static struct Packet *ssh2_pkt_init(int pkt_type);
434 static void ssh_pkt_ensure(struct Packet *, int length);
435 static void ssh_pkt_adddata(struct Packet *, void *data, int len);
436 static void ssh_pkt_addbyte(struct Packet *, unsigned char value);
437 static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
438 static void ssh_pkt_adduint32(struct Packet *, unsigned long value);
439 static void ssh_pkt_addstring_start(struct Packet *);
440 static void ssh_pkt_addstring_str(struct Packet *, char *data);
441 static void ssh_pkt_addstring_data(struct Packet *, char *data, int len);
442 static void ssh_pkt_addstring(struct Packet *, char *data);
443 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
444 static void ssh1_pkt_addmp(struct Packet *, Bignum b);
445 static void ssh2_pkt_addmp(struct Packet *, Bignum b);
446 static int ssh2_pkt_construct(Ssh, struct Packet *);
447 static void ssh2_pkt_send(Ssh, struct Packet *);
448 static void ssh2_pkt_send_noqueue(Ssh, struct Packet *);
449 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
450 struct Packet *pktin);
451 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
452 struct Packet *pktin);
455 * Buffer management constants. There are several of these for
456 * various different purposes:
458 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
459 * on a local data stream before we throttle the whole SSH
460 * connection (in SSH-1 only). Throttling the whole connection is
461 * pretty drastic so we set this high in the hope it won't
464 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
465 * on the SSH connection itself before we defensively throttle
466 * _all_ local data streams. This is pretty drastic too (though
467 * thankfully unlikely in SSH-2 since the window mechanism should
468 * ensure that the server never has any need to throttle its end
469 * of the connection), so we set this high as well.
471 * - OUR_V2_WINSIZE is the maximum window size we present on SSH-2
474 * - OUR_V2_BIGWIN is the window size we advertise for the only
475 * channel in a simple connection. It must be <= INT_MAX.
478 #define SSH1_BUFFER_LIMIT 32768
479 #define SSH_MAX_BACKLOG 32768
480 #define OUR_V2_WINSIZE 16384
481 #define OUR_V2_BIGWIN 0x7fffffff
482 #define OUR_V2_MAXPKT 0x4000UL
484 /* Maximum length of passwords/passphrases (arbitrary) */
485 #define SSH_MAX_PASSWORD_LEN 100
487 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
489 const static struct ssh_mac *macs[] = {
490 &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
492 const static struct ssh_mac *buggymacs[] = {
493 &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
496 static void *ssh_comp_none_init(void)
500 static void ssh_comp_none_cleanup(void *handle)
503 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
504 unsigned char **outblock, int *outlen)
508 static int ssh_comp_none_disable(void *handle)
512 const static struct ssh_compress ssh_comp_none = {
514 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
515 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
516 ssh_comp_none_disable, NULL
518 extern const struct ssh_compress ssh_zlib;
519 const static struct ssh_compress *compressions[] = {
520 &ssh_zlib, &ssh_comp_none
523 enum { /* channel types */
528 CHAN_SOCKDATA_DORMANT /* one the remote hasn't confirmed */
532 * 2-3-4 tree storing channels.
535 Ssh ssh; /* pointer back to main context */
536 unsigned remoteid, localid;
538 /* True if we opened this channel but server hasn't confirmed. */
541 * In SSH-1, this value contains four bits:
543 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
544 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
545 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
546 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
548 * A channel is completely finished with when all four bits are set.
552 struct ssh1_data_channel {
555 struct ssh2_data_channel {
557 unsigned remwindow, remmaxpkt;
558 /* locwindow is signed so we can cope with excess data. */
559 int locwindow, locmaxwin;
563 struct ssh_agent_channel {
564 unsigned char *message;
565 unsigned char msglen[4];
566 unsigned lensofar, totallen;
568 struct ssh_x11_channel {
571 struct ssh_pfd_channel {
578 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
579 * use this structure in different ways, reflecting SSH-2's
580 * altogether saner approach to port forwarding.
582 * In SSH-1, you arrange a remote forwarding by sending the server
583 * the remote port number, and the local destination host:port.
584 * When a connection comes in, the server sends you back that
585 * host:port pair, and you connect to it. This is a ready-made
586 * security hole if you're not on the ball: a malicious server
587 * could send you back _any_ host:port pair, so if you trustingly
588 * connect to the address it gives you then you've just opened the
589 * entire inside of your corporate network just by connecting
590 * through it to a dodgy SSH server. Hence, we must store a list of
591 * host:port pairs we _are_ trying to forward to, and reject a
592 * connection request from the server if it's not in the list.
594 * In SSH-2, each side of the connection minds its own business and
595 * doesn't send unnecessary information to the other. You arrange a
596 * remote forwarding by sending the server just the remote port
597 * number. When a connection comes in, the server tells you which
598 * of its ports was connected to; and _you_ have to remember what
599 * local host:port pair went with that port number.
601 * Hence, in SSH-1 this structure is indexed by destination
602 * host:port pair, whereas in SSH-2 it is indexed by source port.
604 struct ssh_portfwd; /* forward declaration */
606 struct ssh_rportfwd {
607 unsigned sport, dport;
610 struct ssh_portfwd *pfrec;
612 #define free_rportfwd(pf) ( \
613 ((pf) ? (sfree((pf)->sportdesc)) : (void)0 ), sfree(pf) )
616 * Separately to the rportfwd tree (which is for looking up port
617 * open requests from the server), a tree of _these_ structures is
618 * used to keep track of all the currently open port forwardings,
619 * so that we can reconfigure in mid-session if the user requests
623 enum { DESTROY, KEEP, CREATE } status;
625 unsigned sport, dport;
628 struct ssh_rportfwd *remote;
632 #define free_portfwd(pf) ( \
633 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
634 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
637 long length; /* length of `data' actually used */
638 long forcepad; /* SSH-2: force padding to at least this length */
639 int type; /* only used for incoming packets */
640 unsigned long sequence; /* SSH-2 incoming sequence number */
641 unsigned char *data; /* allocated storage */
642 unsigned char *body; /* offset of payload within `data' */
643 long savedpos; /* temporary index into `data' (for strings) */
644 long maxlen; /* amount of storage allocated for `data' */
645 long encrypted_len; /* for SSH-2 total-size counting */
648 * State associated with packet logging
652 struct logblank_t *blanks;
655 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
656 struct Packet *pktin);
657 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
658 struct Packet *pktin);
659 static void ssh1_protocol_setup(Ssh ssh);
660 static void ssh2_protocol_setup(Ssh ssh);
661 static void ssh_size(void *handle, int width, int height);
662 static void ssh_special(void *handle, Telnet_Special);
663 static int ssh2_try_send(struct ssh_channel *c);
664 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
665 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
666 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin);
667 static int ssh_sendbuffer(void *handle);
668 static int ssh_do_close(Ssh ssh, int notify_exit);
669 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
670 static int ssh2_pkt_getbool(struct Packet *pkt);
671 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
672 static void ssh2_timer(void *ctx, long now);
673 static int do_ssh2_transport(Ssh ssh, void *vin, int inlen,
674 struct Packet *pktin);
676 struct rdpkt1_state_tag {
677 long len, pad, biglen, to_read;
678 unsigned long realcrc, gotcrc;
682 struct Packet *pktin;
685 struct rdpkt2_state_tag {
686 long len, pad, payload, packetlen, maclen;
689 unsigned long incoming_sequence;
690 struct Packet *pktin;
693 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
694 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
696 struct queued_handler;
697 struct queued_handler {
699 chandler_fn_t handler;
701 struct queued_handler *next;
705 const struct plug_function_table *fn;
706 /* the above field _must_ be first in the structure */
716 unsigned char session_key[32];
718 int v1_remote_protoflags;
719 int v1_local_protoflags;
720 int agentfwd_enabled;
723 const struct ssh_cipher *cipher;
726 const struct ssh2_cipher *cscipher, *sccipher;
727 void *cs_cipher_ctx, *sc_cipher_ctx;
728 const struct ssh_mac *csmac, *scmac;
729 void *cs_mac_ctx, *sc_mac_ctx;
730 const struct ssh_compress *cscomp, *sccomp;
731 void *cs_comp_ctx, *sc_comp_ctx;
732 const struct ssh_kex *kex;
733 const struct ssh_signkey *hostkey;
734 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
735 int v2_session_id_len;
741 int echoing, editing;
745 int ospeed, ispeed; /* temporaries */
746 int term_width, term_height;
748 tree234 *channels; /* indexed by local id */
749 struct ssh_channel *mainchan; /* primary session channel */
750 int ncmode; /* is primary channel direct-tcpip? */
755 tree234 *rportfwds, *portfwds;
759 SSH_STATE_BEFORE_SIZE,
765 int size_needed, eof_needed;
767 struct Packet **queue;
768 int queuelen, queuesize;
770 unsigned char *deferred_send_data;
771 int deferred_len, deferred_size;
774 * Gross hack: pscp will try to start SFTP but fall back to
775 * scp1 if that fails. This variable is the means by which
776 * scp.c can reach into the SSH code and find out which one it
781 bufchain banner; /* accumulates banners during do_ssh2_authconn */
789 int v1_throttle_count;
792 int v1_stdout_throttling;
793 unsigned long v2_outgoing_sequence;
795 int ssh1_rdpkt_crstate;
796 int ssh2_rdpkt_crstate;
797 int do_ssh_init_crstate;
798 int ssh_gotdata_crstate;
799 int do_ssh1_login_crstate;
800 int do_ssh1_connection_crstate;
801 int do_ssh2_transport_crstate;
802 int do_ssh2_authconn_crstate;
804 void *do_ssh_init_state;
805 void *do_ssh1_login_state;
806 void *do_ssh2_transport_state;
807 void *do_ssh2_authconn_state;
809 struct rdpkt1_state_tag rdpkt1_state;
810 struct rdpkt2_state_tag rdpkt2_state;
812 /* SSH-1 and SSH-2 use this for different things, but both use it */
813 int protocol_initial_phase_done;
815 void (*protocol) (Ssh ssh, void *vin, int inlen,
817 struct Packet *(*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
820 * We maintain a full _copy_ of a Config structure here, not
821 * merely a pointer to it. That way, when we're passed a new
822 * one for reconfiguration, we can check the differences and
823 * potentially reconfigure port forwardings etc in mid-session.
828 * Used to transfer data back from async callbacks.
830 void *agent_response;
831 int agent_response_len;
835 * The SSH connection can be set as `frozen', meaning we are
836 * not currently accepting incoming data from the network. This
837 * is slightly more serious than setting the _socket_ as
838 * frozen, because we may already have had data passed to us
839 * from the network which we need to delay processing until
840 * after the freeze is lifted, so we also need a bufchain to
844 bufchain queued_incoming_data;
847 * Dispatch table for packet types that we may have to deal
850 handler_fn_t packet_dispatch[256];
853 * Queues of one-off handler functions for success/failure
854 * indications from a request.
856 struct queued_handler *qhead, *qtail;
859 * This module deals with sending keepalives.
864 * Track incoming and outgoing data sizes and time, for
867 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
868 unsigned long max_data_size;
870 long next_rekey, last_rekey;
871 char *deferred_rekey_reason; /* points to STATIC string; don't free */
874 #define logevent(s) logevent(ssh->frontend, s)
876 /* logevent, only printf-formatted. */
877 static void logeventf(Ssh ssh, const char *fmt, ...)
883 buf = dupvprintf(fmt, ap);
889 #define bombout(msg) \
891 char *text = dupprintf msg; \
892 ssh_do_close(ssh, FALSE); \
894 connection_fatal(ssh->frontend, "%s", text); \
898 /* Functions to leave bits out of the SSH packet log file. */
900 static void dont_log_password(Ssh ssh, struct Packet *pkt, int blanktype)
902 if (ssh->cfg.logomitpass)
903 pkt->logmode = blanktype;
906 static void dont_log_data(Ssh ssh, struct Packet *pkt, int blanktype)
908 if (ssh->cfg.logomitdata)
909 pkt->logmode = blanktype;
912 static void end_log_omission(Ssh ssh, struct Packet *pkt)
914 pkt->logmode = PKTLOG_EMIT;
917 /* Helper function for common bits of parsing cfg.ttymodes. */
918 static void parse_ttymodes(Ssh ssh, char *modes,
919 void (*do_mode)(void *data, char *mode, char *val),
923 char *t = strchr(modes, '\t');
924 char *m = snewn(t-modes+1, char);
926 strncpy(m, modes, t-modes);
929 val = get_ttymode(ssh->frontend, m);
933 do_mode(data, m, val);
936 modes += strlen(modes) + 1;
940 static int ssh_channelcmp(void *av, void *bv)
942 struct ssh_channel *a = (struct ssh_channel *) av;
943 struct ssh_channel *b = (struct ssh_channel *) bv;
944 if (a->localid < b->localid)
946 if (a->localid > b->localid)
950 static int ssh_channelfind(void *av, void *bv)
952 unsigned *a = (unsigned *) av;
953 struct ssh_channel *b = (struct ssh_channel *) bv;
961 static int ssh_rportcmp_ssh1(void *av, void *bv)
963 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
964 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
966 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
967 return i < 0 ? -1 : +1;
968 if (a->dport > b->dport)
970 if (a->dport < b->dport)
975 static int ssh_rportcmp_ssh2(void *av, void *bv)
977 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
978 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
980 if (a->sport > b->sport)
982 if (a->sport < b->sport)
988 * Special form of strcmp which can cope with NULL inputs. NULL is
989 * defined to sort before even the empty string.
991 static int nullstrcmp(const char *a, const char *b)
993 if (a == NULL && b == NULL)
1002 static int ssh_portcmp(void *av, void *bv)
1004 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1005 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1007 if (a->type > b->type)
1009 if (a->type < b->type)
1011 if (a->addressfamily > b->addressfamily)
1013 if (a->addressfamily < b->addressfamily)
1015 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1016 return i < 0 ? -1 : +1;
1017 if (a->sport > b->sport)
1019 if (a->sport < b->sport)
1021 if (a->type != 'D') {
1022 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1023 return i < 0 ? -1 : +1;
1024 if (a->dport > b->dport)
1026 if (a->dport < b->dport)
1032 static int alloc_channel_id(Ssh ssh)
1034 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1035 unsigned low, high, mid;
1037 struct ssh_channel *c;
1040 * First-fit allocation of channel numbers: always pick the
1041 * lowest unused one. To do this, binary-search using the
1042 * counted B-tree to find the largest channel ID which is in a
1043 * contiguous sequence from the beginning. (Precisely
1044 * everything in that sequence must have ID equal to its tree
1045 * index plus CHANNEL_NUMBER_OFFSET.)
1047 tsize = count234(ssh->channels);
1051 while (high - low > 1) {
1052 mid = (high + low) / 2;
1053 c = index234(ssh->channels, mid);
1054 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1055 low = mid; /* this one is fine */
1057 high = mid; /* this one is past it */
1060 * Now low points to either -1, or the tree index of the
1061 * largest ID in the initial sequence.
1064 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1065 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1067 return low + 1 + CHANNEL_NUMBER_OFFSET;
1070 static void c_write_stderr(int trusted, const char *buf, int len)
1073 for (i = 0; i < len; i++)
1074 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1075 fputc(buf[i], stderr);
1078 static void c_write(Ssh ssh, const char *buf, int len)
1080 if (flags & FLAG_STDERR)
1081 c_write_stderr(1, buf, len);
1083 from_backend(ssh->frontend, 1, buf, len);
1086 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1088 if (flags & FLAG_STDERR)
1089 c_write_stderr(0, buf, len);
1091 from_backend_untrusted(ssh->frontend, buf, len);
1094 static void c_write_str(Ssh ssh, const char *buf)
1096 c_write(ssh, buf, strlen(buf));
1099 static void ssh_free_packet(struct Packet *pkt)
1104 static struct Packet *ssh_new_packet(void)
1106 struct Packet *pkt = snew(struct Packet);
1108 pkt->body = pkt->data = NULL;
1110 pkt->logmode = PKTLOG_EMIT;
1118 * Collect incoming data in the incoming packet buffer.
1119 * Decipher and verify the packet when it is completely read.
1120 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1121 * Update the *data and *datalen variables.
1122 * Return a Packet structure when a packet is completed.
1124 static struct Packet *ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1126 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1128 crBegin(ssh->ssh1_rdpkt_crstate);
1130 st->pktin = ssh_new_packet();
1132 st->pktin->type = 0;
1133 st->pktin->length = 0;
1135 for (st->i = st->len = 0; st->i < 4; st->i++) {
1136 while ((*datalen) == 0)
1138 st->len = (st->len << 8) + **data;
1139 (*data)++, (*datalen)--;
1142 st->pad = 8 - (st->len % 8);
1143 st->biglen = st->len + st->pad;
1144 st->pktin->length = st->len - 5;
1146 if (st->biglen < 0) {
1147 bombout(("Extremely large packet length from server suggests"
1148 " data stream corruption"));
1149 ssh_free_packet(st->pktin);
1153 st->pktin->maxlen = st->biglen;
1154 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1156 st->to_read = st->biglen;
1157 st->p = st->pktin->data;
1158 while (st->to_read > 0) {
1159 st->chunk = st->to_read;
1160 while ((*datalen) == 0)
1162 if (st->chunk > (*datalen))
1163 st->chunk = (*datalen);
1164 memcpy(st->p, *data, st->chunk);
1166 *datalen -= st->chunk;
1168 st->to_read -= st->chunk;
1171 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1172 st->biglen, NULL)) {
1173 bombout(("Network attack (CRC compensation) detected!"));
1174 ssh_free_packet(st->pktin);
1179 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1181 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1182 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1183 if (st->gotcrc != st->realcrc) {
1184 bombout(("Incorrect CRC received on packet"));
1185 ssh_free_packet(st->pktin);
1189 st->pktin->body = st->pktin->data + st->pad + 1;
1190 st->pktin->savedpos = 0;
1192 if (ssh->v1_compressing) {
1193 unsigned char *decompblk;
1195 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1196 st->pktin->body - 1, st->pktin->length + 1,
1197 &decompblk, &decomplen)) {
1198 bombout(("Zlib decompression encountered invalid data"));
1199 ssh_free_packet(st->pktin);
1203 if (st->pktin->maxlen < st->pad + decomplen) {
1204 st->pktin->maxlen = st->pad + decomplen;
1205 st->pktin->data = sresize(st->pktin->data,
1206 st->pktin->maxlen + APIEXTRA,
1208 st->pktin->body = st->pktin->data + st->pad + 1;
1211 memcpy(st->pktin->body - 1, decompblk, decomplen);
1213 st->pktin->length = decomplen - 1;
1216 st->pktin->type = st->pktin->body[-1];
1219 * Log incoming packet, possibly omitting sensitive fields.
1223 struct logblank_t blank;
1224 if (ssh->cfg.logomitdata) {
1225 int do_blank = FALSE, blank_prefix = 0;
1226 /* "Session data" packets - omit the data field */
1227 if ((st->pktin->type == SSH1_SMSG_STDOUT_DATA) ||
1228 (st->pktin->type == SSH1_SMSG_STDERR_DATA)) {
1229 do_blank = TRUE; blank_prefix = 4;
1230 } else if (st->pktin->type == SSH1_MSG_CHANNEL_DATA) {
1231 do_blank = TRUE; blank_prefix = 8;
1234 blank.offset = blank_prefix;
1235 blank.len = st->pktin->length;
1236 blank.type = PKTLOG_OMIT;
1240 log_packet(ssh->logctx,
1241 PKT_INCOMING, st->pktin->type,
1242 ssh1_pkt_type(st->pktin->type),
1243 st->pktin->body, st->pktin->length,
1247 crFinish(st->pktin);
1250 static struct Packet *ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1252 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1254 crBegin(ssh->ssh2_rdpkt_crstate);
1256 st->pktin = ssh_new_packet();
1258 st->pktin->type = 0;
1259 st->pktin->length = 0;
1261 st->cipherblk = ssh->sccipher->blksize;
1264 if (st->cipherblk < 8)
1267 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1270 * Acquire and decrypt the first block of the packet. This will
1271 * contain the length and padding details.
1273 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1274 while ((*datalen) == 0)
1276 st->pktin->data[st->i] = *(*data)++;
1281 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1282 st->pktin->data, st->cipherblk);
1285 * Now get the length and padding figures.
1287 st->len = GET_32BIT(st->pktin->data);
1288 st->pad = st->pktin->data[4];
1291 * _Completely_ silly lengths should be stomped on before they
1292 * do us any more damage.
1294 if (st->len < 0 || st->len > 35000 || st->pad < 4 ||
1295 st->len - st->pad < 1 || (st->len + 4) % st->cipherblk != 0) {
1296 bombout(("Incoming packet was garbled on decryption"));
1297 ssh_free_packet(st->pktin);
1302 * This enables us to deduce the payload length.
1304 st->payload = st->len - st->pad - 1;
1306 st->pktin->length = st->payload + 5;
1309 * So now we can work out the total packet length.
1311 st->packetlen = st->len + 4;
1312 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1315 * Allocate memory for the rest of the packet.
1317 st->pktin->maxlen = st->packetlen + st->maclen;
1318 st->pktin->data = sresize(st->pktin->data,
1319 st->pktin->maxlen + APIEXTRA,
1323 * Read and decrypt the remainder of the packet.
1325 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1327 while ((*datalen) == 0)
1329 st->pktin->data[st->i] = *(*data)++;
1332 /* Decrypt everything _except_ the MAC. */
1334 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1335 st->pktin->data + st->cipherblk,
1336 st->packetlen - st->cipherblk);
1338 st->pktin->encrypted_len = st->packetlen;
1344 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data, st->len + 4,
1345 st->incoming_sequence)) {
1346 bombout(("Incorrect MAC received on packet"));
1347 ssh_free_packet(st->pktin);
1351 st->pktin->sequence = st->incoming_sequence++;
1354 * Decompress packet payload.
1357 unsigned char *newpayload;
1360 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1361 st->pktin->data + 5, st->pktin->length - 5,
1362 &newpayload, &newlen)) {
1363 if (st->pktin->maxlen < newlen + 5) {
1364 st->pktin->maxlen = newlen + 5;
1365 st->pktin->data = sresize(st->pktin->data,
1366 st->pktin->maxlen + APIEXTRA,
1369 st->pktin->length = 5 + newlen;
1370 memcpy(st->pktin->data + 5, newpayload, newlen);
1375 st->pktin->savedpos = 6;
1376 st->pktin->body = st->pktin->data;
1377 st->pktin->type = st->pktin->data[5];
1380 * Log incoming packet, possibly omitting sensitive fields.
1384 struct logblank_t blank;
1385 if (ssh->cfg.logomitdata) {
1386 int do_blank = FALSE, blank_prefix = 0;
1387 /* "Session data" packets - omit the data field */
1388 if (st->pktin->type == SSH2_MSG_CHANNEL_DATA) {
1389 do_blank = TRUE; blank_prefix = 8;
1390 } else if (st->pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
1391 do_blank = TRUE; blank_prefix = 12;
1394 blank.offset = blank_prefix;
1395 blank.len = (st->pktin->length-6) - blank_prefix;
1396 blank.type = PKTLOG_OMIT;
1400 log_packet(ssh->logctx, PKT_INCOMING, st->pktin->type,
1401 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
1403 st->pktin->data+6, st->pktin->length-6,
1407 crFinish(st->pktin);
1410 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1412 int pad, biglen, i, pktoffs;
1416 * XXX various versions of SC (including 8.8.4) screw up the
1417 * register allocation in this function and use the same register
1418 * (D6) for len and as a temporary, with predictable results. The
1419 * following sledgehammer prevents this.
1426 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1427 ssh1_pkt_type(pkt->data[12]),
1428 pkt->body, pkt->length - (pkt->body - pkt->data),
1429 pkt->nblanks, pkt->blanks);
1430 sfree(pkt->blanks); pkt->blanks = NULL;
1433 if (ssh->v1_compressing) {
1434 unsigned char *compblk;
1436 zlib_compress_block(ssh->cs_comp_ctx,
1437 pkt->data + 12, pkt->length - 12,
1438 &compblk, &complen);
1439 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1440 memcpy(pkt->data + 12, compblk, complen);
1442 pkt->length = complen + 12;
1445 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1447 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1448 pad = 8 - (len % 8);
1450 biglen = len + pad; /* len(padding+type+data+CRC) */
1452 for (i = pktoffs; i < 4+8; i++)
1453 pkt->data[i] = random_byte();
1454 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
1455 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
1456 PUT_32BIT(pkt->data + pktoffs, len);
1459 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
1460 pkt->data + pktoffs + 4, biglen);
1462 if (offset_p) *offset_p = pktoffs;
1463 return biglen + 4; /* len(length+padding+type+data+CRC) */
1466 static int s_write(Ssh ssh, void *data, int len)
1469 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len, 0, NULL);
1470 return sk_write(ssh->s, (char *)data, len);
1473 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1475 int len, backlog, offset;
1476 len = s_wrpkt_prepare(ssh, pkt, &offset);
1477 backlog = s_write(ssh, pkt->data + offset, len);
1478 if (backlog > SSH_MAX_BACKLOG)
1479 ssh_throttle_all(ssh, 1, backlog);
1480 ssh_free_packet(pkt);
1483 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1486 len = s_wrpkt_prepare(ssh, pkt, &offset);
1487 if (ssh->deferred_len + len > ssh->deferred_size) {
1488 ssh->deferred_size = ssh->deferred_len + len + 128;
1489 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1493 memcpy(ssh->deferred_send_data + ssh->deferred_len,
1494 pkt->data + offset, len);
1495 ssh->deferred_len += len;
1496 ssh_free_packet(pkt);
1500 * Construct a SSH-1 packet with the specified contents.
1501 * (This all-at-once interface used to be the only one, but now SSH-1
1502 * packets can also be constructed incrementally.)
1504 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
1510 pkt = ssh1_pkt_init(pkttype);
1512 while ((argtype = va_arg(ap, int)) != PKT_END) {
1513 unsigned char *argp, argchar;
1515 unsigned long argint;
1518 /* Actual fields in the packet */
1520 argint = va_arg(ap, int);
1521 ssh_pkt_adduint32(pkt, argint);
1524 argchar = (unsigned char) va_arg(ap, int);
1525 ssh_pkt_addbyte(pkt, argchar);
1528 argp = va_arg(ap, unsigned char *);
1529 arglen = va_arg(ap, int);
1530 ssh_pkt_adddata(pkt, argp, arglen);
1533 sargp = va_arg(ap, char *);
1534 ssh_pkt_addstring(pkt, sargp);
1537 bn = va_arg(ap, Bignum);
1538 ssh1_pkt_addmp(pkt, bn);
1540 /* Tokens for modifications to packet logging */
1542 dont_log_password(ssh, pkt, PKTLOG_BLANK);
1545 dont_log_data(ssh, pkt, PKTLOG_OMIT);
1548 end_log_omission(ssh, pkt);
1556 static void send_packet(Ssh ssh, int pkttype, ...)
1560 va_start(ap, pkttype);
1561 pkt = construct_packet(ssh, pkttype, ap);
1566 static void defer_packet(Ssh ssh, int pkttype, ...)
1570 va_start(ap, pkttype);
1571 pkt = construct_packet(ssh, pkttype, ap);
1573 s_wrpkt_defer(ssh, pkt);
1576 static int ssh_versioncmp(char *a, char *b)
1579 unsigned long av, bv;
1581 av = strtoul(a, &ae, 10);
1582 bv = strtoul(b, &be, 10);
1584 return (av < bv ? -1 : +1);
1589 av = strtoul(ae, &ae, 10);
1590 bv = strtoul(be, &be, 10);
1592 return (av < bv ? -1 : +1);
1597 * Utility routines for putting an SSH-protocol `string' and
1598 * `uint32' into a hash state.
1600 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
1602 unsigned char lenblk[4];
1603 PUT_32BIT(lenblk, len);
1604 h->bytes(s, lenblk, 4);
1605 h->bytes(s, str, len);
1608 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
1610 unsigned char intblk[4];
1611 PUT_32BIT(intblk, i);
1612 h->bytes(s, intblk, 4);
1616 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
1618 static void ssh_pkt_ensure(struct Packet *pkt, int length)
1620 if (pkt->maxlen < length) {
1621 unsigned char *body = pkt->body;
1622 int offset = body ? body - pkt->data : 0;
1623 pkt->maxlen = length + 256;
1624 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
1625 if (body) pkt->body = pkt->data + offset;
1628 static void ssh_pkt_adddata(struct Packet *pkt, void *data, int len)
1630 if (pkt->logmode != PKTLOG_EMIT) {
1632 pkt->blanks = sresize(pkt->blanks, pkt->nblanks, struct logblank_t);
1634 pkt->blanks[pkt->nblanks-1].offset = pkt->length -
1635 (pkt->body - pkt->data);
1636 pkt->blanks[pkt->nblanks-1].len = len;
1637 pkt->blanks[pkt->nblanks-1].type = pkt->logmode;
1640 ssh_pkt_ensure(pkt, pkt->length);
1641 memcpy(pkt->data + pkt->length - len, data, len);
1643 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
1645 ssh_pkt_adddata(pkt, &byte, 1);
1647 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
1649 ssh_pkt_adddata(pkt, &value, 1);
1651 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
1654 PUT_32BIT(x, value);
1655 ssh_pkt_adddata(pkt, x, 4);
1657 static void ssh_pkt_addstring_start(struct Packet *pkt)
1659 ssh_pkt_adduint32(pkt, 0);
1660 pkt->savedpos = pkt->length;
1662 static void ssh_pkt_addstring_str(struct Packet *pkt, char *data)
1664 ssh_pkt_adddata(pkt, data, strlen(data));
1665 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1667 static void ssh_pkt_addstring_data(struct Packet *pkt, char *data, int len)
1669 ssh_pkt_adddata(pkt, data, len);
1670 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1672 static void ssh_pkt_addstring(struct Packet *pkt, char *data)
1674 ssh_pkt_addstring_start(pkt);
1675 ssh_pkt_addstring_str(pkt, data);
1677 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
1679 int len = ssh1_bignum_length(b);
1680 unsigned char *data = snewn(len, unsigned char);
1681 (void) ssh1_write_bignum(data, b);
1682 ssh_pkt_adddata(pkt, data, len);
1685 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
1688 int i, n = (bignum_bitcount(b) + 7) / 8;
1689 p = snewn(n + 1, unsigned char);
1691 for (i = 1; i <= n; i++)
1692 p[i] = bignum_byte(b, n - i);
1694 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1696 memmove(p, p + i, n + 1 - i);
1700 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
1704 p = ssh2_mpint_fmt(b, &len);
1705 ssh_pkt_addstring_start(pkt);
1706 ssh_pkt_addstring_data(pkt, (char *)p, len);
1710 static struct Packet *ssh1_pkt_init(int pkt_type)
1712 struct Packet *pkt = ssh_new_packet();
1713 pkt->length = 4 + 8; /* space for length + max padding */
1714 ssh_pkt_addbyte(pkt, pkt_type);
1715 pkt->body = pkt->data + pkt->length;
1719 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
1720 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
1721 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
1722 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
1723 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
1724 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
1725 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
1726 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
1727 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
1729 static struct Packet *ssh2_pkt_init(int pkt_type)
1731 struct Packet *pkt = ssh_new_packet();
1732 pkt->length = 5; /* space for packet length + padding length */
1734 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
1735 pkt->body = pkt->data + pkt->length; /* after packet type */
1740 * Construct an SSH-2 final-form packet: compress it, encrypt it,
1741 * put the MAC on it. Final packet, ready to be sent, is stored in
1742 * pkt->data. Total length is returned.
1744 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
1746 int cipherblk, maclen, padding, i;
1749 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1750 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1751 pkt->body, pkt->length - (pkt->body - pkt->data),
1752 pkt->nblanks, pkt->blanks);
1753 sfree(pkt->blanks); pkt->blanks = NULL;
1757 * Compress packet payload.
1760 unsigned char *newpayload;
1763 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
1765 &newpayload, &newlen)) {
1767 ssh2_pkt_adddata(pkt, newpayload, newlen);
1773 * Add padding. At least four bytes, and must also bring total
1774 * length (minus MAC) up to a multiple of the block size.
1775 * If pkt->forcepad is set, make sure the packet is at least that size
1778 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
1779 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1781 if (pkt->length + padding < pkt->forcepad)
1782 padding = pkt->forcepad - pkt->length;
1784 (cipherblk - (pkt->length + padding) % cipherblk) % cipherblk;
1785 assert(padding <= 255);
1786 maclen = ssh->csmac ? ssh->csmac->len : 0;
1787 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
1788 pkt->data[4] = padding;
1789 for (i = 0; i < padding; i++)
1790 pkt->data[pkt->length + i] = random_byte();
1791 PUT_32BIT(pkt->data, pkt->length + padding - 4);
1793 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
1794 pkt->length + padding,
1795 ssh->v2_outgoing_sequence);
1796 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
1799 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
1800 pkt->data, pkt->length + padding);
1802 pkt->encrypted_len = pkt->length + padding;
1804 /* Ready-to-send packet starts at pkt->data. We return length. */
1805 return pkt->length + padding + maclen;
1809 * Routines called from the main SSH code to send packets. There
1810 * are quite a few of these, because we have two separate
1811 * mechanisms for delaying the sending of packets:
1813 * - In order to send an IGNORE message and a password message in
1814 * a single fixed-length blob, we require the ability to
1815 * concatenate the encrypted forms of those two packets _into_ a
1816 * single blob and then pass it to our <network.h> transport
1817 * layer in one go. Hence, there's a deferment mechanism which
1818 * works after packet encryption.
1820 * - In order to avoid sending any connection-layer messages
1821 * during repeat key exchange, we have to queue up any such
1822 * outgoing messages _before_ they are encrypted (and in
1823 * particular before they're allocated sequence numbers), and
1824 * then send them once we've finished.
1826 * I call these mechanisms `defer' and `queue' respectively, so as
1827 * to distinguish them reasonably easily.
1829 * The functions send_noqueue() and defer_noqueue() free the packet
1830 * structure they are passed. Every outgoing packet goes through
1831 * precisely one of these functions in its life; packets passed to
1832 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
1833 * these or get queued, and then when the queue is later emptied
1834 * the packets are all passed to defer_noqueue().
1836 * When using a CBC-mode cipher, it's necessary to ensure that an
1837 * attacker can't provide data to be encrypted using an IV that they
1838 * know. We ensure this by prefixing each packet that might contain
1839 * user data with an SSH_MSG_IGNORE. This is done using the deferral
1840 * mechanism, so in this case send_noqueue() ends up redirecting to
1841 * defer_noqueue(). If you don't like this inefficiency, don't use
1845 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
1846 static void ssh_pkt_defersend(Ssh);
1849 * Send an SSH-2 packet immediately, without queuing or deferring.
1851 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
1855 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
1856 /* We need to send two packets, so use the deferral mechanism. */
1857 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
1858 ssh_pkt_defersend(ssh);
1861 len = ssh2_pkt_construct(ssh, pkt);
1862 backlog = s_write(ssh, pkt->data, len);
1863 if (backlog > SSH_MAX_BACKLOG)
1864 ssh_throttle_all(ssh, 1, backlog);
1866 ssh->outgoing_data_size += pkt->encrypted_len;
1867 if (!ssh->kex_in_progress &&
1868 ssh->max_data_size != 0 &&
1869 ssh->outgoing_data_size > ssh->max_data_size)
1870 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
1872 ssh_free_packet(pkt);
1876 * Defer an SSH-2 packet.
1878 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
1881 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
1882 ssh->deferred_len == 0 && !noignore) {
1884 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
1885 * get encrypted with a known IV.
1887 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
1888 ssh2_pkt_addstring_start(ipkt);
1889 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
1891 len = ssh2_pkt_construct(ssh, pkt);
1892 if (ssh->deferred_len + len > ssh->deferred_size) {
1893 ssh->deferred_size = ssh->deferred_len + len + 128;
1894 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1898 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->data, len);
1899 ssh->deferred_len += len;
1900 ssh->deferred_data_size += pkt->encrypted_len;
1901 ssh_free_packet(pkt);
1905 * Queue an SSH-2 packet.
1907 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
1909 assert(ssh->queueing);
1911 if (ssh->queuelen >= ssh->queuesize) {
1912 ssh->queuesize = ssh->queuelen + 32;
1913 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
1916 ssh->queue[ssh->queuelen++] = pkt;
1920 * Either queue or send a packet, depending on whether queueing is
1923 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
1926 ssh2_pkt_queue(ssh, pkt);
1928 ssh2_pkt_send_noqueue(ssh, pkt);
1932 * Either queue or defer a packet, depending on whether queueing is
1935 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
1938 ssh2_pkt_queue(ssh, pkt);
1940 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
1944 * Send the whole deferred data block constructed by
1945 * ssh2_pkt_defer() or SSH-1's defer_packet().
1947 * The expected use of the defer mechanism is that you call
1948 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
1949 * not currently queueing, this simply sets up deferred_send_data
1950 * and then sends it. If we _are_ currently queueing, the calls to
1951 * ssh2_pkt_defer() put the deferred packets on to the queue
1952 * instead, and therefore ssh_pkt_defersend() has no deferred data
1953 * to send. Hence, there's no need to make it conditional on
1956 static void ssh_pkt_defersend(Ssh ssh)
1959 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
1960 ssh->deferred_len = ssh->deferred_size = 0;
1961 sfree(ssh->deferred_send_data);
1962 ssh->deferred_send_data = NULL;
1963 if (backlog > SSH_MAX_BACKLOG)
1964 ssh_throttle_all(ssh, 1, backlog);
1966 ssh->outgoing_data_size += ssh->deferred_data_size;
1967 if (!ssh->kex_in_progress &&
1968 ssh->max_data_size != 0 &&
1969 ssh->outgoing_data_size > ssh->max_data_size)
1970 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
1971 ssh->deferred_data_size = 0;
1975 * Send a packet whose length needs to be disguised (typically
1976 * passwords or keyboard-interactive responses).
1978 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
1984 * The simplest way to do this is to adjust the
1985 * variable-length padding field in the outgoing packet.
1987 * Currently compiled out, because some Cisco SSH servers
1988 * don't like excessively padded packets (bah, why's it
1991 pkt->forcepad = padsize;
1992 ssh2_pkt_send(ssh, pkt);
1997 * If we can't do that, however, an alternative approach is
1998 * to use the pkt_defer mechanism to bundle the packet
1999 * tightly together with an SSH_MSG_IGNORE such that their
2000 * combined length is a constant. So first we construct the
2001 * final form of this packet and defer its sending.
2003 ssh2_pkt_defer(ssh, pkt);
2006 * Now construct an SSH_MSG_IGNORE which includes a string
2007 * that's an exact multiple of the cipher block size. (If
2008 * the cipher is NULL so that the block size is
2009 * unavailable, we don't do this trick at all, because we
2010 * gain nothing by it.)
2012 if (ssh->cscipher) {
2015 stringlen = (256 - ssh->deferred_len);
2016 stringlen += ssh->cscipher->blksize - 1;
2017 stringlen -= (stringlen % ssh->cscipher->blksize);
2020 * Temporarily disable actual compression, so we
2021 * can guarantee to get this string exactly the
2022 * length we want it. The compression-disabling
2023 * routine should return an integer indicating how
2024 * many bytes we should adjust our string length
2028 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2030 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2031 ssh2_pkt_addstring_start(pkt);
2032 for (i = 0; i < stringlen; i++) {
2033 char c = (char) random_byte();
2034 ssh2_pkt_addstring_data(pkt, &c, 1);
2036 ssh2_pkt_defer(ssh, pkt);
2038 ssh_pkt_defersend(ssh);
2043 * Send all queued SSH-2 packets. We send them by means of
2044 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2045 * packets that needed to be lumped together.
2047 static void ssh2_pkt_queuesend(Ssh ssh)
2051 assert(!ssh->queueing);
2053 for (i = 0; i < ssh->queuelen; i++)
2054 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2057 ssh_pkt_defersend(ssh);
2061 void bndebug(char *string, Bignum b)
2065 p = ssh2_mpint_fmt(b, &len);
2066 debug(("%s", string));
2067 for (i = 0; i < len; i++)
2068 debug((" %02x", p[i]));
2074 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2078 p = ssh2_mpint_fmt(b, &len);
2079 hash_string(h, s, p, len);
2084 * Packet decode functions for both SSH-1 and SSH-2.
2086 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2088 unsigned long value;
2089 if (pkt->length - pkt->savedpos < 4)
2090 return 0; /* arrgh, no way to decline (FIXME?) */
2091 value = GET_32BIT(pkt->body + pkt->savedpos);
2095 static int ssh2_pkt_getbool(struct Packet *pkt)
2097 unsigned long value;
2098 if (pkt->length - pkt->savedpos < 1)
2099 return 0; /* arrgh, no way to decline (FIXME?) */
2100 value = pkt->body[pkt->savedpos] != 0;
2104 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2109 if (pkt->length - pkt->savedpos < 4)
2111 len = GET_32BIT(pkt->body + pkt->savedpos);
2116 if (pkt->length - pkt->savedpos < *length)
2118 *p = (char *)(pkt->body + pkt->savedpos);
2119 pkt->savedpos += *length;
2121 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2123 if (pkt->length - pkt->savedpos < length)
2125 pkt->savedpos += length;
2126 return pkt->body + (pkt->savedpos - length);
2128 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2129 unsigned char **keystr)
2133 j = makekey(pkt->body + pkt->savedpos,
2134 pkt->length - pkt->savedpos,
2141 assert(pkt->savedpos < pkt->length);
2145 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2150 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2151 pkt->length - pkt->savedpos, &b);
2159 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2165 ssh_pkt_getstring(pkt, &p, &length);
2170 b = bignum_from_bytes((unsigned char *)p, length);
2175 * Helper function to add an SSH-2 signature blob to a packet.
2176 * Expects to be shown the public key blob as well as the signature
2177 * blob. Normally works just like ssh2_pkt_addstring, but will
2178 * fiddle with the signature packet if necessary for
2179 * BUG_SSH2_RSA_PADDING.
2181 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2182 void *pkblob_v, int pkblob_len,
2183 void *sigblob_v, int sigblob_len)
2185 unsigned char *pkblob = (unsigned char *)pkblob_v;
2186 unsigned char *sigblob = (unsigned char *)sigblob_v;
2188 /* dmemdump(pkblob, pkblob_len); */
2189 /* dmemdump(sigblob, sigblob_len); */
2192 * See if this is in fact an ssh-rsa signature and a buggy
2193 * server; otherwise we can just do this the easy way.
2195 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) &&
2196 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2197 int pos, len, siglen;
2200 * Find the byte length of the modulus.
2203 pos = 4+7; /* skip over "ssh-rsa" */
2204 pos += 4 + GET_32BIT(pkblob+pos); /* skip over exponent */
2205 len = GET_32BIT(pkblob+pos); /* find length of modulus */
2206 pos += 4; /* find modulus itself */
2207 while (len > 0 && pkblob[pos] == 0)
2209 /* debug(("modulus length is %d\n", len)); */
2212 * Now find the signature integer.
2214 pos = 4+7; /* skip over "ssh-rsa" */
2215 siglen = GET_32BIT(sigblob+pos);
2216 /* debug(("signature length is %d\n", siglen)); */
2218 if (len != siglen) {
2219 unsigned char newlen[4];
2220 ssh2_pkt_addstring_start(pkt);
2221 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2222 /* dmemdump(sigblob, pos); */
2223 pos += 4; /* point to start of actual sig */
2224 PUT_32BIT(newlen, len);
2225 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2226 /* dmemdump(newlen, 4); */
2228 while (len-- > siglen) {
2229 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2230 /* dmemdump(newlen, 1); */
2232 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2233 /* dmemdump(sigblob+pos, siglen); */
2237 /* Otherwise fall through and do it the easy way. */
2240 ssh2_pkt_addstring_start(pkt);
2241 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2245 * Examine the remote side's version string and compare it against
2246 * a list of known buggy implementations.
2248 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2250 char *imp; /* pointer to implementation part */
2252 imp += strcspn(imp, "-");
2254 imp += strcspn(imp, "-");
2257 ssh->remote_bugs = 0;
2260 * General notes on server version strings:
2261 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2262 * here -- in particular, we've heard of one that's perfectly happy
2263 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2264 * so we can't distinguish them.
2266 if (ssh->cfg.sshbug_ignore1 == FORCE_ON ||
2267 (ssh->cfg.sshbug_ignore1 == AUTO &&
2268 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2269 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2270 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2271 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2273 * These versions don't support SSH1_MSG_IGNORE, so we have
2274 * to use a different defence against password length
2277 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2278 logevent("We believe remote version has SSH-1 ignore bug");
2281 if (ssh->cfg.sshbug_plainpw1 == FORCE_ON ||
2282 (ssh->cfg.sshbug_plainpw1 == AUTO &&
2283 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2285 * These versions need a plain password sent; they can't
2286 * handle having a null and a random length of data after
2289 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2290 logevent("We believe remote version needs a plain SSH-1 password");
2293 if (ssh->cfg.sshbug_rsa1 == FORCE_ON ||
2294 (ssh->cfg.sshbug_rsa1 == AUTO &&
2295 (!strcmp(imp, "Cisco-1.25")))) {
2297 * These versions apparently have no clue whatever about
2298 * RSA authentication and will panic and die if they see
2299 * an AUTH_RSA message.
2301 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2302 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2305 if (ssh->cfg.sshbug_hmac2 == FORCE_ON ||
2306 (ssh->cfg.sshbug_hmac2 == AUTO &&
2307 !wc_match("* VShell", imp) &&
2308 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2309 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2310 wc_match("2.1 *", imp)))) {
2312 * These versions have the HMAC bug.
2314 ssh->remote_bugs |= BUG_SSH2_HMAC;
2315 logevent("We believe remote version has SSH-2 HMAC bug");
2318 if (ssh->cfg.sshbug_derivekey2 == FORCE_ON ||
2319 (ssh->cfg.sshbug_derivekey2 == AUTO &&
2320 !wc_match("* VShell", imp) &&
2321 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2323 * These versions have the key-derivation bug (failing to
2324 * include the literal shared secret in the hashes that
2325 * generate the keys).
2327 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2328 logevent("We believe remote version has SSH-2 key-derivation bug");
2331 if (ssh->cfg.sshbug_rsapad2 == FORCE_ON ||
2332 (ssh->cfg.sshbug_rsapad2 == AUTO &&
2333 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2334 wc_match("OpenSSH_3.[0-2]*", imp)))) {
2336 * These versions have the SSH-2 RSA padding bug.
2338 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2339 logevent("We believe remote version has SSH-2 RSA padding bug");
2342 if (ssh->cfg.sshbug_pksessid2 == FORCE_ON ||
2343 (ssh->cfg.sshbug_pksessid2 == AUTO &&
2344 wc_match("OpenSSH_2.[0-2]*", imp))) {
2346 * These versions have the SSH-2 session-ID bug in
2347 * public-key authentication.
2349 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2350 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2353 if (ssh->cfg.sshbug_rekey2 == FORCE_ON ||
2354 (ssh->cfg.sshbug_rekey2 == AUTO &&
2355 (wc_match("DigiSSH_2.0", imp) ||
2356 wc_match("OpenSSH_2.[0-4]*", imp) ||
2357 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2358 wc_match("Sun_SSH_1.0", imp) ||
2359 wc_match("Sun_SSH_1.0.1", imp) ||
2360 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2361 wc_match("WeOnlyDo-*", imp)))) {
2363 * These versions have the SSH-2 rekey bug.
2365 ssh->remote_bugs |= BUG_SSH2_REKEY;
2366 logevent("We believe remote version has SSH-2 rekey bug");
2371 * The `software version' part of an SSH version string is required
2372 * to contain no spaces or minus signs.
2374 static void ssh_fix_verstring(char *str)
2376 /* Eat "SSH-<protoversion>-". */
2377 assert(*str == 'S'); str++;
2378 assert(*str == 'S'); str++;
2379 assert(*str == 'H'); str++;
2380 assert(*str == '-'); str++;
2381 while (*str && *str != '-') str++;
2382 assert(*str == '-'); str++;
2384 /* Convert minus signs and spaces in the remaining string into
2387 if (*str == '-' || *str == ' ')
2394 * Send an appropriate SSH version string.
2396 static void ssh_send_verstring(Ssh ssh, char *svers)
2400 if (ssh->version == 2) {
2402 * Construct a v2 version string.
2404 verstring = dupprintf("SSH-2.0-%s\015\012", sshver);
2407 * Construct a v1 version string.
2409 verstring = dupprintf("SSH-%s-%s\012",
2410 (ssh_versioncmp(svers, "1.5") <= 0 ?
2415 ssh_fix_verstring(verstring);
2417 if (ssh->version == 2) {
2420 * Record our version string.
2422 len = strcspn(verstring, "\015\012");
2423 ssh->v_c = snewn(len + 1, char);
2424 memcpy(ssh->v_c, verstring, len);
2428 logeventf(ssh, "We claim version: %.*s",
2429 strcspn(verstring, "\015\012"), verstring);
2430 s_write(ssh, verstring, strlen(verstring));
2434 static int do_ssh_init(Ssh ssh, unsigned char c)
2436 struct do_ssh_init_state {
2444 crState(do_ssh_init_state);
2446 crBegin(ssh->do_ssh_init_crstate);
2448 /* Search for a line beginning with the string "SSH-" in the input. */
2450 if (c != 'S') goto no;
2452 if (c != 'S') goto no;
2454 if (c != 'H') goto no;
2456 if (c != '-') goto no;
2465 s->vstring = snewn(s->vstrsize, char);
2466 strcpy(s->vstring, "SSH-");
2470 crReturn(1); /* get another char */
2471 if (s->vslen >= s->vstrsize - 1) {
2473 s->vstring = sresize(s->vstring, s->vstrsize, char);
2475 s->vstring[s->vslen++] = c;
2478 s->version[s->i] = '\0';
2480 } else if (s->i < sizeof(s->version) - 1)
2481 s->version[s->i++] = c;
2482 } else if (c == '\012')
2486 ssh->agentfwd_enabled = FALSE;
2487 ssh->rdpkt2_state.incoming_sequence = 0;
2489 s->vstring[s->vslen] = 0;
2490 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
2491 logeventf(ssh, "Server version: %s", s->vstring);
2492 ssh_detect_bugs(ssh, s->vstring);
2495 * Decide which SSH protocol version to support.
2498 /* Anything strictly below "2.0" means protocol 1 is supported. */
2499 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
2500 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2501 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
2503 if (ssh->cfg.sshprot == 0 && !s->proto1) {
2504 bombout(("SSH protocol version 1 required by user but not provided by server"));
2507 if (ssh->cfg.sshprot == 3 && !s->proto2) {
2508 bombout(("SSH protocol version 2 required by user but not provided by server"));
2512 if (s->proto2 && (ssh->cfg.sshprot >= 2 || !s->proto1))
2517 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
2519 /* Send the version string, if we haven't already */
2520 if (ssh->cfg.sshprot != 3)
2521 ssh_send_verstring(ssh, s->version);
2523 if (ssh->version == 2) {
2526 * Record their version string.
2528 len = strcspn(s->vstring, "\015\012");
2529 ssh->v_s = snewn(len + 1, char);
2530 memcpy(ssh->v_s, s->vstring, len);
2534 * Initialise SSH-2 protocol.
2536 ssh->protocol = ssh2_protocol;
2537 ssh2_protocol_setup(ssh);
2538 ssh->s_rdpkt = ssh2_rdpkt;
2541 * Initialise SSH-1 protocol.
2543 ssh->protocol = ssh1_protocol;
2544 ssh1_protocol_setup(ssh);
2545 ssh->s_rdpkt = ssh1_rdpkt;
2547 if (ssh->version == 2)
2548 do_ssh2_transport(ssh, NULL, -1, NULL);
2550 update_specials_menu(ssh->frontend);
2551 ssh->state = SSH_STATE_BEFORE_SIZE;
2552 ssh->pinger = pinger_new(&ssh->cfg, &ssh_backend, ssh);
2559 static void ssh_process_incoming_data(Ssh ssh,
2560 unsigned char **data, int *datalen)
2562 struct Packet *pktin;
2564 pktin = ssh->s_rdpkt(ssh, data, datalen);
2566 ssh->protocol(ssh, NULL, 0, pktin);
2567 ssh_free_packet(pktin);
2571 static void ssh_queue_incoming_data(Ssh ssh,
2572 unsigned char **data, int *datalen)
2574 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
2579 static void ssh_process_queued_incoming_data(Ssh ssh)
2582 unsigned char *data;
2585 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
2586 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
2590 while (!ssh->frozen && len > 0)
2591 ssh_process_incoming_data(ssh, &data, &len);
2594 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
2598 static void ssh_set_frozen(Ssh ssh, int frozen)
2601 sk_set_frozen(ssh->s, frozen);
2602 ssh->frozen = frozen;
2605 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
2607 /* Log raw data, if we're in that mode. */
2609 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
2612 crBegin(ssh->ssh_gotdata_crstate);
2615 * To begin with, feed the characters one by one to the
2616 * protocol initialisation / selection function do_ssh_init().
2617 * When that returns 0, we're done with the initial greeting
2618 * exchange and can move on to packet discipline.
2621 int ret; /* need not be kept across crReturn */
2623 crReturnV; /* more data please */
2624 ret = do_ssh_init(ssh, *data);
2632 * We emerge from that loop when the initial negotiation is
2633 * over and we have selected an s_rdpkt function. Now pass
2634 * everything to s_rdpkt, and then pass the resulting packets
2635 * to the proper protocol handler.
2639 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
2641 ssh_queue_incoming_data(ssh, &data, &datalen);
2642 /* This uses up all data and cannot cause anything interesting
2643 * to happen; indeed, for anything to happen at all, we must
2644 * return, so break out. */
2646 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
2647 /* This uses up some or all data, and may freeze the
2649 ssh_process_queued_incoming_data(ssh);
2651 /* This uses up some or all data, and may freeze the
2653 ssh_process_incoming_data(ssh, &data, &datalen);
2655 /* FIXME this is probably EBW. */
2656 if (ssh->state == SSH_STATE_CLOSED)
2659 /* We're out of data. Go and get some more. */
2665 static int ssh_do_close(Ssh ssh, int notify_exit)
2668 struct ssh_channel *c;
2670 ssh->state = SSH_STATE_CLOSED;
2671 expire_timer_context(ssh);
2676 notify_remote_exit(ssh->frontend);
2681 * Now we must shut down any port- and X-forwarded channels going
2682 * through this connection.
2684 if (ssh->channels) {
2685 while (NULL != (c = index234(ssh->channels, 0))) {
2688 x11_close(c->u.x11.s);
2691 pfd_close(c->u.pfd.s);
2694 del234(ssh->channels, c); /* moving next one to index 0 */
2695 if (ssh->version == 2)
2696 bufchain_clear(&c->v.v2.outbuffer);
2701 * Go through port-forwardings, and close any associated
2702 * listening sockets.
2704 if (ssh->portfwds) {
2705 struct ssh_portfwd *pf;
2706 while (NULL != (pf = index234(ssh->portfwds, 0))) {
2707 /* Dispose of any listening socket. */
2709 pfd_terminate(pf->local);
2710 del234(ssh->portfwds, pf); /* moving next one to index 0 */
2718 static void ssh_log(Plug plug, int type, SockAddr addr, int port,
2719 const char *error_msg, int error_code)
2721 Ssh ssh = (Ssh) plug;
2722 char addrbuf[256], *msg;
2724 sk_getaddr(addr, addrbuf, lenof(addrbuf));
2727 msg = dupprintf("Connecting to %s port %d", addrbuf, port);
2729 msg = dupprintf("Failed to connect to %s: %s", addrbuf, error_msg);
2735 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
2738 Ssh ssh = (Ssh) plug;
2739 int need_notify = ssh_do_close(ssh, FALSE);
2742 if (!ssh->close_expected)
2743 error_msg = "Server unexpectedly closed network connection";
2745 error_msg = "Server closed network connection";
2748 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
2752 notify_remote_exit(ssh->frontend);
2755 logevent(error_msg);
2756 if (!ssh->close_expected || !ssh->clean_exit)
2757 connection_fatal(ssh->frontend, "%s", error_msg);
2761 static int ssh_receive(Plug plug, int urgent, char *data, int len)
2763 Ssh ssh = (Ssh) plug;
2764 ssh_gotdata(ssh, (unsigned char *)data, len);
2765 if (ssh->state == SSH_STATE_CLOSED) {
2766 ssh_do_close(ssh, TRUE);
2772 static void ssh_sent(Plug plug, int bufsize)
2774 Ssh ssh = (Ssh) plug;
2776 * If the send backlog on the SSH socket itself clears, we
2777 * should unthrottle the whole world if it was throttled.
2779 if (bufsize < SSH_MAX_BACKLOG)
2780 ssh_throttle_all(ssh, 0, bufsize);
2784 * Connect to specified host and port.
2785 * Returns an error message, or NULL on success.
2786 * Also places the canonical host name into `realhost'. It must be
2787 * freed by the caller.
2789 static const char *connect_to_host(Ssh ssh, char *host, int port,
2790 char **realhost, int nodelay, int keepalive)
2792 static const struct plug_function_table fn_table = {
2803 ssh->savedhost = snewn(1 + strlen(host), char);
2804 strcpy(ssh->savedhost, host);
2807 port = 22; /* default ssh port */
2808 ssh->savedport = port;
2813 logeventf(ssh, "Looking up host \"%s\"%s", host,
2814 (ssh->cfg.addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
2815 (ssh->cfg.addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" : "")));
2816 addr = name_lookup(host, port, realhost, &ssh->cfg,
2817 ssh->cfg.addressfamily);
2818 if ((err = sk_addr_error(addr)) != NULL) {
2826 ssh->fn = &fn_table;
2827 ssh->s = new_connection(addr, *realhost, port,
2828 0, 1, nodelay, keepalive, (Plug) ssh, &ssh->cfg);
2829 if ((err = sk_socket_error(ssh->s)) != NULL) {
2831 notify_remote_exit(ssh->frontend);
2836 * If the SSH version number's fixed, set it now, and if it's SSH-2,
2837 * send the version string too.
2839 if (ssh->cfg.sshprot == 0)
2841 if (ssh->cfg.sshprot == 3) {
2843 ssh_send_verstring(ssh, NULL);
2850 * Throttle or unthrottle the SSH connection.
2852 static void ssh1_throttle(Ssh ssh, int adjust)
2854 int old_count = ssh->v1_throttle_count;
2855 ssh->v1_throttle_count += adjust;
2856 assert(ssh->v1_throttle_count >= 0);
2857 if (ssh->v1_throttle_count && !old_count) {
2858 ssh_set_frozen(ssh, 1);
2859 } else if (!ssh->v1_throttle_count && old_count) {
2860 ssh_set_frozen(ssh, 0);
2865 * Throttle or unthrottle _all_ local data streams (for when sends
2866 * on the SSH connection itself back up).
2868 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
2871 struct ssh_channel *c;
2873 if (enable == ssh->throttled_all)
2875 ssh->throttled_all = enable;
2876 ssh->overall_bufsize = bufsize;
2879 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
2881 case CHAN_MAINSESSION:
2883 * This is treated separately, outside the switch.
2887 x11_override_throttle(c->u.x11.s, enable);
2890 /* Agent channels require no buffer management. */
2893 pfd_override_throttle(c->u.pfd.s, enable);
2899 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
2901 Ssh ssh = (Ssh) sshv;
2903 ssh->agent_response = reply;
2904 ssh->agent_response_len = replylen;
2906 if (ssh->version == 1)
2907 do_ssh1_login(ssh, NULL, -1, NULL);
2909 do_ssh2_authconn(ssh, NULL, -1, NULL);
2912 static void ssh_dialog_callback(void *sshv, int ret)
2914 Ssh ssh = (Ssh) sshv;
2916 ssh->user_response = ret;
2918 if (ssh->version == 1)
2919 do_ssh1_login(ssh, NULL, -1, NULL);
2921 do_ssh2_transport(ssh, NULL, -1, NULL);
2924 * This may have unfrozen the SSH connection, so do a
2927 ssh_process_queued_incoming_data(ssh);
2930 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
2932 struct ssh_channel *c = (struct ssh_channel *)cv;
2934 void *sentreply = reply;
2937 /* Fake SSH_AGENT_FAILURE. */
2938 sentreply = "\0\0\0\1\5";
2941 if (ssh->version == 2) {
2942 ssh2_add_channel_data(c, sentreply, replylen);
2945 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
2946 PKT_INT, c->remoteid,
2949 PKT_DATA, sentreply, replylen,
2958 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
2959 * non-NULL, otherwise just close the connection. `client_reason' == NULL
2960 * => log `wire_reason'.
2962 static void ssh_disconnect(Ssh ssh, char *client_reason, char *wire_reason,
2963 int code, int clean_exit)
2967 client_reason = wire_reason;
2969 error = dupprintf("Disconnected: %s", client_reason);
2971 error = dupstr("Disconnected");
2973 if (ssh->version == 1) {
2974 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
2976 } else if (ssh->version == 2) {
2977 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
2978 ssh2_pkt_adduint32(pktout, code);
2979 ssh2_pkt_addstring(pktout, wire_reason);
2980 ssh2_pkt_addstring(pktout, "en"); /* language tag */
2981 ssh2_pkt_send_noqueue(ssh, pktout);
2984 ssh->close_expected = TRUE;
2985 ssh->clean_exit = clean_exit;
2986 ssh_closing((Plug)ssh, error, 0, 0);
2991 * Handle the key exchange and user authentication phases.
2993 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
2994 struct Packet *pktin)
2997 unsigned char cookie[8], *ptr;
2998 struct RSAKey servkey, hostkey;
2999 struct MD5Context md5c;
3000 struct do_ssh1_login_state {
3002 unsigned char *rsabuf, *keystr1, *keystr2;
3003 unsigned long supported_ciphers_mask, supported_auths_mask;
3004 int tried_publickey, tried_agent;
3005 int tis_auth_refused, ccard_auth_refused;
3006 unsigned char session_id[16];
3009 void *publickey_blob;
3010 int publickey_bloblen;
3011 char *publickey_comment;
3012 int publickey_encrypted;
3013 prompts_t *cur_prompt;
3016 unsigned char request[5], *response, *p;
3026 crState(do_ssh1_login_state);
3028 crBegin(ssh->do_ssh1_login_crstate);
3033 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3034 bombout(("Public key packet not received"));
3038 logevent("Received public keys");
3040 ptr = ssh_pkt_getdata(pktin, 8);
3042 bombout(("SSH-1 public key packet stopped before random cookie"));
3045 memcpy(cookie, ptr, 8);
3047 if (!ssh1_pkt_getrsakey(pktin, &servkey, &s->keystr1) ||
3048 !ssh1_pkt_getrsakey(pktin, &hostkey, &s->keystr2)) {
3049 bombout(("Failed to read SSH-1 public keys from public key packet"));
3054 * Log the host key fingerprint.
3058 logevent("Host key fingerprint is:");
3059 strcpy(logmsg, " ");
3060 hostkey.comment = NULL;
3061 rsa_fingerprint(logmsg + strlen(logmsg),
3062 sizeof(logmsg) - strlen(logmsg), &hostkey);
3066 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
3067 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
3068 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
3070 ssh->v1_local_protoflags =
3071 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
3072 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
3075 MD5Update(&md5c, s->keystr2, hostkey.bytes);
3076 MD5Update(&md5c, s->keystr1, servkey.bytes);
3077 MD5Update(&md5c, cookie, 8);
3078 MD5Final(s->session_id, &md5c);
3080 for (i = 0; i < 32; i++)
3081 ssh->session_key[i] = random_byte();
3084 * Verify that the `bits' and `bytes' parameters match.
3086 if (hostkey.bits > hostkey.bytes * 8 ||
3087 servkey.bits > servkey.bytes * 8) {
3088 bombout(("SSH-1 public keys were badly formatted"));
3092 s->len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
3094 s->rsabuf = snewn(s->len, unsigned char);
3097 * Verify the host key.
3101 * First format the key into a string.
3103 int len = rsastr_len(&hostkey);
3104 char fingerprint[100];
3105 char *keystr = snewn(len, char);
3106 rsastr_fmt(keystr, &hostkey);
3107 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
3109 ssh_set_frozen(ssh, 1);
3110 s->dlgret = verify_ssh_host_key(ssh->frontend,
3111 ssh->savedhost, ssh->savedport,
3112 "rsa", keystr, fingerprint,
3113 ssh_dialog_callback, ssh);
3115 if (s->dlgret < 0) {
3119 bombout(("Unexpected data from server while waiting"
3120 " for user host key response"));
3123 } while (pktin || inlen > 0);
3124 s->dlgret = ssh->user_response;
3126 ssh_set_frozen(ssh, 0);
3128 if (s->dlgret == 0) {
3129 ssh_disconnect(ssh, "User aborted at host key verification",
3135 for (i = 0; i < 32; i++) {
3136 s->rsabuf[i] = ssh->session_key[i];
3138 s->rsabuf[i] ^= s->session_id[i];
3141 if (hostkey.bytes > servkey.bytes) {
3142 ret = rsaencrypt(s->rsabuf, 32, &servkey);
3144 ret = rsaencrypt(s->rsabuf, servkey.bytes, &hostkey);
3146 ret = rsaencrypt(s->rsabuf, 32, &hostkey);
3148 ret = rsaencrypt(s->rsabuf, hostkey.bytes, &servkey);
3151 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
3155 logevent("Encrypted session key");
3158 int cipher_chosen = 0, warn = 0;
3159 char *cipher_string = NULL;
3161 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
3162 int next_cipher = ssh->cfg.ssh_cipherlist[i];
3163 if (next_cipher == CIPHER_WARN) {
3164 /* If/when we choose a cipher, warn about it */
3166 } else if (next_cipher == CIPHER_AES) {
3167 /* XXX Probably don't need to mention this. */
3168 logevent("AES not supported in SSH-1, skipping");
3170 switch (next_cipher) {
3171 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
3172 cipher_string = "3DES"; break;
3173 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
3174 cipher_string = "Blowfish"; break;
3175 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
3176 cipher_string = "single-DES"; break;
3178 if (s->supported_ciphers_mask & (1 << s->cipher_type))
3182 if (!cipher_chosen) {
3183 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
3184 bombout(("Server violates SSH-1 protocol by not "
3185 "supporting 3DES encryption"));
3187 /* shouldn't happen */
3188 bombout(("No supported ciphers found"));
3192 /* Warn about chosen cipher if necessary. */
3194 ssh_set_frozen(ssh, 1);
3195 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
3196 ssh_dialog_callback, ssh);
3197 if (s->dlgret < 0) {
3201 bombout(("Unexpected data from server while waiting"
3202 " for user response"));
3205 } while (pktin || inlen > 0);
3206 s->dlgret = ssh->user_response;
3208 ssh_set_frozen(ssh, 0);
3209 if (s->dlgret == 0) {
3210 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
3217 switch (s->cipher_type) {
3218 case SSH_CIPHER_3DES:
3219 logevent("Using 3DES encryption");
3221 case SSH_CIPHER_DES:
3222 logevent("Using single-DES encryption");
3224 case SSH_CIPHER_BLOWFISH:
3225 logevent("Using Blowfish encryption");
3229 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
3230 PKT_CHAR, s->cipher_type,
3231 PKT_DATA, cookie, 8,
3232 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
3233 PKT_DATA, s->rsabuf, s->len,
3234 PKT_INT, ssh->v1_local_protoflags, PKT_END);
3236 logevent("Trying to enable encryption...");
3240 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
3241 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
3243 ssh->v1_cipher_ctx = ssh->cipher->make_context();
3244 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
3245 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
3247 ssh->crcda_ctx = crcda_make_context();
3248 logevent("Installing CRC compensation attack detector");
3250 if (servkey.modulus) {
3251 sfree(servkey.modulus);
3252 servkey.modulus = NULL;
3254 if (servkey.exponent) {
3255 sfree(servkey.exponent);
3256 servkey.exponent = NULL;
3258 if (hostkey.modulus) {
3259 sfree(hostkey.modulus);
3260 hostkey.modulus = NULL;
3262 if (hostkey.exponent) {
3263 sfree(hostkey.exponent);
3264 hostkey.exponent = NULL;
3268 if (pktin->type != SSH1_SMSG_SUCCESS) {
3269 bombout(("Encryption not successfully enabled"));
3273 logevent("Successfully started encryption");
3275 fflush(stdout); /* FIXME eh? */
3277 if (!*ssh->cfg.username) {
3278 int ret; /* need not be kept over crReturn */
3279 s->cur_prompt = new_prompts(ssh->frontend);
3280 s->cur_prompt->to_server = TRUE;
3281 s->cur_prompt->name = dupstr("SSH login name");
3282 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE,
3283 lenof(s->username));
3284 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3287 crWaitUntil(!pktin);
3288 ret = get_userpass_input(s->cur_prompt, in, inlen);
3293 * Failed to get a username. Terminate.
3295 free_prompts(s->cur_prompt);
3296 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
3299 memcpy(s->username, s->cur_prompt->prompts[0]->result,
3300 lenof(s->username));
3301 free_prompts(s->cur_prompt);
3303 strncpy(s->username, ssh->cfg.username, sizeof(s->username));
3304 s->username[sizeof(s->username)-1] = '\0';
3307 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, s->username, PKT_END);
3309 char *userlog = dupprintf("Sent username \"%s\"", s->username);
3311 if (flags & FLAG_INTERACTIVE &&
3312 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
3313 c_write_str(ssh, userlog);
3314 c_write_str(ssh, "\r\n");
3322 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA)) {
3323 /* We must not attempt PK auth. Pretend we've already tried it. */
3324 s->tried_publickey = s->tried_agent = 1;
3326 s->tried_publickey = s->tried_agent = 0;
3328 s->tis_auth_refused = s->ccard_auth_refused = 0;
3330 * Load the public half of any configured keyfile for later use.
3332 if (!filename_is_null(ssh->cfg.keyfile)) {
3334 logeventf(ssh, "Reading private key file \"%.150s\"",
3335 filename_to_str(&ssh->cfg.keyfile));
3336 keytype = key_type(&ssh->cfg.keyfile);
3337 if (keytype == SSH_KEYTYPE_SSH1) {
3339 if (rsakey_pubblob(&ssh->cfg.keyfile,
3340 &s->publickey_blob, &s->publickey_bloblen,
3341 &s->publickey_comment, &error)) {
3342 s->publickey_encrypted = rsakey_encrypted(&ssh->cfg.keyfile,
3346 logeventf(ssh, "Unable to load private key (%s)", error);
3347 msgbuf = dupprintf("Unable to load private key file "
3348 "\"%.150s\" (%s)\r\n",
3349 filename_to_str(&ssh->cfg.keyfile),
3351 c_write_str(ssh, msgbuf);
3353 s->publickey_blob = NULL;
3357 logeventf(ssh, "Unable to use this key file (%s)",
3358 key_type_to_str(keytype));
3359 msgbuf = dupprintf("Unable to use key file \"%.150s\""
3361 filename_to_str(&ssh->cfg.keyfile),
3362 key_type_to_str(keytype));
3363 c_write_str(ssh, msgbuf);
3365 s->publickey_blob = NULL;
3368 s->publickey_blob = NULL;
3370 while (pktin->type == SSH1_SMSG_FAILURE) {
3371 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
3373 if (ssh->cfg.tryagent && agent_exists() && !s->tried_agent) {
3375 * Attempt RSA authentication using Pageant.
3381 logevent("Pageant is running. Requesting keys.");
3383 /* Request the keys held by the agent. */
3384 PUT_32BIT(s->request, 1);
3385 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
3386 if (!agent_query(s->request, 5, &r, &s->responselen,
3387 ssh_agent_callback, ssh)) {
3391 bombout(("Unexpected data from server while waiting"
3392 " for agent response"));
3395 } while (pktin || inlen > 0);
3396 r = ssh->agent_response;
3397 s->responselen = ssh->agent_response_len;
3399 s->response = (unsigned char *) r;
3400 if (s->response && s->responselen >= 5 &&
3401 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
3402 s->p = s->response + 5;
3403 s->nkeys = GET_32BIT(s->p);
3405 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
3406 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
3407 unsigned char *pkblob = s->p;
3411 do { /* do while (0) to make breaking easy */
3412 n = ssh1_read_bignum
3413 (s->p, s->responselen-(s->p-s->response),
3418 n = ssh1_read_bignum
3419 (s->p, s->responselen-(s->p-s->response),
3424 if (s->responselen - (s->p-s->response) < 4)
3426 s->commentlen = GET_32BIT(s->p);
3428 if (s->responselen - (s->p-s->response) <
3431 s->commentp = (char *)s->p;
3432 s->p += s->commentlen;
3436 logevent("Pageant key list packet was truncated");
3440 if (s->publickey_blob) {
3441 if (!memcmp(pkblob, s->publickey_blob,
3442 s->publickey_bloblen)) {
3443 logeventf(ssh, "Pageant key #%d matches "
3444 "configured key file", s->keyi);
3445 s->tried_publickey = 1;
3447 /* Skip non-configured key */
3450 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
3451 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3452 PKT_BIGNUM, s->key.modulus, PKT_END);
3454 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3455 logevent("Key refused");
3458 logevent("Received RSA challenge");
3459 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3460 bombout(("Server's RSA challenge was badly formatted"));
3465 char *agentreq, *q, *ret;
3468 len = 1 + 4; /* message type, bit count */
3469 len += ssh1_bignum_length(s->key.exponent);
3470 len += ssh1_bignum_length(s->key.modulus);
3471 len += ssh1_bignum_length(s->challenge);
3472 len += 16; /* session id */
3473 len += 4; /* response format */
3474 agentreq = snewn(4 + len, char);
3475 PUT_32BIT(agentreq, len);
3477 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
3478 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
3480 q += ssh1_write_bignum(q, s->key.exponent);
3481 q += ssh1_write_bignum(q, s->key.modulus);
3482 q += ssh1_write_bignum(q, s->challenge);
3483 memcpy(q, s->session_id, 16);
3485 PUT_32BIT(q, 1); /* response format */
3486 if (!agent_query(agentreq, len + 4, &vret, &retlen,
3487 ssh_agent_callback, ssh)) {
3492 bombout(("Unexpected data from server"
3493 " while waiting for agent"
3497 } while (pktin || inlen > 0);
3498 vret = ssh->agent_response;
3499 retlen = ssh->agent_response_len;
3504 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
3505 logevent("Sending Pageant's response");
3506 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3507 PKT_DATA, ret + 5, 16,
3511 if (pktin->type == SSH1_SMSG_SUCCESS) {
3513 ("Pageant's response accepted");
3514 if (flags & FLAG_VERBOSE) {
3515 c_write_str(ssh, "Authenticated using"
3517 c_write(ssh, s->commentp,
3519 c_write_str(ssh, "\" from agent\r\n");
3524 ("Pageant's response not accepted");
3527 ("Pageant failed to answer challenge");
3531 logevent("No reply received from Pageant");
3534 freebn(s->key.exponent);
3535 freebn(s->key.modulus);
3536 freebn(s->challenge);
3541 if (s->publickey_blob && !s->tried_publickey)
3542 logevent("Configured key file not in Pageant");
3547 if (s->publickey_blob && !s->tried_publickey) {
3549 * Try public key authentication with the specified
3552 int got_passphrase; /* need not be kept over crReturn */
3553 if (flags & FLAG_VERBOSE)
3554 c_write_str(ssh, "Trying public key authentication.\r\n");
3555 logeventf(ssh, "Trying public key \"%s\"",
3556 filename_to_str(&ssh->cfg.keyfile));
3557 s->tried_publickey = 1;
3558 got_passphrase = FALSE;
3559 while (!got_passphrase) {
3561 * Get a passphrase, if necessary.
3563 char *passphrase = NULL; /* only written after crReturn */
3565 if (!s->publickey_encrypted) {
3566 if (flags & FLAG_VERBOSE)
3567 c_write_str(ssh, "No passphrase required.\r\n");
3570 int ret; /* need not be kept over crReturn */
3571 s->cur_prompt = new_prompts(ssh->frontend);
3572 s->cur_prompt->to_server = FALSE;
3573 s->cur_prompt->name = dupstr("SSH key passphrase");
3574 add_prompt(s->cur_prompt,
3575 dupprintf("Passphrase for key \"%.100s\": ",
3576 s->publickey_comment),
3577 FALSE, SSH_MAX_PASSWORD_LEN);
3578 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3581 crWaitUntil(!pktin);
3582 ret = get_userpass_input(s->cur_prompt, in, inlen);
3586 /* Failed to get a passphrase. Terminate. */
3587 free_prompts(s->cur_prompt);
3588 ssh_disconnect(ssh, NULL, "Unable to authenticate",
3592 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
3593 free_prompts(s->cur_prompt);
3596 * Try decrypting key with passphrase.
3598 ret = loadrsakey(&ssh->cfg.keyfile, &s->key, passphrase,
3601 memset(passphrase, 0, strlen(passphrase));
3605 /* Correct passphrase. */
3606 got_passphrase = TRUE;
3607 } else if (ret == 0) {
3608 c_write_str(ssh, "Couldn't load private key from ");
3609 c_write_str(ssh, filename_to_str(&ssh->cfg.keyfile));
3610 c_write_str(ssh, " (");
3611 c_write_str(ssh, error);
3612 c_write_str(ssh, ").\r\n");
3613 got_passphrase = FALSE;
3614 break; /* go and try something else */
3615 } else if (ret == -1) {
3616 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
3617 got_passphrase = FALSE;
3620 assert(0 && "unexpected return from loadrsakey()");
3621 got_passphrase = FALSE; /* placate optimisers */
3625 if (got_passphrase) {
3628 * Send a public key attempt.
3630 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3631 PKT_BIGNUM, s->key.modulus, PKT_END);
3634 if (pktin->type == SSH1_SMSG_FAILURE) {
3635 c_write_str(ssh, "Server refused our public key.\r\n");
3636 continue; /* go and try something else */
3638 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3639 bombout(("Bizarre response to offer of public key"));
3645 unsigned char buffer[32];
3646 Bignum challenge, response;
3648 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3649 bombout(("Server's RSA challenge was badly formatted"));
3652 response = rsadecrypt(challenge, &s->key);
3653 freebn(s->key.private_exponent);/* burn the evidence */
3655 for (i = 0; i < 32; i++) {
3656 buffer[i] = bignum_byte(response, 31 - i);
3660 MD5Update(&md5c, buffer, 32);
3661 MD5Update(&md5c, s->session_id, 16);
3662 MD5Final(buffer, &md5c);
3664 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3665 PKT_DATA, buffer, 16, PKT_END);
3672 if (pktin->type == SSH1_SMSG_FAILURE) {
3673 if (flags & FLAG_VERBOSE)
3674 c_write_str(ssh, "Failed to authenticate with"
3675 " our public key.\r\n");
3676 continue; /* go and try something else */
3677 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
3678 bombout(("Bizarre response to RSA authentication response"));
3682 break; /* we're through! */
3688 * Otherwise, try various forms of password-like authentication.
3690 s->cur_prompt = new_prompts(ssh->frontend);
3692 if (ssh->cfg.try_tis_auth &&
3693 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
3694 !s->tis_auth_refused) {
3695 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
3696 logevent("Requested TIS authentication");
3697 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
3699 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
3700 logevent("TIS authentication declined");
3701 if (flags & FLAG_INTERACTIVE)
3702 c_write_str(ssh, "TIS authentication refused.\r\n");
3703 s->tis_auth_refused = 1;
3708 char *instr_suf, *prompt;
3710 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3712 bombout(("TIS challenge packet was badly formed"));
3715 logevent("Received TIS challenge");
3716 s->cur_prompt->to_server = TRUE;
3717 s->cur_prompt->name = dupstr("SSH TIS authentication");
3718 /* Prompt heuristic comes from OpenSSH */
3719 if (memchr(challenge, '\n', challengelen)) {
3720 instr_suf = dupstr("");
3721 prompt = dupprintf("%.*s", challengelen, challenge);
3723 instr_suf = dupprintf("%.*s", challengelen, challenge);
3724 prompt = dupstr("Response: ");
3726 s->cur_prompt->instruction =
3727 dupprintf("Using TIS authentication.%s%s",
3728 (*instr_suf) ? "\n" : "",
3730 s->cur_prompt->instr_reqd = TRUE;
3731 add_prompt(s->cur_prompt, prompt, FALSE, SSH_MAX_PASSWORD_LEN);
3735 if (ssh->cfg.try_tis_auth &&
3736 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
3737 !s->ccard_auth_refused) {
3738 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
3739 logevent("Requested CryptoCard authentication");
3740 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
3742 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
3743 logevent("CryptoCard authentication declined");
3744 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
3745 s->ccard_auth_refused = 1;
3750 char *instr_suf, *prompt;
3752 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3754 bombout(("CryptoCard challenge packet was badly formed"));
3757 logevent("Received CryptoCard challenge");
3758 s->cur_prompt->to_server = TRUE;
3759 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
3760 s->cur_prompt->name_reqd = FALSE;
3761 /* Prompt heuristic comes from OpenSSH */
3762 if (memchr(challenge, '\n', challengelen)) {
3763 instr_suf = dupstr("");
3764 prompt = dupprintf("%.*s", challengelen, challenge);
3766 instr_suf = dupprintf("%.*s", challengelen, challenge);
3767 prompt = dupstr("Response: ");
3769 s->cur_prompt->instruction =
3770 dupprintf("Using CryptoCard authentication.%s%s",
3771 (*instr_suf) ? "\n" : "",
3773 s->cur_prompt->instr_reqd = TRUE;
3774 add_prompt(s->cur_prompt, prompt, FALSE, SSH_MAX_PASSWORD_LEN);
3778 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
3779 s->cur_prompt->to_server = TRUE;
3780 s->cur_prompt->name = dupstr("SSH password");
3781 add_prompt(s->cur_prompt, dupprintf("%.90s@%.90s's password: ",
3782 s->username, ssh->savedhost),
3783 FALSE, SSH_MAX_PASSWORD_LEN);
3787 * Show password prompt, having first obtained it via a TIS
3788 * or CryptoCard exchange if we're doing TIS or CryptoCard
3792 int ret; /* need not be kept over crReturn */
3793 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3796 crWaitUntil(!pktin);
3797 ret = get_userpass_input(s->cur_prompt, in, inlen);
3802 * Failed to get a password (for example
3803 * because one was supplied on the command line
3804 * which has already failed to work). Terminate.
3806 free_prompts(s->cur_prompt);
3807 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
3812 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
3814 * Defence against traffic analysis: we send a
3815 * whole bunch of packets containing strings of
3816 * different lengths. One of these strings is the
3817 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
3818 * The others are all random data in
3819 * SSH1_MSG_IGNORE packets. This way a passive
3820 * listener can't tell which is the password, and
3821 * hence can't deduce the password length.
3823 * Anybody with a password length greater than 16
3824 * bytes is going to have enough entropy in their
3825 * password that a listener won't find it _that_
3826 * much help to know how long it is. So what we'll
3829 * - if password length < 16, we send 15 packets
3830 * containing string lengths 1 through 15
3832 * - otherwise, we let N be the nearest multiple
3833 * of 8 below the password length, and send 8
3834 * packets containing string lengths N through
3835 * N+7. This won't obscure the order of
3836 * magnitude of the password length, but it will
3837 * introduce a bit of extra uncertainty.
3839 * A few servers can't deal with SSH1_MSG_IGNORE, at
3840 * least in this context. For these servers, we need
3841 * an alternative defence. We make use of the fact
3842 * that the password is interpreted as a C string:
3843 * so we can append a NUL, then some random data.
3845 * A few servers can deal with neither SSH1_MSG_IGNORE
3846 * here _nor_ a padded password string.
3847 * For these servers we are left with no defences
3848 * against password length sniffing.
3850 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
3851 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
3853 * The server can deal with SSH1_MSG_IGNORE, so
3854 * we can use the primary defence.
3856 int bottom, top, pwlen, i;
3859 pwlen = strlen(s->cur_prompt->prompts[0]->result);
3861 bottom = 0; /* zero length passwords are OK! :-) */
3864 bottom = pwlen & ~7;
3868 assert(pwlen >= bottom && pwlen <= top);
3870 randomstr = snewn(top + 1, char);
3872 for (i = bottom; i <= top; i++) {
3874 defer_packet(ssh, s->pwpkt_type,
3875 PKTT_PASSWORD, PKT_STR,
3876 s->cur_prompt->prompts[0]->result,
3877 PKTT_OTHER, PKT_END);
3879 for (j = 0; j < i; j++) {
3881 randomstr[j] = random_byte();
3882 } while (randomstr[j] == '\0');
3884 randomstr[i] = '\0';
3885 defer_packet(ssh, SSH1_MSG_IGNORE,
3886 PKT_STR, randomstr, PKT_END);
3889 logevent("Sending password with camouflage packets");
3890 ssh_pkt_defersend(ssh);
3893 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
3895 * The server can't deal with SSH1_MSG_IGNORE
3896 * but can deal with padded passwords, so we
3897 * can use the secondary defence.
3903 len = strlen(s->cur_prompt->prompts[0]->result);
3904 if (len < sizeof(string)) {
3906 strcpy(string, s->cur_prompt->prompts[0]->result);
3907 len++; /* cover the zero byte */
3908 while (len < sizeof(string)) {
3909 string[len++] = (char) random_byte();
3912 ss = s->cur_prompt->prompts[0]->result;
3914 logevent("Sending length-padded password");
3915 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
3916 PKT_INT, len, PKT_DATA, ss, len,
3917 PKTT_OTHER, PKT_END);
3920 * The server is believed unable to cope with
3921 * any of our password camouflage methods.
3924 len = strlen(s->cur_prompt->prompts[0]->result);
3925 logevent("Sending unpadded password");
3926 send_packet(ssh, s->pwpkt_type,
3927 PKTT_PASSWORD, PKT_INT, len,
3928 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
3929 PKTT_OTHER, PKT_END);
3932 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
3933 PKT_STR, s->cur_prompt->prompts[0]->result,
3934 PKTT_OTHER, PKT_END);
3936 logevent("Sent password");
3937 free_prompts(s->cur_prompt);
3939 if (pktin->type == SSH1_SMSG_FAILURE) {
3940 if (flags & FLAG_VERBOSE)
3941 c_write_str(ssh, "Access denied\r\n");
3942 logevent("Authentication refused");
3943 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
3944 bombout(("Strange packet received, type %d", pktin->type));
3950 if (s->publickey_blob) {
3951 sfree(s->publickey_blob);
3952 sfree(s->publickey_comment);
3955 logevent("Authentication successful");
3960 void sshfwd_close(struct ssh_channel *c)
3964 if (ssh->state == SSH_STATE_CLOSED)
3967 if (c && !c->closes) {
3969 * If halfopen is true, we have sent
3970 * CHANNEL_OPEN for this channel, but it hasn't even been
3971 * acknowledged by the server. So we must set a close flag
3972 * on it now, and then when the server acks the channel
3973 * open, we can close it then.
3976 if (ssh->version == 1) {
3977 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
3980 struct Packet *pktout;
3981 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
3982 ssh2_pkt_adduint32(pktout, c->remoteid);
3983 ssh2_pkt_send(ssh, pktout);
3986 c->closes = 1; /* sent MSG_CLOSE */
3987 if (c->type == CHAN_X11) {
3989 logevent("Forwarded X11 connection terminated");
3990 } else if (c->type == CHAN_SOCKDATA ||
3991 c->type == CHAN_SOCKDATA_DORMANT) {
3993 logevent("Forwarded port closed");
3998 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
4002 if (ssh->state == SSH_STATE_CLOSED)
4005 if (ssh->version == 1) {
4006 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
4007 PKT_INT, c->remoteid,
4008 PKT_INT, len, PKTT_DATA, PKT_DATA, buf, len,
4009 PKTT_OTHER, PKT_END);
4011 * In SSH-1 we can return 0 here - implying that forwarded
4012 * connections are never individually throttled - because
4013 * the only circumstance that can cause throttling will be
4014 * the whole SSH connection backing up, in which case
4015 * _everything_ will be throttled as a whole.
4019 ssh2_add_channel_data(c, buf, len);
4020 return ssh2_try_send(c);
4024 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
4028 if (ssh->state == SSH_STATE_CLOSED)
4031 if (ssh->version == 1) {
4032 if (c->v.v1.throttling && bufsize < SSH1_BUFFER_LIMIT) {
4033 c->v.v1.throttling = 0;
4034 ssh1_throttle(ssh, -1);
4037 ssh2_set_window(c, c->v.v2.locmaxwin - bufsize);
4041 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
4043 struct queued_handler *qh = ssh->qhead;
4047 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
4050 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
4051 ssh->packet_dispatch[qh->msg1] = NULL;
4054 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
4055 ssh->packet_dispatch[qh->msg2] = NULL;
4059 ssh->qhead = qh->next;
4061 if (ssh->qhead->msg1 > 0) {
4062 assert(ssh->packet_dispatch[ssh->qhead->msg1] == NULL);
4063 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
4065 if (ssh->qhead->msg2 > 0) {
4066 assert(ssh->packet_dispatch[ssh->qhead->msg2] == NULL);
4067 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
4070 ssh->qhead = ssh->qtail = NULL;
4071 ssh->packet_dispatch[pktin->type] = NULL;
4074 qh->handler(ssh, pktin, qh->ctx);
4079 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
4080 chandler_fn_t handler, void *ctx)
4082 struct queued_handler *qh;
4084 qh = snew(struct queued_handler);
4087 qh->handler = handler;
4091 if (ssh->qtail == NULL) {
4095 assert(ssh->packet_dispatch[qh->msg1] == NULL);
4096 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
4099 assert(ssh->packet_dispatch[qh->msg2] == NULL);
4100 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
4103 ssh->qtail->next = qh;
4108 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
4110 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
4112 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
4113 SSH2_MSG_REQUEST_SUCCESS)) {
4114 logeventf(ssh, "Remote port forwarding from %s enabled",
4117 logeventf(ssh, "Remote port forwarding from %s refused",
4120 rpf = del234(ssh->rportfwds, pf);
4126 static void ssh_setup_portfwd(Ssh ssh, const Config *cfg)
4128 const char *portfwd_strptr = cfg->portfwd;
4129 struct ssh_portfwd *epf;
4132 if (!ssh->portfwds) {
4133 ssh->portfwds = newtree234(ssh_portcmp);
4136 * Go through the existing port forwardings and tag them
4137 * with status==DESTROY. Any that we want to keep will be
4138 * re-enabled (status==KEEP) as we go through the
4139 * configuration and find out which bits are the same as
4142 struct ssh_portfwd *epf;
4144 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4145 epf->status = DESTROY;
4148 while (*portfwd_strptr) {
4149 char address_family, type;
4150 int sport,dport,sserv,dserv;
4151 char sports[256], dports[256], saddr[256], host[256];
4154 address_family = 'A';
4156 if (*portfwd_strptr == 'A' ||
4157 *portfwd_strptr == '4' ||
4158 *portfwd_strptr == '6')
4159 address_family = *portfwd_strptr++;
4160 if (*portfwd_strptr == 'L' ||
4161 *portfwd_strptr == 'R' ||
4162 *portfwd_strptr == 'D')
4163 type = *portfwd_strptr++;
4168 while (*portfwd_strptr && *portfwd_strptr != '\t') {
4169 if (*portfwd_strptr == ':') {
4171 * We've seen a colon in the middle of the
4172 * source port number. This means that
4173 * everything we've seen until now is the
4174 * source _address_, so we'll move it into
4175 * saddr and start sports from the beginning
4180 if (ssh->version == 1 && type == 'R') {
4181 logeventf(ssh, "SSH-1 cannot handle remote source address "
4182 "spec \"%s\"; ignoring", sports);
4184 strcpy(saddr, sports);
4187 if (n < lenof(sports)-1) sports[n++] = *portfwd_strptr++;
4191 if (*portfwd_strptr == '\t')
4194 while (*portfwd_strptr && *portfwd_strptr != ':') {
4195 if (n < lenof(host)-1) host[n++] = *portfwd_strptr++;
4198 if (*portfwd_strptr == ':')
4201 while (*portfwd_strptr) {
4202 if (n < lenof(dports)-1) dports[n++] = *portfwd_strptr++;
4206 dport = atoi(dports);
4210 dport = net_service_lookup(dports);
4212 logeventf(ssh, "Service lookup failed for destination"
4213 " port \"%s\"", dports);
4217 while (*portfwd_strptr) portfwd_strptr++;
4221 portfwd_strptr++; /* eat the NUL and move to next one */
4223 sport = atoi(sports);
4227 sport = net_service_lookup(sports);
4229 logeventf(ssh, "Service lookup failed for source"
4230 " port \"%s\"", sports);
4233 if (sport && dport) {
4234 /* Set up a description of the source port. */
4235 struct ssh_portfwd *pfrec, *epfrec;
4237 pfrec = snew(struct ssh_portfwd);
4239 pfrec->saddr = *saddr ? dupstr(saddr) : NULL;
4240 pfrec->sserv = sserv ? dupstr(sports) : NULL;
4241 pfrec->sport = sport;
4242 pfrec->daddr = *host ? dupstr(host) : NULL;
4243 pfrec->dserv = dserv ? dupstr(dports) : NULL;
4244 pfrec->dport = dport;
4245 pfrec->local = NULL;
4246 pfrec->remote = NULL;
4247 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
4248 address_family == '6' ? ADDRTYPE_IPV6 :
4251 epfrec = add234(ssh->portfwds, pfrec);
4252 if (epfrec != pfrec) {
4254 * We already have a port forwarding with precisely
4255 * these parameters. Hence, no need to do anything;
4256 * simply tag the existing one as KEEP.
4258 epfrec->status = KEEP;
4259 free_portfwd(pfrec);
4261 pfrec->status = CREATE;
4267 * Now go through and destroy any port forwardings which were
4270 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4271 if (epf->status == DESTROY) {
4274 message = dupprintf("%s port forwarding from %s%s%d",
4275 epf->type == 'L' ? "local" :
4276 epf->type == 'R' ? "remote" : "dynamic",
4277 epf->saddr ? epf->saddr : "",
4278 epf->saddr ? ":" : "",
4281 if (epf->type != 'D') {
4282 char *msg2 = dupprintf("%s to %s:%d", message,
4283 epf->daddr, epf->dport);
4288 logeventf(ssh, "Cancelling %s", message);
4292 struct ssh_rportfwd *rpf = epf->remote;
4293 struct Packet *pktout;
4296 * Cancel the port forwarding at the server
4299 if (ssh->version == 1) {
4301 * We cannot cancel listening ports on the
4302 * server side in SSH-1! There's no message
4303 * to support it. Instead, we simply remove
4304 * the rportfwd record from the local end
4305 * so that any connections the server tries
4306 * to make on it are rejected.
4309 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4310 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
4311 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
4313 ssh2_pkt_addstring(pktout, epf->saddr);
4314 } else if (ssh->cfg.rport_acceptall) {
4315 /* XXX: ssh->cfg.rport_acceptall may not represent
4316 * what was used to open the original connection,
4317 * since it's reconfigurable. */
4318 ssh2_pkt_addstring(pktout, "0.0.0.0");
4320 ssh2_pkt_addstring(pktout, "127.0.0.1");
4322 ssh2_pkt_adduint32(pktout, epf->sport);
4323 ssh2_pkt_send(ssh, pktout);
4326 del234(ssh->rportfwds, rpf);
4328 } else if (epf->local) {
4329 pfd_terminate(epf->local);
4332 delpos234(ssh->portfwds, i);
4334 i--; /* so we don't skip one in the list */
4338 * And finally, set up any new port forwardings (status==CREATE).
4340 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4341 if (epf->status == CREATE) {
4342 char *sportdesc, *dportdesc;
4343 sportdesc = dupprintf("%s%s%s%s%d%s",
4344 epf->saddr ? epf->saddr : "",
4345 epf->saddr ? ":" : "",
4346 epf->sserv ? epf->sserv : "",
4347 epf->sserv ? "(" : "",
4349 epf->sserv ? ")" : "");
4350 if (epf->type == 'D') {
4353 dportdesc = dupprintf("%s:%s%s%d%s",
4355 epf->dserv ? epf->dserv : "",
4356 epf->dserv ? "(" : "",
4358 epf->dserv ? ")" : "");
4361 if (epf->type == 'L') {
4362 const char *err = pfd_addforward(epf->daddr, epf->dport,
4363 epf->saddr, epf->sport,
4366 epf->addressfamily);
4368 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
4369 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4370 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4371 sportdesc, dportdesc,
4372 err ? " failed: " : "", err ? err : "");
4373 } else if (epf->type == 'D') {
4374 const char *err = pfd_addforward(NULL, -1,
4375 epf->saddr, epf->sport,
4378 epf->addressfamily);
4380 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
4381 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4382 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4384 err ? " failed: " : "", err ? err : "");
4386 struct ssh_rportfwd *pf;
4389 * Ensure the remote port forwardings tree exists.
4391 if (!ssh->rportfwds) {
4392 if (ssh->version == 1)
4393 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
4395 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
4398 pf = snew(struct ssh_rportfwd);
4399 strncpy(pf->dhost, epf->daddr, lenof(pf->dhost)-1);
4400 pf->dhost[lenof(pf->dhost)-1] = '\0';
4401 pf->dport = epf->dport;
4402 pf->sport = epf->sport;
4403 if (add234(ssh->rportfwds, pf) != pf) {
4404 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
4405 epf->daddr, epf->dport);
4408 logeventf(ssh, "Requesting remote port %s"
4409 " forward to %s", sportdesc, dportdesc);
4411 pf->sportdesc = sportdesc;
4416 if (ssh->version == 1) {
4417 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
4418 PKT_INT, epf->sport,
4419 PKT_STR, epf->daddr,
4420 PKT_INT, epf->dport,
4422 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
4424 ssh_rportfwd_succfail, pf);
4426 struct Packet *pktout;
4427 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4428 ssh2_pkt_addstring(pktout, "tcpip-forward");
4429 ssh2_pkt_addbool(pktout, 1);/* want reply */
4431 ssh2_pkt_addstring(pktout, epf->saddr);
4432 } else if (cfg->rport_acceptall) {
4433 ssh2_pkt_addstring(pktout, "0.0.0.0");
4435 ssh2_pkt_addstring(pktout, "127.0.0.1");
4437 ssh2_pkt_adduint32(pktout, epf->sport);
4438 ssh2_pkt_send(ssh, pktout);
4440 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
4441 SSH2_MSG_REQUEST_FAILURE,
4442 ssh_rportfwd_succfail, pf);
4451 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
4454 int stringlen, bufsize;
4456 ssh_pkt_getstring(pktin, &string, &stringlen);
4457 if (string == NULL) {
4458 bombout(("Incoming terminal data packet was badly formed"));
4462 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
4464 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
4465 ssh->v1_stdout_throttling = 1;
4466 ssh1_throttle(ssh, +1);
4470 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
4472 /* Remote side is trying to open a channel to talk to our
4473 * X-Server. Give them back a local channel number. */
4474 struct ssh_channel *c;
4475 int remoteid = ssh_pkt_getuint32(pktin);
4477 logevent("Received X11 connect request");
4478 /* Refuse if X11 forwarding is disabled. */
4479 if (!ssh->X11_fwd_enabled) {
4480 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4481 PKT_INT, remoteid, PKT_END);
4482 logevent("Rejected X11 connect request");
4484 c = snew(struct ssh_channel);
4487 if (x11_init(&c->u.x11.s, ssh->cfg.x11_display, c,
4488 ssh->x11auth, NULL, -1, &ssh->cfg) != NULL) {
4489 logevent("Opening X11 forward connection failed");
4491 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4492 PKT_INT, remoteid, PKT_END);
4495 ("Opening X11 forward connection succeeded");
4496 c->remoteid = remoteid;
4497 c->halfopen = FALSE;
4498 c->localid = alloc_channel_id(ssh);
4500 c->v.v1.throttling = 0;
4501 c->type = CHAN_X11; /* identify channel type */
4502 add234(ssh->channels, c);
4503 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4504 PKT_INT, c->remoteid, PKT_INT,
4505 c->localid, PKT_END);
4506 logevent("Opened X11 forward channel");
4511 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
4513 /* Remote side is trying to open a channel to talk to our
4514 * agent. Give them back a local channel number. */
4515 struct ssh_channel *c;
4516 int remoteid = ssh_pkt_getuint32(pktin);
4518 /* Refuse if agent forwarding is disabled. */
4519 if (!ssh->agentfwd_enabled) {
4520 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4521 PKT_INT, remoteid, PKT_END);
4523 c = snew(struct ssh_channel);
4525 c->remoteid = remoteid;
4526 c->halfopen = FALSE;
4527 c->localid = alloc_channel_id(ssh);
4529 c->v.v1.throttling = 0;
4530 c->type = CHAN_AGENT; /* identify channel type */
4531 c->u.a.lensofar = 0;
4532 add234(ssh->channels, c);
4533 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4534 PKT_INT, c->remoteid, PKT_INT, c->localid,
4539 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
4541 /* Remote side is trying to open a channel to talk to a
4542 * forwarded port. Give them back a local channel number. */
4543 struct ssh_channel *c;
4544 struct ssh_rportfwd pf, *pfp;
4549 c = snew(struct ssh_channel);
4552 remoteid = ssh_pkt_getuint32(pktin);
4553 ssh_pkt_getstring(pktin, &host, &hostsize);
4554 port = ssh_pkt_getuint32(pktin);
4556 if (hostsize >= lenof(pf.dhost))
4557 hostsize = lenof(pf.dhost)-1;
4558 memcpy(pf.dhost, host, hostsize);
4559 pf.dhost[hostsize] = '\0';
4561 pfp = find234(ssh->rportfwds, &pf, NULL);
4564 logeventf(ssh, "Rejected remote port open request for %s:%d",
4566 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4567 PKT_INT, remoteid, PKT_END);
4569 logeventf(ssh, "Received remote port open request for %s:%d",
4571 e = pfd_newconnect(&c->u.pfd.s, pf.dhost, port,
4572 c, &ssh->cfg, pfp->pfrec->addressfamily);
4574 logeventf(ssh, "Port open failed: %s", e);
4576 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4577 PKT_INT, remoteid, PKT_END);
4579 c->remoteid = remoteid;
4580 c->halfopen = FALSE;
4581 c->localid = alloc_channel_id(ssh);
4583 c->v.v1.throttling = 0;
4584 c->type = CHAN_SOCKDATA; /* identify channel type */
4585 add234(ssh->channels, c);
4586 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4587 PKT_INT, c->remoteid, PKT_INT,
4588 c->localid, PKT_END);
4589 logevent("Forwarded port opened successfully");
4594 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
4596 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4597 unsigned int localid = ssh_pkt_getuint32(pktin);
4598 struct ssh_channel *c;
4600 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4601 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4602 c->remoteid = localid;
4603 c->halfopen = FALSE;
4604 c->type = CHAN_SOCKDATA;
4605 c->v.v1.throttling = 0;
4606 pfd_confirm(c->u.pfd.s);
4609 if (c && c->closes) {
4611 * We have a pending close on this channel,
4612 * which we decided on before the server acked
4613 * the channel open. So now we know the
4614 * remoteid, we can close it again.
4616 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE,
4617 PKT_INT, c->remoteid, PKT_END);
4621 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
4623 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4624 struct ssh_channel *c;
4626 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4627 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4628 logevent("Forwarded connection refused by server");
4629 pfd_close(c->u.pfd.s);
4630 del234(ssh->channels, c);
4635 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
4637 /* Remote side closes a channel. */
4638 unsigned i = ssh_pkt_getuint32(pktin);
4639 struct ssh_channel *c;
4640 c = find234(ssh->channels, &i, ssh_channelfind);
4641 if (c && !c->halfopen) {
4644 (pktin->type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
4646 if ((c->closes == 0) && (c->type == CHAN_X11)) {
4647 logevent("Forwarded X11 connection terminated");
4648 assert(c->u.x11.s != NULL);
4649 x11_close(c->u.x11.s);
4652 if ((c->closes == 0) && (c->type == CHAN_SOCKDATA)) {
4653 logevent("Forwarded port closed");
4654 assert(c->u.pfd.s != NULL);
4655 pfd_close(c->u.pfd.s);
4659 c->closes |= (closetype << 2); /* seen this message */
4660 if (!(c->closes & closetype)) {
4661 send_packet(ssh, pktin->type, PKT_INT, c->remoteid,
4663 c->closes |= closetype; /* sent it too */
4666 if (c->closes == 15) {
4667 del234(ssh->channels, c);
4671 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
4672 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
4673 "_CONFIRMATION", c ? "half-open" : "nonexistent",
4678 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
4680 /* Data sent down one of our channels. */
4681 int i = ssh_pkt_getuint32(pktin);
4684 struct ssh_channel *c;
4686 ssh_pkt_getstring(pktin, &p, &len);
4688 c = find234(ssh->channels, &i, ssh_channelfind);
4693 bufsize = x11_send(c->u.x11.s, p, len);
4696 bufsize = pfd_send(c->u.pfd.s, p, len);
4699 /* Data for an agent message. Buffer it. */
4701 if (c->u.a.lensofar < 4) {
4702 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)len);
4703 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
4707 c->u.a.lensofar += l;
4709 if (c->u.a.lensofar == 4) {
4711 4 + GET_32BIT(c->u.a.msglen);
4712 c->u.a.message = snewn(c->u.a.totallen,
4714 memcpy(c->u.a.message, c->u.a.msglen, 4);
4716 if (c->u.a.lensofar >= 4 && len > 0) {
4718 min(c->u.a.totallen - c->u.a.lensofar,
4720 memcpy(c->u.a.message + c->u.a.lensofar, p,
4724 c->u.a.lensofar += l;
4726 if (c->u.a.lensofar == c->u.a.totallen) {
4729 if (agent_query(c->u.a.message,
4732 ssh_agentf_callback, c))
4733 ssh_agentf_callback(c, reply, replylen);
4734 sfree(c->u.a.message);
4735 c->u.a.lensofar = 0;
4738 bufsize = 0; /* agent channels never back up */
4741 if (!c->v.v1.throttling && bufsize > SSH1_BUFFER_LIMIT) {
4742 c->v.v1.throttling = 1;
4743 ssh1_throttle(ssh, +1);
4748 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
4750 ssh->exitcode = ssh_pkt_getuint32(pktin);
4751 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
4752 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
4754 * In case `helpful' firewalls or proxies tack
4755 * extra human-readable text on the end of the
4756 * session which we might mistake for another
4757 * encrypted packet, we close the session once
4758 * we've sent EXIT_CONFIRMATION.
4760 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
4763 /* Helper function to deal with sending tty modes for REQUEST_PTY */
4764 static void ssh1_send_ttymode(void *data, char *mode, char *val)
4766 struct Packet *pktout = (struct Packet *)data;
4768 unsigned int arg = 0;
4769 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
4770 if (i == lenof(ssh_ttymodes)) return;
4771 switch (ssh_ttymodes[i].type) {
4773 arg = ssh_tty_parse_specchar(val);
4776 arg = ssh_tty_parse_boolean(val);
4779 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
4780 ssh2_pkt_addbyte(pktout, arg);
4784 static void do_ssh1_connection(Ssh ssh, unsigned char *in, int inlen,
4785 struct Packet *pktin)
4787 crBegin(ssh->do_ssh1_connection_crstate);
4789 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
4790 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
4791 ssh1_smsg_stdout_stderr_data;
4793 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
4794 ssh1_msg_channel_open_confirmation;
4795 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
4796 ssh1_msg_channel_open_failure;
4797 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
4798 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
4799 ssh1_msg_channel_close;
4800 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
4801 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
4803 if (ssh->cfg.agentfwd && agent_exists()) {
4804 logevent("Requesting agent forwarding");
4805 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
4809 if (pktin->type != SSH1_SMSG_SUCCESS
4810 && pktin->type != SSH1_SMSG_FAILURE) {
4811 bombout(("Protocol confusion"));
4813 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4814 logevent("Agent forwarding refused");
4816 logevent("Agent forwarding enabled");
4817 ssh->agentfwd_enabled = TRUE;
4818 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
4822 if (ssh->cfg.x11_forward) {
4823 char proto[20], data[64];
4824 logevent("Requesting X11 forwarding");
4825 ssh->x11auth = x11_invent_auth(proto, sizeof(proto),
4826 data, sizeof(data), ssh->cfg.x11_auth);
4827 x11_get_real_auth(ssh->x11auth, ssh->cfg.x11_display);
4829 * Note that while we blank the X authentication data here, we don't
4830 * take any special action to blank the start of an X11 channel,
4831 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
4832 * without having session blanking enabled is likely to leak your
4833 * cookie into the log.
4835 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
4836 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
4838 PKTT_PASSWORD, PKT_STR, data, PKTT_OTHER,
4839 PKT_INT, x11_get_screen_number(ssh->cfg.x11_display),
4842 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
4844 PKTT_PASSWORD, PKT_STR, data, PKTT_OTHER, PKT_END);
4849 if (pktin->type != SSH1_SMSG_SUCCESS
4850 && pktin->type != SSH1_SMSG_FAILURE) {
4851 bombout(("Protocol confusion"));
4853 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4854 logevent("X11 forwarding refused");
4856 logevent("X11 forwarding enabled");
4857 ssh->X11_fwd_enabled = TRUE;
4858 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
4862 ssh_setup_portfwd(ssh, &ssh->cfg);
4863 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
4865 if (!ssh->cfg.nopty) {
4867 /* Unpick the terminal-speed string. */
4868 /* XXX perhaps we should allow no speeds to be sent. */
4869 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
4870 sscanf(ssh->cfg.termspeed, "%d,%d", &ssh->ospeed, &ssh->ispeed);
4871 /* Send the pty request. */
4872 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
4873 ssh_pkt_addstring(pkt, ssh->cfg.termtype);
4874 ssh_pkt_adduint32(pkt, ssh->term_height);
4875 ssh_pkt_adduint32(pkt, ssh->term_width);
4876 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
4877 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
4878 parse_ttymodes(ssh, ssh->cfg.ttymodes,
4879 ssh1_send_ttymode, (void *)pkt);
4880 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
4881 ssh_pkt_adduint32(pkt, ssh->ispeed);
4882 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
4883 ssh_pkt_adduint32(pkt, ssh->ospeed);
4884 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
4886 ssh->state = SSH_STATE_INTERMED;
4890 if (pktin->type != SSH1_SMSG_SUCCESS
4891 && pktin->type != SSH1_SMSG_FAILURE) {
4892 bombout(("Protocol confusion"));
4894 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4895 c_write_str(ssh, "Server refused to allocate pty\r\n");
4896 ssh->editing = ssh->echoing = 1;
4898 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
4899 ssh->ospeed, ssh->ispeed);
4901 ssh->editing = ssh->echoing = 1;
4904 if (ssh->cfg.compression) {
4905 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
4909 if (pktin->type != SSH1_SMSG_SUCCESS
4910 && pktin->type != SSH1_SMSG_FAILURE) {
4911 bombout(("Protocol confusion"));
4913 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4914 c_write_str(ssh, "Server refused to compress\r\n");
4916 logevent("Started compression");
4917 ssh->v1_compressing = TRUE;
4918 ssh->cs_comp_ctx = zlib_compress_init();
4919 logevent("Initialised zlib (RFC1950) compression");
4920 ssh->sc_comp_ctx = zlib_decompress_init();
4921 logevent("Initialised zlib (RFC1950) decompression");
4925 * Start the shell or command.
4927 * Special case: if the first-choice command is an SSH-2
4928 * subsystem (hence not usable here) and the second choice
4929 * exists, we fall straight back to that.
4932 char *cmd = ssh->cfg.remote_cmd_ptr;
4934 if (!cmd) cmd = ssh->cfg.remote_cmd;
4936 if (ssh->cfg.ssh_subsys && ssh->cfg.remote_cmd_ptr2) {
4937 cmd = ssh->cfg.remote_cmd_ptr2;
4938 ssh->fallback_cmd = TRUE;
4941 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
4943 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
4944 logevent("Started session");
4947 ssh->state = SSH_STATE_SESSION;
4948 if (ssh->size_needed)
4949 ssh_size(ssh, ssh->term_width, ssh->term_height);
4950 if (ssh->eof_needed)
4951 ssh_special(ssh, TS_EOF);
4954 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
4956 ssh->channels = newtree234(ssh_channelcmp);
4960 * By this point, most incoming packets are already being
4961 * handled by the dispatch table, and we need only pay
4962 * attention to the unusual ones.
4967 if (pktin->type == SSH1_SMSG_SUCCESS) {
4968 /* may be from EXEC_SHELL on some servers */
4969 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4970 /* may be from EXEC_SHELL on some servers
4971 * if no pty is available or in other odd cases. Ignore */
4973 bombout(("Strange packet received: type %d", pktin->type));
4978 int len = min(inlen, 512);
4979 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
4980 PKT_INT, len, PKTT_DATA, PKT_DATA, in, len,
4981 PKTT_OTHER, PKT_END);
4992 * Handle the top-level SSH-2 protocol.
4994 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
4999 ssh_pkt_getstring(pktin, &msg, &msglen);
5000 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
5003 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
5005 /* log reason code in disconnect message */
5009 ssh_pkt_getstring(pktin, &msg, &msglen);
5010 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
5013 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
5015 /* Do nothing, because we're ignoring it! Duhh. */
5018 static void ssh1_protocol_setup(Ssh ssh)
5023 * Most messages are handled by the coroutines.
5025 for (i = 0; i < 256; i++)
5026 ssh->packet_dispatch[i] = NULL;
5029 * These special message types we install handlers for.
5031 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
5032 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
5033 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
5036 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
5037 struct Packet *pktin)
5039 unsigned char *in=(unsigned char*)vin;
5040 if (ssh->state == SSH_STATE_CLOSED)
5043 if (pktin && ssh->packet_dispatch[pktin->type]) {
5044 ssh->packet_dispatch[pktin->type](ssh, pktin);
5048 if (!ssh->protocol_initial_phase_done) {
5049 if (do_ssh1_login(ssh, in, inlen, pktin))
5050 ssh->protocol_initial_phase_done = TRUE;
5055 do_ssh1_connection(ssh, in, inlen, pktin);
5059 * Utility routine for decoding comma-separated strings in KEXINIT.
5061 static int in_commasep_string(char *needle, char *haystack, int haylen)
5064 if (!needle || !haystack) /* protect against null pointers */
5066 needlen = strlen(needle);
5069 * Is it at the start of the string?
5071 if (haylen >= needlen && /* haystack is long enough */
5072 !memcmp(needle, haystack, needlen) && /* initial match */
5073 (haylen == needlen || haystack[needlen] == ',')
5074 /* either , or EOS follows */
5078 * If not, search for the next comma and resume after that.
5079 * If no comma found, terminate.
5081 while (haylen > 0 && *haystack != ',')
5082 haylen--, haystack++;
5085 haylen--, haystack++; /* skip over comma itself */
5090 * Similar routine for checking whether we have the first string in a list.
5092 static int first_in_commasep_string(char *needle, char *haystack, int haylen)
5095 if (!needle || !haystack) /* protect against null pointers */
5097 needlen = strlen(needle);
5099 * Is it at the start of the string?
5101 if (haylen >= needlen && /* haystack is long enough */
5102 !memcmp(needle, haystack, needlen) && /* initial match */
5103 (haylen == needlen || haystack[needlen] == ',')
5104 /* either , or EOS follows */
5112 * SSH-2 key creation method.
5113 * (Currently assumes 2 lots of any hash are sufficient to generate
5114 * keys/IVs for any cipher/MAC. SSH2_MKKEY_ITERS documents this assumption.)
5116 #define SSH2_MKKEY_ITERS (2)
5117 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H, char chr,
5118 unsigned char *keyspace)
5120 const struct ssh_hash *h = ssh->kex->hash;
5122 /* First hlen bytes. */
5124 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5125 hash_mpint(h, s, K);
5126 h->bytes(s, H, h->hlen);
5127 h->bytes(s, &chr, 1);
5128 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
5129 h->final(s, keyspace);
5130 /* Next hlen bytes. */
5132 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5133 hash_mpint(h, s, K);
5134 h->bytes(s, H, h->hlen);
5135 h->bytes(s, keyspace, h->hlen);
5136 h->final(s, keyspace + h->hlen);
5140 * Handle the SSH-2 transport layer.
5142 static int do_ssh2_transport(Ssh ssh, void *vin, int inlen,
5143 struct Packet *pktin)
5145 unsigned char *in = (unsigned char *)vin;
5146 struct do_ssh2_transport_state {
5147 int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
5148 Bignum p, g, e, f, K;
5151 int kex_init_value, kex_reply_value;
5152 const struct ssh_mac **maclist;
5154 const struct ssh2_cipher *cscipher_tobe;
5155 const struct ssh2_cipher *sccipher_tobe;
5156 const struct ssh_mac *csmac_tobe;
5157 const struct ssh_mac *scmac_tobe;
5158 const struct ssh_compress *cscomp_tobe;
5159 const struct ssh_compress *sccomp_tobe;
5160 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
5161 int hostkeylen, siglen, rsakeylen;
5162 void *hkey; /* actual host key */
5163 void *rsakey; /* for RSA kex */
5164 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
5165 int n_preferred_kex;
5166 const struct ssh_kexes *preferred_kex[KEX_MAX];
5167 int n_preferred_ciphers;
5168 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
5169 const struct ssh_compress *preferred_comp;
5170 int got_session_id, activated_authconn;
5171 struct Packet *pktout;
5176 crState(do_ssh2_transport_state);
5178 crBegin(ssh->do_ssh2_transport_crstate);
5180 s->cscipher_tobe = s->sccipher_tobe = NULL;
5181 s->csmac_tobe = s->scmac_tobe = NULL;
5182 s->cscomp_tobe = s->sccomp_tobe = NULL;
5184 s->got_session_id = s->activated_authconn = FALSE;
5187 * Be prepared to work around the buggy MAC problem.
5189 if (ssh->remote_bugs & BUG_SSH2_HMAC)
5190 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
5192 s->maclist = macs, s->nmacs = lenof(macs);
5195 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
5197 int i, j, commalist_started;
5200 * Set up the preferred key exchange. (NULL => warn below here)
5202 s->n_preferred_kex = 0;
5203 for (i = 0; i < KEX_MAX; i++) {
5204 switch (ssh->cfg.ssh_kexlist[i]) {
5206 s->preferred_kex[s->n_preferred_kex++] =
5207 &ssh_diffiehellman_gex;
5210 s->preferred_kex[s->n_preferred_kex++] =
5211 &ssh_diffiehellman_group14;
5214 s->preferred_kex[s->n_preferred_kex++] =
5215 &ssh_diffiehellman_group1;
5218 s->preferred_kex[s->n_preferred_kex++] =
5222 /* Flag for later. Don't bother if it's the last in
5224 if (i < KEX_MAX - 1) {
5225 s->preferred_kex[s->n_preferred_kex++] = NULL;
5232 * Set up the preferred ciphers. (NULL => warn below here)
5234 s->n_preferred_ciphers = 0;
5235 for (i = 0; i < CIPHER_MAX; i++) {
5236 switch (ssh->cfg.ssh_cipherlist[i]) {
5237 case CIPHER_BLOWFISH:
5238 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
5241 if (ssh->cfg.ssh2_des_cbc) {
5242 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
5246 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
5249 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
5251 case CIPHER_ARCFOUR:
5252 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
5255 /* Flag for later. Don't bother if it's the last in
5257 if (i < CIPHER_MAX - 1) {
5258 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
5265 * Set up preferred compression.
5267 if (ssh->cfg.compression)
5268 s->preferred_comp = &ssh_zlib;
5270 s->preferred_comp = &ssh_comp_none;
5273 * Enable queueing of outgoing auth- or connection-layer
5274 * packets while we are in the middle of a key exchange.
5276 ssh->queueing = TRUE;
5279 * Flag that KEX is in progress.
5281 ssh->kex_in_progress = TRUE;
5284 * Construct and send our key exchange packet.
5286 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
5287 for (i = 0; i < 16; i++)
5288 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
5289 /* List key exchange algorithms. */
5290 ssh2_pkt_addstring_start(s->pktout);
5291 commalist_started = 0;
5292 for (i = 0; i < s->n_preferred_kex; i++) {
5293 const struct ssh_kexes *k = s->preferred_kex[i];
5294 if (!k) continue; /* warning flag */
5295 for (j = 0; j < k->nkexes; j++) {
5296 if (commalist_started)
5297 ssh2_pkt_addstring_str(s->pktout, ",");
5298 ssh2_pkt_addstring_str(s->pktout, k->list[j]->name);
5299 commalist_started = 1;
5302 /* List server host key algorithms. */
5303 ssh2_pkt_addstring_start(s->pktout);
5304 for (i = 0; i < lenof(hostkey_algs); i++) {
5305 ssh2_pkt_addstring_str(s->pktout, hostkey_algs[i]->name);
5306 if (i < lenof(hostkey_algs) - 1)
5307 ssh2_pkt_addstring_str(s->pktout, ",");
5309 /* List client->server encryption algorithms. */
5310 ssh2_pkt_addstring_start(s->pktout);
5311 commalist_started = 0;
5312 for (i = 0; i < s->n_preferred_ciphers; i++) {
5313 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5314 if (!c) continue; /* warning flag */
5315 for (j = 0; j < c->nciphers; j++) {
5316 if (commalist_started)
5317 ssh2_pkt_addstring_str(s->pktout, ",");
5318 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
5319 commalist_started = 1;
5322 /* List server->client encryption algorithms. */
5323 ssh2_pkt_addstring_start(s->pktout);
5324 commalist_started = 0;
5325 for (i = 0; i < s->n_preferred_ciphers; i++) {
5326 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5327 if (!c) continue; /* warning flag */
5328 for (j = 0; j < c->nciphers; j++) {
5329 if (commalist_started)
5330 ssh2_pkt_addstring_str(s->pktout, ",");
5331 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
5332 commalist_started = 1;
5335 /* List client->server MAC algorithms. */
5336 ssh2_pkt_addstring_start(s->pktout);
5337 for (i = 0; i < s->nmacs; i++) {
5338 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5339 if (i < s->nmacs - 1)
5340 ssh2_pkt_addstring_str(s->pktout, ",");
5342 /* List server->client MAC algorithms. */
5343 ssh2_pkt_addstring_start(s->pktout);
5344 for (i = 0; i < s->nmacs; i++) {
5345 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5346 if (i < s->nmacs - 1)
5347 ssh2_pkt_addstring_str(s->pktout, ",");
5349 /* List client->server 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 server->client compression algorithms. */
5361 ssh2_pkt_addstring_start(s->pktout);
5362 assert(lenof(compressions) > 1);
5363 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
5364 for (i = 0; i < lenof(compressions); i++) {
5365 const struct ssh_compress *c = compressions[i];
5366 if (c != s->preferred_comp) {
5367 ssh2_pkt_addstring_str(s->pktout, ",");
5368 ssh2_pkt_addstring_str(s->pktout, c->name);
5371 /* List client->server languages. Empty list. */
5372 ssh2_pkt_addstring_start(s->pktout);
5373 /* List server->client languages. Empty list. */
5374 ssh2_pkt_addstring_start(s->pktout);
5375 /* First KEX packet does _not_ follow, because we're not that brave. */
5376 ssh2_pkt_addbool(s->pktout, FALSE);
5378 ssh2_pkt_adduint32(s->pktout, 0);
5381 s->our_kexinitlen = s->pktout->length - 5;
5382 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
5383 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
5385 ssh2_pkt_send_noqueue(ssh, s->pktout);
5391 * Now examine the other side's KEXINIT to see what we're up
5395 char *str, *preferred;
5398 if (pktin->type != SSH2_MSG_KEXINIT) {
5399 bombout(("expected key exchange packet from server"));
5403 ssh->hostkey = NULL;
5404 s->cscipher_tobe = NULL;
5405 s->sccipher_tobe = NULL;
5406 s->csmac_tobe = NULL;
5407 s->scmac_tobe = NULL;
5408 s->cscomp_tobe = NULL;
5409 s->sccomp_tobe = NULL;
5410 s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
5412 pktin->savedpos += 16; /* skip garbage cookie */
5413 ssh_pkt_getstring(pktin, &str, &len); /* key exchange algorithms */
5416 for (i = 0; i < s->n_preferred_kex; i++) {
5417 const struct ssh_kexes *k = s->preferred_kex[i];
5421 for (j = 0; j < k->nkexes; j++) {
5422 if (!preferred) preferred = k->list[j]->name;
5423 if (in_commasep_string(k->list[j]->name, str, len)) {
5424 ssh->kex = k->list[j];
5433 bombout(("Couldn't agree a key exchange algorithm (available: %s)",
5434 str ? str : "(null)"));
5438 * Note that the server's guess is considered wrong if it doesn't match
5439 * the first algorithm in our list, even if it's still the algorithm
5442 s->guessok = first_in_commasep_string(preferred, str, len);
5443 ssh_pkt_getstring(pktin, &str, &len); /* host key algorithms */
5444 for (i = 0; i < lenof(hostkey_algs); i++) {
5445 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
5446 ssh->hostkey = hostkey_algs[i];
5450 s->guessok = s->guessok &&
5451 first_in_commasep_string(hostkey_algs[0]->name, str, len);
5452 ssh_pkt_getstring(pktin, &str, &len); /* client->server cipher */
5453 for (i = 0; i < s->n_preferred_ciphers; i++) {
5454 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5456 s->warn_cscipher = TRUE;
5458 for (j = 0; j < c->nciphers; j++) {
5459 if (in_commasep_string(c->list[j]->name, str, len)) {
5460 s->cscipher_tobe = c->list[j];
5465 if (s->cscipher_tobe)
5468 if (!s->cscipher_tobe) {
5469 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
5470 str ? str : "(null)"));
5474 ssh_pkt_getstring(pktin, &str, &len); /* server->client cipher */
5475 for (i = 0; i < s->n_preferred_ciphers; i++) {
5476 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5478 s->warn_sccipher = TRUE;
5480 for (j = 0; j < c->nciphers; j++) {
5481 if (in_commasep_string(c->list[j]->name, str, len)) {
5482 s->sccipher_tobe = c->list[j];
5487 if (s->sccipher_tobe)
5490 if (!s->sccipher_tobe) {
5491 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
5492 str ? str : "(null)"));
5496 ssh_pkt_getstring(pktin, &str, &len); /* client->server mac */
5497 for (i = 0; i < s->nmacs; i++) {
5498 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5499 s->csmac_tobe = s->maclist[i];
5503 ssh_pkt_getstring(pktin, &str, &len); /* server->client mac */
5504 for (i = 0; i < s->nmacs; i++) {
5505 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5506 s->scmac_tobe = s->maclist[i];
5510 ssh_pkt_getstring(pktin, &str, &len); /* client->server compression */
5511 for (i = 0; i < lenof(compressions) + 1; i++) {
5512 const struct ssh_compress *c =
5513 i == 0 ? s->preferred_comp : compressions[i - 1];
5514 if (in_commasep_string(c->name, str, len)) {
5519 ssh_pkt_getstring(pktin, &str, &len); /* server->client compression */
5520 for (i = 0; i < lenof(compressions) + 1; i++) {
5521 const struct ssh_compress *c =
5522 i == 0 ? s->preferred_comp : compressions[i - 1];
5523 if (in_commasep_string(c->name, str, len)) {
5528 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
5529 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
5530 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
5533 ssh_set_frozen(ssh, 1);
5534 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
5536 ssh_dialog_callback, ssh);
5537 if (s->dlgret < 0) {
5541 bombout(("Unexpected data from server while"
5542 " waiting for user response"));
5545 } while (pktin || inlen > 0);
5546 s->dlgret = ssh->user_response;
5548 ssh_set_frozen(ssh, 0);
5549 if (s->dlgret == 0) {
5550 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
5556 if (s->warn_cscipher) {
5557 ssh_set_frozen(ssh, 1);
5558 s->dlgret = askalg(ssh->frontend,
5559 "client-to-server cipher",
5560 s->cscipher_tobe->name,
5561 ssh_dialog_callback, ssh);
5562 if (s->dlgret < 0) {
5566 bombout(("Unexpected data from server while"
5567 " waiting for user response"));
5570 } while (pktin || inlen > 0);
5571 s->dlgret = ssh->user_response;
5573 ssh_set_frozen(ssh, 0);
5574 if (s->dlgret == 0) {
5575 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
5581 if (s->warn_sccipher) {
5582 ssh_set_frozen(ssh, 1);
5583 s->dlgret = askalg(ssh->frontend,
5584 "server-to-client cipher",
5585 s->sccipher_tobe->name,
5586 ssh_dialog_callback, ssh);
5587 if (s->dlgret < 0) {
5591 bombout(("Unexpected data from server while"
5592 " waiting for user response"));
5595 } while (pktin || inlen > 0);
5596 s->dlgret = ssh->user_response;
5598 ssh_set_frozen(ssh, 0);
5599 if (s->dlgret == 0) {
5600 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
5606 ssh->exhash = ssh->kex->hash->init();
5607 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
5608 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
5609 hash_string(ssh->kex->hash, ssh->exhash,
5610 s->our_kexinit, s->our_kexinitlen);
5611 sfree(s->our_kexinit);
5612 if (pktin->length > 5)
5613 hash_string(ssh->kex->hash, ssh->exhash,
5614 pktin->data + 5, pktin->length - 5);
5616 if (s->ignorepkt) /* first_kex_packet_follows */
5617 crWaitUntil(pktin); /* Ignore packet */
5620 if (ssh->kex->main_type == KEXTYPE_DH) {
5622 * Work out the number of bits of key we will need from the
5623 * key exchange. We start with the maximum key length of
5629 csbits = s->cscipher_tobe->keylen;
5630 scbits = s->sccipher_tobe->keylen;
5631 s->nbits = (csbits > scbits ? csbits : scbits);
5633 /* The keys only have hlen-bit entropy, since they're based on
5634 * a hash. So cap the key size at hlen bits. */
5635 if (s->nbits > ssh->kex->hash->hlen * 8)
5636 s->nbits = ssh->kex->hash->hlen * 8;
5639 * If we're doing Diffie-Hellman group exchange, start by
5640 * requesting a group.
5642 if (!ssh->kex->pdata) {
5643 logevent("Doing Diffie-Hellman group exchange");
5644 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
5646 * Work out how big a DH group we will need to allow that
5649 s->pbits = 512 << ((s->nbits - 1) / 64);
5650 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
5651 ssh2_pkt_adduint32(s->pktout, s->pbits);
5652 ssh2_pkt_send_noqueue(ssh, s->pktout);
5655 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
5656 bombout(("expected key exchange group packet from server"));
5659 s->p = ssh2_pkt_getmp(pktin);
5660 s->g = ssh2_pkt_getmp(pktin);
5661 if (!s->p || !s->g) {
5662 bombout(("unable to read mp-ints from incoming group packet"));
5665 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
5666 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
5667 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
5669 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
5670 ssh->kex_ctx = dh_setup_group(ssh->kex);
5671 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
5672 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
5673 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
5674 ssh->kex->groupname);
5677 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
5678 ssh->kex->hash->text_name);
5680 * Now generate and send e for Diffie-Hellman.
5682 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
5683 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
5684 s->pktout = ssh2_pkt_init(s->kex_init_value);
5685 ssh2_pkt_addmp(s->pktout, s->e);
5686 ssh2_pkt_send_noqueue(ssh, s->pktout);
5688 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
5690 if (pktin->type != s->kex_reply_value) {
5691 bombout(("expected key exchange reply packet from server"));
5694 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
5695 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
5696 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
5697 s->f = ssh2_pkt_getmp(pktin);
5699 bombout(("unable to parse key exchange reply packet"));
5702 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
5704 s->K = dh_find_K(ssh->kex_ctx, s->f);
5706 /* We assume everything from now on will be quick, and it might
5707 * involve user interaction. */
5708 set_busy_status(ssh->frontend, BUSY_NOT);
5710 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
5711 if (!ssh->kex->pdata) {
5712 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
5713 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
5714 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
5716 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
5717 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
5719 dh_cleanup(ssh->kex_ctx);
5721 if (!ssh->kex->pdata) {
5726 logeventf(ssh, "Doing RSA key exchange with hash %s",
5727 ssh->kex->hash->text_name);
5728 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
5730 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
5734 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
5735 bombout(("expected RSA public key packet from server"));
5739 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
5740 hash_string(ssh->kex->hash, ssh->exhash,
5741 s->hostkeydata, s->hostkeylen);
5742 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
5746 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
5747 s->rsakeydata = snewn(s->rsakeylen, char);
5748 memcpy(s->rsakeydata, keydata, s->rsakeylen);
5751 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
5753 sfree(s->rsakeydata);
5754 bombout(("unable to parse RSA public key from server"));
5758 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
5761 * Next, set up a shared secret K, of precisely KLEN -
5762 * 2*HLEN - 49 bits, where KLEN is the bit length of the
5763 * RSA key modulus and HLEN is the bit length of the hash
5767 int klen = ssh_rsakex_klen(s->rsakey);
5768 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
5770 unsigned char *kstr1, *kstr2, *outstr;
5771 int kstr1len, kstr2len, outstrlen;
5773 s->K = bn_power_2(nbits - 1);
5775 for (i = 0; i < nbits; i++) {
5777 byte = random_byte();
5779 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
5783 * Encode this as an mpint.
5785 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
5786 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
5787 PUT_32BIT(kstr2, kstr1len);
5788 memcpy(kstr2 + 4, kstr1, kstr1len);
5791 * Encrypt it with the given RSA key.
5793 outstrlen = (klen + 7) / 8;
5794 outstr = snewn(outstrlen, unsigned char);
5795 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
5796 outstr, outstrlen, s->rsakey);
5799 * And send it off in a return packet.
5801 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
5802 ssh2_pkt_addstring_start(s->pktout);
5803 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
5804 ssh2_pkt_send_noqueue(ssh, s->pktout);
5806 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
5813 ssh_rsakex_freekey(s->rsakey);
5816 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
5817 sfree(s->rsakeydata);
5818 bombout(("expected signature packet from server"));
5822 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
5824 sfree(s->rsakeydata);
5827 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
5828 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
5829 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
5831 ssh->kex_ctx = NULL;
5834 debug(("Exchange hash is:\n"));
5835 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
5839 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
5840 (char *)s->exchange_hash,
5841 ssh->kex->hash->hlen)) {
5842 bombout(("Server's host key did not match the signature supplied"));
5847 * Authenticate remote host: verify host key. (We've already
5848 * checked the signature of the exchange hash.)
5850 s->keystr = ssh->hostkey->fmtkey(s->hkey);
5851 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
5852 ssh_set_frozen(ssh, 1);
5853 s->dlgret = verify_ssh_host_key(ssh->frontend,
5854 ssh->savedhost, ssh->savedport,
5855 ssh->hostkey->keytype, s->keystr,
5857 ssh_dialog_callback, ssh);
5858 if (s->dlgret < 0) {
5862 bombout(("Unexpected data from server while waiting"
5863 " for user host key response"));
5866 } while (pktin || inlen > 0);
5867 s->dlgret = ssh->user_response;
5869 ssh_set_frozen(ssh, 0);
5870 if (s->dlgret == 0) {
5871 ssh_disconnect(ssh, "User aborted at host key verification", NULL,
5875 if (!s->got_session_id) { /* don't bother logging this in rekeys */
5876 logevent("Host key fingerprint is:");
5877 logevent(s->fingerprint);
5879 sfree(s->fingerprint);
5881 ssh->hostkey->freekey(s->hkey);
5884 * The exchange hash from the very first key exchange is also
5885 * the session id, used in session key construction and
5888 if (!s->got_session_id) {
5889 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
5890 memcpy(ssh->v2_session_id, s->exchange_hash,
5891 sizeof(s->exchange_hash));
5892 ssh->v2_session_id_len = ssh->kex->hash->hlen;
5893 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
5894 s->got_session_id = TRUE;
5898 * Send SSH2_MSG_NEWKEYS.
5900 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
5901 ssh2_pkt_send_noqueue(ssh, s->pktout);
5902 ssh->outgoing_data_size = 0; /* start counting from here */
5905 * We've sent client NEWKEYS, so create and initialise
5906 * client-to-server session keys.
5908 if (ssh->cs_cipher_ctx)
5909 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
5910 ssh->cscipher = s->cscipher_tobe;
5911 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
5913 if (ssh->cs_mac_ctx)
5914 ssh->csmac->free_context(ssh->cs_mac_ctx);
5915 ssh->csmac = s->csmac_tobe;
5916 ssh->cs_mac_ctx = ssh->csmac->make_context();
5918 if (ssh->cs_comp_ctx)
5919 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
5920 ssh->cscomp = s->cscomp_tobe;
5921 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
5924 * Set IVs on client-to-server keys. Here we use the exchange
5925 * hash from the _first_ key exchange.
5928 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
5929 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
5930 ssh2_mkkey(ssh,s->K,s->exchange_hash,'C',keyspace);
5931 assert((ssh->cscipher->keylen+7) / 8 <=
5932 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
5933 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
5934 ssh2_mkkey(ssh,s->K,s->exchange_hash,'A',keyspace);
5935 assert(ssh->cscipher->blksize <=
5936 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
5937 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
5938 ssh2_mkkey(ssh,s->K,s->exchange_hash,'E',keyspace);
5939 assert(ssh->csmac->len <=
5940 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
5941 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
5942 memset(keyspace, 0, sizeof(keyspace));
5945 logeventf(ssh, "Initialised %.200s client->server encryption",
5946 ssh->cscipher->text_name);
5947 logeventf(ssh, "Initialised %.200s client->server MAC algorithm",
5948 ssh->csmac->text_name);
5949 if (ssh->cscomp->text_name)
5950 logeventf(ssh, "Initialised %s compression",
5951 ssh->cscomp->text_name);
5954 * Now our end of the key exchange is complete, we can send all
5955 * our queued higher-layer packets.
5957 ssh->queueing = FALSE;
5958 ssh2_pkt_queuesend(ssh);
5961 * Expect SSH2_MSG_NEWKEYS from server.
5964 if (pktin->type != SSH2_MSG_NEWKEYS) {
5965 bombout(("expected new-keys packet from server"));
5968 ssh->incoming_data_size = 0; /* start counting from here */
5971 * We've seen server NEWKEYS, so create and initialise
5972 * server-to-client session keys.
5974 if (ssh->sc_cipher_ctx)
5975 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
5976 ssh->sccipher = s->sccipher_tobe;
5977 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
5979 if (ssh->sc_mac_ctx)
5980 ssh->scmac->free_context(ssh->sc_mac_ctx);
5981 ssh->scmac = s->scmac_tobe;
5982 ssh->sc_mac_ctx = ssh->scmac->make_context();
5984 if (ssh->sc_comp_ctx)
5985 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
5986 ssh->sccomp = s->sccomp_tobe;
5987 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
5990 * Set IVs on server-to-client keys. Here we use the exchange
5991 * hash from the _first_ key exchange.
5994 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
5995 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
5996 ssh2_mkkey(ssh,s->K,s->exchange_hash,'D',keyspace);
5997 assert((ssh->sccipher->keylen+7) / 8 <=
5998 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
5999 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
6000 ssh2_mkkey(ssh,s->K,s->exchange_hash,'B',keyspace);
6001 assert(ssh->sccipher->blksize <=
6002 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6003 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
6004 ssh2_mkkey(ssh,s->K,s->exchange_hash,'F',keyspace);
6005 assert(ssh->scmac->len <=
6006 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6007 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
6008 memset(keyspace, 0, sizeof(keyspace));
6010 logeventf(ssh, "Initialised %.200s server->client encryption",
6011 ssh->sccipher->text_name);
6012 logeventf(ssh, "Initialised %.200s server->client MAC algorithm",
6013 ssh->scmac->text_name);
6014 if (ssh->sccomp->text_name)
6015 logeventf(ssh, "Initialised %s decompression",
6016 ssh->sccomp->text_name);
6019 * Free shared secret.
6024 * Key exchange is over. Loop straight back round if we have a
6025 * deferred rekey reason.
6027 if (ssh->deferred_rekey_reason) {
6028 logevent(ssh->deferred_rekey_reason);
6030 ssh->deferred_rekey_reason = NULL;
6031 goto begin_key_exchange;
6035 * Otherwise, schedule a timer for our next rekey.
6037 ssh->kex_in_progress = FALSE;
6038 ssh->last_rekey = GETTICKCOUNT();
6039 if (ssh->cfg.ssh_rekey_time != 0)
6040 ssh->next_rekey = schedule_timer(ssh->cfg.ssh_rekey_time*60*TICKSPERSEC,
6044 * If this is the first key exchange phase, we must pass the
6045 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
6046 * wants to see it but because it will need time to initialise
6047 * itself before it sees an actual packet. In subsequent key
6048 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
6049 * it would only confuse the layer above.
6051 if (s->activated_authconn) {
6054 s->activated_authconn = TRUE;
6057 * Now we're encrypting. Begin returning 1 to the protocol main
6058 * function so that other things can run on top of the
6059 * transport. If we ever see a KEXINIT, we must go back to the
6062 * We _also_ go back to the start if we see pktin==NULL and
6063 * inlen==-1, because this is a special signal meaning
6064 * `initiate client-driven rekey', and `in' contains a message
6065 * giving the reason for the rekey.
6067 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
6068 (!pktin && inlen == -1))) {
6073 logevent("Server initiated key re-exchange");
6076 * Special case: if the server bug is set that doesn't
6077 * allow rekeying, we give a different log message and
6078 * continue waiting. (If such a server _initiates_ a rekey,
6079 * we process it anyway!)
6081 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
6082 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
6084 /* Reset the counters, so that at least this message doesn't
6085 * hit the event log _too_ often. */
6086 ssh->outgoing_data_size = 0;
6087 ssh->incoming_data_size = 0;
6088 if (ssh->cfg.ssh_rekey_time != 0) {
6090 schedule_timer(ssh->cfg.ssh_rekey_time*60*TICKSPERSEC,
6093 goto wait_for_rekey; /* this is utterly horrid */
6095 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
6098 goto begin_key_exchange;
6104 * Add data to an SSH-2 channel output buffer.
6106 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
6109 bufchain_add(&c->v.v2.outbuffer, buf, len);
6113 * Attempt to send data on an SSH-2 channel.
6115 static int ssh2_try_send(struct ssh_channel *c)
6118 struct Packet *pktout;
6120 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
6123 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
6124 if ((unsigned)len > c->v.v2.remwindow)
6125 len = c->v.v2.remwindow;
6126 if ((unsigned)len > c->v.v2.remmaxpkt)
6127 len = c->v.v2.remmaxpkt;
6128 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
6129 ssh2_pkt_adduint32(pktout, c->remoteid);
6130 ssh2_pkt_addstring_start(pktout);
6131 dont_log_data(ssh, pktout, PKTLOG_OMIT);
6132 ssh2_pkt_addstring_data(pktout, data, len);
6133 end_log_omission(ssh, pktout);
6134 ssh2_pkt_send(ssh, pktout);
6135 bufchain_consume(&c->v.v2.outbuffer, len);
6136 c->v.v2.remwindow -= len;
6140 * After having sent as much data as we can, return the amount
6143 return bufchain_size(&c->v.v2.outbuffer);
6146 static void ssh2_try_send_and_unthrottle(struct ssh_channel *c)
6150 return; /* don't send on closing channels */
6151 bufsize = ssh2_try_send(c);
6154 case CHAN_MAINSESSION:
6155 /* stdin need not receive an unthrottle
6156 * notification since it will be polled */
6159 x11_unthrottle(c->u.x11.s);
6162 /* agent sockets are request/response and need no
6163 * buffer management */
6166 pfd_unthrottle(c->u.pfd.s);
6173 * Potentially enlarge the window on an SSH-2 channel.
6175 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin)
6180 * Never send WINDOW_ADJUST for a channel that the remote side
6181 * already thinks it's closed; there's no point, since it won't
6182 * be sending any more data anyway.
6188 * Only send a WINDOW_ADJUST if there's significantly more window
6189 * available than the other end thinks there is. This saves us
6190 * sending a WINDOW_ADJUST for every character in a shell session.
6192 * "Significant" is arbitrarily defined as half the window size.
6194 if (newwin / 2 >= c->v.v2.locwindow) {
6195 struct Packet *pktout;
6197 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
6198 ssh2_pkt_adduint32(pktout, c->remoteid);
6199 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
6200 ssh2_pkt_send(ssh, pktout);
6201 c->v.v2.locwindow = newwin;
6205 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
6207 unsigned i = ssh_pkt_getuint32(pktin);
6208 struct ssh_channel *c;
6209 c = find234(ssh->channels, &i, ssh_channelfind);
6210 if (c && !c->closes) {
6211 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
6212 ssh2_try_send_and_unthrottle(c);
6216 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
6220 unsigned i = ssh_pkt_getuint32(pktin);
6221 struct ssh_channel *c;
6222 c = find234(ssh->channels, &i, ssh_channelfind);
6224 return; /* nonexistent channel */
6225 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
6226 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
6227 return; /* extended but not stderr */
6228 ssh_pkt_getstring(pktin, &data, &length);
6231 c->v.v2.locwindow -= length;
6233 case CHAN_MAINSESSION:
6235 from_backend(ssh->frontend, pktin->type ==
6236 SSH2_MSG_CHANNEL_EXTENDED_DATA,
6240 bufsize = x11_send(c->u.x11.s, data, length);
6243 bufsize = pfd_send(c->u.pfd.s, data, length);
6246 while (length > 0) {
6247 if (c->u.a.lensofar < 4) {
6248 unsigned int l = min(4 - c->u.a.lensofar,
6250 memcpy(c->u.a.msglen + c->u.a.lensofar,
6254 c->u.a.lensofar += l;
6256 if (c->u.a.lensofar == 4) {
6258 4 + GET_32BIT(c->u.a.msglen);
6259 c->u.a.message = snewn(c->u.a.totallen,
6261 memcpy(c->u.a.message, c->u.a.msglen, 4);
6263 if (c->u.a.lensofar >= 4 && length > 0) {
6265 min(c->u.a.totallen - c->u.a.lensofar,
6267 memcpy(c->u.a.message + c->u.a.lensofar,
6271 c->u.a.lensofar += l;
6273 if (c->u.a.lensofar == c->u.a.totallen) {
6276 if (agent_query(c->u.a.message,
6279 ssh_agentf_callback, c))
6280 ssh_agentf_callback(c, reply, replylen);
6281 sfree(c->u.a.message);
6282 c->u.a.lensofar = 0;
6289 * If we are not buffering too much data,
6290 * enlarge the window again at the remote side.
6291 * If we are buffering too much, we may still
6292 * need to adjust the window if the server's
6295 ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
6296 c->v.v2.locmaxwin - bufsize : 0);
6300 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
6302 unsigned i = ssh_pkt_getuint32(pktin);
6303 struct ssh_channel *c;
6305 c = find234(ssh->channels, &i, ssh_channelfind);
6307 return; /* nonexistent channel */
6309 if (c->type == CHAN_X11) {
6311 * Remote EOF on an X11 channel means we should
6312 * wrap up and close the channel ourselves.
6314 x11_close(c->u.x11.s);
6316 } else if (c->type == CHAN_AGENT) {
6318 } else if (c->type == CHAN_SOCKDATA) {
6319 pfd_close(c->u.pfd.s);
6324 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
6326 unsigned i = ssh_pkt_getuint32(pktin);
6327 struct ssh_channel *c;
6328 struct Packet *pktout;
6330 c = find234(ssh->channels, &i, ssh_channelfind);
6331 if (!c || c->halfopen) {
6332 bombout(("Received CHANNEL_CLOSE for %s channel %d\n",
6333 c ? "half-open" : "nonexistent", i));
6336 /* Do pre-close processing on the channel. */
6338 case CHAN_MAINSESSION:
6339 ssh->mainchan = NULL;
6340 update_specials_menu(ssh->frontend);
6343 if (c->u.x11.s != NULL)
6344 x11_close(c->u.x11.s);
6351 if (c->u.pfd.s != NULL)
6352 pfd_close(c->u.pfd.s);
6356 if (c->closes == 0) {
6357 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
6358 ssh2_pkt_adduint32(pktout, c->remoteid);
6359 ssh2_pkt_send(ssh, pktout);
6361 del234(ssh->channels, c);
6362 bufchain_clear(&c->v.v2.outbuffer);
6366 * See if that was the last channel left open.
6367 * (This is only our termination condition if we're
6368 * not running in -N mode.)
6370 if (!ssh->cfg.ssh_no_shell && count234(ssh->channels) == 0) {
6372 * We used to send SSH_MSG_DISCONNECT here,
6373 * because I'd believed that _every_ conforming
6374 * SSH-2 connection had to end with a disconnect
6375 * being sent by at least one side; apparently
6376 * I was wrong and it's perfectly OK to
6377 * unceremoniously slam the connection shut
6378 * when you're done, and indeed OpenSSH feels
6379 * this is more polite than sending a
6380 * DISCONNECT. So now we don't.
6382 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
6386 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
6388 unsigned i = ssh_pkt_getuint32(pktin);
6389 struct ssh_channel *c;
6390 struct Packet *pktout;
6392 c = find234(ssh->channels, &i, ssh_channelfind);
6394 return; /* nonexistent channel */
6395 if (c->type != CHAN_SOCKDATA_DORMANT)
6396 return; /* dunno why they're confirming this */
6397 c->remoteid = ssh_pkt_getuint32(pktin);
6398 c->halfopen = FALSE;
6399 c->type = CHAN_SOCKDATA;
6400 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
6401 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
6403 pfd_confirm(c->u.pfd.s);
6406 * We have a pending close on this channel,
6407 * which we decided on before the server acked
6408 * the channel open. So now we know the
6409 * remoteid, we can close it again.
6411 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
6412 ssh2_pkt_adduint32(pktout, c->remoteid);
6413 ssh2_pkt_send(ssh, pktout);
6417 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
6419 static const char *const reasons[] = {
6420 "<unknown reason code>",
6421 "Administratively prohibited",
6423 "Unknown channel type",
6424 "Resource shortage",
6426 unsigned i = ssh_pkt_getuint32(pktin);
6427 unsigned reason_code;
6428 char *reason_string;
6430 struct ssh_channel *c;
6431 c = find234(ssh->channels, &i, ssh_channelfind);
6433 return; /* nonexistent channel */
6434 if (c->type != CHAN_SOCKDATA_DORMANT)
6435 return; /* dunno why they're failing this */
6437 reason_code = ssh_pkt_getuint32(pktin);
6438 if (reason_code >= lenof(reasons))
6439 reason_code = 0; /* ensure reasons[reason_code] in range */
6440 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
6441 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
6442 reasons[reason_code], reason_length, reason_string);
6444 pfd_close(c->u.pfd.s);
6446 del234(ssh->channels, c);
6450 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
6454 int typelen, want_reply;
6455 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
6456 struct ssh_channel *c;
6457 struct Packet *pktout;
6459 localid = ssh_pkt_getuint32(pktin);
6460 ssh_pkt_getstring(pktin, &type, &typelen);
6461 want_reply = ssh2_pkt_getbool(pktin);
6464 * First, check that the channel exists. Otherwise,
6465 * we can instantly disconnect with a rude message.
6467 c = find234(ssh->channels, &localid, ssh_channelfind);
6469 char *buf = dupprintf("Received channel request for nonexistent"
6470 " channel %d", localid);
6471 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6477 * Having got the channel number, we now look at
6478 * the request type string to see if it's something
6481 if (c == ssh->mainchan) {
6483 * We recognise "exit-status" and "exit-signal" on
6484 * the primary channel.
6486 if (typelen == 11 &&
6487 !memcmp(type, "exit-status", 11)) {
6489 ssh->exitcode = ssh_pkt_getuint32(pktin);
6490 logeventf(ssh, "Server sent command exit status %d",
6492 reply = SSH2_MSG_CHANNEL_SUCCESS;
6494 } else if (typelen == 11 &&
6495 !memcmp(type, "exit-signal", 11)) {
6497 int is_plausible = TRUE, is_int = FALSE;
6498 char *fmt_sig = "", *fmt_msg = "";
6500 int msglen = 0, core = FALSE;
6501 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
6502 * provide an `int' for the signal, despite its
6503 * having been a `string' in the drafts since at
6504 * least 2001. (Fixed in session.c 1.147.) Try to
6505 * infer which we can safely parse it as. */
6507 unsigned char *p = pktin->body +
6509 long len = pktin->length - pktin->savedpos;
6510 unsigned long num = GET_32BIT(p); /* what is it? */
6511 /* If it's 0, it hardly matters; assume string */
6515 int maybe_int = FALSE, maybe_str = FALSE;
6516 #define CHECK_HYPOTHESIS(offset, result) \
6519 if (q >= 0 && q+4 <= len) { \
6520 q = q + 4 + GET_32BIT(p+q); \
6521 if (q >= 0 && q+4 <= len && \
6522 ((q = q + 4 + GET_32BIT(p+q))!= 0) && q == len) \
6526 CHECK_HYPOTHESIS(4+1, maybe_int);
6527 CHECK_HYPOTHESIS(4+num+1, maybe_str);
6528 #undef CHECK_HYPOTHESIS
6529 if (maybe_int && !maybe_str)
6531 else if (!maybe_int && maybe_str)
6534 /* Crikey. Either or neither. Panic. */
6535 is_plausible = FALSE;
6538 ssh->exitcode = 128; /* means `unknown signal' */
6541 /* Old non-standard OpenSSH. */
6542 int signum = ssh_pkt_getuint32(pktin);
6543 fmt_sig = dupprintf(" %d", signum);
6544 ssh->exitcode = 128 + signum;
6546 /* As per the drafts. */
6549 ssh_pkt_getstring(pktin, &sig, &siglen);
6550 /* Signal name isn't supposed to be blank, but
6551 * let's cope gracefully if it is. */
6553 fmt_sig = dupprintf(" \"%.*s\"",
6558 * Really hideous method of translating the
6559 * signal description back into a locally
6560 * meaningful number.
6565 #define TRANSLATE_SIGNAL(s) \
6566 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
6567 ssh->exitcode = 128 + SIG ## s
6569 TRANSLATE_SIGNAL(ABRT);
6572 TRANSLATE_SIGNAL(ALRM);
6575 TRANSLATE_SIGNAL(FPE);
6578 TRANSLATE_SIGNAL(HUP);
6581 TRANSLATE_SIGNAL(ILL);
6584 TRANSLATE_SIGNAL(INT);
6587 TRANSLATE_SIGNAL(KILL);
6590 TRANSLATE_SIGNAL(PIPE);
6593 TRANSLATE_SIGNAL(QUIT);
6596 TRANSLATE_SIGNAL(SEGV);
6599 TRANSLATE_SIGNAL(TERM);
6602 TRANSLATE_SIGNAL(USR1);
6605 TRANSLATE_SIGNAL(USR2);
6607 #undef TRANSLATE_SIGNAL
6609 ssh->exitcode = 128;
6611 core = ssh2_pkt_getbool(pktin);
6612 ssh_pkt_getstring(pktin, &msg, &msglen);
6614 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
6616 /* ignore lang tag */
6617 } /* else don't attempt to parse */
6618 logeventf(ssh, "Server exited on signal%s%s%s",
6619 fmt_sig, core ? " (core dumped)" : "",
6621 if (*fmt_sig) sfree(fmt_sig);
6622 if (*fmt_msg) sfree(fmt_msg);
6623 reply = SSH2_MSG_CHANNEL_SUCCESS;
6628 * This is a channel request we don't know
6629 * about, so we now either ignore the request
6630 * or respond with CHANNEL_FAILURE, depending
6633 reply = SSH2_MSG_CHANNEL_FAILURE;
6636 pktout = ssh2_pkt_init(reply);
6637 ssh2_pkt_adduint32(pktout, c->remoteid);
6638 ssh2_pkt_send(ssh, pktout);
6642 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
6645 int typelen, want_reply;
6646 struct Packet *pktout;
6648 ssh_pkt_getstring(pktin, &type, &typelen);
6649 want_reply = ssh2_pkt_getbool(pktin);
6652 * We currently don't support any global requests
6653 * at all, so we either ignore the request or
6654 * respond with REQUEST_FAILURE, depending on
6658 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
6659 ssh2_pkt_send(ssh, pktout);
6663 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
6671 struct ssh_channel *c;
6672 unsigned remid, winsize, pktsize;
6673 struct Packet *pktout;
6675 ssh_pkt_getstring(pktin, &type, &typelen);
6676 c = snew(struct ssh_channel);
6679 remid = ssh_pkt_getuint32(pktin);
6680 winsize = ssh_pkt_getuint32(pktin);
6681 pktsize = ssh_pkt_getuint32(pktin);
6683 if (typelen == 3 && !memcmp(type, "x11", 3)) {
6686 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
6687 addrstr = snewn(peeraddrlen+1, char);
6688 memcpy(addrstr, peeraddr, peeraddrlen);
6689 addrstr[peeraddrlen] = '\0';
6690 peerport = ssh_pkt_getuint32(pktin);
6692 logeventf(ssh, "Received X11 connect request from %s:%d",
6695 if (!ssh->X11_fwd_enabled)
6696 error = "X11 forwarding is not enabled";
6697 else if (x11_init(&c->u.x11.s, ssh->cfg.x11_display, c,
6698 ssh->x11auth, addrstr, peerport,
6699 &ssh->cfg) != NULL) {
6700 error = "Unable to open an X11 connection";
6702 logevent("Opening X11 forward connection succeeded");
6707 } else if (typelen == 15 &&
6708 !memcmp(type, "forwarded-tcpip", 15)) {
6709 struct ssh_rportfwd pf, *realpf;
6712 ssh_pkt_getstring(pktin, &dummy, &dummylen);/* skip address */
6713 pf.sport = ssh_pkt_getuint32(pktin);
6714 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
6715 peerport = ssh_pkt_getuint32(pktin);
6716 realpf = find234(ssh->rportfwds, &pf, NULL);
6717 logeventf(ssh, "Received remote port %d open request "
6718 "from %s:%d", pf.sport, peeraddr, peerport);
6719 if (realpf == NULL) {
6720 error = "Remote port is not recognised";
6722 const char *e = pfd_newconnect(&c->u.pfd.s,
6726 realpf->pfrec->addressfamily);
6727 logeventf(ssh, "Attempting to forward remote port to "
6728 "%s:%d", realpf->dhost, realpf->dport);
6730 logeventf(ssh, "Port open failed: %s", e);
6731 error = "Port open failed";
6733 logevent("Forwarded port opened successfully");
6734 c->type = CHAN_SOCKDATA;
6737 } else if (typelen == 22 &&
6738 !memcmp(type, "auth-agent@openssh.com", 22)) {
6739 if (!ssh->agentfwd_enabled)
6740 error = "Agent forwarding is not enabled";
6742 c->type = CHAN_AGENT; /* identify channel type */
6743 c->u.a.lensofar = 0;
6746 error = "Unsupported channel type requested";
6749 c->remoteid = remid;
6750 c->halfopen = FALSE;
6752 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
6753 ssh2_pkt_adduint32(pktout, c->remoteid);
6754 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
6755 ssh2_pkt_addstring(pktout, error);
6756 ssh2_pkt_addstring(pktout, "en"); /* language tag */
6757 ssh2_pkt_send(ssh, pktout);
6758 logeventf(ssh, "Rejected channel open: %s", error);
6761 c->localid = alloc_channel_id(ssh);
6763 c->v.v2.locwindow = c->v.v2.locmaxwin = OUR_V2_WINSIZE;
6764 c->v.v2.remwindow = winsize;
6765 c->v.v2.remmaxpkt = pktsize;
6766 bufchain_init(&c->v.v2.outbuffer);
6767 add234(ssh->channels, c);
6768 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
6769 ssh2_pkt_adduint32(pktout, c->remoteid);
6770 ssh2_pkt_adduint32(pktout, c->localid);
6771 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
6772 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
6773 ssh2_pkt_send(ssh, pktout);
6778 * Buffer banner messages for later display at some convenient point.
6780 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
6782 /* Arbitrary limit to prevent unbounded inflation of buffer */
6783 if (bufchain_size(&ssh->banner) <= 131072) {
6784 char *banner = NULL;
6786 ssh_pkt_getstring(pktin, &banner, &size);
6788 bufchain_add(&ssh->banner, banner, size);
6792 /* Helper function to deal with sending tty modes for "pty-req" */
6793 static void ssh2_send_ttymode(void *data, char *mode, char *val)
6795 struct Packet *pktout = (struct Packet *)data;
6797 unsigned int arg = 0;
6798 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
6799 if (i == lenof(ssh_ttymodes)) return;
6800 switch (ssh_ttymodes[i].type) {
6802 arg = ssh_tty_parse_specchar(val);
6805 arg = ssh_tty_parse_boolean(val);
6808 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
6809 ssh2_pkt_adduint32(pktout, arg);
6813 * Handle the SSH-2 userauth and connection layers.
6815 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
6816 struct Packet *pktin)
6818 struct do_ssh2_authconn_state {
6821 AUTH_TYPE_PUBLICKEY,
6822 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
6823 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
6825 AUTH_TYPE_KEYBOARD_INTERACTIVE,
6826 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
6828 int done_service_req;
6829 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
6830 int tried_pubkey_config, done_agent;
6831 int kbd_inter_refused;
6833 prompts_t *cur_prompt;
6838 void *publickey_blob;
6839 int publickey_bloblen;
6840 int publickey_encrypted;
6841 char *publickey_algorithm;
6842 char *publickey_comment;
6843 unsigned char agent_request[5], *agent_response, *agentp;
6844 int agent_responselen;
6845 unsigned char *pkblob_in_agent;
6847 char *pkblob, *alg, *commentp;
6848 int pklen, alglen, commentlen;
6849 int siglen, retlen, len;
6850 char *q, *agentreq, *ret;
6852 int num_env, env_left, env_ok;
6853 struct Packet *pktout;
6855 crState(do_ssh2_authconn_state);
6857 crBegin(ssh->do_ssh2_authconn_crstate);
6859 s->done_service_req = FALSE;
6860 s->we_are_in = FALSE;
6861 if (!ssh->cfg.ssh_no_userauth) {
6863 * Request userauth protocol, and await a response to it.
6865 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
6866 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
6867 ssh2_pkt_send(ssh, s->pktout);
6868 crWaitUntilV(pktin);
6869 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
6870 s->done_service_req = TRUE;
6872 if (!s->done_service_req) {
6874 * Request connection protocol directly, without authentication.
6876 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
6877 ssh2_pkt_addstring(s->pktout, "ssh-connection");
6878 ssh2_pkt_send(ssh, s->pktout);
6879 crWaitUntilV(pktin);
6880 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
6881 s->we_are_in = TRUE; /* no auth required */
6883 bombout(("Server refused service request"));
6888 /* Arrange to be able to deal with any BANNERs that come in.
6889 * (We do this now as packets may come in during the next bit.) */
6890 bufchain_init(&ssh->banner);
6891 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
6892 ssh2_msg_userauth_banner;
6895 * Misc one-time setup for authentication.
6897 s->publickey_blob = NULL;
6898 if (!s->we_are_in) {
6901 * Load the public half of any configured public key file
6904 if (!filename_is_null(ssh->cfg.keyfile)) {
6906 logeventf(ssh, "Reading private key file \"%.150s\"",
6907 filename_to_str(&ssh->cfg.keyfile));
6908 keytype = key_type(&ssh->cfg.keyfile);
6909 if (keytype == SSH_KEYTYPE_SSH2) {
6912 ssh2_userkey_loadpub(&ssh->cfg.keyfile,
6913 &s->publickey_algorithm,
6914 &s->publickey_bloblen,
6915 &s->publickey_comment, &error);
6916 if (s->publickey_blob) {
6917 s->publickey_encrypted =
6918 ssh2_userkey_encrypted(&ssh->cfg.keyfile, NULL);
6921 logeventf(ssh, "Unable to load private key (%s)",
6923 msgbuf = dupprintf("Unable to load private key file "
6924 "\"%.150s\" (%s)\r\n",
6925 filename_to_str(&ssh->cfg.keyfile),
6927 c_write_str(ssh, msgbuf);
6932 logeventf(ssh, "Unable to use this key file (%s)",
6933 key_type_to_str(keytype));
6934 msgbuf = dupprintf("Unable to use key file \"%.150s\""
6936 filename_to_str(&ssh->cfg.keyfile),
6937 key_type_to_str(keytype));
6938 c_write_str(ssh, msgbuf);
6940 s->publickey_blob = NULL;
6945 * Find out about any keys Pageant has (but if there's a
6946 * public key configured, filter out all others).
6949 s->agent_response = NULL;
6950 s->pkblob_in_agent = NULL;
6951 if (ssh->cfg.tryagent && agent_exists()) {
6955 logevent("Pageant is running. Requesting keys.");
6957 /* Request the keys held by the agent. */
6958 PUT_32BIT(s->agent_request, 1);
6959 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
6960 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
6961 ssh_agent_callback, ssh)) {
6965 bombout(("Unexpected data from server while"
6966 " waiting for agent response"));
6969 } while (pktin || inlen > 0);
6970 r = ssh->agent_response;
6971 s->agent_responselen = ssh->agent_response_len;
6973 s->agent_response = (unsigned char *) r;
6974 if (s->agent_response && s->agent_responselen >= 5 &&
6975 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
6978 p = s->agent_response + 5;
6979 s->nkeys = GET_32BIT(p);
6981 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
6982 if (s->publickey_blob) {
6983 /* See if configured key is in agent. */
6984 for (keyi = 0; keyi < s->nkeys; keyi++) {
6985 s->pklen = GET_32BIT(p);
6986 if (s->pklen == s->publickey_bloblen &&
6987 !memcmp(p+4, s->publickey_blob,
6988 s->publickey_bloblen)) {
6989 logeventf(ssh, "Pageant key #%d matches "
6990 "configured key file", keyi);
6992 s->pkblob_in_agent = p;
6996 p += GET_32BIT(p) + 4; /* comment */
6998 if (!s->pkblob_in_agent) {
6999 logevent("Configured key file not in Pageant");
7009 * We repeat this whole loop, including the username prompt,
7010 * until we manage a successful authentication. If the user
7011 * types the wrong _password_, they can be sent back to the
7012 * beginning to try another username, if this is configured on.
7013 * (If they specify a username in the config, they are never
7014 * asked, even if they do give a wrong password.)
7016 * I think this best serves the needs of
7018 * - the people who have no configuration, no keys, and just
7019 * want to try repeated (username,password) pairs until they
7020 * type both correctly
7022 * - people who have keys and configuration but occasionally
7023 * need to fall back to passwords
7025 * - people with a key held in Pageant, who might not have
7026 * logged in to a particular machine before; so they want to
7027 * type a username, and then _either_ their key will be
7028 * accepted, _or_ they will type a password. If they mistype
7029 * the username they will want to be able to get back and
7032 s->username[0] = '\0';
7033 s->got_username = FALSE;
7034 while (!s->we_are_in) {
7038 if (s->got_username && !ssh->cfg.change_username) {
7040 * We got a username last time round this loop, and
7041 * with change_username turned off we don't try to get
7044 } else if (!*ssh->cfg.username) {
7045 int ret; /* need not be kept over crReturn */
7046 s->cur_prompt = new_prompts(ssh->frontend);
7047 s->cur_prompt->to_server = TRUE;
7048 s->cur_prompt->name = dupstr("SSH login name");
7049 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE,
7050 lenof(s->username));
7051 ret = get_userpass_input(s->cur_prompt, NULL, 0);
7054 crWaitUntilV(!pktin);
7055 ret = get_userpass_input(s->cur_prompt, in, inlen);
7060 * get_userpass_input() failed to get a username.
7063 free_prompts(s->cur_prompt);
7064 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
7067 memcpy(s->username, s->cur_prompt->prompts[0]->result,
7068 lenof(s->username));
7069 free_prompts(s->cur_prompt);
7072 strncpy(s->username, ssh->cfg.username, sizeof(s->username));
7073 s->username[sizeof(s->username)-1] = '\0';
7074 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
7075 stuff = dupprintf("Using username \"%s\".\r\n", s->username);
7076 c_write_str(ssh, stuff);
7080 s->got_username = TRUE;
7083 * Send an authentication request using method "none": (a)
7084 * just in case it succeeds, and (b) so that we know what
7085 * authentication methods we can usefully try next.
7087 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
7089 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7090 ssh2_pkt_addstring(s->pktout, s->username);
7091 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
7092 ssh2_pkt_addstring(s->pktout, "none"); /* method */
7093 ssh2_pkt_send(ssh, s->pktout);
7094 s->type = AUTH_TYPE_NONE;
7096 s->we_are_in = FALSE;
7098 s->tried_pubkey_config = FALSE;
7099 s->kbd_inter_refused = FALSE;
7101 /* Reset agent request state. */
7102 s->done_agent = FALSE;
7103 if (s->agent_response) {
7104 if (s->pkblob_in_agent) {
7105 s->agentp = s->pkblob_in_agent;
7107 s->agentp = s->agent_response + 5 + 4;
7114 * Wait for the result of the last authentication request.
7117 crWaitUntilV(pktin);
7119 * Now is a convenient point to spew any banner material
7120 * that we've accumulated. (This should ensure that when
7121 * we exit the auth loop, we haven't any left to deal
7125 int size = bufchain_size(&ssh->banner);
7127 * Don't show the banner if we're operating in
7128 * non-verbose non-interactive mode. (It's probably
7129 * a script, which means nobody will read the
7130 * banner _anyway_, and moreover the printing of
7131 * the banner will screw up processing on the
7132 * output of (say) plink.)
7134 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
7135 char *banner = snewn(size, char);
7136 bufchain_fetch(&ssh->banner, banner, size);
7137 c_write_untrusted(ssh, banner, size);
7140 bufchain_clear(&ssh->banner);
7142 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
7143 logevent("Access granted");
7144 s->we_are_in = TRUE;
7148 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE) {
7149 bombout(("Strange packet received during authentication: "
7150 "type %d", pktin->type));
7157 * OK, we're now sitting on a USERAUTH_FAILURE message, so
7158 * we can look at the string in it and know what we can
7159 * helpfully try next.
7161 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
7164 ssh_pkt_getstring(pktin, &methods, &methlen);
7165 if (!ssh2_pkt_getbool(pktin)) {
7167 * We have received an unequivocal Access
7168 * Denied. This can translate to a variety of
7171 * - if we'd just tried "none" authentication,
7172 * it's not worth printing anything at all
7174 * - if we'd just tried a public key _offer_,
7175 * the message should be "Server refused our
7176 * key" (or no message at all if the key
7177 * came from Pageant)
7179 * - if we'd just tried anything else, the
7180 * message really should be "Access denied".
7182 * Additionally, if we'd just tried password
7183 * authentication, we should break out of this
7184 * whole loop so as to go back to the username
7185 * prompt (iff we're configured to allow
7186 * username change attempts).
7188 if (s->type == AUTH_TYPE_NONE) {
7190 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
7191 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
7192 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
7193 c_write_str(ssh, "Server refused our key\r\n");
7194 logevent("Server refused public key");
7195 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
7196 /* server declined keyboard-interactive; ignore */
7198 c_write_str(ssh, "Access denied\r\n");
7199 logevent("Access denied");
7200 if (s->type == AUTH_TYPE_PASSWORD &&
7201 ssh->cfg.change_username) {
7202 /* XXX perhaps we should allow
7203 * keyboard-interactive to do this too? */
7204 s->we_are_in = FALSE;
7209 c_write_str(ssh, "Further authentication required\r\n");
7210 logevent("Further authentication required");
7214 in_commasep_string("publickey", methods, methlen);
7216 in_commasep_string("password", methods, methlen);
7217 s->can_keyb_inter = ssh->cfg.try_ki_auth &&
7218 in_commasep_string("keyboard-interactive", methods, methlen);
7221 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
7223 if (s->can_pubkey && !s->done_agent && s->nkeys) {
7226 * Attempt public-key authentication using a key from Pageant.
7229 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
7231 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
7233 /* Unpack key from agent response */
7234 s->pklen = GET_32BIT(s->agentp);
7236 s->pkblob = (char *)s->agentp;
7237 s->agentp += s->pklen;
7238 s->alglen = GET_32BIT(s->pkblob);
7239 s->alg = s->pkblob + 4;
7240 s->commentlen = GET_32BIT(s->agentp);
7242 s->commentp = (char *)s->agentp;
7243 s->agentp += s->commentlen;
7244 /* s->agentp now points at next key, if any */
7246 /* See if server will accept it */
7247 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7248 ssh2_pkt_addstring(s->pktout, s->username);
7249 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7250 /* service requested */
7251 ssh2_pkt_addstring(s->pktout, "publickey");
7253 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
7254 ssh2_pkt_addstring_start(s->pktout);
7255 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
7256 ssh2_pkt_addstring_start(s->pktout);
7257 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
7258 ssh2_pkt_send(ssh, s->pktout);
7259 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
7261 crWaitUntilV(pktin);
7262 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
7264 /* Offer of key refused. */
7271 if (flags & FLAG_VERBOSE) {
7272 c_write_str(ssh, "Authenticating with "
7274 c_write(ssh, s->commentp, s->commentlen);
7275 c_write_str(ssh, "\" from agent\r\n");
7279 * Server is willing to accept the key.
7280 * Construct a SIGN_REQUEST.
7282 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7283 ssh2_pkt_addstring(s->pktout, s->username);
7284 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7285 /* service requested */
7286 ssh2_pkt_addstring(s->pktout, "publickey");
7288 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
7289 ssh2_pkt_addstring_start(s->pktout);
7290 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
7291 ssh2_pkt_addstring_start(s->pktout);
7292 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
7294 /* Ask agent for signature. */
7295 s->siglen = s->pktout->length - 5 + 4 +
7296 ssh->v2_session_id_len;
7297 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
7299 s->len = 1; /* message type */
7300 s->len += 4 + s->pklen; /* key blob */
7301 s->len += 4 + s->siglen; /* data to sign */
7302 s->len += 4; /* flags */
7303 s->agentreq = snewn(4 + s->len, char);
7304 PUT_32BIT(s->agentreq, s->len);
7305 s->q = s->agentreq + 4;
7306 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
7307 PUT_32BIT(s->q, s->pklen);
7309 memcpy(s->q, s->pkblob, s->pklen);
7311 PUT_32BIT(s->q, s->siglen);
7313 /* Now the data to be signed... */
7314 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
7315 PUT_32BIT(s->q, ssh->v2_session_id_len);
7318 memcpy(s->q, ssh->v2_session_id,
7319 ssh->v2_session_id_len);
7320 s->q += ssh->v2_session_id_len;
7321 memcpy(s->q, s->pktout->data + 5,
7322 s->pktout->length - 5);
7323 s->q += s->pktout->length - 5;
7324 /* And finally the (zero) flags word. */
7326 if (!agent_query(s->agentreq, s->len + 4,
7328 ssh_agent_callback, ssh)) {
7332 bombout(("Unexpected data from server"
7333 " while waiting for agent"
7337 } while (pktin || inlen > 0);
7338 vret = ssh->agent_response;
7339 s->retlen = ssh->agent_response_len;
7344 if (s->ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
7345 logevent("Sending Pageant's response");
7346 ssh2_add_sigblob(ssh, s->pktout,
7347 s->pkblob, s->pklen,
7349 GET_32BIT(s->ret + 5));
7350 ssh2_pkt_send(ssh, s->pktout);
7351 s->type = AUTH_TYPE_PUBLICKEY;
7353 /* FIXME: less drastic response */
7354 bombout(("Pageant failed to answer challenge"));
7360 /* Do we have any keys left to try? */
7361 if (s->pkblob_in_agent) {
7362 s->done_agent = TRUE;
7363 s->tried_pubkey_config = TRUE;
7366 if (s->keyi >= s->nkeys)
7367 s->done_agent = TRUE;
7370 } else if (s->can_pubkey && s->publickey_blob &&
7371 !s->tried_pubkey_config) {
7373 struct ssh2_userkey *key; /* not live over crReturn */
7374 char *passphrase; /* not live over crReturn */
7376 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
7378 s->tried_pubkey_config = TRUE;
7381 * Try the public key supplied in the configuration.
7383 * First, offer the public blob to see if the server is
7384 * willing to accept it.
7386 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7387 ssh2_pkt_addstring(s->pktout, s->username);
7388 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7389 /* service requested */
7390 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
7391 ssh2_pkt_addbool(s->pktout, FALSE);
7392 /* no signature included */
7393 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
7394 ssh2_pkt_addstring_start(s->pktout);
7395 ssh2_pkt_addstring_data(s->pktout,
7396 (char *)s->publickey_blob,
7397 s->publickey_bloblen);
7398 ssh2_pkt_send(ssh, s->pktout);
7399 logevent("Offered public key");
7401 crWaitUntilV(pktin);
7402 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
7403 /* Key refused. Give up. */
7404 s->gotit = TRUE; /* reconsider message next loop */
7405 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
7406 continue; /* process this new message */
7408 logevent("Offer of public key accepted");
7411 * Actually attempt a serious authentication using
7414 if (flags & FLAG_VERBOSE) {
7415 c_write_str(ssh, "Authenticating with public key \"");
7416 c_write_str(ssh, s->publickey_comment);
7417 c_write_str(ssh, "\"\r\n");
7421 const char *error; /* not live over crReturn */
7422 if (s->publickey_encrypted) {
7424 * Get a passphrase from the user.
7426 int ret; /* need not be kept over crReturn */
7427 s->cur_prompt = new_prompts(ssh->frontend);
7428 s->cur_prompt->to_server = FALSE;
7429 s->cur_prompt->name = dupstr("SSH key passphrase");
7430 add_prompt(s->cur_prompt,
7431 dupprintf("Passphrase for key \"%.100s\": ",
7432 s->publickey_comment),
7433 FALSE, SSH_MAX_PASSWORD_LEN);
7434 ret = get_userpass_input(s->cur_prompt, NULL, 0);
7437 crWaitUntilV(!pktin);
7438 ret = get_userpass_input(s->cur_prompt,
7443 /* Failed to get a passphrase. Terminate. */
7444 free_prompts(s->cur_prompt);
7445 ssh_disconnect(ssh, NULL,
7446 "Unable to authenticate",
7447 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
7452 dupstr(s->cur_prompt->prompts[0]->result);
7453 free_prompts(s->cur_prompt);
7455 passphrase = NULL; /* no passphrase needed */
7459 * Try decrypting the key.
7461 key = ssh2_load_userkey(&ssh->cfg.keyfile, passphrase,
7464 /* burn the evidence */
7465 memset(passphrase, 0, strlen(passphrase));
7468 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
7470 (key == SSH2_WRONG_PASSPHRASE)) {
7471 c_write_str(ssh, "Wrong passphrase\r\n");
7473 /* and loop again */
7475 c_write_str(ssh, "Unable to load private key (");
7476 c_write_str(ssh, error);
7477 c_write_str(ssh, ")\r\n");
7479 break; /* try something else */
7485 unsigned char *pkblob, *sigblob, *sigdata;
7486 int pkblob_len, sigblob_len, sigdata_len;
7490 * We have loaded the private key and the server
7491 * has announced that it's willing to accept it.
7492 * Hallelujah. Generate a signature and send it.
7494 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7495 ssh2_pkt_addstring(s->pktout, s->username);
7496 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7497 /* service requested */
7498 ssh2_pkt_addstring(s->pktout, "publickey");
7500 ssh2_pkt_addbool(s->pktout, TRUE);
7501 /* signature follows */
7502 ssh2_pkt_addstring(s->pktout, key->alg->name);
7503 pkblob = key->alg->public_blob(key->data,
7505 ssh2_pkt_addstring_start(s->pktout);
7506 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
7510 * The data to be signed is:
7514 * followed by everything so far placed in the
7517 sigdata_len = s->pktout->length - 5 + 4 +
7518 ssh->v2_session_id_len;
7519 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
7521 sigdata = snewn(sigdata_len, unsigned char);
7523 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
7524 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
7527 memcpy(sigdata+p, ssh->v2_session_id,
7528 ssh->v2_session_id_len);
7529 p += ssh->v2_session_id_len;
7530 memcpy(sigdata+p, s->pktout->data + 5,
7531 s->pktout->length - 5);
7532 p += s->pktout->length - 5;
7533 assert(p == sigdata_len);
7534 sigblob = key->alg->sign(key->data, (char *)sigdata,
7535 sigdata_len, &sigblob_len);
7536 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
7537 sigblob, sigblob_len);
7542 ssh2_pkt_send(ssh, s->pktout);
7543 s->type = AUTH_TYPE_PUBLICKEY;
7544 key->alg->freekey(key->data);
7547 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
7550 * Keyboard-interactive authentication.
7553 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
7555 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
7557 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7558 ssh2_pkt_addstring(s->pktout, s->username);
7559 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7560 /* service requested */
7561 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
7563 ssh2_pkt_addstring(s->pktout, ""); /* lang */
7564 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
7565 ssh2_pkt_send(ssh, s->pktout);
7567 crWaitUntilV(pktin);
7568 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
7569 /* Server is not willing to do keyboard-interactive
7570 * at all (or, bizarrely but legally, accepts the
7571 * user without actually issuing any prompts).
7572 * Give up on it entirely. */
7574 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE)
7575 logevent("Keyboard-interactive authentication refused");
7576 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
7577 s->kbd_inter_refused = TRUE; /* don't try it again */
7582 * Loop while the server continues to send INFO_REQUESTs.
7584 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
7586 char *name, *inst, *lang;
7587 int name_len, inst_len, lang_len;
7591 * We've got a fresh USERAUTH_INFO_REQUEST.
7592 * Get the preamble and start building a prompt.
7594 ssh_pkt_getstring(pktin, &name, &name_len);
7595 ssh_pkt_getstring(pktin, &inst, &inst_len);
7596 ssh_pkt_getstring(pktin, &lang, &lang_len);
7597 s->cur_prompt = new_prompts(ssh->frontend);
7598 s->cur_prompt->to_server = TRUE;
7600 /* FIXME: better prefix to distinguish from
7602 s->cur_prompt->name =
7603 dupprintf("SSH server: %.*s", name_len, name);
7604 s->cur_prompt->name_reqd = TRUE;
7606 s->cur_prompt->name =
7607 dupstr("SSH server authentication");
7608 s->cur_prompt->name_reqd = FALSE;
7610 /* FIXME: ugly to print "Using..." in prompt _every_
7611 * time round. Can this be done more subtly? */
7612 s->cur_prompt->instruction =
7613 dupprintf("Using keyboard-interactive authentication.%s%.*s",
7614 inst_len ? "\n" : "", inst_len, inst);
7615 s->cur_prompt->instr_reqd = TRUE;
7618 * Get the prompts from the packet.
7620 s->num_prompts = ssh_pkt_getuint32(pktin);
7621 for (i = 0; i < s->num_prompts; i++) {
7625 static char noprompt[] =
7626 "<server failed to send prompt>: ";
7628 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
7629 echo = ssh2_pkt_getbool(pktin);
7632 prompt_len = lenof(noprompt)-1;
7634 add_prompt(s->cur_prompt,
7635 dupprintf("%.*s", prompt_len, prompt),
7636 echo, SSH_MAX_PASSWORD_LEN);
7640 * Get the user's responses.
7642 if (s->num_prompts) {
7643 int ret; /* not live over crReturn */
7644 ret = get_userpass_input(s->cur_prompt, NULL, 0);
7647 crWaitUntilV(!pktin);
7648 ret = get_userpass_input(s->cur_prompt, in, inlen);
7653 * Failed to get responses. Terminate.
7655 free_prompts(s->cur_prompt);
7656 ssh_disconnect(ssh, NULL, "Unable to authenticate",
7657 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
7664 * Send the responses to the server.
7666 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
7667 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
7668 for (i=0; i < s->num_prompts; i++) {
7669 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
7670 ssh2_pkt_addstring(s->pktout,
7671 s->cur_prompt->prompts[i]->result);
7672 end_log_omission(ssh, s->pktout);
7674 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
7677 * Get the next packet in case it's another
7680 crWaitUntilV(pktin);
7685 * We should have SUCCESS or FAILURE now.
7689 } else if (s->can_passwd) {
7692 * Plain old password authentication.
7694 int ret; /* not live over crReturn */
7695 int changereq_first_time; /* not live over crReturn */
7697 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
7699 s->cur_prompt = new_prompts(ssh->frontend);
7700 s->cur_prompt->to_server = TRUE;
7701 s->cur_prompt->name = dupstr("SSH password");
7702 add_prompt(s->cur_prompt, dupprintf("%.90s@%.90s's password: ",
7705 FALSE, SSH_MAX_PASSWORD_LEN);
7707 ret = get_userpass_input(s->cur_prompt, NULL, 0);
7710 crWaitUntilV(!pktin);
7711 ret = get_userpass_input(s->cur_prompt, in, inlen);
7716 * Failed to get responses. Terminate.
7718 free_prompts(s->cur_prompt);
7719 ssh_disconnect(ssh, NULL, "Unable to authenticate",
7720 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
7725 * Squirrel away the password. (We may need it later if
7726 * asked to change it.)
7728 s->password = dupstr(s->cur_prompt->prompts[0]->result);
7729 free_prompts(s->cur_prompt);
7732 * Send the password packet.
7734 * We pad out the password packet to 256 bytes to make
7735 * it harder for an attacker to find the length of the
7738 * Anyone using a password longer than 256 bytes
7739 * probably doesn't have much to worry about from
7740 * people who find out how long their password is!
7742 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7743 ssh2_pkt_addstring(s->pktout, s->username);
7744 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7745 /* service requested */
7746 ssh2_pkt_addstring(s->pktout, "password");
7747 ssh2_pkt_addbool(s->pktout, FALSE);
7748 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
7749 ssh2_pkt_addstring(s->pktout, s->password);
7750 end_log_omission(ssh, s->pktout);
7751 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
7752 logevent("Sent password");
7753 s->type = AUTH_TYPE_PASSWORD;
7756 * Wait for next packet, in case it's a password change
7759 crWaitUntilV(pktin);
7760 changereq_first_time = TRUE;
7762 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
7765 * We're being asked for a new password
7766 * (perhaps not for the first time).
7767 * Loop until the server accepts it.
7770 int got_new = FALSE; /* not live over crReturn */
7771 char *prompt; /* not live over crReturn */
7772 int prompt_len; /* not live over crReturn */
7776 if (changereq_first_time)
7777 msg = "Server requested password change";
7779 msg = "Server rejected new password";
7781 c_write_str(ssh, msg);
7782 c_write_str(ssh, "\r\n");
7785 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
7787 s->cur_prompt = new_prompts(ssh->frontend);
7788 s->cur_prompt->to_server = TRUE;
7789 s->cur_prompt->name = dupstr("New SSH password");
7790 s->cur_prompt->instruction =
7791 dupprintf("%.*s", prompt_len, prompt);
7792 s->cur_prompt->instr_reqd = TRUE;
7794 * There's no explicit requirement in the protocol
7795 * for the "old" passwords in the original and
7796 * password-change messages to be the same, and
7797 * apparently some Cisco kit supports password change
7798 * by the user entering a blank password originally
7799 * and the real password subsequently, so,
7800 * reluctantly, we prompt for the old password again.
7802 * (On the other hand, some servers don't even bother
7803 * to check this field.)
7805 add_prompt(s->cur_prompt,
7806 dupstr("Current password (blank for previously entered password): "),
7807 FALSE, SSH_MAX_PASSWORD_LEN);
7808 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
7809 FALSE, SSH_MAX_PASSWORD_LEN);
7810 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
7811 FALSE, SSH_MAX_PASSWORD_LEN);
7814 * Loop until the user manages to enter the same
7819 ret = get_userpass_input(s->cur_prompt, NULL, 0);
7822 crWaitUntilV(!pktin);
7823 ret = get_userpass_input(s->cur_prompt, in, inlen);
7828 * Failed to get responses. Terminate.
7830 /* burn the evidence */
7831 free_prompts(s->cur_prompt);
7832 memset(s->password, 0, strlen(s->password));
7834 ssh_disconnect(ssh, NULL, "Unable to authenticate",
7835 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
7841 * If the user specified a new original password
7842 * (IYSWIM), overwrite any previously specified
7844 * (A side effect is that the user doesn't have to
7845 * re-enter it if they louse up the new password.)
7847 if (s->cur_prompt->prompts[0]->result[0]) {
7848 memset(s->password, 0, strlen(s->password));
7849 /* burn the evidence */
7852 dupstr(s->cur_prompt->prompts[0]->result);
7856 * Check the two new passwords match.
7858 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
7859 s->cur_prompt->prompts[2]->result)
7862 /* They don't. Silly user. */
7863 c_write_str(ssh, "Passwords do not match\r\n");
7868 * Send the new password (along with the old one).
7869 * (see above for padding rationale)
7871 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7872 ssh2_pkt_addstring(s->pktout, s->username);
7873 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7874 /* service requested */
7875 ssh2_pkt_addstring(s->pktout, "password");
7876 ssh2_pkt_addbool(s->pktout, TRUE);
7877 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
7878 ssh2_pkt_addstring(s->pktout, s->password);
7879 ssh2_pkt_addstring(s->pktout,
7880 s->cur_prompt->prompts[1]->result);
7881 free_prompts(s->cur_prompt);
7882 end_log_omission(ssh, s->pktout);
7883 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
7884 logevent("Sent new password");
7887 * Now see what the server has to say about it.
7888 * (If it's CHANGEREQ again, it's not happy with the
7891 crWaitUntilV(pktin);
7892 changereq_first_time = FALSE;
7897 * We need to reexamine the current pktin at the top
7898 * of the loop. Either:
7899 * - we weren't asked to change password at all, in
7900 * which case it's a SUCCESS or FAILURE with the
7902 * - we sent a new password, and the server was
7903 * either OK with it (SUCCESS or FAILURE w/partial
7904 * success) or unhappy with the _old_ password
7905 * (FAILURE w/o partial success)
7906 * In any of these cases, we go back to the top of
7907 * the loop and start again.
7912 * We don't need the old password any more, in any
7913 * case. Burn the evidence.
7915 memset(s->password, 0, strlen(s->password));
7920 ssh_disconnect(ssh, NULL,
7921 "No supported authentication methods available",
7922 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
7930 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
7932 /* Clear up various bits and pieces from authentication. */
7933 if (s->publickey_blob) {
7934 sfree(s->publickey_blob);
7935 sfree(s->publickey_comment);
7937 if (s->agent_response)
7938 sfree(s->agent_response);
7941 * Now the connection protocol has started, one way or another.
7944 ssh->channels = newtree234(ssh_channelcmp);
7947 * Set up handlers for some connection protocol messages, so we
7948 * don't have to handle them repeatedly in this coroutine.
7950 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
7951 ssh2_msg_channel_window_adjust;
7952 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
7953 ssh2_msg_global_request;
7956 * Create the main session channel.
7958 if (ssh->cfg.ssh_no_shell) {
7959 ssh->mainchan = NULL;
7960 } else if (*ssh->cfg.ssh_nc_host) {
7962 * Just start a direct-tcpip channel and use it as the main
7965 ssh->mainchan = snew(struct ssh_channel);
7966 ssh->mainchan->ssh = ssh;
7967 ssh->mainchan->localid = alloc_channel_id(ssh);
7969 "Opening direct-tcpip channel to %s:%d in place of session",
7970 ssh->cfg.ssh_nc_host, ssh->cfg.ssh_nc_port);
7971 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7972 ssh2_pkt_addstring(s->pktout, "direct-tcpip");
7973 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
7974 ssh->mainchan->v.v2.locwindow = ssh->mainchan->v.v2.locmaxwin =
7975 ssh->cfg.ssh_simple ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
7976 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
7977 ssh2_pkt_adduint32(s->pktout, OUR_V2_MAXPKT); /* our max pkt size */
7978 ssh2_pkt_addstring(s->pktout, ssh->cfg.ssh_nc_host);
7979 ssh2_pkt_adduint32(s->pktout, ssh->cfg.ssh_nc_port);
7981 * There's nothing meaningful to put in the originator
7982 * fields, but some servers insist on syntactically correct
7985 ssh2_pkt_addstring(s->pktout, "0.0.0.0");
7986 ssh2_pkt_adduint32(s->pktout, 0);
7987 ssh2_pkt_send(ssh, s->pktout);
7989 crWaitUntilV(pktin);
7990 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
7991 bombout(("Server refused to open a direct-tcpip channel"));
7993 /* FIXME: error data comes back in FAILURE packet */
7995 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
7996 bombout(("Server's channel confirmation cited wrong channel"));
7999 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
8000 ssh->mainchan->halfopen = FALSE;
8001 ssh->mainchan->type = CHAN_MAINSESSION;
8002 ssh->mainchan->closes = 0;
8003 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8004 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8005 bufchain_init(&ssh->mainchan->v.v2.outbuffer);
8006 add234(ssh->channels, ssh->mainchan);
8007 update_specials_menu(ssh->frontend);
8008 logevent("Opened direct-tcpip channel");
8011 ssh->mainchan = snew(struct ssh_channel);
8012 ssh->mainchan->ssh = ssh;
8013 ssh->mainchan->localid = alloc_channel_id(ssh);
8014 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
8015 ssh2_pkt_addstring(s->pktout, "session");
8016 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
8017 ssh->mainchan->v.v2.locwindow = ssh->mainchan->v.v2.locmaxwin =
8018 ssh->cfg.ssh_simple ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
8019 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
8020 ssh2_pkt_adduint32(s->pktout, OUR_V2_MAXPKT); /* our max pkt size */
8021 ssh2_pkt_send(ssh, s->pktout);
8022 crWaitUntilV(pktin);
8023 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
8024 bombout(("Server refused to open a session"));
8026 /* FIXME: error data comes back in FAILURE packet */
8028 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
8029 bombout(("Server's channel confirmation cited wrong channel"));
8032 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
8033 ssh->mainchan->halfopen = FALSE;
8034 ssh->mainchan->type = CHAN_MAINSESSION;
8035 ssh->mainchan->closes = 0;
8036 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8037 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8038 bufchain_init(&ssh->mainchan->v.v2.outbuffer);
8039 add234(ssh->channels, ssh->mainchan);
8040 update_specials_menu(ssh->frontend);
8041 logevent("Opened channel for session");
8042 ssh->ncmode = FALSE;
8046 * Now we have a channel, make dispatch table entries for
8047 * general channel-based messages.
8049 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
8050 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
8051 ssh2_msg_channel_data;
8052 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
8053 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
8054 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
8055 ssh2_msg_channel_open_confirmation;
8056 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
8057 ssh2_msg_channel_open_failure;
8058 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
8059 ssh2_msg_channel_request;
8060 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
8061 ssh2_msg_channel_open;
8063 if (ssh->cfg.ssh_simple) {
8065 * This message indicates to the server that we promise
8066 * not to try to run any other channel in parallel with
8067 * this one, so it's safe for it to advertise a very large
8068 * window and leave the flow control to TCP.
8070 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8071 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8072 ssh2_pkt_addstring(s->pktout, "simple@putty.projects.tartarus.org");
8073 ssh2_pkt_addbool(s->pktout, 0); /* no reply */
8074 ssh2_pkt_send(ssh, s->pktout);
8078 * Potentially enable X11 forwarding.
8080 if (ssh->mainchan && !ssh->ncmode && ssh->cfg.x11_forward) {
8081 char proto[20], data[64];
8082 logevent("Requesting X11 forwarding");
8083 ssh->x11auth = x11_invent_auth(proto, sizeof(proto),
8084 data, sizeof(data), ssh->cfg.x11_auth);
8085 x11_get_real_auth(ssh->x11auth, ssh->cfg.x11_display);
8086 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8087 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8088 ssh2_pkt_addstring(s->pktout, "x11-req");
8089 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8090 ssh2_pkt_addbool(s->pktout, 0); /* many connections */
8091 ssh2_pkt_addstring(s->pktout, proto);
8093 * Note that while we blank the X authentication data here, we don't
8094 * take any special action to blank the start of an X11 channel,
8095 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
8096 * without having session blanking enabled is likely to leak your
8097 * cookie into the log.
8099 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8100 ssh2_pkt_addstring(s->pktout, data);
8101 end_log_omission(ssh, s->pktout);
8102 ssh2_pkt_adduint32(s->pktout, x11_get_screen_number(ssh->cfg.x11_display));
8103 ssh2_pkt_send(ssh, s->pktout);
8105 crWaitUntilV(pktin);
8107 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8108 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8109 bombout(("Unexpected response to X11 forwarding request:"
8110 " packet type %d", pktin->type));
8113 logevent("X11 forwarding refused");
8115 logevent("X11 forwarding enabled");
8116 ssh->X11_fwd_enabled = TRUE;
8121 * Enable port forwardings.
8123 ssh_setup_portfwd(ssh, &ssh->cfg);
8126 * Potentially enable agent forwarding.
8128 if (ssh->mainchan && !ssh->ncmode && ssh->cfg.agentfwd && agent_exists()) {
8129 logevent("Requesting OpenSSH-style agent forwarding");
8130 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8131 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8132 ssh2_pkt_addstring(s->pktout, "auth-agent-req@openssh.com");
8133 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8134 ssh2_pkt_send(ssh, s->pktout);
8136 crWaitUntilV(pktin);
8138 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8139 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8140 bombout(("Unexpected response to agent forwarding request:"
8141 " packet type %d", pktin->type));
8144 logevent("Agent forwarding refused");
8146 logevent("Agent forwarding enabled");
8147 ssh->agentfwd_enabled = TRUE;
8152 * Now allocate a pty for the session.
8154 if (ssh->mainchan && !ssh->ncmode && !ssh->cfg.nopty) {
8155 /* Unpick the terminal-speed string. */
8156 /* XXX perhaps we should allow no speeds to be sent. */
8157 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
8158 sscanf(ssh->cfg.termspeed, "%d,%d", &ssh->ospeed, &ssh->ispeed);
8159 /* Build the pty request. */
8160 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8161 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
8162 ssh2_pkt_addstring(s->pktout, "pty-req");
8163 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8164 ssh2_pkt_addstring(s->pktout, ssh->cfg.termtype);
8165 ssh2_pkt_adduint32(s->pktout, ssh->term_width);
8166 ssh2_pkt_adduint32(s->pktout, ssh->term_height);
8167 ssh2_pkt_adduint32(s->pktout, 0); /* pixel width */
8168 ssh2_pkt_adduint32(s->pktout, 0); /* pixel height */
8169 ssh2_pkt_addstring_start(s->pktout);
8170 parse_ttymodes(ssh, ssh->cfg.ttymodes,
8171 ssh2_send_ttymode, (void *)s->pktout);
8172 ssh2_pkt_addbyte(s->pktout, SSH2_TTY_OP_ISPEED);
8173 ssh2_pkt_adduint32(s->pktout, ssh->ispeed);
8174 ssh2_pkt_addbyte(s->pktout, SSH2_TTY_OP_OSPEED);
8175 ssh2_pkt_adduint32(s->pktout, ssh->ospeed);
8176 ssh2_pkt_addstring_data(s->pktout, "\0", 1); /* TTY_OP_END */
8177 ssh2_pkt_send(ssh, s->pktout);
8178 ssh->state = SSH_STATE_INTERMED;
8180 crWaitUntilV(pktin);
8182 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8183 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8184 bombout(("Unexpected response to pty request:"
8185 " packet type %d", pktin->type));
8188 c_write_str(ssh, "Server refused to allocate pty\r\n");
8189 ssh->editing = ssh->echoing = 1;
8191 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
8192 ssh->ospeed, ssh->ispeed);
8195 ssh->editing = ssh->echoing = 1;
8199 * Send environment variables.
8201 * Simplest thing here is to send all the requests at once, and
8202 * then wait for a whole bunch of successes or failures.
8204 if (ssh->mainchan && !ssh->ncmode && *ssh->cfg.environmt) {
8205 char *e = ssh->cfg.environmt;
8206 char *var, *varend, *val;
8212 while (*e && *e != '\t') e++;
8214 if (*e == '\t') e++;
8219 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8220 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8221 ssh2_pkt_addstring(s->pktout, "env");
8222 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8223 ssh2_pkt_addstring_start(s->pktout);
8224 ssh2_pkt_addstring_data(s->pktout, var, varend-var);
8225 ssh2_pkt_addstring(s->pktout, val);
8226 ssh2_pkt_send(ssh, s->pktout);
8231 logeventf(ssh, "Sent %d environment variables", s->num_env);
8234 s->env_left = s->num_env;
8236 while (s->env_left > 0) {
8237 crWaitUntilV(pktin);
8239 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8240 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8241 bombout(("Unexpected response to environment request:"
8242 " packet type %d", pktin->type));
8252 if (s->env_ok == s->num_env) {
8253 logevent("All environment variables successfully set");
8254 } else if (s->env_ok == 0) {
8255 logevent("All environment variables refused");
8256 c_write_str(ssh, "Server refused to set environment variables\r\n");
8258 logeventf(ssh, "%d environment variables refused",
8259 s->num_env - s->env_ok);
8260 c_write_str(ssh, "Server refused to set all environment variables\r\n");
8265 * Start a shell or a remote command. We may have to attempt
8266 * this twice if the config data has provided a second choice
8269 if (ssh->mainchan && !ssh->ncmode) while (1) {
8273 if (ssh->fallback_cmd) {
8274 subsys = ssh->cfg.ssh_subsys2;
8275 cmd = ssh->cfg.remote_cmd_ptr2;
8277 subsys = ssh->cfg.ssh_subsys;
8278 cmd = ssh->cfg.remote_cmd_ptr;
8279 if (!cmd) cmd = ssh->cfg.remote_cmd;
8282 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8283 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
8285 ssh2_pkt_addstring(s->pktout, "subsystem");
8286 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8287 ssh2_pkt_addstring(s->pktout, cmd);
8289 ssh2_pkt_addstring(s->pktout, "exec");
8290 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8291 ssh2_pkt_addstring(s->pktout, cmd);
8293 ssh2_pkt_addstring(s->pktout, "shell");
8294 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8296 ssh2_pkt_send(ssh, s->pktout);
8298 crWaitUntilV(pktin);
8300 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8301 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8302 bombout(("Unexpected response to shell/command request:"
8303 " packet type %d", pktin->type));
8307 * We failed to start the command. If this is the
8308 * fallback command, we really are finished; if it's
8309 * not, and if the fallback command exists, try falling
8310 * back to it before complaining.
8312 if (!ssh->fallback_cmd && ssh->cfg.remote_cmd_ptr2 != NULL) {
8313 logevent("Primary command failed; attempting fallback");
8314 ssh->fallback_cmd = TRUE;
8317 bombout(("Server refused to start a shell/command"));
8320 logevent("Started a shell/command");
8325 ssh->state = SSH_STATE_SESSION;
8326 if (ssh->size_needed)
8327 ssh_size(ssh, ssh->term_width, ssh->term_height);
8328 if (ssh->eof_needed)
8329 ssh_special(ssh, TS_EOF);
8335 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
8340 s->try_send = FALSE;
8344 * _All_ the connection-layer packets we expect to
8345 * receive are now handled by the dispatch table.
8346 * Anything that reaches here must be bogus.
8349 bombout(("Strange packet received: type %d", pktin->type));
8351 } else if (ssh->mainchan) {
8353 * We have spare data. Add it to the channel buffer.
8355 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
8360 struct ssh_channel *c;
8362 * Try to send data on all channels if we can.
8364 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
8365 ssh2_try_send_and_unthrottle(c);
8373 * Handlers for SSH-2 messages that might arrive at any moment.
8375 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
8377 /* log reason code in disconnect message */
8379 int nowlen, reason, msglen;
8381 reason = ssh_pkt_getuint32(pktin);
8382 ssh_pkt_getstring(pktin, &msg, &msglen);
8384 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
8385 buf = dupprintf("Received disconnect message (%s)",
8386 ssh2_disconnect_reasons[reason]);
8388 buf = dupprintf("Received disconnect message (unknown"
8389 " type %d)", reason);
8393 buf = dupprintf("Disconnection message text: %n%.*s",
8394 &nowlen, msglen, msg);
8396 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
8398 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
8399 ssh2_disconnect_reasons[reason] : "unknown",
8404 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
8406 /* log the debug message */
8411 /* XXX maybe we should actually take notice of this */
8412 always_display = ssh2_pkt_getbool(pktin);
8413 ssh_pkt_getstring(pktin, &msg, &msglen);
8415 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
8418 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
8420 struct Packet *pktout;
8421 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
8422 ssh2_pkt_adduint32(pktout, pktin->sequence);
8424 * UNIMPLEMENTED messages MUST appear in the same order as the
8425 * messages they respond to. Hence, never queue them.
8427 ssh2_pkt_send_noqueue(ssh, pktout);
8431 * Handle the top-level SSH-2 protocol.
8433 static void ssh2_protocol_setup(Ssh ssh)
8438 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
8440 for (i = 0; i < 256; i++)
8441 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
8444 * Any message we actually understand, we set to NULL so that
8445 * the coroutines will get it.
8447 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = NULL;
8448 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = NULL;
8449 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = NULL;
8450 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = NULL;
8451 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = NULL;
8452 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = NULL;
8453 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = NULL;
8454 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = NULL; duplicate case value */
8455 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = NULL; duplicate case value */
8456 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = NULL;
8457 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = NULL;
8458 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = NULL;
8459 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = NULL;
8460 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = NULL;
8461 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
8462 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = NULL;
8463 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = NULL; duplicate case value */
8464 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = NULL; duplicate case value */
8465 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = NULL;
8466 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = NULL;
8467 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = NULL;
8468 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = NULL;
8469 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = NULL;
8470 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = NULL;
8471 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = NULL;
8472 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = NULL;
8473 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = NULL;
8474 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = NULL;
8475 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = NULL;
8476 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = NULL;
8477 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = NULL;
8478 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = NULL;
8479 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = NULL;
8482 * These special message types we install handlers for.
8484 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
8485 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
8486 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
8489 static void ssh2_timer(void *ctx, long now)
8493 if (ssh->state == SSH_STATE_CLOSED)
8496 if (!ssh->kex_in_progress && ssh->cfg.ssh_rekey_time != 0 &&
8497 now - ssh->next_rekey >= 0) {
8498 do_ssh2_transport(ssh, "timeout", -1, NULL);
8502 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
8503 struct Packet *pktin)
8505 unsigned char *in = (unsigned char *)vin;
8506 if (ssh->state == SSH_STATE_CLOSED)
8510 ssh->incoming_data_size += pktin->encrypted_len;
8511 if (!ssh->kex_in_progress &&
8512 ssh->max_data_size != 0 &&
8513 ssh->incoming_data_size > ssh->max_data_size)
8514 do_ssh2_transport(ssh, "too much data received", -1, NULL);
8517 if (pktin && ssh->packet_dispatch[pktin->type]) {
8518 ssh->packet_dispatch[pktin->type](ssh, pktin);
8522 if (!ssh->protocol_initial_phase_done ||
8523 (pktin && pktin->type >= 20 && pktin->type < 50)) {
8524 if (do_ssh2_transport(ssh, in, inlen, pktin) &&
8525 !ssh->protocol_initial_phase_done) {
8526 ssh->protocol_initial_phase_done = TRUE;
8528 * Allow authconn to initialise itself.
8530 do_ssh2_authconn(ssh, NULL, 0, NULL);
8533 do_ssh2_authconn(ssh, in, inlen, pktin);
8538 * Called to set up the connection.
8540 * Returns an error message, or NULL on success.
8542 static const char *ssh_init(void *frontend_handle, void **backend_handle,
8544 char *host, int port, char **realhost, int nodelay,
8550 ssh = snew(struct ssh_tag);
8551 ssh->cfg = *cfg; /* STRUCTURE COPY */
8552 ssh->version = 0; /* when not ready yet */
8555 ssh->v1_cipher_ctx = NULL;
8556 ssh->crcda_ctx = NULL;
8557 ssh->cscipher = NULL;
8558 ssh->cs_cipher_ctx = NULL;
8559 ssh->sccipher = NULL;
8560 ssh->sc_cipher_ctx = NULL;
8562 ssh->cs_mac_ctx = NULL;
8564 ssh->sc_mac_ctx = NULL;
8566 ssh->cs_comp_ctx = NULL;
8568 ssh->sc_comp_ctx = NULL;
8570 ssh->kex_ctx = NULL;
8571 ssh->hostkey = NULL;
8573 ssh->close_expected = FALSE;
8574 ssh->clean_exit = FALSE;
8575 ssh->state = SSH_STATE_PREPACKET;
8576 ssh->size_needed = FALSE;
8577 ssh->eof_needed = FALSE;
8580 ssh->deferred_send_data = NULL;
8581 ssh->deferred_len = 0;
8582 ssh->deferred_size = 0;
8583 ssh->fallback_cmd = 0;
8584 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
8585 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
8586 ssh->x11auth = NULL;
8587 ssh->v1_compressing = FALSE;
8588 ssh->v2_outgoing_sequence = 0;
8589 ssh->ssh1_rdpkt_crstate = 0;
8590 ssh->ssh2_rdpkt_crstate = 0;
8591 ssh->do_ssh_init_crstate = 0;
8592 ssh->ssh_gotdata_crstate = 0;
8593 ssh->do_ssh1_connection_crstate = 0;
8594 ssh->do_ssh1_login_crstate = 0;
8595 ssh->do_ssh2_transport_crstate = 0;
8596 ssh->do_ssh2_authconn_crstate = 0;
8597 ssh->do_ssh_init_state = NULL;
8598 ssh->do_ssh1_login_state = NULL;
8599 ssh->do_ssh2_transport_state = NULL;
8600 ssh->do_ssh2_authconn_state = NULL;
8603 ssh->mainchan = NULL;
8604 ssh->throttled_all = 0;
8605 ssh->v1_stdout_throttling = 0;
8607 ssh->queuelen = ssh->queuesize = 0;
8608 ssh->queueing = FALSE;
8609 ssh->qhead = ssh->qtail = NULL;
8610 ssh->deferred_rekey_reason = NULL;
8611 bufchain_init(&ssh->queued_incoming_data);
8612 ssh->frozen = FALSE;
8614 *backend_handle = ssh;
8617 if (crypto_startup() == 0)
8618 return "Microsoft high encryption pack not installed!";
8621 ssh->frontend = frontend_handle;
8622 ssh->term_width = ssh->cfg.width;
8623 ssh->term_height = ssh->cfg.height;
8625 ssh->channels = NULL;
8626 ssh->rportfwds = NULL;
8627 ssh->portfwds = NULL;
8632 ssh->v1_throttle_count = 0;
8633 ssh->overall_bufsize = 0;
8634 ssh->fallback_cmd = 0;
8636 ssh->protocol = NULL;
8638 ssh->protocol_initial_phase_done = FALSE;
8642 ssh->incoming_data_size = ssh->outgoing_data_size =
8643 ssh->deferred_data_size = 0L;
8644 ssh->max_data_size = parse_blocksize(ssh->cfg.ssh_rekey_data);
8645 ssh->kex_in_progress = FALSE;
8647 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
8656 static void ssh_free(void *handle)
8658 Ssh ssh = (Ssh) handle;
8659 struct ssh_channel *c;
8660 struct ssh_rportfwd *pf;
8662 if (ssh->v1_cipher_ctx)
8663 ssh->cipher->free_context(ssh->v1_cipher_ctx);
8664 if (ssh->cs_cipher_ctx)
8665 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
8666 if (ssh->sc_cipher_ctx)
8667 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
8668 if (ssh->cs_mac_ctx)
8669 ssh->csmac->free_context(ssh->cs_mac_ctx);
8670 if (ssh->sc_mac_ctx)
8671 ssh->scmac->free_context(ssh->sc_mac_ctx);
8672 if (ssh->cs_comp_ctx) {
8674 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
8676 zlib_compress_cleanup(ssh->cs_comp_ctx);
8678 if (ssh->sc_comp_ctx) {
8680 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
8682 zlib_decompress_cleanup(ssh->sc_comp_ctx);
8685 dh_cleanup(ssh->kex_ctx);
8686 sfree(ssh->savedhost);
8688 while (ssh->queuelen-- > 0)
8689 ssh_free_packet(ssh->queue[ssh->queuelen]);
8692 while (ssh->qhead) {
8693 struct queued_handler *qh = ssh->qhead;
8694 ssh->qhead = qh->next;
8697 ssh->qhead = ssh->qtail = NULL;
8699 if (ssh->channels) {
8700 while ((c = delpos234(ssh->channels, 0)) != NULL) {
8703 if (c->u.x11.s != NULL)
8704 x11_close(c->u.x11.s);
8707 if (c->u.pfd.s != NULL)
8708 pfd_close(c->u.pfd.s);
8713 freetree234(ssh->channels);
8714 ssh->channels = NULL;
8717 if (ssh->rportfwds) {
8718 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
8720 freetree234(ssh->rportfwds);
8721 ssh->rportfwds = NULL;
8723 sfree(ssh->deferred_send_data);
8725 x11_free_auth(ssh->x11auth);
8726 sfree(ssh->do_ssh_init_state);
8727 sfree(ssh->do_ssh1_login_state);
8728 sfree(ssh->do_ssh2_transport_state);
8729 sfree(ssh->do_ssh2_authconn_state);
8732 if (ssh->crcda_ctx) {
8733 crcda_free_context(ssh->crcda_ctx);
8734 ssh->crcda_ctx = NULL;
8737 ssh_do_close(ssh, TRUE);
8738 expire_timer_context(ssh);
8740 pinger_free(ssh->pinger);
8741 bufchain_clear(&ssh->queued_incoming_data);
8748 * Reconfigure the SSH backend.
8750 static void ssh_reconfig(void *handle, Config *cfg)
8752 Ssh ssh = (Ssh) handle;
8753 char *rekeying = NULL, rekey_mandatory = FALSE;
8754 unsigned long old_max_data_size;
8756 pinger_reconfig(ssh->pinger, &ssh->cfg, cfg);
8758 ssh_setup_portfwd(ssh, cfg);
8760 if (ssh->cfg.ssh_rekey_time != cfg->ssh_rekey_time &&
8761 cfg->ssh_rekey_time != 0) {
8762 long new_next = ssh->last_rekey + cfg->ssh_rekey_time*60*TICKSPERSEC;
8763 long now = GETTICKCOUNT();
8765 if (new_next - now < 0) {
8766 rekeying = "timeout shortened";
8768 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
8772 old_max_data_size = ssh->max_data_size;
8773 ssh->max_data_size = parse_blocksize(cfg->ssh_rekey_data);
8774 if (old_max_data_size != ssh->max_data_size &&
8775 ssh->max_data_size != 0) {
8776 if (ssh->outgoing_data_size > ssh->max_data_size ||
8777 ssh->incoming_data_size > ssh->max_data_size)
8778 rekeying = "data limit lowered";
8781 if (ssh->cfg.compression != cfg->compression) {
8782 rekeying = "compression setting changed";
8783 rekey_mandatory = TRUE;
8786 if (ssh->cfg.ssh2_des_cbc != cfg->ssh2_des_cbc ||
8787 memcmp(ssh->cfg.ssh_cipherlist, cfg->ssh_cipherlist,
8788 sizeof(ssh->cfg.ssh_cipherlist))) {
8789 rekeying = "cipher settings changed";
8790 rekey_mandatory = TRUE;
8793 ssh->cfg = *cfg; /* STRUCTURE COPY */
8796 if (!ssh->kex_in_progress) {
8797 do_ssh2_transport(ssh, rekeying, -1, NULL);
8798 } else if (rekey_mandatory) {
8799 ssh->deferred_rekey_reason = rekeying;
8805 * Called to send data down the SSH connection.
8807 static int ssh_send(void *handle, char *buf, int len)
8809 Ssh ssh = (Ssh) handle;
8811 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
8814 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
8816 return ssh_sendbuffer(ssh);
8820 * Called to query the current amount of buffered stdin data.
8822 static int ssh_sendbuffer(void *handle)
8824 Ssh ssh = (Ssh) handle;
8827 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
8831 * If the SSH socket itself has backed up, add the total backup
8832 * size on that to any individual buffer on the stdin channel.
8835 if (ssh->throttled_all)
8836 override_value = ssh->overall_bufsize;
8838 if (ssh->version == 1) {
8839 return override_value;
8840 } else if (ssh->version == 2) {
8841 if (!ssh->mainchan || ssh->mainchan->closes > 0)
8842 return override_value;
8844 return (override_value +
8845 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
8852 * Called to set the size of the window from SSH's POV.
8854 static void ssh_size(void *handle, int width, int height)
8856 Ssh ssh = (Ssh) handle;
8857 struct Packet *pktout;
8859 ssh->term_width = width;
8860 ssh->term_height = height;
8862 switch (ssh->state) {
8863 case SSH_STATE_BEFORE_SIZE:
8864 case SSH_STATE_PREPACKET:
8865 case SSH_STATE_CLOSED:
8866 break; /* do nothing */
8867 case SSH_STATE_INTERMED:
8868 ssh->size_needed = TRUE; /* buffer for later */
8870 case SSH_STATE_SESSION:
8871 if (!ssh->cfg.nopty) {
8872 if (ssh->version == 1) {
8873 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
8874 PKT_INT, ssh->term_height,
8875 PKT_INT, ssh->term_width,
8876 PKT_INT, 0, PKT_INT, 0, PKT_END);
8877 } else if (ssh->mainchan) {
8878 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8879 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
8880 ssh2_pkt_addstring(pktout, "window-change");
8881 ssh2_pkt_addbool(pktout, 0);
8882 ssh2_pkt_adduint32(pktout, ssh->term_width);
8883 ssh2_pkt_adduint32(pktout, ssh->term_height);
8884 ssh2_pkt_adduint32(pktout, 0);
8885 ssh2_pkt_adduint32(pktout, 0);
8886 ssh2_pkt_send(ssh, pktout);
8894 * Return a list of the special codes that make sense in this
8897 static const struct telnet_special *ssh_get_specials(void *handle)
8899 static const struct telnet_special ssh1_ignore_special[] = {
8900 {"IGNORE message", TS_NOP}
8902 static const struct telnet_special ssh2_transport_specials[] = {
8903 {"IGNORE message", TS_NOP},
8904 {"Repeat key exchange", TS_REKEY},
8906 static const struct telnet_special ssh2_session_specials[] = {
8909 /* These are the signal names defined by draft-ietf-secsh-connect-23.
8910 * They include all the ISO C signals, but are a subset of the POSIX
8911 * required signals. */
8912 {"SIGINT (Interrupt)", TS_SIGINT},
8913 {"SIGTERM (Terminate)", TS_SIGTERM},
8914 {"SIGKILL (Kill)", TS_SIGKILL},
8915 {"SIGQUIT (Quit)", TS_SIGQUIT},
8916 {"SIGHUP (Hangup)", TS_SIGHUP},
8917 {"More signals", TS_SUBMENU},
8918 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
8919 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
8920 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
8921 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
8924 static const struct telnet_special specials_end[] = {
8927 /* XXX review this length for any changes: */
8928 static struct telnet_special ssh_specials[lenof(ssh2_transport_specials) +
8929 lenof(ssh2_session_specials) +
8930 lenof(specials_end)];
8931 Ssh ssh = (Ssh) handle;
8933 #define ADD_SPECIALS(name) \
8935 assert((i + lenof(name)) <= lenof(ssh_specials)); \
8936 memcpy(&ssh_specials[i], name, sizeof name); \
8940 if (ssh->version == 1) {
8941 /* Don't bother offering IGNORE if we've decided the remote
8942 * won't cope with it, since we wouldn't bother sending it if
8944 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
8945 ADD_SPECIALS(ssh1_ignore_special);
8946 } else if (ssh->version == 2) {
8947 ADD_SPECIALS(ssh2_transport_specials);
8949 ADD_SPECIALS(ssh2_session_specials);
8950 } /* else we're not ready yet */
8953 ADD_SPECIALS(specials_end);
8954 return ssh_specials;
8962 * Send special codes. TS_EOF is useful for `plink', so you
8963 * can send an EOF and collect resulting output (e.g. `plink
8966 static void ssh_special(void *handle, Telnet_Special code)
8968 Ssh ssh = (Ssh) handle;
8969 struct Packet *pktout;
8971 if (code == TS_EOF) {
8972 if (ssh->state != SSH_STATE_SESSION) {
8974 * Buffer the EOF in case we are pre-SESSION, so we can
8975 * send it as soon as we reach SESSION.
8978 ssh->eof_needed = TRUE;
8981 if (ssh->version == 1) {
8982 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
8983 } else if (ssh->mainchan) {
8984 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
8985 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
8986 ssh2_pkt_send(ssh, pktout);
8987 ssh->send_ok = 0; /* now stop trying to read from stdin */
8989 logevent("Sent EOF message");
8990 } else if (code == TS_PING || code == TS_NOP) {
8991 if (ssh->state == SSH_STATE_CLOSED
8992 || ssh->state == SSH_STATE_PREPACKET) return;
8993 if (ssh->version == 1) {
8994 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
8995 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
8997 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
8998 ssh2_pkt_addstring_start(pktout);
8999 ssh2_pkt_send_noqueue(ssh, pktout);
9001 } else if (code == TS_REKEY) {
9002 if (!ssh->kex_in_progress && ssh->version == 2) {
9003 do_ssh2_transport(ssh, "at user request", -1, NULL);
9005 } else if (code == TS_BRK) {
9006 if (ssh->state == SSH_STATE_CLOSED
9007 || ssh->state == SSH_STATE_PREPACKET) return;
9008 if (ssh->version == 1) {
9009 logevent("Unable to send BREAK signal in SSH-1");
9010 } else if (ssh->mainchan) {
9011 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9012 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9013 ssh2_pkt_addstring(pktout, "break");
9014 ssh2_pkt_addbool(pktout, 0);
9015 ssh2_pkt_adduint32(pktout, 0); /* default break length */
9016 ssh2_pkt_send(ssh, pktout);
9019 /* Is is a POSIX signal? */
9020 char *signame = NULL;
9021 if (code == TS_SIGABRT) signame = "ABRT";
9022 if (code == TS_SIGALRM) signame = "ALRM";
9023 if (code == TS_SIGFPE) signame = "FPE";
9024 if (code == TS_SIGHUP) signame = "HUP";
9025 if (code == TS_SIGILL) signame = "ILL";
9026 if (code == TS_SIGINT) signame = "INT";
9027 if (code == TS_SIGKILL) signame = "KILL";
9028 if (code == TS_SIGPIPE) signame = "PIPE";
9029 if (code == TS_SIGQUIT) signame = "QUIT";
9030 if (code == TS_SIGSEGV) signame = "SEGV";
9031 if (code == TS_SIGTERM) signame = "TERM";
9032 if (code == TS_SIGUSR1) signame = "USR1";
9033 if (code == TS_SIGUSR2) signame = "USR2";
9034 /* The SSH-2 protocol does in principle support arbitrary named
9035 * signals, including signame@domain, but we don't support those. */
9037 /* It's a signal. */
9038 if (ssh->version == 2 && ssh->mainchan) {
9039 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9040 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9041 ssh2_pkt_addstring(pktout, "signal");
9042 ssh2_pkt_addbool(pktout, 0);
9043 ssh2_pkt_addstring(pktout, signame);
9044 ssh2_pkt_send(ssh, pktout);
9045 logeventf(ssh, "Sent signal SIG%s", signame);
9048 /* Never heard of it. Do nothing */
9053 void *new_sock_channel(void *handle, Socket s)
9055 Ssh ssh = (Ssh) handle;
9056 struct ssh_channel *c;
9057 c = snew(struct ssh_channel);
9062 c->localid = alloc_channel_id(ssh);
9064 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
9066 bufchain_init(&c->v.v2.outbuffer);
9067 add234(ssh->channels, c);
9073 * This is called when stdout/stderr (the entity to which
9074 * from_backend sends data) manages to clear some backlog.
9076 static void ssh_unthrottle(void *handle, int bufsize)
9078 Ssh ssh = (Ssh) handle;
9079 if (ssh->version == 1) {
9080 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
9081 ssh->v1_stdout_throttling = 0;
9082 ssh1_throttle(ssh, -1);
9085 ssh2_set_window(ssh->mainchan,
9086 ssh->mainchan->v.v2.locmaxwin - bufsize);
9090 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
9092 struct ssh_channel *c = (struct ssh_channel *)channel;
9094 struct Packet *pktout;
9096 logeventf(ssh, "Opening forwarded connection to %s:%d", hostname, port);
9098 if (ssh->version == 1) {
9099 send_packet(ssh, SSH1_MSG_PORT_OPEN,
9100 PKT_INT, c->localid,
9103 /* PKT_STR, <org:orgport>, */
9106 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
9107 ssh2_pkt_addstring(pktout, "direct-tcpip");
9108 ssh2_pkt_adduint32(pktout, c->localid);
9109 c->v.v2.locwindow = c->v.v2.locmaxwin = OUR_V2_WINSIZE;
9110 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
9111 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
9112 ssh2_pkt_addstring(pktout, hostname);
9113 ssh2_pkt_adduint32(pktout, port);
9115 * We make up values for the originator data; partly it's
9116 * too much hassle to keep track, and partly I'm not
9117 * convinced the server should be told details like that
9118 * about my local network configuration.
9119 * The "originator IP address" is syntactically a numeric
9120 * IP address, and some servers (e.g., Tectia) get upset
9121 * if it doesn't match this syntax.
9123 ssh2_pkt_addstring(pktout, "0.0.0.0");
9124 ssh2_pkt_adduint32(pktout, 0);
9125 ssh2_pkt_send(ssh, pktout);
9129 static int ssh_connected(void *handle)
9131 Ssh ssh = (Ssh) handle;
9132 return ssh->s != NULL;
9135 static int ssh_sendok(void *handle)
9137 Ssh ssh = (Ssh) handle;
9138 return ssh->send_ok;
9141 static int ssh_ldisc(void *handle, int option)
9143 Ssh ssh = (Ssh) handle;
9144 if (option == LD_ECHO)
9145 return ssh->echoing;
9146 if (option == LD_EDIT)
9147 return ssh->editing;
9151 static void ssh_provide_ldisc(void *handle, void *ldisc)
9153 Ssh ssh = (Ssh) handle;
9157 static void ssh_provide_logctx(void *handle, void *logctx)
9159 Ssh ssh = (Ssh) handle;
9160 ssh->logctx = logctx;
9163 static int ssh_return_exitcode(void *handle)
9165 Ssh ssh = (Ssh) handle;
9169 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
9173 * cfg_info for SSH is the currently running version of the
9174 * protocol. (1 for 1; 2 for 2; 0 for not-decided-yet.)
9176 static int ssh_cfg_info(void *handle)
9178 Ssh ssh = (Ssh) handle;
9179 return ssh->version;
9183 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
9184 * that fails. This variable is the means by which scp.c can reach
9185 * into the SSH code and find out which one it got.
9187 extern int ssh_fallback_cmd(void *handle)
9189 Ssh ssh = (Ssh) handle;
9190 return ssh->fallback_cmd;
9193 Backend ssh_backend = {
9203 ssh_return_exitcode,