24 #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
25 #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
26 #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
27 #define SSH1_CMSG_USER 4 /* 0x4 */
28 #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
29 #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
30 #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
31 #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
32 #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
33 #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
34 #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
35 #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
36 #define SSH1_SMSG_SUCCESS 14 /* 0xe */
37 #define SSH1_SMSG_FAILURE 15 /* 0xf */
38 #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
39 #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
40 #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
41 #define SSH1_CMSG_EOF 19 /* 0x13 */
42 #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
43 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
44 #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
45 #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
46 #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
47 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
48 #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
49 #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
50 #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
51 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
52 #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
53 #define SSH1_MSG_IGNORE 32 /* 0x20 */
54 #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
55 #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
56 #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
57 #define SSH1_MSG_DEBUG 36 /* 0x24 */
58 #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
59 #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
60 #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
61 #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
62 #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
63 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
64 #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
66 #define SSH1_AUTH_RHOSTS 1 /* 0x1 */
67 #define SSH1_AUTH_RSA 2 /* 0x2 */
68 #define SSH1_AUTH_PASSWORD 3 /* 0x3 */
69 #define SSH1_AUTH_RHOSTS_RSA 4 /* 0x4 */
70 #define SSH1_AUTH_TIS 5 /* 0x5 */
71 #define SSH1_AUTH_CCARD 16 /* 0x10 */
73 #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
74 /* Mask for protoflags we will echo back to server if seen */
75 #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
77 #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
78 #define SSH2_MSG_IGNORE 2 /* 0x2 */
79 #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
80 #define SSH2_MSG_DEBUG 4 /* 0x4 */
81 #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
82 #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
83 #define SSH2_MSG_KEXINIT 20 /* 0x14 */
84 #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
85 #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
86 #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
87 #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
88 #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
89 #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
90 #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
91 #define SSH2_MSG_KEXRSA_PUBKEY 30 /* 0x1e */
92 #define SSH2_MSG_KEXRSA_SECRET 31 /* 0x1f */
93 #define SSH2_MSG_KEXRSA_DONE 32 /* 0x20 */
94 #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
95 #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
96 #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
97 #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
98 #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
99 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
100 #define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */
101 #define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */
102 #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
103 #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
104 #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
105 #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
106 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
107 #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
108 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
109 #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
110 #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
111 #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
112 #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
113 #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
114 #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
115 #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
116 #define SSH2_MSG_USERAUTH_GSSAPI_RESPONSE 60
117 #define SSH2_MSG_USERAUTH_GSSAPI_TOKEN 61
118 #define SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE 63
119 #define SSH2_MSG_USERAUTH_GSSAPI_ERROR 64
120 #define SSH2_MSG_USERAUTH_GSSAPI_ERRTOK 65
121 #define SSH2_MSG_USERAUTH_GSSAPI_MIC 66
124 * Packet type contexts, so that ssh2_pkt_type can correctly decode
125 * the ambiguous type numbers back into the correct type strings.
135 SSH2_PKTCTX_PUBLICKEY,
136 SSH2_PKTCTX_PASSWORD,
141 #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
142 #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
143 #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
144 #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
145 #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
146 #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
147 #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
148 #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
149 #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
150 #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
151 #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
152 #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
153 #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
154 #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
155 #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
157 static const char *const ssh2_disconnect_reasons[] = {
159 "host not allowed to connect",
161 "key exchange failed",
162 "host authentication failed",
165 "service not available",
166 "protocol version not supported",
167 "host key not verifiable",
170 "too many connections",
171 "auth cancelled by user",
172 "no more auth methods available",
176 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
177 #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
178 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
179 #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
181 #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
184 * Various remote-bug flags.
186 #define BUG_CHOKES_ON_SSH1_IGNORE 1
187 #define BUG_SSH2_HMAC 2
188 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
189 #define BUG_CHOKES_ON_RSA 8
190 #define BUG_SSH2_RSA_PADDING 16
191 #define BUG_SSH2_DERIVEKEY 32
192 #define BUG_SSH2_REKEY 64
193 #define BUG_SSH2_PK_SESSIONID 128
194 #define BUG_SSH2_MAXPKT 256
197 * Codes for terminal modes.
198 * Most of these are the same in SSH-1 and SSH-2.
199 * This list is derived from RFC 4254 and
202 static const struct {
203 const char* const mode;
205 enum { TTY_OP_CHAR, TTY_OP_BOOL } type;
207 /* "V" prefix discarded for special characters relative to SSH specs */
208 { "INTR", 1, TTY_OP_CHAR },
209 { "QUIT", 2, TTY_OP_CHAR },
210 { "ERASE", 3, TTY_OP_CHAR },
211 { "KILL", 4, TTY_OP_CHAR },
212 { "EOF", 5, TTY_OP_CHAR },
213 { "EOL", 6, TTY_OP_CHAR },
214 { "EOL2", 7, TTY_OP_CHAR },
215 { "START", 8, TTY_OP_CHAR },
216 { "STOP", 9, TTY_OP_CHAR },
217 { "SUSP", 10, TTY_OP_CHAR },
218 { "DSUSP", 11, TTY_OP_CHAR },
219 { "REPRINT", 12, TTY_OP_CHAR },
220 { "WERASE", 13, TTY_OP_CHAR },
221 { "LNEXT", 14, TTY_OP_CHAR },
222 { "FLUSH", 15, TTY_OP_CHAR },
223 { "SWTCH", 16, TTY_OP_CHAR },
224 { "STATUS", 17, TTY_OP_CHAR },
225 { "DISCARD", 18, TTY_OP_CHAR },
226 { "IGNPAR", 30, TTY_OP_BOOL },
227 { "PARMRK", 31, TTY_OP_BOOL },
228 { "INPCK", 32, TTY_OP_BOOL },
229 { "ISTRIP", 33, TTY_OP_BOOL },
230 { "INLCR", 34, TTY_OP_BOOL },
231 { "IGNCR", 35, TTY_OP_BOOL },
232 { "ICRNL", 36, TTY_OP_BOOL },
233 { "IUCLC", 37, TTY_OP_BOOL },
234 { "IXON", 38, TTY_OP_BOOL },
235 { "IXANY", 39, TTY_OP_BOOL },
236 { "IXOFF", 40, TTY_OP_BOOL },
237 { "IMAXBEL", 41, TTY_OP_BOOL },
238 { "ISIG", 50, TTY_OP_BOOL },
239 { "ICANON", 51, TTY_OP_BOOL },
240 { "XCASE", 52, TTY_OP_BOOL },
241 { "ECHO", 53, TTY_OP_BOOL },
242 { "ECHOE", 54, TTY_OP_BOOL },
243 { "ECHOK", 55, TTY_OP_BOOL },
244 { "ECHONL", 56, TTY_OP_BOOL },
245 { "NOFLSH", 57, TTY_OP_BOOL },
246 { "TOSTOP", 58, TTY_OP_BOOL },
247 { "IEXTEN", 59, TTY_OP_BOOL },
248 { "ECHOCTL", 60, TTY_OP_BOOL },
249 { "ECHOKE", 61, TTY_OP_BOOL },
250 { "PENDIN", 62, TTY_OP_BOOL }, /* XXX is this a real mode? */
251 { "OPOST", 70, TTY_OP_BOOL },
252 { "OLCUC", 71, TTY_OP_BOOL },
253 { "ONLCR", 72, TTY_OP_BOOL },
254 { "OCRNL", 73, TTY_OP_BOOL },
255 { "ONOCR", 74, TTY_OP_BOOL },
256 { "ONLRET", 75, TTY_OP_BOOL },
257 { "CS7", 90, TTY_OP_BOOL },
258 { "CS8", 91, TTY_OP_BOOL },
259 { "PARENB", 92, TTY_OP_BOOL },
260 { "PARODD", 93, TTY_OP_BOOL }
263 /* Miscellaneous other tty-related constants. */
264 #define SSH_TTY_OP_END 0
265 /* The opcodes for ISPEED/OSPEED differ between SSH-1 and SSH-2. */
266 #define SSH1_TTY_OP_ISPEED 192
267 #define SSH1_TTY_OP_OSPEED 193
268 #define SSH2_TTY_OP_ISPEED 128
269 #define SSH2_TTY_OP_OSPEED 129
271 /* Helper functions for parsing tty-related config. */
272 static unsigned int ssh_tty_parse_specchar(char *s)
277 ret = ctrlparse(s, &next);
278 if (!next) ret = s[0];
280 ret = 255; /* special value meaning "don't set" */
284 static unsigned int ssh_tty_parse_boolean(char *s)
286 if (stricmp(s, "yes") == 0 ||
287 stricmp(s, "on") == 0 ||
288 stricmp(s, "true") == 0 ||
289 stricmp(s, "+") == 0)
291 else if (stricmp(s, "no") == 0 ||
292 stricmp(s, "off") == 0 ||
293 stricmp(s, "false") == 0 ||
294 stricmp(s, "-") == 0)
295 return 0; /* false */
297 return (atoi(s) != 0);
300 #define translate(x) if (type == x) return #x
301 #define translatek(x,ctx) if (type == x && (pkt_kctx == ctx)) return #x
302 #define translatea(x,ctx) if (type == x && (pkt_actx == ctx)) return #x
303 static char *ssh1_pkt_type(int type)
305 translate(SSH1_MSG_DISCONNECT);
306 translate(SSH1_SMSG_PUBLIC_KEY);
307 translate(SSH1_CMSG_SESSION_KEY);
308 translate(SSH1_CMSG_USER);
309 translate(SSH1_CMSG_AUTH_RSA);
310 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
311 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
312 translate(SSH1_CMSG_AUTH_PASSWORD);
313 translate(SSH1_CMSG_REQUEST_PTY);
314 translate(SSH1_CMSG_WINDOW_SIZE);
315 translate(SSH1_CMSG_EXEC_SHELL);
316 translate(SSH1_CMSG_EXEC_CMD);
317 translate(SSH1_SMSG_SUCCESS);
318 translate(SSH1_SMSG_FAILURE);
319 translate(SSH1_CMSG_STDIN_DATA);
320 translate(SSH1_SMSG_STDOUT_DATA);
321 translate(SSH1_SMSG_STDERR_DATA);
322 translate(SSH1_CMSG_EOF);
323 translate(SSH1_SMSG_EXIT_STATUS);
324 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
325 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
326 translate(SSH1_MSG_CHANNEL_DATA);
327 translate(SSH1_MSG_CHANNEL_CLOSE);
328 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
329 translate(SSH1_SMSG_X11_OPEN);
330 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
331 translate(SSH1_MSG_PORT_OPEN);
332 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
333 translate(SSH1_SMSG_AGENT_OPEN);
334 translate(SSH1_MSG_IGNORE);
335 translate(SSH1_CMSG_EXIT_CONFIRMATION);
336 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
337 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
338 translate(SSH1_MSG_DEBUG);
339 translate(SSH1_CMSG_REQUEST_COMPRESSION);
340 translate(SSH1_CMSG_AUTH_TIS);
341 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
342 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
343 translate(SSH1_CMSG_AUTH_CCARD);
344 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
345 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
348 static char *ssh2_pkt_type(Pkt_KCtx pkt_kctx, Pkt_ACtx pkt_actx, int type)
350 translatea(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE,SSH2_PKTCTX_GSSAPI);
351 translatea(SSH2_MSG_USERAUTH_GSSAPI_TOKEN,SSH2_PKTCTX_GSSAPI);
352 translatea(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE,SSH2_PKTCTX_GSSAPI);
353 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERROR,SSH2_PKTCTX_GSSAPI);
354 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK,SSH2_PKTCTX_GSSAPI);
355 translatea(SSH2_MSG_USERAUTH_GSSAPI_MIC, SSH2_PKTCTX_GSSAPI);
356 translate(SSH2_MSG_DISCONNECT);
357 translate(SSH2_MSG_IGNORE);
358 translate(SSH2_MSG_UNIMPLEMENTED);
359 translate(SSH2_MSG_DEBUG);
360 translate(SSH2_MSG_SERVICE_REQUEST);
361 translate(SSH2_MSG_SERVICE_ACCEPT);
362 translate(SSH2_MSG_KEXINIT);
363 translate(SSH2_MSG_NEWKEYS);
364 translatek(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP);
365 translatek(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP);
366 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
367 translatek(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
368 translatek(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
369 translatek(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
370 translatek(SSH2_MSG_KEXRSA_PUBKEY, SSH2_PKTCTX_RSAKEX);
371 translatek(SSH2_MSG_KEXRSA_SECRET, SSH2_PKTCTX_RSAKEX);
372 translatek(SSH2_MSG_KEXRSA_DONE, SSH2_PKTCTX_RSAKEX);
373 translate(SSH2_MSG_USERAUTH_REQUEST);
374 translate(SSH2_MSG_USERAUTH_FAILURE);
375 translate(SSH2_MSG_USERAUTH_SUCCESS);
376 translate(SSH2_MSG_USERAUTH_BANNER);
377 translatea(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
378 translatea(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
379 translatea(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
380 translatea(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
381 translate(SSH2_MSG_GLOBAL_REQUEST);
382 translate(SSH2_MSG_REQUEST_SUCCESS);
383 translate(SSH2_MSG_REQUEST_FAILURE);
384 translate(SSH2_MSG_CHANNEL_OPEN);
385 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
386 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
387 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
388 translate(SSH2_MSG_CHANNEL_DATA);
389 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
390 translate(SSH2_MSG_CHANNEL_EOF);
391 translate(SSH2_MSG_CHANNEL_CLOSE);
392 translate(SSH2_MSG_CHANNEL_REQUEST);
393 translate(SSH2_MSG_CHANNEL_SUCCESS);
394 translate(SSH2_MSG_CHANNEL_FAILURE);
400 /* Enumeration values for fields in SSH-1 packets */
402 PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
403 /* These values are for communicating relevant semantics of
404 * fields to the packet logging code. */
405 PKTT_OTHER, PKTT_PASSWORD, PKTT_DATA
409 * Coroutine mechanics for the sillier bits of the code. If these
410 * macros look impenetrable to you, you might find it helpful to
413 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
415 * which explains the theory behind these macros.
417 * In particular, if you are getting `case expression not constant'
418 * errors when building with MS Visual Studio, this is because MS's
419 * Edit and Continue debugging feature causes their compiler to
420 * violate ANSI C. To disable Edit and Continue debugging:
422 * - right-click ssh.c in the FileView
424 * - select the C/C++ tab and the General category
425 * - under `Debug info:', select anything _other_ than `Program
426 * Database for Edit and Continue'.
428 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
431 if (!ssh->t) ssh->t = snew(struct t); \
433 #define crFinish(z) } *crLine = 0; return (z); }
434 #define crFinishV } *crLine = 0; return; }
435 #define crReturn(z) \
437 *crLine =__LINE__; return (z); case __LINE__:;\
441 *crLine=__LINE__; return; case __LINE__:;\
443 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
444 #define crStopV do{ *crLine = 0; return; }while(0)
445 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
446 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
448 typedef struct ssh_tag *Ssh;
451 static struct Packet *ssh1_pkt_init(int pkt_type);
452 static struct Packet *ssh2_pkt_init(int pkt_type);
453 static void ssh_pkt_ensure(struct Packet *, int length);
454 static void ssh_pkt_adddata(struct Packet *, void *data, int len);
455 static void ssh_pkt_addbyte(struct Packet *, unsigned char value);
456 static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
457 static void ssh_pkt_adduint32(struct Packet *, unsigned long value);
458 static void ssh_pkt_addstring_start(struct Packet *);
459 static void ssh_pkt_addstring_str(struct Packet *, char *data);
460 static void ssh_pkt_addstring_data(struct Packet *, char *data, int len);
461 static void ssh_pkt_addstring(struct Packet *, char *data);
462 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
463 static void ssh1_pkt_addmp(struct Packet *, Bignum b);
464 static void ssh2_pkt_addmp(struct Packet *, Bignum b);
465 static int ssh2_pkt_construct(Ssh, struct Packet *);
466 static void ssh2_pkt_send(Ssh, struct Packet *);
467 static void ssh2_pkt_send_noqueue(Ssh, struct Packet *);
468 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
469 struct Packet *pktin);
470 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
471 struct Packet *pktin);
474 * Buffer management constants. There are several of these for
475 * various different purposes:
477 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
478 * on a local data stream before we throttle the whole SSH
479 * connection (in SSH-1 only). Throttling the whole connection is
480 * pretty drastic so we set this high in the hope it won't
483 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
484 * on the SSH connection itself before we defensively throttle
485 * _all_ local data streams. This is pretty drastic too (though
486 * thankfully unlikely in SSH-2 since the window mechanism should
487 * ensure that the server never has any need to throttle its end
488 * of the connection), so we set this high as well.
490 * - OUR_V2_WINSIZE is the maximum window size we present on SSH-2
493 * - OUR_V2_BIGWIN is the window size we advertise for the only
494 * channel in a simple connection. It must be <= INT_MAX.
497 #define SSH1_BUFFER_LIMIT 32768
498 #define SSH_MAX_BACKLOG 32768
499 #define OUR_V2_WINSIZE 16384
500 #define OUR_V2_BIGWIN 0x7fffffff
501 #define OUR_V2_MAXPKT 0x4000UL
503 /* Maximum length of passwords/passphrases (arbitrary) */
504 #define SSH_MAX_PASSWORD_LEN 100
506 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
508 const static struct ssh_mac *macs[] = {
509 &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
511 const static struct ssh_mac *buggymacs[] = {
512 &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
515 static void *ssh_comp_none_init(void)
519 static void ssh_comp_none_cleanup(void *handle)
522 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
523 unsigned char **outblock, int *outlen)
527 static int ssh_comp_none_disable(void *handle)
531 const static struct ssh_compress ssh_comp_none = {
533 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
534 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
535 ssh_comp_none_disable, NULL
537 extern const struct ssh_compress ssh_zlib;
538 const static struct ssh_compress *compressions[] = {
539 &ssh_zlib, &ssh_comp_none
542 enum { /* channel types */
547 CHAN_SOCKDATA_DORMANT /* one the remote hasn't confirmed */
551 * little structure to keep track of outstanding WINDOW_ADJUSTs
559 * 2-3-4 tree storing channels.
562 Ssh ssh; /* pointer back to main context */
563 unsigned remoteid, localid;
565 /* True if we opened this channel but server hasn't confirmed. */
568 * In SSH-1, this value contains four bits:
570 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
571 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
572 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
573 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
575 * A channel is completely finished with when all four bits are set.
579 * True if this channel is causing the underlying connection to be
584 struct ssh2_data_channel {
586 unsigned remwindow, remmaxpkt;
587 /* locwindow is signed so we can cope with excess data. */
588 int locwindow, locmaxwin;
590 * remlocwin is the amount of local window that we think
591 * the remote end had available to it after it sent the
592 * last data packet or window adjust ack.
596 * These store the list of window adjusts that haven't
599 struct winadj *winadj_head, *winadj_tail;
600 enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
604 struct ssh_agent_channel {
605 unsigned char *message;
606 unsigned char msglen[4];
607 unsigned lensofar, totallen;
609 struct ssh_x11_channel {
612 struct ssh_pfd_channel {
619 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
620 * use this structure in different ways, reflecting SSH-2's
621 * altogether saner approach to port forwarding.
623 * In SSH-1, you arrange a remote forwarding by sending the server
624 * the remote port number, and the local destination host:port.
625 * When a connection comes in, the server sends you back that
626 * host:port pair, and you connect to it. This is a ready-made
627 * security hole if you're not on the ball: a malicious server
628 * could send you back _any_ host:port pair, so if you trustingly
629 * connect to the address it gives you then you've just opened the
630 * entire inside of your corporate network just by connecting
631 * through it to a dodgy SSH server. Hence, we must store a list of
632 * host:port pairs we _are_ trying to forward to, and reject a
633 * connection request from the server if it's not in the list.
635 * In SSH-2, each side of the connection minds its own business and
636 * doesn't send unnecessary information to the other. You arrange a
637 * remote forwarding by sending the server just the remote port
638 * number. When a connection comes in, the server tells you which
639 * of its ports was connected to; and _you_ have to remember what
640 * local host:port pair went with that port number.
642 * Hence, in SSH-1 this structure is indexed by destination
643 * host:port pair, whereas in SSH-2 it is indexed by source port.
645 struct ssh_portfwd; /* forward declaration */
647 struct ssh_rportfwd {
648 unsigned sport, dport;
651 struct ssh_portfwd *pfrec;
653 #define free_rportfwd(pf) ( \
654 ((pf) ? (sfree((pf)->sportdesc)) : (void)0 ), sfree(pf) )
657 * Separately to the rportfwd tree (which is for looking up port
658 * open requests from the server), a tree of _these_ structures is
659 * used to keep track of all the currently open port forwardings,
660 * so that we can reconfigure in mid-session if the user requests
664 enum { DESTROY, KEEP, CREATE } status;
666 unsigned sport, dport;
669 struct ssh_rportfwd *remote;
673 #define free_portfwd(pf) ( \
674 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
675 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
678 long length; /* length of `data' actually used */
679 long forcepad; /* SSH-2: force padding to at least this length */
680 int type; /* only used for incoming packets */
681 unsigned long sequence; /* SSH-2 incoming sequence number */
682 unsigned char *data; /* allocated storage */
683 unsigned char *body; /* offset of payload within `data' */
684 long savedpos; /* temporary index into `data' (for strings) */
685 long maxlen; /* amount of storage allocated for `data' */
686 long encrypted_len; /* for SSH-2 total-size counting */
689 * State associated with packet logging
693 struct logblank_t *blanks;
696 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
697 struct Packet *pktin);
698 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
699 struct Packet *pktin);
700 static void ssh1_protocol_setup(Ssh ssh);
701 static void ssh2_protocol_setup(Ssh ssh);
702 static void ssh_size(void *handle, int width, int height);
703 static void ssh_special(void *handle, Telnet_Special);
704 static int ssh2_try_send(struct ssh_channel *c);
705 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
706 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
707 static void ssh2_set_window(struct ssh_channel *c, int newwin);
708 static int ssh_sendbuffer(void *handle);
709 static int ssh_do_close(Ssh ssh, int notify_exit);
710 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
711 static int ssh2_pkt_getbool(struct Packet *pkt);
712 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
713 static void ssh2_timer(void *ctx, long now);
714 static int do_ssh2_transport(Ssh ssh, void *vin, int inlen,
715 struct Packet *pktin);
717 struct rdpkt1_state_tag {
718 long len, pad, biglen, to_read;
719 unsigned long realcrc, gotcrc;
723 struct Packet *pktin;
726 struct rdpkt2_state_tag {
727 long len, pad, payload, packetlen, maclen;
730 unsigned long incoming_sequence;
731 struct Packet *pktin;
734 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
735 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
737 struct queued_handler;
738 struct queued_handler {
740 chandler_fn_t handler;
742 struct queued_handler *next;
746 const struct plug_function_table *fn;
747 /* the above field _must_ be first in the structure */
757 unsigned char session_key[32];
759 int v1_remote_protoflags;
760 int v1_local_protoflags;
761 int agentfwd_enabled;
764 const struct ssh_cipher *cipher;
767 const struct ssh2_cipher *cscipher, *sccipher;
768 void *cs_cipher_ctx, *sc_cipher_ctx;
769 const struct ssh_mac *csmac, *scmac;
770 void *cs_mac_ctx, *sc_mac_ctx;
771 const struct ssh_compress *cscomp, *sccomp;
772 void *cs_comp_ctx, *sc_comp_ctx;
773 const struct ssh_kex *kex;
774 const struct ssh_signkey *hostkey;
775 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
776 int v2_session_id_len;
782 int echoing, editing;
786 int ospeed, ispeed; /* temporaries */
787 int term_width, term_height;
789 tree234 *channels; /* indexed by local id */
790 struct ssh_channel *mainchan; /* primary session channel */
791 int ncmode; /* is primary channel direct-tcpip? */
796 tree234 *rportfwds, *portfwds;
800 SSH_STATE_BEFORE_SIZE,
806 int size_needed, eof_needed;
808 struct Packet **queue;
809 int queuelen, queuesize;
811 unsigned char *deferred_send_data;
812 int deferred_len, deferred_size;
815 * Gross hack: pscp will try to start SFTP but fall back to
816 * scp1 if that fails. This variable is the means by which
817 * scp.c can reach into the SSH code and find out which one it
822 bufchain banner; /* accumulates banners during do_ssh2_authconn */
827 struct X11Display *x11disp;
830 int conn_throttle_count;
833 int v1_stdout_throttling;
834 unsigned long v2_outgoing_sequence;
836 int ssh1_rdpkt_crstate;
837 int ssh2_rdpkt_crstate;
838 int do_ssh_init_crstate;
839 int ssh_gotdata_crstate;
840 int do_ssh1_login_crstate;
841 int do_ssh1_connection_crstate;
842 int do_ssh2_transport_crstate;
843 int do_ssh2_authconn_crstate;
845 void *do_ssh_init_state;
846 void *do_ssh1_login_state;
847 void *do_ssh2_transport_state;
848 void *do_ssh2_authconn_state;
850 struct rdpkt1_state_tag rdpkt1_state;
851 struct rdpkt2_state_tag rdpkt2_state;
853 /* SSH-1 and SSH-2 use this for different things, but both use it */
854 int protocol_initial_phase_done;
856 void (*protocol) (Ssh ssh, void *vin, int inlen,
858 struct Packet *(*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
861 * We maintain a full _copy_ of a Config structure here, not
862 * merely a pointer to it. That way, when we're passed a new
863 * one for reconfiguration, we can check the differences and
864 * potentially reconfigure port forwardings etc in mid-session.
869 * Used to transfer data back from async callbacks.
871 void *agent_response;
872 int agent_response_len;
876 * The SSH connection can be set as `frozen', meaning we are
877 * not currently accepting incoming data from the network. This
878 * is slightly more serious than setting the _socket_ as
879 * frozen, because we may already have had data passed to us
880 * from the network which we need to delay processing until
881 * after the freeze is lifted, so we also need a bufchain to
885 bufchain queued_incoming_data;
888 * Dispatch table for packet types that we may have to deal
891 handler_fn_t packet_dispatch[256];
894 * Queues of one-off handler functions for success/failure
895 * indications from a request.
897 struct queued_handler *qhead, *qtail;
900 * This module deals with sending keepalives.
905 * Track incoming and outgoing data sizes and time, for
908 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
909 unsigned long max_data_size;
911 long next_rekey, last_rekey;
912 char *deferred_rekey_reason; /* points to STATIC string; don't free */
915 * Fully qualified host name, which we need if doing GSSAPI.
920 #define logevent(s) logevent(ssh->frontend, s)
922 /* logevent, only printf-formatted. */
923 static void logeventf(Ssh ssh, const char *fmt, ...)
929 buf = dupvprintf(fmt, ap);
935 #define bombout(msg) \
937 char *text = dupprintf msg; \
938 ssh_do_close(ssh, FALSE); \
940 connection_fatal(ssh->frontend, "%s", text); \
944 /* Functions to leave bits out of the SSH packet log file. */
946 static void dont_log_password(Ssh ssh, struct Packet *pkt, int blanktype)
948 if (ssh->cfg.logomitpass)
949 pkt->logmode = blanktype;
952 static void dont_log_data(Ssh ssh, struct Packet *pkt, int blanktype)
954 if (ssh->cfg.logomitdata)
955 pkt->logmode = blanktype;
958 static void end_log_omission(Ssh ssh, struct Packet *pkt)
960 pkt->logmode = PKTLOG_EMIT;
963 /* Helper function for common bits of parsing cfg.ttymodes. */
964 static void parse_ttymodes(Ssh ssh, char *modes,
965 void (*do_mode)(void *data, char *mode, char *val),
969 char *t = strchr(modes, '\t');
970 char *m = snewn(t-modes+1, char);
972 strncpy(m, modes, t-modes);
975 val = get_ttymode(ssh->frontend, m);
979 do_mode(data, m, val);
982 modes += strlen(modes) + 1;
986 static int ssh_channelcmp(void *av, void *bv)
988 struct ssh_channel *a = (struct ssh_channel *) av;
989 struct ssh_channel *b = (struct ssh_channel *) bv;
990 if (a->localid < b->localid)
992 if (a->localid > b->localid)
996 static int ssh_channelfind(void *av, void *bv)
998 unsigned *a = (unsigned *) av;
999 struct ssh_channel *b = (struct ssh_channel *) bv;
1000 if (*a < b->localid)
1002 if (*a > b->localid)
1007 static int ssh_rportcmp_ssh1(void *av, void *bv)
1009 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1010 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1012 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
1013 return i < 0 ? -1 : +1;
1014 if (a->dport > b->dport)
1016 if (a->dport < b->dport)
1021 static int ssh_rportcmp_ssh2(void *av, void *bv)
1023 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1024 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1026 if (a->sport > b->sport)
1028 if (a->sport < b->sport)
1034 * Special form of strcmp which can cope with NULL inputs. NULL is
1035 * defined to sort before even the empty string.
1037 static int nullstrcmp(const char *a, const char *b)
1039 if (a == NULL && b == NULL)
1045 return strcmp(a, b);
1048 static int ssh_portcmp(void *av, void *bv)
1050 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1051 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1053 if (a->type > b->type)
1055 if (a->type < b->type)
1057 if (a->addressfamily > b->addressfamily)
1059 if (a->addressfamily < b->addressfamily)
1061 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1062 return i < 0 ? -1 : +1;
1063 if (a->sport > b->sport)
1065 if (a->sport < b->sport)
1067 if (a->type != 'D') {
1068 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1069 return i < 0 ? -1 : +1;
1070 if (a->dport > b->dport)
1072 if (a->dport < b->dport)
1078 static int alloc_channel_id(Ssh ssh)
1080 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1081 unsigned low, high, mid;
1083 struct ssh_channel *c;
1086 * First-fit allocation of channel numbers: always pick the
1087 * lowest unused one. To do this, binary-search using the
1088 * counted B-tree to find the largest channel ID which is in a
1089 * contiguous sequence from the beginning. (Precisely
1090 * everything in that sequence must have ID equal to its tree
1091 * index plus CHANNEL_NUMBER_OFFSET.)
1093 tsize = count234(ssh->channels);
1097 while (high - low > 1) {
1098 mid = (high + low) / 2;
1099 c = index234(ssh->channels, mid);
1100 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1101 low = mid; /* this one is fine */
1103 high = mid; /* this one is past it */
1106 * Now low points to either -1, or the tree index of the
1107 * largest ID in the initial sequence.
1110 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1111 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1113 return low + 1 + CHANNEL_NUMBER_OFFSET;
1116 static void c_write_stderr(int trusted, const char *buf, int len)
1119 for (i = 0; i < len; i++)
1120 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1121 fputc(buf[i], stderr);
1124 static void c_write(Ssh ssh, const char *buf, int len)
1126 if (flags & FLAG_STDERR)
1127 c_write_stderr(1, buf, len);
1129 from_backend(ssh->frontend, 1, buf, len);
1132 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1134 if (flags & FLAG_STDERR)
1135 c_write_stderr(0, buf, len);
1137 from_backend_untrusted(ssh->frontend, buf, len);
1140 static void c_write_str(Ssh ssh, const char *buf)
1142 c_write(ssh, buf, strlen(buf));
1145 static void ssh_free_packet(struct Packet *pkt)
1150 static struct Packet *ssh_new_packet(void)
1152 struct Packet *pkt = snew(struct Packet);
1154 pkt->body = pkt->data = NULL;
1156 pkt->logmode = PKTLOG_EMIT;
1164 * Collect incoming data in the incoming packet buffer.
1165 * Decipher and verify the packet when it is completely read.
1166 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1167 * Update the *data and *datalen variables.
1168 * Return a Packet structure when a packet is completed.
1170 static struct Packet *ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1172 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1174 crBegin(ssh->ssh1_rdpkt_crstate);
1176 st->pktin = ssh_new_packet();
1178 st->pktin->type = 0;
1179 st->pktin->length = 0;
1181 for (st->i = st->len = 0; st->i < 4; st->i++) {
1182 while ((*datalen) == 0)
1184 st->len = (st->len << 8) + **data;
1185 (*data)++, (*datalen)--;
1188 st->pad = 8 - (st->len % 8);
1189 st->biglen = st->len + st->pad;
1190 st->pktin->length = st->len - 5;
1192 if (st->biglen < 0) {
1193 bombout(("Extremely large packet length from server suggests"
1194 " data stream corruption"));
1195 ssh_free_packet(st->pktin);
1199 st->pktin->maxlen = st->biglen;
1200 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1202 st->to_read = st->biglen;
1203 st->p = st->pktin->data;
1204 while (st->to_read > 0) {
1205 st->chunk = st->to_read;
1206 while ((*datalen) == 0)
1208 if (st->chunk > (*datalen))
1209 st->chunk = (*datalen);
1210 memcpy(st->p, *data, st->chunk);
1212 *datalen -= st->chunk;
1214 st->to_read -= st->chunk;
1217 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1218 st->biglen, NULL)) {
1219 bombout(("Network attack (CRC compensation) detected!"));
1220 ssh_free_packet(st->pktin);
1225 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1227 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1228 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1229 if (st->gotcrc != st->realcrc) {
1230 bombout(("Incorrect CRC received on packet"));
1231 ssh_free_packet(st->pktin);
1235 st->pktin->body = st->pktin->data + st->pad + 1;
1236 st->pktin->savedpos = 0;
1238 if (ssh->v1_compressing) {
1239 unsigned char *decompblk;
1241 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1242 st->pktin->body - 1, st->pktin->length + 1,
1243 &decompblk, &decomplen)) {
1244 bombout(("Zlib decompression encountered invalid data"));
1245 ssh_free_packet(st->pktin);
1249 if (st->pktin->maxlen < st->pad + decomplen) {
1250 st->pktin->maxlen = st->pad + decomplen;
1251 st->pktin->data = sresize(st->pktin->data,
1252 st->pktin->maxlen + APIEXTRA,
1254 st->pktin->body = st->pktin->data + st->pad + 1;
1257 memcpy(st->pktin->body - 1, decompblk, decomplen);
1259 st->pktin->length = decomplen - 1;
1262 st->pktin->type = st->pktin->body[-1];
1265 * Log incoming packet, possibly omitting sensitive fields.
1269 struct logblank_t blank;
1270 if (ssh->cfg.logomitdata) {
1271 int do_blank = FALSE, blank_prefix = 0;
1272 /* "Session data" packets - omit the data field */
1273 if ((st->pktin->type == SSH1_SMSG_STDOUT_DATA) ||
1274 (st->pktin->type == SSH1_SMSG_STDERR_DATA)) {
1275 do_blank = TRUE; blank_prefix = 4;
1276 } else if (st->pktin->type == SSH1_MSG_CHANNEL_DATA) {
1277 do_blank = TRUE; blank_prefix = 8;
1280 blank.offset = blank_prefix;
1281 blank.len = st->pktin->length;
1282 blank.type = PKTLOG_OMIT;
1286 log_packet(ssh->logctx,
1287 PKT_INCOMING, st->pktin->type,
1288 ssh1_pkt_type(st->pktin->type),
1289 st->pktin->body, st->pktin->length,
1290 nblanks, &blank, NULL);
1293 crFinish(st->pktin);
1296 static struct Packet *ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1298 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1300 crBegin(ssh->ssh2_rdpkt_crstate);
1302 st->pktin = ssh_new_packet();
1304 st->pktin->type = 0;
1305 st->pktin->length = 0;
1307 st->cipherblk = ssh->sccipher->blksize;
1310 if (st->cipherblk < 8)
1313 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1316 * Acquire and decrypt the first block of the packet. This will
1317 * contain the length and padding details.
1319 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1320 while ((*datalen) == 0)
1322 st->pktin->data[st->i] = *(*data)++;
1327 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1328 st->pktin->data, st->cipherblk);
1331 * Now get the length and padding figures.
1333 st->len = GET_32BIT(st->pktin->data);
1334 st->pad = st->pktin->data[4];
1337 * _Completely_ silly lengths should be stomped on before they
1338 * do us any more damage.
1340 if (st->len < 0 || st->len > 35000 || st->pad < 4 ||
1341 st->len - st->pad < 1 || (st->len + 4) % st->cipherblk != 0) {
1342 bombout(("Incoming packet was garbled on decryption"));
1343 ssh_free_packet(st->pktin);
1348 * This enables us to deduce the payload length.
1350 st->payload = st->len - st->pad - 1;
1352 st->pktin->length = st->payload + 5;
1355 * So now we can work out the total packet length.
1357 st->packetlen = st->len + 4;
1358 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1361 * Allocate memory for the rest of the packet.
1363 st->pktin->maxlen = st->packetlen + st->maclen;
1364 st->pktin->data = sresize(st->pktin->data,
1365 st->pktin->maxlen + APIEXTRA,
1369 * Read and decrypt the remainder of the packet.
1371 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1373 while ((*datalen) == 0)
1375 st->pktin->data[st->i] = *(*data)++;
1378 /* Decrypt everything _except_ the MAC. */
1380 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1381 st->pktin->data + st->cipherblk,
1382 st->packetlen - st->cipherblk);
1384 st->pktin->encrypted_len = st->packetlen;
1390 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data, st->len + 4,
1391 st->incoming_sequence)) {
1392 bombout(("Incorrect MAC received on packet"));
1393 ssh_free_packet(st->pktin);
1397 st->pktin->sequence = st->incoming_sequence++;
1400 * Decompress packet payload.
1403 unsigned char *newpayload;
1406 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1407 st->pktin->data + 5, st->pktin->length - 5,
1408 &newpayload, &newlen)) {
1409 if (st->pktin->maxlen < newlen + 5) {
1410 st->pktin->maxlen = newlen + 5;
1411 st->pktin->data = sresize(st->pktin->data,
1412 st->pktin->maxlen + APIEXTRA,
1415 st->pktin->length = 5 + newlen;
1416 memcpy(st->pktin->data + 5, newpayload, newlen);
1421 st->pktin->savedpos = 6;
1422 st->pktin->body = st->pktin->data;
1423 st->pktin->type = st->pktin->data[5];
1426 * Log incoming packet, possibly omitting sensitive fields.
1430 struct logblank_t blank;
1431 if (ssh->cfg.logomitdata) {
1432 int do_blank = FALSE, blank_prefix = 0;
1433 /* "Session data" packets - omit the data field */
1434 if (st->pktin->type == SSH2_MSG_CHANNEL_DATA) {
1435 do_blank = TRUE; blank_prefix = 8;
1436 } else if (st->pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
1437 do_blank = TRUE; blank_prefix = 12;
1440 blank.offset = blank_prefix;
1441 blank.len = (st->pktin->length-6) - blank_prefix;
1442 blank.type = PKTLOG_OMIT;
1446 log_packet(ssh->logctx, PKT_INCOMING, st->pktin->type,
1447 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
1449 st->pktin->data+6, st->pktin->length-6,
1450 nblanks, &blank, &st->pktin->sequence);
1453 crFinish(st->pktin);
1456 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1458 int pad, biglen, i, pktoffs;
1462 * XXX various versions of SC (including 8.8.4) screw up the
1463 * register allocation in this function and use the same register
1464 * (D6) for len and as a temporary, with predictable results. The
1465 * following sledgehammer prevents this.
1472 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1473 ssh1_pkt_type(pkt->data[12]),
1474 pkt->body, pkt->length - (pkt->body - pkt->data),
1475 pkt->nblanks, pkt->blanks, NULL);
1476 sfree(pkt->blanks); pkt->blanks = NULL;
1479 if (ssh->v1_compressing) {
1480 unsigned char *compblk;
1482 zlib_compress_block(ssh->cs_comp_ctx,
1483 pkt->data + 12, pkt->length - 12,
1484 &compblk, &complen);
1485 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1486 memcpy(pkt->data + 12, compblk, complen);
1488 pkt->length = complen + 12;
1491 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1493 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1494 pad = 8 - (len % 8);
1496 biglen = len + pad; /* len(padding+type+data+CRC) */
1498 for (i = pktoffs; i < 4+8; i++)
1499 pkt->data[i] = random_byte();
1500 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
1501 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
1502 PUT_32BIT(pkt->data + pktoffs, len);
1505 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
1506 pkt->data + pktoffs + 4, biglen);
1508 if (offset_p) *offset_p = pktoffs;
1509 return biglen + 4; /* len(length+padding+type+data+CRC) */
1512 static int s_write(Ssh ssh, void *data, int len)
1515 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
1517 return sk_write(ssh->s, (char *)data, len);
1520 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1522 int len, backlog, offset;
1523 len = s_wrpkt_prepare(ssh, pkt, &offset);
1524 backlog = s_write(ssh, pkt->data + offset, len);
1525 if (backlog > SSH_MAX_BACKLOG)
1526 ssh_throttle_all(ssh, 1, backlog);
1527 ssh_free_packet(pkt);
1530 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1533 len = s_wrpkt_prepare(ssh, pkt, &offset);
1534 if (ssh->deferred_len + len > ssh->deferred_size) {
1535 ssh->deferred_size = ssh->deferred_len + len + 128;
1536 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1540 memcpy(ssh->deferred_send_data + ssh->deferred_len,
1541 pkt->data + offset, len);
1542 ssh->deferred_len += len;
1543 ssh_free_packet(pkt);
1547 * Construct a SSH-1 packet with the specified contents.
1548 * (This all-at-once interface used to be the only one, but now SSH-1
1549 * packets can also be constructed incrementally.)
1551 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
1557 pkt = ssh1_pkt_init(pkttype);
1559 while ((argtype = va_arg(ap, int)) != PKT_END) {
1560 unsigned char *argp, argchar;
1562 unsigned long argint;
1565 /* Actual fields in the packet */
1567 argint = va_arg(ap, int);
1568 ssh_pkt_adduint32(pkt, argint);
1571 argchar = (unsigned char) va_arg(ap, int);
1572 ssh_pkt_addbyte(pkt, argchar);
1575 argp = va_arg(ap, unsigned char *);
1576 arglen = va_arg(ap, int);
1577 ssh_pkt_adddata(pkt, argp, arglen);
1580 sargp = va_arg(ap, char *);
1581 ssh_pkt_addstring(pkt, sargp);
1584 bn = va_arg(ap, Bignum);
1585 ssh1_pkt_addmp(pkt, bn);
1587 /* Tokens for modifications to packet logging */
1589 dont_log_password(ssh, pkt, PKTLOG_BLANK);
1592 dont_log_data(ssh, pkt, PKTLOG_OMIT);
1595 end_log_omission(ssh, pkt);
1603 static void send_packet(Ssh ssh, int pkttype, ...)
1607 va_start(ap, pkttype);
1608 pkt = construct_packet(ssh, pkttype, ap);
1613 static void defer_packet(Ssh ssh, int pkttype, ...)
1617 va_start(ap, pkttype);
1618 pkt = construct_packet(ssh, pkttype, ap);
1620 s_wrpkt_defer(ssh, pkt);
1623 static int ssh_versioncmp(char *a, char *b)
1626 unsigned long av, bv;
1628 av = strtoul(a, &ae, 10);
1629 bv = strtoul(b, &be, 10);
1631 return (av < bv ? -1 : +1);
1636 av = strtoul(ae, &ae, 10);
1637 bv = strtoul(be, &be, 10);
1639 return (av < bv ? -1 : +1);
1644 * Utility routines for putting an SSH-protocol `string' and
1645 * `uint32' into a hash state.
1647 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
1649 unsigned char lenblk[4];
1650 PUT_32BIT(lenblk, len);
1651 h->bytes(s, lenblk, 4);
1652 h->bytes(s, str, len);
1655 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
1657 unsigned char intblk[4];
1658 PUT_32BIT(intblk, i);
1659 h->bytes(s, intblk, 4);
1663 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
1665 static void ssh_pkt_ensure(struct Packet *pkt, int length)
1667 if (pkt->maxlen < length) {
1668 unsigned char *body = pkt->body;
1669 int offset = body ? body - pkt->data : 0;
1670 pkt->maxlen = length + 256;
1671 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
1672 if (body) pkt->body = pkt->data + offset;
1675 static void ssh_pkt_adddata(struct Packet *pkt, void *data, int len)
1677 if (pkt->logmode != PKTLOG_EMIT) {
1679 pkt->blanks = sresize(pkt->blanks, pkt->nblanks, struct logblank_t);
1681 pkt->blanks[pkt->nblanks-1].offset = pkt->length -
1682 (pkt->body - pkt->data);
1683 pkt->blanks[pkt->nblanks-1].len = len;
1684 pkt->blanks[pkt->nblanks-1].type = pkt->logmode;
1687 ssh_pkt_ensure(pkt, pkt->length);
1688 memcpy(pkt->data + pkt->length - len, data, len);
1690 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
1692 ssh_pkt_adddata(pkt, &byte, 1);
1694 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
1696 ssh_pkt_adddata(pkt, &value, 1);
1698 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
1701 PUT_32BIT(x, value);
1702 ssh_pkt_adddata(pkt, x, 4);
1704 static void ssh_pkt_addstring_start(struct Packet *pkt)
1706 ssh_pkt_adduint32(pkt, 0);
1707 pkt->savedpos = pkt->length;
1709 static void ssh_pkt_addstring_str(struct Packet *pkt, char *data)
1711 ssh_pkt_adddata(pkt, data, strlen(data));
1712 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1714 static void ssh_pkt_addstring_data(struct Packet *pkt, char *data, int len)
1716 ssh_pkt_adddata(pkt, data, len);
1717 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1719 static void ssh_pkt_addstring(struct Packet *pkt, char *data)
1721 ssh_pkt_addstring_start(pkt);
1722 ssh_pkt_addstring_str(pkt, data);
1724 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
1726 int len = ssh1_bignum_length(b);
1727 unsigned char *data = snewn(len, unsigned char);
1728 (void) ssh1_write_bignum(data, b);
1729 ssh_pkt_adddata(pkt, data, len);
1732 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
1735 int i, n = (bignum_bitcount(b) + 7) / 8;
1736 p = snewn(n + 1, unsigned char);
1738 for (i = 1; i <= n; i++)
1739 p[i] = bignum_byte(b, n - i);
1741 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1743 memmove(p, p + i, n + 1 - i);
1747 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
1751 p = ssh2_mpint_fmt(b, &len);
1752 ssh_pkt_addstring_start(pkt);
1753 ssh_pkt_addstring_data(pkt, (char *)p, len);
1757 static struct Packet *ssh1_pkt_init(int pkt_type)
1759 struct Packet *pkt = ssh_new_packet();
1760 pkt->length = 4 + 8; /* space for length + max padding */
1761 ssh_pkt_addbyte(pkt, pkt_type);
1762 pkt->body = pkt->data + pkt->length;
1766 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
1767 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
1768 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
1769 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
1770 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
1771 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
1772 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
1773 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
1774 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
1776 static struct Packet *ssh2_pkt_init(int pkt_type)
1778 struct Packet *pkt = ssh_new_packet();
1779 pkt->length = 5; /* space for packet length + padding length */
1781 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
1782 pkt->body = pkt->data + pkt->length; /* after packet type */
1787 * Construct an SSH-2 final-form packet: compress it, encrypt it,
1788 * put the MAC on it. Final packet, ready to be sent, is stored in
1789 * pkt->data. Total length is returned.
1791 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
1793 int cipherblk, maclen, padding, i;
1796 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1797 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1798 pkt->body, pkt->length - (pkt->body - pkt->data),
1799 pkt->nblanks, pkt->blanks, &ssh->v2_outgoing_sequence);
1800 sfree(pkt->blanks); pkt->blanks = NULL;
1804 * Compress packet payload.
1807 unsigned char *newpayload;
1810 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
1812 &newpayload, &newlen)) {
1814 ssh2_pkt_adddata(pkt, newpayload, newlen);
1820 * Add padding. At least four bytes, and must also bring total
1821 * length (minus MAC) up to a multiple of the block size.
1822 * If pkt->forcepad is set, make sure the packet is at least that size
1825 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
1826 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
1828 if (pkt->length + padding < pkt->forcepad)
1829 padding = pkt->forcepad - pkt->length;
1831 (cipherblk - (pkt->length + padding) % cipherblk) % cipherblk;
1832 assert(padding <= 255);
1833 maclen = ssh->csmac ? ssh->csmac->len : 0;
1834 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
1835 pkt->data[4] = padding;
1836 for (i = 0; i < padding; i++)
1837 pkt->data[pkt->length + i] = random_byte();
1838 PUT_32BIT(pkt->data, pkt->length + padding - 4);
1840 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
1841 pkt->length + padding,
1842 ssh->v2_outgoing_sequence);
1843 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
1846 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
1847 pkt->data, pkt->length + padding);
1849 pkt->encrypted_len = pkt->length + padding;
1851 /* Ready-to-send packet starts at pkt->data. We return length. */
1852 return pkt->length + padding + maclen;
1856 * Routines called from the main SSH code to send packets. There
1857 * are quite a few of these, because we have two separate
1858 * mechanisms for delaying the sending of packets:
1860 * - In order to send an IGNORE message and a password message in
1861 * a single fixed-length blob, we require the ability to
1862 * concatenate the encrypted forms of those two packets _into_ a
1863 * single blob and then pass it to our <network.h> transport
1864 * layer in one go. Hence, there's a deferment mechanism which
1865 * works after packet encryption.
1867 * - In order to avoid sending any connection-layer messages
1868 * during repeat key exchange, we have to queue up any such
1869 * outgoing messages _before_ they are encrypted (and in
1870 * particular before they're allocated sequence numbers), and
1871 * then send them once we've finished.
1873 * I call these mechanisms `defer' and `queue' respectively, so as
1874 * to distinguish them reasonably easily.
1876 * The functions send_noqueue() and defer_noqueue() free the packet
1877 * structure they are passed. Every outgoing packet goes through
1878 * precisely one of these functions in its life; packets passed to
1879 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
1880 * these or get queued, and then when the queue is later emptied
1881 * the packets are all passed to defer_noqueue().
1883 * When using a CBC-mode cipher, it's necessary to ensure that an
1884 * attacker can't provide data to be encrypted using an IV that they
1885 * know. We ensure this by prefixing each packet that might contain
1886 * user data with an SSH_MSG_IGNORE. This is done using the deferral
1887 * mechanism, so in this case send_noqueue() ends up redirecting to
1888 * defer_noqueue(). If you don't like this inefficiency, don't use
1892 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
1893 static void ssh_pkt_defersend(Ssh);
1896 * Send an SSH-2 packet immediately, without queuing or deferring.
1898 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
1902 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
1903 /* We need to send two packets, so use the deferral mechanism. */
1904 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
1905 ssh_pkt_defersend(ssh);
1908 len = ssh2_pkt_construct(ssh, pkt);
1909 backlog = s_write(ssh, pkt->data, len);
1910 if (backlog > SSH_MAX_BACKLOG)
1911 ssh_throttle_all(ssh, 1, backlog);
1913 ssh->outgoing_data_size += pkt->encrypted_len;
1914 if (!ssh->kex_in_progress &&
1915 ssh->max_data_size != 0 &&
1916 ssh->outgoing_data_size > ssh->max_data_size)
1917 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
1919 ssh_free_packet(pkt);
1923 * Defer an SSH-2 packet.
1925 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
1928 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
1929 ssh->deferred_len == 0 && !noignore) {
1931 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
1932 * get encrypted with a known IV.
1934 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
1935 ssh2_pkt_addstring_start(ipkt);
1936 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
1938 len = ssh2_pkt_construct(ssh, pkt);
1939 if (ssh->deferred_len + len > ssh->deferred_size) {
1940 ssh->deferred_size = ssh->deferred_len + len + 128;
1941 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1945 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->data, len);
1946 ssh->deferred_len += len;
1947 ssh->deferred_data_size += pkt->encrypted_len;
1948 ssh_free_packet(pkt);
1952 * Queue an SSH-2 packet.
1954 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
1956 assert(ssh->queueing);
1958 if (ssh->queuelen >= ssh->queuesize) {
1959 ssh->queuesize = ssh->queuelen + 32;
1960 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
1963 ssh->queue[ssh->queuelen++] = pkt;
1967 * Either queue or send a packet, depending on whether queueing is
1970 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
1973 ssh2_pkt_queue(ssh, pkt);
1975 ssh2_pkt_send_noqueue(ssh, pkt);
1979 * Either queue or defer a packet, depending on whether queueing is
1982 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
1985 ssh2_pkt_queue(ssh, pkt);
1987 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
1991 * Send the whole deferred data block constructed by
1992 * ssh2_pkt_defer() or SSH-1's defer_packet().
1994 * The expected use of the defer mechanism is that you call
1995 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
1996 * not currently queueing, this simply sets up deferred_send_data
1997 * and then sends it. If we _are_ currently queueing, the calls to
1998 * ssh2_pkt_defer() put the deferred packets on to the queue
1999 * instead, and therefore ssh_pkt_defersend() has no deferred data
2000 * to send. Hence, there's no need to make it conditional on
2003 static void ssh_pkt_defersend(Ssh ssh)
2006 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2007 ssh->deferred_len = ssh->deferred_size = 0;
2008 sfree(ssh->deferred_send_data);
2009 ssh->deferred_send_data = NULL;
2010 if (backlog > SSH_MAX_BACKLOG)
2011 ssh_throttle_all(ssh, 1, backlog);
2013 ssh->outgoing_data_size += ssh->deferred_data_size;
2014 if (!ssh->kex_in_progress &&
2015 ssh->max_data_size != 0 &&
2016 ssh->outgoing_data_size > ssh->max_data_size)
2017 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2018 ssh->deferred_data_size = 0;
2022 * Send a packet whose length needs to be disguised (typically
2023 * passwords or keyboard-interactive responses).
2025 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2031 * The simplest way to do this is to adjust the
2032 * variable-length padding field in the outgoing packet.
2034 * Currently compiled out, because some Cisco SSH servers
2035 * don't like excessively padded packets (bah, why's it
2038 pkt->forcepad = padsize;
2039 ssh2_pkt_send(ssh, pkt);
2044 * If we can't do that, however, an alternative approach is
2045 * to use the pkt_defer mechanism to bundle the packet
2046 * tightly together with an SSH_MSG_IGNORE such that their
2047 * combined length is a constant. So first we construct the
2048 * final form of this packet and defer its sending.
2050 ssh2_pkt_defer(ssh, pkt);
2053 * Now construct an SSH_MSG_IGNORE which includes a string
2054 * that's an exact multiple of the cipher block size. (If
2055 * the cipher is NULL so that the block size is
2056 * unavailable, we don't do this trick at all, because we
2057 * gain nothing by it.)
2059 if (ssh->cscipher) {
2062 stringlen = (256 - ssh->deferred_len);
2063 stringlen += ssh->cscipher->blksize - 1;
2064 stringlen -= (stringlen % ssh->cscipher->blksize);
2067 * Temporarily disable actual compression, so we
2068 * can guarantee to get this string exactly the
2069 * length we want it. The compression-disabling
2070 * routine should return an integer indicating how
2071 * many bytes we should adjust our string length
2075 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2077 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2078 ssh2_pkt_addstring_start(pkt);
2079 for (i = 0; i < stringlen; i++) {
2080 char c = (char) random_byte();
2081 ssh2_pkt_addstring_data(pkt, &c, 1);
2083 ssh2_pkt_defer(ssh, pkt);
2085 ssh_pkt_defersend(ssh);
2090 * Send all queued SSH-2 packets. We send them by means of
2091 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2092 * packets that needed to be lumped together.
2094 static void ssh2_pkt_queuesend(Ssh ssh)
2098 assert(!ssh->queueing);
2100 for (i = 0; i < ssh->queuelen; i++)
2101 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2104 ssh_pkt_defersend(ssh);
2108 void bndebug(char *string, Bignum b)
2112 p = ssh2_mpint_fmt(b, &len);
2113 debug(("%s", string));
2114 for (i = 0; i < len; i++)
2115 debug((" %02x", p[i]));
2121 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2125 p = ssh2_mpint_fmt(b, &len);
2126 hash_string(h, s, p, len);
2131 * Packet decode functions for both SSH-1 and SSH-2.
2133 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2135 unsigned long value;
2136 if (pkt->length - pkt->savedpos < 4)
2137 return 0; /* arrgh, no way to decline (FIXME?) */
2138 value = GET_32BIT(pkt->body + pkt->savedpos);
2142 static int ssh2_pkt_getbool(struct Packet *pkt)
2144 unsigned long value;
2145 if (pkt->length - pkt->savedpos < 1)
2146 return 0; /* arrgh, no way to decline (FIXME?) */
2147 value = pkt->body[pkt->savedpos] != 0;
2151 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2156 if (pkt->length - pkt->savedpos < 4)
2158 len = GET_32BIT(pkt->body + pkt->savedpos);
2163 if (pkt->length - pkt->savedpos < *length)
2165 *p = (char *)(pkt->body + pkt->savedpos);
2166 pkt->savedpos += *length;
2168 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2170 if (pkt->length - pkt->savedpos < length)
2172 pkt->savedpos += length;
2173 return pkt->body + (pkt->savedpos - length);
2175 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2176 unsigned char **keystr)
2180 j = makekey(pkt->body + pkt->savedpos,
2181 pkt->length - pkt->savedpos,
2188 assert(pkt->savedpos < pkt->length);
2192 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2197 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2198 pkt->length - pkt->savedpos, &b);
2206 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2212 ssh_pkt_getstring(pkt, &p, &length);
2217 b = bignum_from_bytes((unsigned char *)p, length);
2222 * Helper function to add an SSH-2 signature blob to a packet.
2223 * Expects to be shown the public key blob as well as the signature
2224 * blob. Normally works just like ssh2_pkt_addstring, but will
2225 * fiddle with the signature packet if necessary for
2226 * BUG_SSH2_RSA_PADDING.
2228 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2229 void *pkblob_v, int pkblob_len,
2230 void *sigblob_v, int sigblob_len)
2232 unsigned char *pkblob = (unsigned char *)pkblob_v;
2233 unsigned char *sigblob = (unsigned char *)sigblob_v;
2235 /* dmemdump(pkblob, pkblob_len); */
2236 /* dmemdump(sigblob, sigblob_len); */
2239 * See if this is in fact an ssh-rsa signature and a buggy
2240 * server; otherwise we can just do this the easy way.
2242 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) &&
2243 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2244 int pos, len, siglen;
2247 * Find the byte length of the modulus.
2250 pos = 4+7; /* skip over "ssh-rsa" */
2251 pos += 4 + GET_32BIT(pkblob+pos); /* skip over exponent */
2252 len = GET_32BIT(pkblob+pos); /* find length of modulus */
2253 pos += 4; /* find modulus itself */
2254 while (len > 0 && pkblob[pos] == 0)
2256 /* debug(("modulus length is %d\n", len)); */
2259 * Now find the signature integer.
2261 pos = 4+7; /* skip over "ssh-rsa" */
2262 siglen = GET_32BIT(sigblob+pos);
2263 /* debug(("signature length is %d\n", siglen)); */
2265 if (len != siglen) {
2266 unsigned char newlen[4];
2267 ssh2_pkt_addstring_start(pkt);
2268 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2269 /* dmemdump(sigblob, pos); */
2270 pos += 4; /* point to start of actual sig */
2271 PUT_32BIT(newlen, len);
2272 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2273 /* dmemdump(newlen, 4); */
2275 while (len-- > siglen) {
2276 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2277 /* dmemdump(newlen, 1); */
2279 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2280 /* dmemdump(sigblob+pos, siglen); */
2284 /* Otherwise fall through and do it the easy way. */
2287 ssh2_pkt_addstring_start(pkt);
2288 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2292 * Examine the remote side's version string and compare it against
2293 * a list of known buggy implementations.
2295 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2297 char *imp; /* pointer to implementation part */
2299 imp += strcspn(imp, "-");
2301 imp += strcspn(imp, "-");
2304 ssh->remote_bugs = 0;
2307 * General notes on server version strings:
2308 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2309 * here -- in particular, we've heard of one that's perfectly happy
2310 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2311 * so we can't distinguish them.
2313 if (ssh->cfg.sshbug_ignore1 == FORCE_ON ||
2314 (ssh->cfg.sshbug_ignore1 == AUTO &&
2315 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2316 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2317 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2318 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2320 * These versions don't support SSH1_MSG_IGNORE, so we have
2321 * to use a different defence against password length
2324 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2325 logevent("We believe remote version has SSH-1 ignore bug");
2328 if (ssh->cfg.sshbug_plainpw1 == FORCE_ON ||
2329 (ssh->cfg.sshbug_plainpw1 == AUTO &&
2330 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2332 * These versions need a plain password sent; they can't
2333 * handle having a null and a random length of data after
2336 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2337 logevent("We believe remote version needs a plain SSH-1 password");
2340 if (ssh->cfg.sshbug_rsa1 == FORCE_ON ||
2341 (ssh->cfg.sshbug_rsa1 == AUTO &&
2342 (!strcmp(imp, "Cisco-1.25")))) {
2344 * These versions apparently have no clue whatever about
2345 * RSA authentication and will panic and die if they see
2346 * an AUTH_RSA message.
2348 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2349 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2352 if (ssh->cfg.sshbug_hmac2 == FORCE_ON ||
2353 (ssh->cfg.sshbug_hmac2 == AUTO &&
2354 !wc_match("* VShell", imp) &&
2355 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2356 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2357 wc_match("2.1 *", imp)))) {
2359 * These versions have the HMAC bug.
2361 ssh->remote_bugs |= BUG_SSH2_HMAC;
2362 logevent("We believe remote version has SSH-2 HMAC bug");
2365 if (ssh->cfg.sshbug_derivekey2 == FORCE_ON ||
2366 (ssh->cfg.sshbug_derivekey2 == AUTO &&
2367 !wc_match("* VShell", imp) &&
2368 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2370 * These versions have the key-derivation bug (failing to
2371 * include the literal shared secret in the hashes that
2372 * generate the keys).
2374 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2375 logevent("We believe remote version has SSH-2 key-derivation bug");
2378 if (ssh->cfg.sshbug_rsapad2 == FORCE_ON ||
2379 (ssh->cfg.sshbug_rsapad2 == AUTO &&
2380 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2381 wc_match("OpenSSH_3.[0-2]*", imp)))) {
2383 * These versions have the SSH-2 RSA padding bug.
2385 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2386 logevent("We believe remote version has SSH-2 RSA padding bug");
2389 if (ssh->cfg.sshbug_pksessid2 == FORCE_ON ||
2390 (ssh->cfg.sshbug_pksessid2 == AUTO &&
2391 wc_match("OpenSSH_2.[0-2]*", imp))) {
2393 * These versions have the SSH-2 session-ID bug in
2394 * public-key authentication.
2396 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2397 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2400 if (ssh->cfg.sshbug_rekey2 == FORCE_ON ||
2401 (ssh->cfg.sshbug_rekey2 == AUTO &&
2402 (wc_match("DigiSSH_2.0", imp) ||
2403 wc_match("OpenSSH_2.[0-4]*", imp) ||
2404 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2405 wc_match("Sun_SSH_1.0", imp) ||
2406 wc_match("Sun_SSH_1.0.1", imp) ||
2407 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2408 wc_match("WeOnlyDo-*", imp)))) {
2410 * These versions have the SSH-2 rekey bug.
2412 ssh->remote_bugs |= BUG_SSH2_REKEY;
2413 logevent("We believe remote version has SSH-2 rekey bug");
2416 if (ssh->cfg.sshbug_maxpkt2 == FORCE_ON ||
2417 (ssh->cfg.sshbug_maxpkt2 == AUTO &&
2418 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2419 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2421 * This version ignores our makpkt and needs to be throttled.
2423 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2424 logevent("We believe remote version ignores SSH-2 maximum packet size");
2429 * The `software version' part of an SSH version string is required
2430 * to contain no spaces or minus signs.
2432 static void ssh_fix_verstring(char *str)
2434 /* Eat "SSH-<protoversion>-". */
2435 assert(*str == 'S'); str++;
2436 assert(*str == 'S'); str++;
2437 assert(*str == 'H'); str++;
2438 assert(*str == '-'); str++;
2439 while (*str && *str != '-') str++;
2440 assert(*str == '-'); str++;
2442 /* Convert minus signs and spaces in the remaining string into
2445 if (*str == '-' || *str == ' ')
2452 * Send an appropriate SSH version string.
2454 static void ssh_send_verstring(Ssh ssh, char *svers)
2458 if (ssh->version == 2) {
2460 * Construct a v2 version string.
2462 verstring = dupprintf("SSH-2.0-%s\015\012", sshver);
2465 * Construct a v1 version string.
2467 verstring = dupprintf("SSH-%s-%s\012",
2468 (ssh_versioncmp(svers, "1.5") <= 0 ?
2473 ssh_fix_verstring(verstring);
2475 if (ssh->version == 2) {
2478 * Record our version string.
2480 len = strcspn(verstring, "\015\012");
2481 ssh->v_c = snewn(len + 1, char);
2482 memcpy(ssh->v_c, verstring, len);
2486 logeventf(ssh, "We claim version: %.*s",
2487 strcspn(verstring, "\015\012"), verstring);
2488 s_write(ssh, verstring, strlen(verstring));
2492 static int do_ssh_init(Ssh ssh, unsigned char c)
2494 struct do_ssh_init_state {
2502 crState(do_ssh_init_state);
2504 crBegin(ssh->do_ssh_init_crstate);
2506 /* Search for a line beginning with the string "SSH-" in the input. */
2508 if (c != 'S') goto no;
2510 if (c != 'S') goto no;
2512 if (c != 'H') goto no;
2514 if (c != '-') goto no;
2523 s->vstring = snewn(s->vstrsize, char);
2524 strcpy(s->vstring, "SSH-");
2528 crReturn(1); /* get another char */
2529 if (s->vslen >= s->vstrsize - 1) {
2531 s->vstring = sresize(s->vstring, s->vstrsize, char);
2533 s->vstring[s->vslen++] = c;
2536 s->version[s->i] = '\0';
2538 } else if (s->i < sizeof(s->version) - 1)
2539 s->version[s->i++] = c;
2540 } else if (c == '\012')
2544 ssh->agentfwd_enabled = FALSE;
2545 ssh->rdpkt2_state.incoming_sequence = 0;
2547 s->vstring[s->vslen] = 0;
2548 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
2549 logeventf(ssh, "Server version: %s", s->vstring);
2550 ssh_detect_bugs(ssh, s->vstring);
2553 * Decide which SSH protocol version to support.
2556 /* Anything strictly below "2.0" means protocol 1 is supported. */
2557 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
2558 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2559 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
2561 if (ssh->cfg.sshprot == 0 && !s->proto1) {
2562 bombout(("SSH protocol version 1 required by user but not provided by server"));
2565 if (ssh->cfg.sshprot == 3 && !s->proto2) {
2566 bombout(("SSH protocol version 2 required by user but not provided by server"));
2570 if (s->proto2 && (ssh->cfg.sshprot >= 2 || !s->proto1))
2575 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
2577 /* Send the version string, if we haven't already */
2578 if (ssh->cfg.sshprot != 3)
2579 ssh_send_verstring(ssh, s->version);
2581 if (ssh->version == 2) {
2584 * Record their version string.
2586 len = strcspn(s->vstring, "\015\012");
2587 ssh->v_s = snewn(len + 1, char);
2588 memcpy(ssh->v_s, s->vstring, len);
2592 * Initialise SSH-2 protocol.
2594 ssh->protocol = ssh2_protocol;
2595 ssh2_protocol_setup(ssh);
2596 ssh->s_rdpkt = ssh2_rdpkt;
2599 * Initialise SSH-1 protocol.
2601 ssh->protocol = ssh1_protocol;
2602 ssh1_protocol_setup(ssh);
2603 ssh->s_rdpkt = ssh1_rdpkt;
2605 if (ssh->version == 2)
2606 do_ssh2_transport(ssh, NULL, -1, NULL);
2608 update_specials_menu(ssh->frontend);
2609 ssh->state = SSH_STATE_BEFORE_SIZE;
2610 ssh->pinger = pinger_new(&ssh->cfg, &ssh_backend, ssh);
2617 static void ssh_process_incoming_data(Ssh ssh,
2618 unsigned char **data, int *datalen)
2620 struct Packet *pktin;
2622 pktin = ssh->s_rdpkt(ssh, data, datalen);
2624 ssh->protocol(ssh, NULL, 0, pktin);
2625 ssh_free_packet(pktin);
2629 static void ssh_queue_incoming_data(Ssh ssh,
2630 unsigned char **data, int *datalen)
2632 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
2637 static void ssh_process_queued_incoming_data(Ssh ssh)
2640 unsigned char *data;
2643 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
2644 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
2648 while (!ssh->frozen && len > 0)
2649 ssh_process_incoming_data(ssh, &data, &len);
2652 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
2656 static void ssh_set_frozen(Ssh ssh, int frozen)
2659 sk_set_frozen(ssh->s, frozen);
2660 ssh->frozen = frozen;
2663 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
2665 /* Log raw data, if we're in that mode. */
2667 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
2670 crBegin(ssh->ssh_gotdata_crstate);
2673 * To begin with, feed the characters one by one to the
2674 * protocol initialisation / selection function do_ssh_init().
2675 * When that returns 0, we're done with the initial greeting
2676 * exchange and can move on to packet discipline.
2679 int ret; /* need not be kept across crReturn */
2681 crReturnV; /* more data please */
2682 ret = do_ssh_init(ssh, *data);
2690 * We emerge from that loop when the initial negotiation is
2691 * over and we have selected an s_rdpkt function. Now pass
2692 * everything to s_rdpkt, and then pass the resulting packets
2693 * to the proper protocol handler.
2697 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
2699 ssh_queue_incoming_data(ssh, &data, &datalen);
2700 /* This uses up all data and cannot cause anything interesting
2701 * to happen; indeed, for anything to happen at all, we must
2702 * return, so break out. */
2704 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
2705 /* This uses up some or all data, and may freeze the
2707 ssh_process_queued_incoming_data(ssh);
2709 /* This uses up some or all data, and may freeze the
2711 ssh_process_incoming_data(ssh, &data, &datalen);
2713 /* FIXME this is probably EBW. */
2714 if (ssh->state == SSH_STATE_CLOSED)
2717 /* We're out of data. Go and get some more. */
2723 static int ssh_do_close(Ssh ssh, int notify_exit)
2726 struct ssh_channel *c;
2728 ssh->state = SSH_STATE_CLOSED;
2729 expire_timer_context(ssh);
2734 notify_remote_exit(ssh->frontend);
2739 * Now we must shut down any port- and X-forwarded channels going
2740 * through this connection.
2742 if (ssh->channels) {
2743 while (NULL != (c = index234(ssh->channels, 0))) {
2746 x11_close(c->u.x11.s);
2749 pfd_close(c->u.pfd.s);
2752 del234(ssh->channels, c); /* moving next one to index 0 */
2753 if (ssh->version == 2)
2754 bufchain_clear(&c->v.v2.outbuffer);
2759 * Go through port-forwardings, and close any associated
2760 * listening sockets.
2762 if (ssh->portfwds) {
2763 struct ssh_portfwd *pf;
2764 while (NULL != (pf = index234(ssh->portfwds, 0))) {
2765 /* Dispose of any listening socket. */
2767 pfd_terminate(pf->local);
2768 del234(ssh->portfwds, pf); /* moving next one to index 0 */
2776 static void ssh_log(Plug plug, int type, SockAddr addr, int port,
2777 const char *error_msg, int error_code)
2779 Ssh ssh = (Ssh) plug;
2780 char addrbuf[256], *msg;
2782 sk_getaddr(addr, addrbuf, lenof(addrbuf));
2785 msg = dupprintf("Connecting to %s port %d", addrbuf, port);
2787 msg = dupprintf("Failed to connect to %s: %s", addrbuf, error_msg);
2793 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
2796 Ssh ssh = (Ssh) plug;
2797 int need_notify = ssh_do_close(ssh, FALSE);
2800 if (!ssh->close_expected)
2801 error_msg = "Server unexpectedly closed network connection";
2803 error_msg = "Server closed network connection";
2806 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
2810 notify_remote_exit(ssh->frontend);
2813 logevent(error_msg);
2814 if (!ssh->close_expected || !ssh->clean_exit)
2815 connection_fatal(ssh->frontend, "%s", error_msg);
2819 static int ssh_receive(Plug plug, int urgent, char *data, int len)
2821 Ssh ssh = (Ssh) plug;
2822 ssh_gotdata(ssh, (unsigned char *)data, len);
2823 if (ssh->state == SSH_STATE_CLOSED) {
2824 ssh_do_close(ssh, TRUE);
2830 static void ssh_sent(Plug plug, int bufsize)
2832 Ssh ssh = (Ssh) plug;
2834 * If the send backlog on the SSH socket itself clears, we
2835 * should unthrottle the whole world if it was throttled.
2837 if (bufsize < SSH_MAX_BACKLOG)
2838 ssh_throttle_all(ssh, 0, bufsize);
2842 * Connect to specified host and port.
2843 * Returns an error message, or NULL on success.
2844 * Also places the canonical host name into `realhost'. It must be
2845 * freed by the caller.
2847 static const char *connect_to_host(Ssh ssh, char *host, int port,
2848 char **realhost, int nodelay, int keepalive)
2850 static const struct plug_function_table fn_table = {
2861 if (*ssh->cfg.loghost) {
2864 ssh->savedhost = dupstr(ssh->cfg.loghost);
2865 ssh->savedport = 22; /* default ssh port */
2868 * A colon suffix on savedhost also lets us affect
2871 * (FIXME: do something about IPv6 address literals here.)
2873 colon = strrchr(ssh->savedhost, ':');
2877 ssh->savedport = atoi(colon);
2880 ssh->savedhost = dupstr(host);
2882 port = 22; /* default ssh port */
2883 ssh->savedport = port;
2889 logeventf(ssh, "Looking up host \"%s\"%s", host,
2890 (ssh->cfg.addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
2891 (ssh->cfg.addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" : "")));
2892 addr = name_lookup(host, port, realhost, &ssh->cfg,
2893 ssh->cfg.addressfamily);
2894 if ((err = sk_addr_error(addr)) != NULL) {
2898 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
2903 ssh->fn = &fn_table;
2904 ssh->s = new_connection(addr, *realhost, port,
2905 0, 1, nodelay, keepalive, (Plug) ssh, &ssh->cfg);
2906 if ((err = sk_socket_error(ssh->s)) != NULL) {
2908 notify_remote_exit(ssh->frontend);
2913 * If the SSH version number's fixed, set it now, and if it's SSH-2,
2914 * send the version string too.
2916 if (ssh->cfg.sshprot == 0)
2918 if (ssh->cfg.sshprot == 3) {
2920 ssh_send_verstring(ssh, NULL);
2924 * loghost, if configured, overrides realhost.
2926 if (*ssh->cfg.loghost) {
2928 *realhost = dupstr(ssh->cfg.loghost);
2935 * Throttle or unthrottle the SSH connection.
2937 static void ssh_throttle_conn(Ssh ssh, int adjust)
2939 int old_count = ssh->conn_throttle_count;
2940 ssh->conn_throttle_count += adjust;
2941 assert(ssh->conn_throttle_count >= 0);
2942 if (ssh->conn_throttle_count && !old_count) {
2943 ssh_set_frozen(ssh, 1);
2944 } else if (!ssh->conn_throttle_count && old_count) {
2945 ssh_set_frozen(ssh, 0);
2950 * Throttle or unthrottle _all_ local data streams (for when sends
2951 * on the SSH connection itself back up).
2953 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
2956 struct ssh_channel *c;
2958 if (enable == ssh->throttled_all)
2960 ssh->throttled_all = enable;
2961 ssh->overall_bufsize = bufsize;
2964 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
2966 case CHAN_MAINSESSION:
2968 * This is treated separately, outside the switch.
2972 x11_override_throttle(c->u.x11.s, enable);
2975 /* Agent channels require no buffer management. */
2978 pfd_override_throttle(c->u.pfd.s, enable);
2984 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
2986 Ssh ssh = (Ssh) sshv;
2988 ssh->agent_response = reply;
2989 ssh->agent_response_len = replylen;
2991 if (ssh->version == 1)
2992 do_ssh1_login(ssh, NULL, -1, NULL);
2994 do_ssh2_authconn(ssh, NULL, -1, NULL);
2997 static void ssh_dialog_callback(void *sshv, int ret)
2999 Ssh ssh = (Ssh) sshv;
3001 ssh->user_response = ret;
3003 if (ssh->version == 1)
3004 do_ssh1_login(ssh, NULL, -1, NULL);
3006 do_ssh2_transport(ssh, NULL, -1, NULL);
3009 * This may have unfrozen the SSH connection, so do a
3012 ssh_process_queued_incoming_data(ssh);
3015 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3017 struct ssh_channel *c = (struct ssh_channel *)cv;
3019 void *sentreply = reply;
3022 /* Fake SSH_AGENT_FAILURE. */
3023 sentreply = "\0\0\0\1\5";
3026 if (ssh->version == 2) {
3027 ssh2_add_channel_data(c, sentreply, replylen);
3030 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3031 PKT_INT, c->remoteid,
3034 PKT_DATA, sentreply, replylen,
3043 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3044 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3045 * => log `wire_reason'.
3047 static void ssh_disconnect(Ssh ssh, char *client_reason, char *wire_reason,
3048 int code, int clean_exit)
3052 client_reason = wire_reason;
3054 error = dupprintf("Disconnected: %s", client_reason);
3056 error = dupstr("Disconnected");
3058 if (ssh->version == 1) {
3059 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3061 } else if (ssh->version == 2) {
3062 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3063 ssh2_pkt_adduint32(pktout, code);
3064 ssh2_pkt_addstring(pktout, wire_reason);
3065 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3066 ssh2_pkt_send_noqueue(ssh, pktout);
3069 ssh->close_expected = TRUE;
3070 ssh->clean_exit = clean_exit;
3071 ssh_closing((Plug)ssh, error, 0, 0);
3076 * Handle the key exchange and user authentication phases.
3078 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
3079 struct Packet *pktin)
3082 unsigned char cookie[8], *ptr;
3083 struct RSAKey servkey, hostkey;
3084 struct MD5Context md5c;
3085 struct do_ssh1_login_state {
3087 unsigned char *rsabuf, *keystr1, *keystr2;
3088 unsigned long supported_ciphers_mask, supported_auths_mask;
3089 int tried_publickey, tried_agent;
3090 int tis_auth_refused, ccard_auth_refused;
3091 unsigned char session_id[16];
3094 void *publickey_blob;
3095 int publickey_bloblen;
3096 char *publickey_comment;
3097 int publickey_encrypted;
3098 prompts_t *cur_prompt;
3101 unsigned char request[5], *response, *p;
3111 crState(do_ssh1_login_state);
3113 crBegin(ssh->do_ssh1_login_crstate);
3118 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3119 bombout(("Public key packet not received"));
3123 logevent("Received public keys");
3125 ptr = ssh_pkt_getdata(pktin, 8);
3127 bombout(("SSH-1 public key packet stopped before random cookie"));
3130 memcpy(cookie, ptr, 8);
3132 if (!ssh1_pkt_getrsakey(pktin, &servkey, &s->keystr1) ||
3133 !ssh1_pkt_getrsakey(pktin, &hostkey, &s->keystr2)) {
3134 bombout(("Failed to read SSH-1 public keys from public key packet"));
3139 * Log the host key fingerprint.
3143 logevent("Host key fingerprint is:");
3144 strcpy(logmsg, " ");
3145 hostkey.comment = NULL;
3146 rsa_fingerprint(logmsg + strlen(logmsg),
3147 sizeof(logmsg) - strlen(logmsg), &hostkey);
3151 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
3152 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
3153 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
3154 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
3155 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
3157 ssh->v1_local_protoflags =
3158 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
3159 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
3162 MD5Update(&md5c, s->keystr2, hostkey.bytes);
3163 MD5Update(&md5c, s->keystr1, servkey.bytes);
3164 MD5Update(&md5c, cookie, 8);
3165 MD5Final(s->session_id, &md5c);
3167 for (i = 0; i < 32; i++)
3168 ssh->session_key[i] = random_byte();
3171 * Verify that the `bits' and `bytes' parameters match.
3173 if (hostkey.bits > hostkey.bytes * 8 ||
3174 servkey.bits > servkey.bytes * 8) {
3175 bombout(("SSH-1 public keys were badly formatted"));
3179 s->len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
3181 s->rsabuf = snewn(s->len, unsigned char);
3184 * Verify the host key.
3188 * First format the key into a string.
3190 int len = rsastr_len(&hostkey);
3191 char fingerprint[100];
3192 char *keystr = snewn(len, char);
3193 rsastr_fmt(keystr, &hostkey);
3194 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
3196 ssh_set_frozen(ssh, 1);
3197 s->dlgret = verify_ssh_host_key(ssh->frontend,
3198 ssh->savedhost, ssh->savedport,
3199 "rsa", keystr, fingerprint,
3200 ssh_dialog_callback, ssh);
3202 if (s->dlgret < 0) {
3206 bombout(("Unexpected data from server while waiting"
3207 " for user host key response"));
3210 } while (pktin || inlen > 0);
3211 s->dlgret = ssh->user_response;
3213 ssh_set_frozen(ssh, 0);
3215 if (s->dlgret == 0) {
3216 ssh_disconnect(ssh, "User aborted at host key verification",
3222 for (i = 0; i < 32; i++) {
3223 s->rsabuf[i] = ssh->session_key[i];
3225 s->rsabuf[i] ^= s->session_id[i];
3228 if (hostkey.bytes > servkey.bytes) {
3229 ret = rsaencrypt(s->rsabuf, 32, &servkey);
3231 ret = rsaencrypt(s->rsabuf, servkey.bytes, &hostkey);
3233 ret = rsaencrypt(s->rsabuf, 32, &hostkey);
3235 ret = rsaencrypt(s->rsabuf, hostkey.bytes, &servkey);
3238 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
3242 logevent("Encrypted session key");
3245 int cipher_chosen = 0, warn = 0;
3246 char *cipher_string = NULL;
3248 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
3249 int next_cipher = ssh->cfg.ssh_cipherlist[i];
3250 if (next_cipher == CIPHER_WARN) {
3251 /* If/when we choose a cipher, warn about it */
3253 } else if (next_cipher == CIPHER_AES) {
3254 /* XXX Probably don't need to mention this. */
3255 logevent("AES not supported in SSH-1, skipping");
3257 switch (next_cipher) {
3258 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
3259 cipher_string = "3DES"; break;
3260 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
3261 cipher_string = "Blowfish"; break;
3262 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
3263 cipher_string = "single-DES"; break;
3265 if (s->supported_ciphers_mask & (1 << s->cipher_type))
3269 if (!cipher_chosen) {
3270 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
3271 bombout(("Server violates SSH-1 protocol by not "
3272 "supporting 3DES encryption"));
3274 /* shouldn't happen */
3275 bombout(("No supported ciphers found"));
3279 /* Warn about chosen cipher if necessary. */
3281 ssh_set_frozen(ssh, 1);
3282 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
3283 ssh_dialog_callback, ssh);
3284 if (s->dlgret < 0) {
3288 bombout(("Unexpected data from server while waiting"
3289 " for user response"));
3292 } while (pktin || inlen > 0);
3293 s->dlgret = ssh->user_response;
3295 ssh_set_frozen(ssh, 0);
3296 if (s->dlgret == 0) {
3297 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
3304 switch (s->cipher_type) {
3305 case SSH_CIPHER_3DES:
3306 logevent("Using 3DES encryption");
3308 case SSH_CIPHER_DES:
3309 logevent("Using single-DES encryption");
3311 case SSH_CIPHER_BLOWFISH:
3312 logevent("Using Blowfish encryption");
3316 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
3317 PKT_CHAR, s->cipher_type,
3318 PKT_DATA, cookie, 8,
3319 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
3320 PKT_DATA, s->rsabuf, s->len,
3321 PKT_INT, ssh->v1_local_protoflags, PKT_END);
3323 logevent("Trying to enable encryption...");
3327 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
3328 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
3330 ssh->v1_cipher_ctx = ssh->cipher->make_context();
3331 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
3332 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
3334 ssh->crcda_ctx = crcda_make_context();
3335 logevent("Installing CRC compensation attack detector");
3337 if (servkey.modulus) {
3338 sfree(servkey.modulus);
3339 servkey.modulus = NULL;
3341 if (servkey.exponent) {
3342 sfree(servkey.exponent);
3343 servkey.exponent = NULL;
3345 if (hostkey.modulus) {
3346 sfree(hostkey.modulus);
3347 hostkey.modulus = NULL;
3349 if (hostkey.exponent) {
3350 sfree(hostkey.exponent);
3351 hostkey.exponent = NULL;
3355 if (pktin->type != SSH1_SMSG_SUCCESS) {
3356 bombout(("Encryption not successfully enabled"));
3360 logevent("Successfully started encryption");
3362 fflush(stdout); /* FIXME eh? */
3364 if (!get_remote_username(&ssh->cfg, s->username,
3365 sizeof(s->username))) {
3366 int ret; /* need not be kept over crReturn */
3367 s->cur_prompt = new_prompts(ssh->frontend);
3368 s->cur_prompt->to_server = TRUE;
3369 s->cur_prompt->name = dupstr("SSH login name");
3370 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE,
3371 lenof(s->username));
3372 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3375 crWaitUntil(!pktin);
3376 ret = get_userpass_input(s->cur_prompt, in, inlen);
3381 * Failed to get a username. Terminate.
3383 free_prompts(s->cur_prompt);
3384 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
3387 memcpy(s->username, s->cur_prompt->prompts[0]->result,
3388 lenof(s->username));
3389 free_prompts(s->cur_prompt);
3392 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, s->username, PKT_END);
3394 char *userlog = dupprintf("Sent username \"%s\"", s->username);
3396 if (flags & FLAG_INTERACTIVE &&
3397 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
3398 c_write_str(ssh, userlog);
3399 c_write_str(ssh, "\r\n");
3407 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
3408 /* We must not attempt PK auth. Pretend we've already tried it. */
3409 s->tried_publickey = s->tried_agent = 1;
3411 s->tried_publickey = s->tried_agent = 0;
3413 s->tis_auth_refused = s->ccard_auth_refused = 0;
3415 * Load the public half of any configured keyfile for later use.
3417 if (!filename_is_null(ssh->cfg.keyfile)) {
3419 logeventf(ssh, "Reading private key file \"%.150s\"",
3420 filename_to_str(&ssh->cfg.keyfile));
3421 keytype = key_type(&ssh->cfg.keyfile);
3422 if (keytype == SSH_KEYTYPE_SSH1) {
3424 if (rsakey_pubblob(&ssh->cfg.keyfile,
3425 &s->publickey_blob, &s->publickey_bloblen,
3426 &s->publickey_comment, &error)) {
3427 s->publickey_encrypted = rsakey_encrypted(&ssh->cfg.keyfile,
3431 logeventf(ssh, "Unable to load private key (%s)", error);
3432 msgbuf = dupprintf("Unable to load private key file "
3433 "\"%.150s\" (%s)\r\n",
3434 filename_to_str(&ssh->cfg.keyfile),
3436 c_write_str(ssh, msgbuf);
3438 s->publickey_blob = NULL;
3442 logeventf(ssh, "Unable to use this key file (%s)",
3443 key_type_to_str(keytype));
3444 msgbuf = dupprintf("Unable to use key file \"%.150s\""
3446 filename_to_str(&ssh->cfg.keyfile),
3447 key_type_to_str(keytype));
3448 c_write_str(ssh, msgbuf);
3450 s->publickey_blob = NULL;
3453 s->publickey_blob = NULL;
3455 while (pktin->type == SSH1_SMSG_FAILURE) {
3456 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
3458 if (ssh->cfg.tryagent && agent_exists() && !s->tried_agent) {
3460 * Attempt RSA authentication using Pageant.
3466 logevent("Pageant is running. Requesting keys.");
3468 /* Request the keys held by the agent. */
3469 PUT_32BIT(s->request, 1);
3470 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
3471 if (!agent_query(s->request, 5, &r, &s->responselen,
3472 ssh_agent_callback, ssh)) {
3476 bombout(("Unexpected data from server while waiting"
3477 " for agent response"));
3480 } while (pktin || inlen > 0);
3481 r = ssh->agent_response;
3482 s->responselen = ssh->agent_response_len;
3484 s->response = (unsigned char *) r;
3485 if (s->response && s->responselen >= 5 &&
3486 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
3487 s->p = s->response + 5;
3488 s->nkeys = GET_32BIT(s->p);
3490 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
3491 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
3492 unsigned char *pkblob = s->p;
3496 do { /* do while (0) to make breaking easy */
3497 n = ssh1_read_bignum
3498 (s->p, s->responselen-(s->p-s->response),
3503 n = ssh1_read_bignum
3504 (s->p, s->responselen-(s->p-s->response),
3509 if (s->responselen - (s->p-s->response) < 4)
3511 s->commentlen = GET_32BIT(s->p);
3513 if (s->responselen - (s->p-s->response) <
3516 s->commentp = (char *)s->p;
3517 s->p += s->commentlen;
3521 logevent("Pageant key list packet was truncated");
3525 if (s->publickey_blob) {
3526 if (!memcmp(pkblob, s->publickey_blob,
3527 s->publickey_bloblen)) {
3528 logeventf(ssh, "Pageant key #%d matches "
3529 "configured key file", s->keyi);
3530 s->tried_publickey = 1;
3532 /* Skip non-configured key */
3535 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
3536 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3537 PKT_BIGNUM, s->key.modulus, PKT_END);
3539 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3540 logevent("Key refused");
3543 logevent("Received RSA challenge");
3544 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3545 bombout(("Server's RSA challenge was badly formatted"));
3550 char *agentreq, *q, *ret;
3553 len = 1 + 4; /* message type, bit count */
3554 len += ssh1_bignum_length(s->key.exponent);
3555 len += ssh1_bignum_length(s->key.modulus);
3556 len += ssh1_bignum_length(s->challenge);
3557 len += 16; /* session id */
3558 len += 4; /* response format */
3559 agentreq = snewn(4 + len, char);
3560 PUT_32BIT(agentreq, len);
3562 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
3563 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
3565 q += ssh1_write_bignum(q, s->key.exponent);
3566 q += ssh1_write_bignum(q, s->key.modulus);
3567 q += ssh1_write_bignum(q, s->challenge);
3568 memcpy(q, s->session_id, 16);
3570 PUT_32BIT(q, 1); /* response format */
3571 if (!agent_query(agentreq, len + 4, &vret, &retlen,
3572 ssh_agent_callback, ssh)) {
3577 bombout(("Unexpected data from server"
3578 " while waiting for agent"
3582 } while (pktin || inlen > 0);
3583 vret = ssh->agent_response;
3584 retlen = ssh->agent_response_len;
3589 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
3590 logevent("Sending Pageant's response");
3591 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3592 PKT_DATA, ret + 5, 16,
3596 if (pktin->type == SSH1_SMSG_SUCCESS) {
3598 ("Pageant's response accepted");
3599 if (flags & FLAG_VERBOSE) {
3600 c_write_str(ssh, "Authenticated using"
3602 c_write(ssh, s->commentp,
3604 c_write_str(ssh, "\" from agent\r\n");
3609 ("Pageant's response not accepted");
3612 ("Pageant failed to answer challenge");
3616 logevent("No reply received from Pageant");
3619 freebn(s->key.exponent);
3620 freebn(s->key.modulus);
3621 freebn(s->challenge);
3626 if (s->publickey_blob && !s->tried_publickey)
3627 logevent("Configured key file not in Pageant");
3632 if (s->publickey_blob && !s->tried_publickey) {
3634 * Try public key authentication with the specified
3637 int got_passphrase; /* need not be kept over crReturn */
3638 if (flags & FLAG_VERBOSE)
3639 c_write_str(ssh, "Trying public key authentication.\r\n");
3640 logeventf(ssh, "Trying public key \"%s\"",
3641 filename_to_str(&ssh->cfg.keyfile));
3642 s->tried_publickey = 1;
3643 got_passphrase = FALSE;
3644 while (!got_passphrase) {
3646 * Get a passphrase, if necessary.
3648 char *passphrase = NULL; /* only written after crReturn */
3650 if (!s->publickey_encrypted) {
3651 if (flags & FLAG_VERBOSE)
3652 c_write_str(ssh, "No passphrase required.\r\n");
3655 int ret; /* need not be kept over crReturn */
3656 s->cur_prompt = new_prompts(ssh->frontend);
3657 s->cur_prompt->to_server = FALSE;
3658 s->cur_prompt->name = dupstr("SSH key passphrase");
3659 add_prompt(s->cur_prompt,
3660 dupprintf("Passphrase for key \"%.100s\": ",
3661 s->publickey_comment),
3662 FALSE, SSH_MAX_PASSWORD_LEN);
3663 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3666 crWaitUntil(!pktin);
3667 ret = get_userpass_input(s->cur_prompt, in, inlen);
3671 /* Failed to get a passphrase. Terminate. */
3672 free_prompts(s->cur_prompt);
3673 ssh_disconnect(ssh, NULL, "Unable to authenticate",
3677 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
3678 free_prompts(s->cur_prompt);
3681 * Try decrypting key with passphrase.
3683 ret = loadrsakey(&ssh->cfg.keyfile, &s->key, passphrase,
3686 memset(passphrase, 0, strlen(passphrase));
3690 /* Correct passphrase. */
3691 got_passphrase = TRUE;
3692 } else if (ret == 0) {
3693 c_write_str(ssh, "Couldn't load private key from ");
3694 c_write_str(ssh, filename_to_str(&ssh->cfg.keyfile));
3695 c_write_str(ssh, " (");
3696 c_write_str(ssh, error);
3697 c_write_str(ssh, ").\r\n");
3698 got_passphrase = FALSE;
3699 break; /* go and try something else */
3700 } else if (ret == -1) {
3701 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
3702 got_passphrase = FALSE;
3705 assert(0 && "unexpected return from loadrsakey()");
3706 got_passphrase = FALSE; /* placate optimisers */
3710 if (got_passphrase) {
3713 * Send a public key attempt.
3715 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3716 PKT_BIGNUM, s->key.modulus, PKT_END);
3719 if (pktin->type == SSH1_SMSG_FAILURE) {
3720 c_write_str(ssh, "Server refused our public key.\r\n");
3721 continue; /* go and try something else */
3723 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3724 bombout(("Bizarre response to offer of public key"));
3730 unsigned char buffer[32];
3731 Bignum challenge, response;
3733 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3734 bombout(("Server's RSA challenge was badly formatted"));
3737 response = rsadecrypt(challenge, &s->key);
3738 freebn(s->key.private_exponent);/* burn the evidence */
3740 for (i = 0; i < 32; i++) {
3741 buffer[i] = bignum_byte(response, 31 - i);
3745 MD5Update(&md5c, buffer, 32);
3746 MD5Update(&md5c, s->session_id, 16);
3747 MD5Final(buffer, &md5c);
3749 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3750 PKT_DATA, buffer, 16, PKT_END);
3757 if (pktin->type == SSH1_SMSG_FAILURE) {
3758 if (flags & FLAG_VERBOSE)
3759 c_write_str(ssh, "Failed to authenticate with"
3760 " our public key.\r\n");
3761 continue; /* go and try something else */
3762 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
3763 bombout(("Bizarre response to RSA authentication response"));
3767 break; /* we're through! */
3773 * Otherwise, try various forms of password-like authentication.
3775 s->cur_prompt = new_prompts(ssh->frontend);
3777 if (ssh->cfg.try_tis_auth &&
3778 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
3779 !s->tis_auth_refused) {
3780 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
3781 logevent("Requested TIS authentication");
3782 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
3784 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
3785 logevent("TIS authentication declined");
3786 if (flags & FLAG_INTERACTIVE)
3787 c_write_str(ssh, "TIS authentication refused.\r\n");
3788 s->tis_auth_refused = 1;
3793 char *instr_suf, *prompt;
3795 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3797 bombout(("TIS challenge packet was badly formed"));
3800 logevent("Received TIS challenge");
3801 s->cur_prompt->to_server = TRUE;
3802 s->cur_prompt->name = dupstr("SSH TIS authentication");
3803 /* Prompt heuristic comes from OpenSSH */
3804 if (memchr(challenge, '\n', challengelen)) {
3805 instr_suf = dupstr("");
3806 prompt = dupprintf("%.*s", challengelen, challenge);
3808 instr_suf = dupprintf("%.*s", challengelen, challenge);
3809 prompt = dupstr("Response: ");
3811 s->cur_prompt->instruction =
3812 dupprintf("Using TIS authentication.%s%s",
3813 (*instr_suf) ? "\n" : "",
3815 s->cur_prompt->instr_reqd = TRUE;
3816 add_prompt(s->cur_prompt, prompt, FALSE, SSH_MAX_PASSWORD_LEN);
3820 if (ssh->cfg.try_tis_auth &&
3821 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
3822 !s->ccard_auth_refused) {
3823 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
3824 logevent("Requested CryptoCard authentication");
3825 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
3827 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
3828 logevent("CryptoCard authentication declined");
3829 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
3830 s->ccard_auth_refused = 1;
3835 char *instr_suf, *prompt;
3837 ssh_pkt_getstring(pktin, &challenge, &challengelen);
3839 bombout(("CryptoCard challenge packet was badly formed"));
3842 logevent("Received CryptoCard challenge");
3843 s->cur_prompt->to_server = TRUE;
3844 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
3845 s->cur_prompt->name_reqd = FALSE;
3846 /* Prompt heuristic comes from OpenSSH */
3847 if (memchr(challenge, '\n', challengelen)) {
3848 instr_suf = dupstr("");
3849 prompt = dupprintf("%.*s", challengelen, challenge);
3851 instr_suf = dupprintf("%.*s", challengelen, challenge);
3852 prompt = dupstr("Response: ");
3854 s->cur_prompt->instruction =
3855 dupprintf("Using CryptoCard authentication.%s%s",
3856 (*instr_suf) ? "\n" : "",
3858 s->cur_prompt->instr_reqd = TRUE;
3859 add_prompt(s->cur_prompt, prompt, FALSE, SSH_MAX_PASSWORD_LEN);
3863 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
3864 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
3865 bombout(("No supported authentication methods available"));
3868 s->cur_prompt->to_server = TRUE;
3869 s->cur_prompt->name = dupstr("SSH password");
3870 add_prompt(s->cur_prompt, dupprintf("%.90s@%.90s's password: ",
3871 s->username, ssh->savedhost),
3872 FALSE, SSH_MAX_PASSWORD_LEN);
3876 * Show password prompt, having first obtained it via a TIS
3877 * or CryptoCard exchange if we're doing TIS or CryptoCard
3881 int ret; /* need not be kept over crReturn */
3882 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3885 crWaitUntil(!pktin);
3886 ret = get_userpass_input(s->cur_prompt, in, inlen);
3891 * Failed to get a password (for example
3892 * because one was supplied on the command line
3893 * which has already failed to work). Terminate.
3895 free_prompts(s->cur_prompt);
3896 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
3901 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
3903 * Defence against traffic analysis: we send a
3904 * whole bunch of packets containing strings of
3905 * different lengths. One of these strings is the
3906 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
3907 * The others are all random data in
3908 * SSH1_MSG_IGNORE packets. This way a passive
3909 * listener can't tell which is the password, and
3910 * hence can't deduce the password length.
3912 * Anybody with a password length greater than 16
3913 * bytes is going to have enough entropy in their
3914 * password that a listener won't find it _that_
3915 * much help to know how long it is. So what we'll
3918 * - if password length < 16, we send 15 packets
3919 * containing string lengths 1 through 15
3921 * - otherwise, we let N be the nearest multiple
3922 * of 8 below the password length, and send 8
3923 * packets containing string lengths N through
3924 * N+7. This won't obscure the order of
3925 * magnitude of the password length, but it will
3926 * introduce a bit of extra uncertainty.
3928 * A few servers can't deal with SSH1_MSG_IGNORE, at
3929 * least in this context. For these servers, we need
3930 * an alternative defence. We make use of the fact
3931 * that the password is interpreted as a C string:
3932 * so we can append a NUL, then some random data.
3934 * A few servers can deal with neither SSH1_MSG_IGNORE
3935 * here _nor_ a padded password string.
3936 * For these servers we are left with no defences
3937 * against password length sniffing.
3939 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
3940 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
3942 * The server can deal with SSH1_MSG_IGNORE, so
3943 * we can use the primary defence.
3945 int bottom, top, pwlen, i;
3948 pwlen = strlen(s->cur_prompt->prompts[0]->result);
3950 bottom = 0; /* zero length passwords are OK! :-) */
3953 bottom = pwlen & ~7;
3957 assert(pwlen >= bottom && pwlen <= top);
3959 randomstr = snewn(top + 1, char);
3961 for (i = bottom; i <= top; i++) {
3963 defer_packet(ssh, s->pwpkt_type,
3964 PKTT_PASSWORD, PKT_STR,
3965 s->cur_prompt->prompts[0]->result,
3966 PKTT_OTHER, PKT_END);
3968 for (j = 0; j < i; j++) {
3970 randomstr[j] = random_byte();
3971 } while (randomstr[j] == '\0');
3973 randomstr[i] = '\0';
3974 defer_packet(ssh, SSH1_MSG_IGNORE,
3975 PKT_STR, randomstr, PKT_END);
3978 logevent("Sending password with camouflage packets");
3979 ssh_pkt_defersend(ssh);
3982 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
3984 * The server can't deal with SSH1_MSG_IGNORE
3985 * but can deal with padded passwords, so we
3986 * can use the secondary defence.
3992 len = strlen(s->cur_prompt->prompts[0]->result);
3993 if (len < sizeof(string)) {
3995 strcpy(string, s->cur_prompt->prompts[0]->result);
3996 len++; /* cover the zero byte */
3997 while (len < sizeof(string)) {
3998 string[len++] = (char) random_byte();
4001 ss = s->cur_prompt->prompts[0]->result;
4003 logevent("Sending length-padded password");
4004 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
4005 PKT_INT, len, PKT_DATA, ss, len,
4006 PKTT_OTHER, PKT_END);
4009 * The server is believed unable to cope with
4010 * any of our password camouflage methods.
4013 len = strlen(s->cur_prompt->prompts[0]->result);
4014 logevent("Sending unpadded password");
4015 send_packet(ssh, s->pwpkt_type,
4016 PKTT_PASSWORD, PKT_INT, len,
4017 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4018 PKTT_OTHER, PKT_END);
4021 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
4022 PKT_STR, s->cur_prompt->prompts[0]->result,
4023 PKTT_OTHER, PKT_END);
4025 logevent("Sent password");
4026 free_prompts(s->cur_prompt);
4028 if (pktin->type == SSH1_SMSG_FAILURE) {
4029 if (flags & FLAG_VERBOSE)
4030 c_write_str(ssh, "Access denied\r\n");
4031 logevent("Authentication refused");
4032 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4033 bombout(("Strange packet received, type %d", pktin->type));
4039 if (s->publickey_blob) {
4040 sfree(s->publickey_blob);
4041 sfree(s->publickey_comment);
4044 logevent("Authentication successful");
4049 void sshfwd_close(struct ssh_channel *c)
4053 if (ssh->state == SSH_STATE_CLOSED)
4056 if (c && !c->closes) {
4058 * If halfopen is true, we have sent
4059 * CHANNEL_OPEN for this channel, but it hasn't even been
4060 * acknowledged by the server. So we must set a close flag
4061 * on it now, and then when the server acks the channel
4062 * open, we can close it then.
4065 if (ssh->version == 1) {
4066 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4069 struct Packet *pktout;
4070 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
4071 ssh2_pkt_adduint32(pktout, c->remoteid);
4072 ssh2_pkt_send(ssh, pktout);
4075 c->closes = 1; /* sent MSG_CLOSE */
4076 if (c->type == CHAN_X11) {
4078 logevent("Forwarded X11 connection terminated");
4079 } else if (c->type == CHAN_SOCKDATA ||
4080 c->type == CHAN_SOCKDATA_DORMANT) {
4082 logevent("Forwarded port closed");
4087 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
4091 if (ssh->state == SSH_STATE_CLOSED)
4094 if (ssh->version == 1) {
4095 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
4096 PKT_INT, c->remoteid,
4097 PKT_INT, len, PKTT_DATA, PKT_DATA, buf, len,
4098 PKTT_OTHER, PKT_END);
4100 * In SSH-1 we can return 0 here - implying that forwarded
4101 * connections are never individually throttled - because
4102 * the only circumstance that can cause throttling will be
4103 * the whole SSH connection backing up, in which case
4104 * _everything_ will be throttled as a whole.
4108 ssh2_add_channel_data(c, buf, len);
4109 return ssh2_try_send(c);
4113 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
4118 if (ssh->state == SSH_STATE_CLOSED)
4121 if (ssh->version == 1) {
4122 buflimit = SSH1_BUFFER_LIMIT;
4124 buflimit = c->v.v2.locmaxwin;
4125 ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
4127 if (c->throttling_conn && bufsize <= buflimit) {
4128 c->throttling_conn = 0;
4129 ssh_throttle_conn(ssh, -1);
4133 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
4135 struct queued_handler *qh = ssh->qhead;
4139 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
4142 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
4143 ssh->packet_dispatch[qh->msg1] = NULL;
4146 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
4147 ssh->packet_dispatch[qh->msg2] = NULL;
4151 ssh->qhead = qh->next;
4153 if (ssh->qhead->msg1 > 0) {
4154 assert(ssh->packet_dispatch[ssh->qhead->msg1] == NULL);
4155 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
4157 if (ssh->qhead->msg2 > 0) {
4158 assert(ssh->packet_dispatch[ssh->qhead->msg2] == NULL);
4159 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
4162 ssh->qhead = ssh->qtail = NULL;
4163 ssh->packet_dispatch[pktin->type] = NULL;
4166 qh->handler(ssh, pktin, qh->ctx);
4171 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
4172 chandler_fn_t handler, void *ctx)
4174 struct queued_handler *qh;
4176 qh = snew(struct queued_handler);
4179 qh->handler = handler;
4183 if (ssh->qtail == NULL) {
4187 assert(ssh->packet_dispatch[qh->msg1] == NULL);
4188 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
4191 assert(ssh->packet_dispatch[qh->msg2] == NULL);
4192 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
4195 ssh->qtail->next = qh;
4200 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
4202 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
4204 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
4205 SSH2_MSG_REQUEST_SUCCESS)) {
4206 logeventf(ssh, "Remote port forwarding from %s enabled",
4209 logeventf(ssh, "Remote port forwarding from %s refused",
4212 rpf = del234(ssh->rportfwds, pf);
4218 static void ssh_setup_portfwd(Ssh ssh, const Config *cfg)
4220 const char *portfwd_strptr = cfg->portfwd;
4221 struct ssh_portfwd *epf;
4224 if (!ssh->portfwds) {
4225 ssh->portfwds = newtree234(ssh_portcmp);
4228 * Go through the existing port forwardings and tag them
4229 * with status==DESTROY. Any that we want to keep will be
4230 * re-enabled (status==KEEP) as we go through the
4231 * configuration and find out which bits are the same as
4234 struct ssh_portfwd *epf;
4236 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4237 epf->status = DESTROY;
4240 while (*portfwd_strptr) {
4241 char address_family, type;
4242 int sport,dport,sserv,dserv;
4243 char sports[256], dports[256], saddr[256], host[256];
4246 address_family = 'A';
4248 if (*portfwd_strptr == 'A' ||
4249 *portfwd_strptr == '4' ||
4250 *portfwd_strptr == '6')
4251 address_family = *portfwd_strptr++;
4252 if (*portfwd_strptr == 'L' ||
4253 *portfwd_strptr == 'R' ||
4254 *portfwd_strptr == 'D')
4255 type = *portfwd_strptr++;
4260 while (*portfwd_strptr && *portfwd_strptr != '\t') {
4261 if (*portfwd_strptr == ':') {
4263 * We've seen a colon in the middle of the
4264 * source port number. This means that
4265 * everything we've seen until now is the
4266 * source _address_, so we'll move it into
4267 * saddr and start sports from the beginning
4272 if (ssh->version == 1 && type == 'R') {
4273 logeventf(ssh, "SSH-1 cannot handle remote source address "
4274 "spec \"%s\"; ignoring", sports);
4276 strcpy(saddr, sports);
4279 if (n < lenof(sports)-1) sports[n++] = *portfwd_strptr++;
4283 if (*portfwd_strptr == '\t')
4286 while (*portfwd_strptr && *portfwd_strptr != ':') {
4287 if (n < lenof(host)-1) host[n++] = *portfwd_strptr++;
4290 if (*portfwd_strptr == ':')
4293 while (*portfwd_strptr) {
4294 if (n < lenof(dports)-1) dports[n++] = *portfwd_strptr++;
4298 dport = atoi(dports);
4302 dport = net_service_lookup(dports);
4304 logeventf(ssh, "Service lookup failed for destination"
4305 " port \"%s\"", dports);
4309 while (*portfwd_strptr) portfwd_strptr++;
4313 portfwd_strptr++; /* eat the NUL and move to next one */
4315 sport = atoi(sports);
4319 sport = net_service_lookup(sports);
4321 logeventf(ssh, "Service lookup failed for source"
4322 " port \"%s\"", sports);
4325 if (sport && dport) {
4326 /* Set up a description of the source port. */
4327 struct ssh_portfwd *pfrec, *epfrec;
4329 pfrec = snew(struct ssh_portfwd);
4331 pfrec->saddr = *saddr ? dupstr(saddr) : NULL;
4332 pfrec->sserv = sserv ? dupstr(sports) : NULL;
4333 pfrec->sport = sport;
4334 pfrec->daddr = *host ? dupstr(host) : NULL;
4335 pfrec->dserv = dserv ? dupstr(dports) : NULL;
4336 pfrec->dport = dport;
4337 pfrec->local = NULL;
4338 pfrec->remote = NULL;
4339 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
4340 address_family == '6' ? ADDRTYPE_IPV6 :
4343 epfrec = add234(ssh->portfwds, pfrec);
4344 if (epfrec != pfrec) {
4346 * We already have a port forwarding with precisely
4347 * these parameters. Hence, no need to do anything;
4348 * simply tag the existing one as KEEP.
4350 epfrec->status = KEEP;
4351 free_portfwd(pfrec);
4353 pfrec->status = CREATE;
4359 * Now go through and destroy any port forwardings which were
4362 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4363 if (epf->status == DESTROY) {
4366 message = dupprintf("%s port forwarding from %s%s%d",
4367 epf->type == 'L' ? "local" :
4368 epf->type == 'R' ? "remote" : "dynamic",
4369 epf->saddr ? epf->saddr : "",
4370 epf->saddr ? ":" : "",
4373 if (epf->type != 'D') {
4374 char *msg2 = dupprintf("%s to %s:%d", message,
4375 epf->daddr, epf->dport);
4380 logeventf(ssh, "Cancelling %s", message);
4384 struct ssh_rportfwd *rpf = epf->remote;
4385 struct Packet *pktout;
4388 * Cancel the port forwarding at the server
4391 if (ssh->version == 1) {
4393 * We cannot cancel listening ports on the
4394 * server side in SSH-1! There's no message
4395 * to support it. Instead, we simply remove
4396 * the rportfwd record from the local end
4397 * so that any connections the server tries
4398 * to make on it are rejected.
4401 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4402 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
4403 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
4405 ssh2_pkt_addstring(pktout, epf->saddr);
4406 } else if (ssh->cfg.rport_acceptall) {
4407 /* XXX: ssh->cfg.rport_acceptall may not represent
4408 * what was used to open the original connection,
4409 * since it's reconfigurable. */
4410 ssh2_pkt_addstring(pktout, "0.0.0.0");
4412 ssh2_pkt_addstring(pktout, "127.0.0.1");
4414 ssh2_pkt_adduint32(pktout, epf->sport);
4415 ssh2_pkt_send(ssh, pktout);
4418 del234(ssh->rportfwds, rpf);
4420 } else if (epf->local) {
4421 pfd_terminate(epf->local);
4424 delpos234(ssh->portfwds, i);
4426 i--; /* so we don't skip one in the list */
4430 * And finally, set up any new port forwardings (status==CREATE).
4432 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4433 if (epf->status == CREATE) {
4434 char *sportdesc, *dportdesc;
4435 sportdesc = dupprintf("%s%s%s%s%d%s",
4436 epf->saddr ? epf->saddr : "",
4437 epf->saddr ? ":" : "",
4438 epf->sserv ? epf->sserv : "",
4439 epf->sserv ? "(" : "",
4441 epf->sserv ? ")" : "");
4442 if (epf->type == 'D') {
4445 dportdesc = dupprintf("%s:%s%s%d%s",
4447 epf->dserv ? epf->dserv : "",
4448 epf->dserv ? "(" : "",
4450 epf->dserv ? ")" : "");
4453 if (epf->type == 'L') {
4454 const char *err = pfd_addforward(epf->daddr, epf->dport,
4455 epf->saddr, epf->sport,
4458 epf->addressfamily);
4460 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
4461 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4462 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4463 sportdesc, dportdesc,
4464 err ? " failed: " : "", err ? err : "");
4465 } else if (epf->type == 'D') {
4466 const char *err = pfd_addforward(NULL, -1,
4467 epf->saddr, epf->sport,
4470 epf->addressfamily);
4472 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
4473 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4474 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4476 err ? " failed: " : "", err ? err : "");
4478 struct ssh_rportfwd *pf;
4481 * Ensure the remote port forwardings tree exists.
4483 if (!ssh->rportfwds) {
4484 if (ssh->version == 1)
4485 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
4487 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
4490 pf = snew(struct ssh_rportfwd);
4491 strncpy(pf->dhost, epf->daddr, lenof(pf->dhost)-1);
4492 pf->dhost[lenof(pf->dhost)-1] = '\0';
4493 pf->dport = epf->dport;
4494 pf->sport = epf->sport;
4495 if (add234(ssh->rportfwds, pf) != pf) {
4496 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
4497 epf->daddr, epf->dport);
4500 logeventf(ssh, "Requesting remote port %s"
4501 " forward to %s", sportdesc, dportdesc);
4503 pf->sportdesc = sportdesc;
4508 if (ssh->version == 1) {
4509 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
4510 PKT_INT, epf->sport,
4511 PKT_STR, epf->daddr,
4512 PKT_INT, epf->dport,
4514 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
4516 ssh_rportfwd_succfail, pf);
4518 struct Packet *pktout;
4519 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4520 ssh2_pkt_addstring(pktout, "tcpip-forward");
4521 ssh2_pkt_addbool(pktout, 1);/* want reply */
4523 ssh2_pkt_addstring(pktout, epf->saddr);
4524 } else if (cfg->rport_acceptall) {
4525 ssh2_pkt_addstring(pktout, "0.0.0.0");
4527 ssh2_pkt_addstring(pktout, "127.0.0.1");
4529 ssh2_pkt_adduint32(pktout, epf->sport);
4530 ssh2_pkt_send(ssh, pktout);
4532 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
4533 SSH2_MSG_REQUEST_FAILURE,
4534 ssh_rportfwd_succfail, pf);
4543 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
4546 int stringlen, bufsize;
4548 ssh_pkt_getstring(pktin, &string, &stringlen);
4549 if (string == NULL) {
4550 bombout(("Incoming terminal data packet was badly formed"));
4554 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
4556 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
4557 ssh->v1_stdout_throttling = 1;
4558 ssh_throttle_conn(ssh, +1);
4562 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
4564 /* Remote side is trying to open a channel to talk to our
4565 * X-Server. Give them back a local channel number. */
4566 struct ssh_channel *c;
4567 int remoteid = ssh_pkt_getuint32(pktin);
4569 logevent("Received X11 connect request");
4570 /* Refuse if X11 forwarding is disabled. */
4571 if (!ssh->X11_fwd_enabled) {
4572 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4573 PKT_INT, remoteid, PKT_END);
4574 logevent("Rejected X11 connect request");
4576 c = snew(struct ssh_channel);
4579 if (x11_init(&c->u.x11.s, ssh->x11disp, c,
4580 NULL, -1, &ssh->cfg) != NULL) {
4581 logevent("Opening X11 forward connection failed");
4583 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4584 PKT_INT, remoteid, PKT_END);
4587 ("Opening X11 forward connection succeeded");
4588 c->remoteid = remoteid;
4589 c->halfopen = FALSE;
4590 c->localid = alloc_channel_id(ssh);
4592 c->throttling_conn = 0;
4593 c->type = CHAN_X11; /* identify channel type */
4594 add234(ssh->channels, c);
4595 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4596 PKT_INT, c->remoteid, PKT_INT,
4597 c->localid, PKT_END);
4598 logevent("Opened X11 forward channel");
4603 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
4605 /* Remote side is trying to open a channel to talk to our
4606 * agent. Give them back a local channel number. */
4607 struct ssh_channel *c;
4608 int remoteid = ssh_pkt_getuint32(pktin);
4610 /* Refuse if agent forwarding is disabled. */
4611 if (!ssh->agentfwd_enabled) {
4612 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4613 PKT_INT, remoteid, PKT_END);
4615 c = snew(struct ssh_channel);
4617 c->remoteid = remoteid;
4618 c->halfopen = FALSE;
4619 c->localid = alloc_channel_id(ssh);
4621 c->throttling_conn = 0;
4622 c->type = CHAN_AGENT; /* identify channel type */
4623 c->u.a.lensofar = 0;
4624 add234(ssh->channels, c);
4625 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4626 PKT_INT, c->remoteid, PKT_INT, c->localid,
4631 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
4633 /* Remote side is trying to open a channel to talk to a
4634 * forwarded port. Give them back a local channel number. */
4635 struct ssh_channel *c;
4636 struct ssh_rportfwd pf, *pfp;
4641 c = snew(struct ssh_channel);
4644 remoteid = ssh_pkt_getuint32(pktin);
4645 ssh_pkt_getstring(pktin, &host, &hostsize);
4646 port = ssh_pkt_getuint32(pktin);
4648 if (hostsize >= lenof(pf.dhost))
4649 hostsize = lenof(pf.dhost)-1;
4650 memcpy(pf.dhost, host, hostsize);
4651 pf.dhost[hostsize] = '\0';
4653 pfp = find234(ssh->rportfwds, &pf, NULL);
4656 logeventf(ssh, "Rejected remote port open request for %s:%d",
4658 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4659 PKT_INT, remoteid, PKT_END);
4661 logeventf(ssh, "Received remote port open request for %s:%d",
4663 e = pfd_newconnect(&c->u.pfd.s, pf.dhost, port,
4664 c, &ssh->cfg, pfp->pfrec->addressfamily);
4666 logeventf(ssh, "Port open failed: %s", e);
4668 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4669 PKT_INT, remoteid, PKT_END);
4671 c->remoteid = remoteid;
4672 c->halfopen = FALSE;
4673 c->localid = alloc_channel_id(ssh);
4675 c->throttling_conn = 0;
4676 c->type = CHAN_SOCKDATA; /* identify channel type */
4677 add234(ssh->channels, c);
4678 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4679 PKT_INT, c->remoteid, PKT_INT,
4680 c->localid, PKT_END);
4681 logevent("Forwarded port opened successfully");
4686 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
4688 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4689 unsigned int localid = ssh_pkt_getuint32(pktin);
4690 struct ssh_channel *c;
4692 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4693 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4694 c->remoteid = localid;
4695 c->halfopen = FALSE;
4696 c->type = CHAN_SOCKDATA;
4697 c->throttling_conn = 0;
4698 pfd_confirm(c->u.pfd.s);
4701 if (c && c->closes) {
4703 * We have a pending close on this channel,
4704 * which we decided on before the server acked
4705 * the channel open. So now we know the
4706 * remoteid, we can close it again.
4708 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE,
4709 PKT_INT, c->remoteid, PKT_END);
4713 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
4715 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4716 struct ssh_channel *c;
4718 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4719 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4720 logevent("Forwarded connection refused by server");
4721 pfd_close(c->u.pfd.s);
4722 del234(ssh->channels, c);
4727 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
4729 /* Remote side closes a channel. */
4730 unsigned i = ssh_pkt_getuint32(pktin);
4731 struct ssh_channel *c;
4732 c = find234(ssh->channels, &i, ssh_channelfind);
4733 if (c && !c->halfopen) {
4736 (pktin->type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
4738 if ((c->closes == 0) && (c->type == CHAN_X11)) {
4739 logevent("Forwarded X11 connection terminated");
4740 assert(c->u.x11.s != NULL);
4741 x11_close(c->u.x11.s);
4744 if ((c->closes == 0) && (c->type == CHAN_SOCKDATA)) {
4745 logevent("Forwarded port closed");
4746 assert(c->u.pfd.s != NULL);
4747 pfd_close(c->u.pfd.s);
4751 c->closes |= (closetype << 2); /* seen this message */
4752 if (!(c->closes & closetype)) {
4753 send_packet(ssh, pktin->type, PKT_INT, c->remoteid,
4755 c->closes |= closetype; /* sent it too */
4758 if (c->closes == 15) {
4759 del234(ssh->channels, c);
4763 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
4764 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
4765 "_CONFIRMATION", c ? "half-open" : "nonexistent",
4770 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
4772 /* Data sent down one of our channels. */
4773 int i = ssh_pkt_getuint32(pktin);
4776 struct ssh_channel *c;
4778 ssh_pkt_getstring(pktin, &p, &len);
4780 c = find234(ssh->channels, &i, ssh_channelfind);
4785 bufsize = x11_send(c->u.x11.s, p, len);
4788 bufsize = pfd_send(c->u.pfd.s, p, len);
4791 /* Data for an agent message. Buffer it. */
4793 if (c->u.a.lensofar < 4) {
4794 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)len);
4795 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
4799 c->u.a.lensofar += l;
4801 if (c->u.a.lensofar == 4) {
4803 4 + GET_32BIT(c->u.a.msglen);
4804 c->u.a.message = snewn(c->u.a.totallen,
4806 memcpy(c->u.a.message, c->u.a.msglen, 4);
4808 if (c->u.a.lensofar >= 4 && len > 0) {
4810 min(c->u.a.totallen - c->u.a.lensofar,
4812 memcpy(c->u.a.message + c->u.a.lensofar, p,
4816 c->u.a.lensofar += l;
4818 if (c->u.a.lensofar == c->u.a.totallen) {
4821 if (agent_query(c->u.a.message,
4824 ssh_agentf_callback, c))
4825 ssh_agentf_callback(c, reply, replylen);
4826 sfree(c->u.a.message);
4827 c->u.a.lensofar = 0;
4830 bufsize = 0; /* agent channels never back up */
4833 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
4834 c->throttling_conn = 1;
4835 ssh_throttle_conn(ssh, +1);
4840 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
4842 ssh->exitcode = ssh_pkt_getuint32(pktin);
4843 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
4844 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
4846 * In case `helpful' firewalls or proxies tack
4847 * extra human-readable text on the end of the
4848 * session which we might mistake for another
4849 * encrypted packet, we close the session once
4850 * we've sent EXIT_CONFIRMATION.
4852 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
4855 /* Helper function to deal with sending tty modes for REQUEST_PTY */
4856 static void ssh1_send_ttymode(void *data, char *mode, char *val)
4858 struct Packet *pktout = (struct Packet *)data;
4860 unsigned int arg = 0;
4861 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
4862 if (i == lenof(ssh_ttymodes)) return;
4863 switch (ssh_ttymodes[i].type) {
4865 arg = ssh_tty_parse_specchar(val);
4868 arg = ssh_tty_parse_boolean(val);
4871 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
4872 ssh2_pkt_addbyte(pktout, arg);
4876 static void do_ssh1_connection(Ssh ssh, unsigned char *in, int inlen,
4877 struct Packet *pktin)
4879 crBegin(ssh->do_ssh1_connection_crstate);
4881 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
4882 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
4883 ssh1_smsg_stdout_stderr_data;
4885 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
4886 ssh1_msg_channel_open_confirmation;
4887 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
4888 ssh1_msg_channel_open_failure;
4889 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
4890 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
4891 ssh1_msg_channel_close;
4892 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
4893 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
4895 if (ssh->cfg.agentfwd && agent_exists()) {
4896 logevent("Requesting agent forwarding");
4897 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
4901 if (pktin->type != SSH1_SMSG_SUCCESS
4902 && pktin->type != SSH1_SMSG_FAILURE) {
4903 bombout(("Protocol confusion"));
4905 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4906 logevent("Agent forwarding refused");
4908 logevent("Agent forwarding enabled");
4909 ssh->agentfwd_enabled = TRUE;
4910 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
4914 if (ssh->cfg.x11_forward) {
4915 logevent("Requesting X11 forwarding");
4916 ssh->x11disp = x11_setup_display(ssh->cfg.x11_display,
4917 ssh->cfg.x11_auth, &ssh->cfg);
4919 * Note that while we blank the X authentication data here, we don't
4920 * take any special action to blank the start of an X11 channel,
4921 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
4922 * without having session blanking enabled is likely to leak your
4923 * cookie into the log.
4925 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
4926 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
4927 PKT_STR, ssh->x11disp->remoteauthprotoname,
4929 PKT_STR, ssh->x11disp->remoteauthdatastring,
4931 PKT_INT, ssh->x11disp->screennum,
4934 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
4935 PKT_STR, ssh->x11disp->remoteauthprotoname,
4937 PKT_STR, ssh->x11disp->remoteauthdatastring,
4944 if (pktin->type != SSH1_SMSG_SUCCESS
4945 && pktin->type != SSH1_SMSG_FAILURE) {
4946 bombout(("Protocol confusion"));
4948 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4949 logevent("X11 forwarding refused");
4951 logevent("X11 forwarding enabled");
4952 ssh->X11_fwd_enabled = TRUE;
4953 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
4957 ssh_setup_portfwd(ssh, &ssh->cfg);
4958 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
4960 if (!ssh->cfg.nopty) {
4962 /* Unpick the terminal-speed string. */
4963 /* XXX perhaps we should allow no speeds to be sent. */
4964 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
4965 sscanf(ssh->cfg.termspeed, "%d,%d", &ssh->ospeed, &ssh->ispeed);
4966 /* Send the pty request. */
4967 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
4968 ssh_pkt_addstring(pkt, ssh->cfg.termtype);
4969 ssh_pkt_adduint32(pkt, ssh->term_height);
4970 ssh_pkt_adduint32(pkt, ssh->term_width);
4971 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
4972 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
4973 parse_ttymodes(ssh, ssh->cfg.ttymodes,
4974 ssh1_send_ttymode, (void *)pkt);
4975 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
4976 ssh_pkt_adduint32(pkt, ssh->ispeed);
4977 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
4978 ssh_pkt_adduint32(pkt, ssh->ospeed);
4979 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
4981 ssh->state = SSH_STATE_INTERMED;
4985 if (pktin->type != SSH1_SMSG_SUCCESS
4986 && pktin->type != SSH1_SMSG_FAILURE) {
4987 bombout(("Protocol confusion"));
4989 } else if (pktin->type == SSH1_SMSG_FAILURE) {
4990 c_write_str(ssh, "Server refused to allocate pty\r\n");
4991 ssh->editing = ssh->echoing = 1;
4993 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
4994 ssh->ospeed, ssh->ispeed);
4996 ssh->editing = ssh->echoing = 1;
4999 if (ssh->cfg.compression) {
5000 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5004 if (pktin->type != SSH1_SMSG_SUCCESS
5005 && pktin->type != SSH1_SMSG_FAILURE) {
5006 bombout(("Protocol confusion"));
5008 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5009 c_write_str(ssh, "Server refused to compress\r\n");
5011 logevent("Started compression");
5012 ssh->v1_compressing = TRUE;
5013 ssh->cs_comp_ctx = zlib_compress_init();
5014 logevent("Initialised zlib (RFC1950) compression");
5015 ssh->sc_comp_ctx = zlib_decompress_init();
5016 logevent("Initialised zlib (RFC1950) decompression");
5020 * Start the shell or command.
5022 * Special case: if the first-choice command is an SSH-2
5023 * subsystem (hence not usable here) and the second choice
5024 * exists, we fall straight back to that.
5027 char *cmd = ssh->cfg.remote_cmd_ptr;
5029 if (!cmd) cmd = ssh->cfg.remote_cmd;
5031 if (ssh->cfg.ssh_subsys && ssh->cfg.remote_cmd_ptr2) {
5032 cmd = ssh->cfg.remote_cmd_ptr2;
5033 ssh->fallback_cmd = TRUE;
5036 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
5038 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
5039 logevent("Started session");
5042 ssh->state = SSH_STATE_SESSION;
5043 if (ssh->size_needed)
5044 ssh_size(ssh, ssh->term_width, ssh->term_height);
5045 if (ssh->eof_needed)
5046 ssh_special(ssh, TS_EOF);
5049 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
5051 ssh->channels = newtree234(ssh_channelcmp);
5055 * By this point, most incoming packets are already being
5056 * handled by the dispatch table, and we need only pay
5057 * attention to the unusual ones.
5062 if (pktin->type == SSH1_SMSG_SUCCESS) {
5063 /* may be from EXEC_SHELL on some servers */
5064 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5065 /* may be from EXEC_SHELL on some servers
5066 * if no pty is available or in other odd cases. Ignore */
5068 bombout(("Strange packet received: type %d", pktin->type));
5073 int len = min(inlen, 512);
5074 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
5075 PKT_INT, len, PKTT_DATA, PKT_DATA, in, len,
5076 PKTT_OTHER, PKT_END);
5087 * Handle the top-level SSH-2 protocol.
5089 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
5094 ssh_pkt_getstring(pktin, &msg, &msglen);
5095 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
5098 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
5100 /* log reason code in disconnect message */
5104 ssh_pkt_getstring(pktin, &msg, &msglen);
5105 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
5108 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
5110 /* Do nothing, because we're ignoring it! Duhh. */
5113 static void ssh1_protocol_setup(Ssh ssh)
5118 * Most messages are handled by the coroutines.
5120 for (i = 0; i < 256; i++)
5121 ssh->packet_dispatch[i] = NULL;
5124 * These special message types we install handlers for.
5126 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
5127 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
5128 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
5131 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
5132 struct Packet *pktin)
5134 unsigned char *in=(unsigned char*)vin;
5135 if (ssh->state == SSH_STATE_CLOSED)
5138 if (pktin && ssh->packet_dispatch[pktin->type]) {
5139 ssh->packet_dispatch[pktin->type](ssh, pktin);
5143 if (!ssh->protocol_initial_phase_done) {
5144 if (do_ssh1_login(ssh, in, inlen, pktin))
5145 ssh->protocol_initial_phase_done = TRUE;
5150 do_ssh1_connection(ssh, in, inlen, pktin);
5154 * Utility routine for decoding comma-separated strings in KEXINIT.
5156 static int in_commasep_string(char *needle, char *haystack, int haylen)
5159 if (!needle || !haystack) /* protect against null pointers */
5161 needlen = strlen(needle);
5164 * Is it at the start of the string?
5166 if (haylen >= needlen && /* haystack is long enough */
5167 !memcmp(needle, haystack, needlen) && /* initial match */
5168 (haylen == needlen || haystack[needlen] == ',')
5169 /* either , or EOS follows */
5173 * If not, search for the next comma and resume after that.
5174 * If no comma found, terminate.
5176 while (haylen > 0 && *haystack != ',')
5177 haylen--, haystack++;
5180 haylen--, haystack++; /* skip over comma itself */
5185 * Similar routine for checking whether we have the first string in a list.
5187 static int first_in_commasep_string(char *needle, char *haystack, int haylen)
5190 if (!needle || !haystack) /* protect against null pointers */
5192 needlen = strlen(needle);
5194 * Is it at the start of the string?
5196 if (haylen >= needlen && /* haystack is long enough */
5197 !memcmp(needle, haystack, needlen) && /* initial match */
5198 (haylen == needlen || haystack[needlen] == ',')
5199 /* either , or EOS follows */
5207 * SSH-2 key creation method.
5208 * (Currently assumes 2 lots of any hash are sufficient to generate
5209 * keys/IVs for any cipher/MAC. SSH2_MKKEY_ITERS documents this assumption.)
5211 #define SSH2_MKKEY_ITERS (2)
5212 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H, char chr,
5213 unsigned char *keyspace)
5215 const struct ssh_hash *h = ssh->kex->hash;
5217 /* First hlen bytes. */
5219 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5220 hash_mpint(h, s, K);
5221 h->bytes(s, H, h->hlen);
5222 h->bytes(s, &chr, 1);
5223 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
5224 h->final(s, keyspace);
5225 /* Next hlen bytes. */
5227 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5228 hash_mpint(h, s, K);
5229 h->bytes(s, H, h->hlen);
5230 h->bytes(s, keyspace, h->hlen);
5231 h->final(s, keyspace + h->hlen);
5235 * Handle the SSH-2 transport layer.
5237 static int do_ssh2_transport(Ssh ssh, void *vin, int inlen,
5238 struct Packet *pktin)
5240 unsigned char *in = (unsigned char *)vin;
5241 struct do_ssh2_transport_state {
5242 int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
5243 Bignum p, g, e, f, K;
5246 int kex_init_value, kex_reply_value;
5247 const struct ssh_mac **maclist;
5249 const struct ssh2_cipher *cscipher_tobe;
5250 const struct ssh2_cipher *sccipher_tobe;
5251 const struct ssh_mac *csmac_tobe;
5252 const struct ssh_mac *scmac_tobe;
5253 const struct ssh_compress *cscomp_tobe;
5254 const struct ssh_compress *sccomp_tobe;
5255 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
5256 int hostkeylen, siglen, rsakeylen;
5257 void *hkey; /* actual host key */
5258 void *rsakey; /* for RSA kex */
5259 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
5260 int n_preferred_kex;
5261 const struct ssh_kexes *preferred_kex[KEX_MAX];
5262 int n_preferred_ciphers;
5263 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
5264 const struct ssh_compress *preferred_comp;
5265 int got_session_id, activated_authconn;
5266 struct Packet *pktout;
5271 crState(do_ssh2_transport_state);
5273 crBegin(ssh->do_ssh2_transport_crstate);
5275 s->cscipher_tobe = s->sccipher_tobe = NULL;
5276 s->csmac_tobe = s->scmac_tobe = NULL;
5277 s->cscomp_tobe = s->sccomp_tobe = NULL;
5279 s->got_session_id = s->activated_authconn = FALSE;
5282 * Be prepared to work around the buggy MAC problem.
5284 if (ssh->remote_bugs & BUG_SSH2_HMAC)
5285 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
5287 s->maclist = macs, s->nmacs = lenof(macs);
5290 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
5292 int i, j, commalist_started;
5295 * Set up the preferred key exchange. (NULL => warn below here)
5297 s->n_preferred_kex = 0;
5298 for (i = 0; i < KEX_MAX; i++) {
5299 switch (ssh->cfg.ssh_kexlist[i]) {
5301 s->preferred_kex[s->n_preferred_kex++] =
5302 &ssh_diffiehellman_gex;
5305 s->preferred_kex[s->n_preferred_kex++] =
5306 &ssh_diffiehellman_group14;
5309 s->preferred_kex[s->n_preferred_kex++] =
5310 &ssh_diffiehellman_group1;
5313 s->preferred_kex[s->n_preferred_kex++] =
5317 /* Flag for later. Don't bother if it's the last in
5319 if (i < KEX_MAX - 1) {
5320 s->preferred_kex[s->n_preferred_kex++] = NULL;
5327 * Set up the preferred ciphers. (NULL => warn below here)
5329 s->n_preferred_ciphers = 0;
5330 for (i = 0; i < CIPHER_MAX; i++) {
5331 switch (ssh->cfg.ssh_cipherlist[i]) {
5332 case CIPHER_BLOWFISH:
5333 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
5336 if (ssh->cfg.ssh2_des_cbc) {
5337 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
5341 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
5344 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
5346 case CIPHER_ARCFOUR:
5347 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
5350 /* Flag for later. Don't bother if it's the last in
5352 if (i < CIPHER_MAX - 1) {
5353 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
5360 * Set up preferred compression.
5362 if (ssh->cfg.compression)
5363 s->preferred_comp = &ssh_zlib;
5365 s->preferred_comp = &ssh_comp_none;
5368 * Enable queueing of outgoing auth- or connection-layer
5369 * packets while we are in the middle of a key exchange.
5371 ssh->queueing = TRUE;
5374 * Flag that KEX is in progress.
5376 ssh->kex_in_progress = TRUE;
5379 * Construct and send our key exchange packet.
5381 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
5382 for (i = 0; i < 16; i++)
5383 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
5384 /* List key exchange algorithms. */
5385 ssh2_pkt_addstring_start(s->pktout);
5386 commalist_started = 0;
5387 for (i = 0; i < s->n_preferred_kex; i++) {
5388 const struct ssh_kexes *k = s->preferred_kex[i];
5389 if (!k) continue; /* warning flag */
5390 for (j = 0; j < k->nkexes; j++) {
5391 if (commalist_started)
5392 ssh2_pkt_addstring_str(s->pktout, ",");
5393 ssh2_pkt_addstring_str(s->pktout, k->list[j]->name);
5394 commalist_started = 1;
5397 /* List server host key algorithms. */
5398 ssh2_pkt_addstring_start(s->pktout);
5399 for (i = 0; i < lenof(hostkey_algs); i++) {
5400 ssh2_pkt_addstring_str(s->pktout, hostkey_algs[i]->name);
5401 if (i < lenof(hostkey_algs) - 1)
5402 ssh2_pkt_addstring_str(s->pktout, ",");
5404 /* List client->server encryption algorithms. */
5405 ssh2_pkt_addstring_start(s->pktout);
5406 commalist_started = 0;
5407 for (i = 0; i < s->n_preferred_ciphers; i++) {
5408 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5409 if (!c) continue; /* warning flag */
5410 for (j = 0; j < c->nciphers; j++) {
5411 if (commalist_started)
5412 ssh2_pkt_addstring_str(s->pktout, ",");
5413 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
5414 commalist_started = 1;
5417 /* List server->client encryption algorithms. */
5418 ssh2_pkt_addstring_start(s->pktout);
5419 commalist_started = 0;
5420 for (i = 0; i < s->n_preferred_ciphers; i++) {
5421 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5422 if (!c) continue; /* warning flag */
5423 for (j = 0; j < c->nciphers; j++) {
5424 if (commalist_started)
5425 ssh2_pkt_addstring_str(s->pktout, ",");
5426 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
5427 commalist_started = 1;
5430 /* List client->server MAC algorithms. */
5431 ssh2_pkt_addstring_start(s->pktout);
5432 for (i = 0; i < s->nmacs; i++) {
5433 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5434 if (i < s->nmacs - 1)
5435 ssh2_pkt_addstring_str(s->pktout, ",");
5437 /* List server->client MAC algorithms. */
5438 ssh2_pkt_addstring_start(s->pktout);
5439 for (i = 0; i < s->nmacs; i++) {
5440 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5441 if (i < s->nmacs - 1)
5442 ssh2_pkt_addstring_str(s->pktout, ",");
5444 /* List client->server compression algorithms. */
5445 ssh2_pkt_addstring_start(s->pktout);
5446 assert(lenof(compressions) > 1);
5447 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
5448 for (i = 0; i < lenof(compressions); i++) {
5449 const struct ssh_compress *c = compressions[i];
5450 if (c != s->preferred_comp) {
5451 ssh2_pkt_addstring_str(s->pktout, ",");
5452 ssh2_pkt_addstring_str(s->pktout, c->name);
5455 /* List server->client compression algorithms. */
5456 ssh2_pkt_addstring_start(s->pktout);
5457 assert(lenof(compressions) > 1);
5458 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
5459 for (i = 0; i < lenof(compressions); i++) {
5460 const struct ssh_compress *c = compressions[i];
5461 if (c != s->preferred_comp) {
5462 ssh2_pkt_addstring_str(s->pktout, ",");
5463 ssh2_pkt_addstring_str(s->pktout, c->name);
5466 /* List client->server languages. Empty list. */
5467 ssh2_pkt_addstring_start(s->pktout);
5468 /* List server->client languages. Empty list. */
5469 ssh2_pkt_addstring_start(s->pktout);
5470 /* First KEX packet does _not_ follow, because we're not that brave. */
5471 ssh2_pkt_addbool(s->pktout, FALSE);
5473 ssh2_pkt_adduint32(s->pktout, 0);
5476 s->our_kexinitlen = s->pktout->length - 5;
5477 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
5478 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
5480 ssh2_pkt_send_noqueue(ssh, s->pktout);
5486 * Now examine the other side's KEXINIT to see what we're up
5490 char *str, *preferred;
5493 if (pktin->type != SSH2_MSG_KEXINIT) {
5494 bombout(("expected key exchange packet from server"));
5498 ssh->hostkey = NULL;
5499 s->cscipher_tobe = NULL;
5500 s->sccipher_tobe = NULL;
5501 s->csmac_tobe = NULL;
5502 s->scmac_tobe = NULL;
5503 s->cscomp_tobe = NULL;
5504 s->sccomp_tobe = NULL;
5505 s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
5507 pktin->savedpos += 16; /* skip garbage cookie */
5508 ssh_pkt_getstring(pktin, &str, &len); /* key exchange algorithms */
5511 for (i = 0; i < s->n_preferred_kex; i++) {
5512 const struct ssh_kexes *k = s->preferred_kex[i];
5516 for (j = 0; j < k->nkexes; j++) {
5517 if (!preferred) preferred = k->list[j]->name;
5518 if (in_commasep_string(k->list[j]->name, str, len)) {
5519 ssh->kex = k->list[j];
5528 bombout(("Couldn't agree a key exchange algorithm (available: %s)",
5529 str ? str : "(null)"));
5533 * Note that the server's guess is considered wrong if it doesn't match
5534 * the first algorithm in our list, even if it's still the algorithm
5537 s->guessok = first_in_commasep_string(preferred, str, len);
5538 ssh_pkt_getstring(pktin, &str, &len); /* host key algorithms */
5539 for (i = 0; i < lenof(hostkey_algs); i++) {
5540 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
5541 ssh->hostkey = hostkey_algs[i];
5545 s->guessok = s->guessok &&
5546 first_in_commasep_string(hostkey_algs[0]->name, str, len);
5547 ssh_pkt_getstring(pktin, &str, &len); /* client->server cipher */
5548 for (i = 0; i < s->n_preferred_ciphers; i++) {
5549 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5551 s->warn_cscipher = TRUE;
5553 for (j = 0; j < c->nciphers; j++) {
5554 if (in_commasep_string(c->list[j]->name, str, len)) {
5555 s->cscipher_tobe = c->list[j];
5560 if (s->cscipher_tobe)
5563 if (!s->cscipher_tobe) {
5564 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
5565 str ? str : "(null)"));
5569 ssh_pkt_getstring(pktin, &str, &len); /* server->client cipher */
5570 for (i = 0; i < s->n_preferred_ciphers; i++) {
5571 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5573 s->warn_sccipher = TRUE;
5575 for (j = 0; j < c->nciphers; j++) {
5576 if (in_commasep_string(c->list[j]->name, str, len)) {
5577 s->sccipher_tobe = c->list[j];
5582 if (s->sccipher_tobe)
5585 if (!s->sccipher_tobe) {
5586 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
5587 str ? str : "(null)"));
5591 ssh_pkt_getstring(pktin, &str, &len); /* client->server mac */
5592 for (i = 0; i < s->nmacs; i++) {
5593 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5594 s->csmac_tobe = s->maclist[i];
5598 ssh_pkt_getstring(pktin, &str, &len); /* server->client mac */
5599 for (i = 0; i < s->nmacs; i++) {
5600 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5601 s->scmac_tobe = s->maclist[i];
5605 ssh_pkt_getstring(pktin, &str, &len); /* client->server compression */
5606 for (i = 0; i < lenof(compressions) + 1; i++) {
5607 const struct ssh_compress *c =
5608 i == 0 ? s->preferred_comp : compressions[i - 1];
5609 if (in_commasep_string(c->name, str, len)) {
5614 ssh_pkt_getstring(pktin, &str, &len); /* server->client compression */
5615 for (i = 0; i < lenof(compressions) + 1; i++) {
5616 const struct ssh_compress *c =
5617 i == 0 ? s->preferred_comp : compressions[i - 1];
5618 if (in_commasep_string(c->name, str, len)) {
5623 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
5624 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
5625 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
5628 ssh_set_frozen(ssh, 1);
5629 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
5631 ssh_dialog_callback, ssh);
5632 if (s->dlgret < 0) {
5636 bombout(("Unexpected data from server while"
5637 " waiting for user response"));
5640 } while (pktin || inlen > 0);
5641 s->dlgret = ssh->user_response;
5643 ssh_set_frozen(ssh, 0);
5644 if (s->dlgret == 0) {
5645 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
5651 if (s->warn_cscipher) {
5652 ssh_set_frozen(ssh, 1);
5653 s->dlgret = askalg(ssh->frontend,
5654 "client-to-server cipher",
5655 s->cscipher_tobe->name,
5656 ssh_dialog_callback, ssh);
5657 if (s->dlgret < 0) {
5661 bombout(("Unexpected data from server while"
5662 " waiting for user response"));
5665 } while (pktin || inlen > 0);
5666 s->dlgret = ssh->user_response;
5668 ssh_set_frozen(ssh, 0);
5669 if (s->dlgret == 0) {
5670 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
5676 if (s->warn_sccipher) {
5677 ssh_set_frozen(ssh, 1);
5678 s->dlgret = askalg(ssh->frontend,
5679 "server-to-client cipher",
5680 s->sccipher_tobe->name,
5681 ssh_dialog_callback, ssh);
5682 if (s->dlgret < 0) {
5686 bombout(("Unexpected data from server while"
5687 " waiting for user response"));
5690 } while (pktin || inlen > 0);
5691 s->dlgret = ssh->user_response;
5693 ssh_set_frozen(ssh, 0);
5694 if (s->dlgret == 0) {
5695 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
5701 ssh->exhash = ssh->kex->hash->init();
5702 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
5703 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
5704 hash_string(ssh->kex->hash, ssh->exhash,
5705 s->our_kexinit, s->our_kexinitlen);
5706 sfree(s->our_kexinit);
5707 if (pktin->length > 5)
5708 hash_string(ssh->kex->hash, ssh->exhash,
5709 pktin->data + 5, pktin->length - 5);
5711 if (s->ignorepkt) /* first_kex_packet_follows */
5712 crWaitUntil(pktin); /* Ignore packet */
5715 if (ssh->kex->main_type == KEXTYPE_DH) {
5717 * Work out the number of bits of key we will need from the
5718 * key exchange. We start with the maximum key length of
5724 csbits = s->cscipher_tobe->keylen;
5725 scbits = s->sccipher_tobe->keylen;
5726 s->nbits = (csbits > scbits ? csbits : scbits);
5728 /* The keys only have hlen-bit entropy, since they're based on
5729 * a hash. So cap the key size at hlen bits. */
5730 if (s->nbits > ssh->kex->hash->hlen * 8)
5731 s->nbits = ssh->kex->hash->hlen * 8;
5734 * If we're doing Diffie-Hellman group exchange, start by
5735 * requesting a group.
5737 if (!ssh->kex->pdata) {
5738 logevent("Doing Diffie-Hellman group exchange");
5739 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
5741 * Work out how big a DH group we will need to allow that
5744 s->pbits = 512 << ((s->nbits - 1) / 64);
5745 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
5746 ssh2_pkt_adduint32(s->pktout, s->pbits);
5747 ssh2_pkt_send_noqueue(ssh, s->pktout);
5750 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
5751 bombout(("expected key exchange group packet from server"));
5754 s->p = ssh2_pkt_getmp(pktin);
5755 s->g = ssh2_pkt_getmp(pktin);
5756 if (!s->p || !s->g) {
5757 bombout(("unable to read mp-ints from incoming group packet"));
5760 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
5761 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
5762 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
5764 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
5765 ssh->kex_ctx = dh_setup_group(ssh->kex);
5766 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
5767 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
5768 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
5769 ssh->kex->groupname);
5772 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
5773 ssh->kex->hash->text_name);
5775 * Now generate and send e for Diffie-Hellman.
5777 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
5778 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
5779 s->pktout = ssh2_pkt_init(s->kex_init_value);
5780 ssh2_pkt_addmp(s->pktout, s->e);
5781 ssh2_pkt_send_noqueue(ssh, s->pktout);
5783 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
5785 if (pktin->type != s->kex_reply_value) {
5786 bombout(("expected key exchange reply packet from server"));
5789 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
5790 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
5791 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
5792 s->f = ssh2_pkt_getmp(pktin);
5794 bombout(("unable to parse key exchange reply packet"));
5797 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
5799 s->K = dh_find_K(ssh->kex_ctx, s->f);
5801 /* We assume everything from now on will be quick, and it might
5802 * involve user interaction. */
5803 set_busy_status(ssh->frontend, BUSY_NOT);
5805 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
5806 if (!ssh->kex->pdata) {
5807 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
5808 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
5809 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
5811 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
5812 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
5814 dh_cleanup(ssh->kex_ctx);
5816 if (!ssh->kex->pdata) {
5821 logeventf(ssh, "Doing RSA key exchange with hash %s",
5822 ssh->kex->hash->text_name);
5823 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
5825 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
5829 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
5830 bombout(("expected RSA public key packet from server"));
5834 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
5835 hash_string(ssh->kex->hash, ssh->exhash,
5836 s->hostkeydata, s->hostkeylen);
5837 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
5841 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
5842 s->rsakeydata = snewn(s->rsakeylen, char);
5843 memcpy(s->rsakeydata, keydata, s->rsakeylen);
5846 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
5848 sfree(s->rsakeydata);
5849 bombout(("unable to parse RSA public key from server"));
5853 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
5856 * Next, set up a shared secret K, of precisely KLEN -
5857 * 2*HLEN - 49 bits, where KLEN is the bit length of the
5858 * RSA key modulus and HLEN is the bit length of the hash
5862 int klen = ssh_rsakex_klen(s->rsakey);
5863 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
5865 unsigned char *kstr1, *kstr2, *outstr;
5866 int kstr1len, kstr2len, outstrlen;
5868 s->K = bn_power_2(nbits - 1);
5870 for (i = 0; i < nbits; i++) {
5872 byte = random_byte();
5874 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
5878 * Encode this as an mpint.
5880 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
5881 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
5882 PUT_32BIT(kstr2, kstr1len);
5883 memcpy(kstr2 + 4, kstr1, kstr1len);
5886 * Encrypt it with the given RSA key.
5888 outstrlen = (klen + 7) / 8;
5889 outstr = snewn(outstrlen, unsigned char);
5890 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
5891 outstr, outstrlen, s->rsakey);
5894 * And send it off in a return packet.
5896 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
5897 ssh2_pkt_addstring_start(s->pktout);
5898 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
5899 ssh2_pkt_send_noqueue(ssh, s->pktout);
5901 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
5908 ssh_rsakex_freekey(s->rsakey);
5911 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
5912 sfree(s->rsakeydata);
5913 bombout(("expected signature packet from server"));
5917 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
5919 sfree(s->rsakeydata);
5922 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
5923 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
5924 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
5926 ssh->kex_ctx = NULL;
5929 debug(("Exchange hash is:\n"));
5930 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
5934 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
5935 (char *)s->exchange_hash,
5936 ssh->kex->hash->hlen)) {
5937 bombout(("Server's host key did not match the signature supplied"));
5942 * Authenticate remote host: verify host key. (We've already
5943 * checked the signature of the exchange hash.)
5945 s->keystr = ssh->hostkey->fmtkey(s->hkey);
5946 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
5947 ssh_set_frozen(ssh, 1);
5948 s->dlgret = verify_ssh_host_key(ssh->frontend,
5949 ssh->savedhost, ssh->savedport,
5950 ssh->hostkey->keytype, s->keystr,
5952 ssh_dialog_callback, ssh);
5953 if (s->dlgret < 0) {
5957 bombout(("Unexpected data from server while waiting"
5958 " for user host key response"));
5961 } while (pktin || inlen > 0);
5962 s->dlgret = ssh->user_response;
5964 ssh_set_frozen(ssh, 0);
5965 if (s->dlgret == 0) {
5966 ssh_disconnect(ssh, "User aborted at host key verification", NULL,
5970 if (!s->got_session_id) { /* don't bother logging this in rekeys */
5971 logevent("Host key fingerprint is:");
5972 logevent(s->fingerprint);
5974 sfree(s->fingerprint);
5976 ssh->hostkey->freekey(s->hkey);
5979 * The exchange hash from the very first key exchange is also
5980 * the session id, used in session key construction and
5983 if (!s->got_session_id) {
5984 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
5985 memcpy(ssh->v2_session_id, s->exchange_hash,
5986 sizeof(s->exchange_hash));
5987 ssh->v2_session_id_len = ssh->kex->hash->hlen;
5988 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
5989 s->got_session_id = TRUE;
5993 * Send SSH2_MSG_NEWKEYS.
5995 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
5996 ssh2_pkt_send_noqueue(ssh, s->pktout);
5997 ssh->outgoing_data_size = 0; /* start counting from here */
6000 * We've sent client NEWKEYS, so create and initialise
6001 * client-to-server session keys.
6003 if (ssh->cs_cipher_ctx)
6004 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
6005 ssh->cscipher = s->cscipher_tobe;
6006 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
6008 if (ssh->cs_mac_ctx)
6009 ssh->csmac->free_context(ssh->cs_mac_ctx);
6010 ssh->csmac = s->csmac_tobe;
6011 ssh->cs_mac_ctx = ssh->csmac->make_context();
6013 if (ssh->cs_comp_ctx)
6014 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
6015 ssh->cscomp = s->cscomp_tobe;
6016 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
6019 * Set IVs on client-to-server keys. Here we use the exchange
6020 * hash from the _first_ key exchange.
6023 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6024 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6025 ssh2_mkkey(ssh,s->K,s->exchange_hash,'C',keyspace);
6026 assert((ssh->cscipher->keylen+7) / 8 <=
6027 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6028 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
6029 ssh2_mkkey(ssh,s->K,s->exchange_hash,'A',keyspace);
6030 assert(ssh->cscipher->blksize <=
6031 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6032 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
6033 ssh2_mkkey(ssh,s->K,s->exchange_hash,'E',keyspace);
6034 assert(ssh->csmac->len <=
6035 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6036 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
6037 memset(keyspace, 0, sizeof(keyspace));
6040 logeventf(ssh, "Initialised %.200s client->server encryption",
6041 ssh->cscipher->text_name);
6042 logeventf(ssh, "Initialised %.200s client->server MAC algorithm",
6043 ssh->csmac->text_name);
6044 if (ssh->cscomp->text_name)
6045 logeventf(ssh, "Initialised %s compression",
6046 ssh->cscomp->text_name);
6049 * Now our end of the key exchange is complete, we can send all
6050 * our queued higher-layer packets.
6052 ssh->queueing = FALSE;
6053 ssh2_pkt_queuesend(ssh);
6056 * Expect SSH2_MSG_NEWKEYS from server.
6059 if (pktin->type != SSH2_MSG_NEWKEYS) {
6060 bombout(("expected new-keys packet from server"));
6063 ssh->incoming_data_size = 0; /* start counting from here */
6066 * We've seen server NEWKEYS, so create and initialise
6067 * server-to-client session keys.
6069 if (ssh->sc_cipher_ctx)
6070 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
6071 ssh->sccipher = s->sccipher_tobe;
6072 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
6074 if (ssh->sc_mac_ctx)
6075 ssh->scmac->free_context(ssh->sc_mac_ctx);
6076 ssh->scmac = s->scmac_tobe;
6077 ssh->sc_mac_ctx = ssh->scmac->make_context();
6079 if (ssh->sc_comp_ctx)
6080 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
6081 ssh->sccomp = s->sccomp_tobe;
6082 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
6085 * Set IVs on server-to-client keys. Here we use the exchange
6086 * hash from the _first_ key exchange.
6089 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6090 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6091 ssh2_mkkey(ssh,s->K,s->exchange_hash,'D',keyspace);
6092 assert((ssh->sccipher->keylen+7) / 8 <=
6093 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6094 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
6095 ssh2_mkkey(ssh,s->K,s->exchange_hash,'B',keyspace);
6096 assert(ssh->sccipher->blksize <=
6097 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6098 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
6099 ssh2_mkkey(ssh,s->K,s->exchange_hash,'F',keyspace);
6100 assert(ssh->scmac->len <=
6101 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6102 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
6103 memset(keyspace, 0, sizeof(keyspace));
6105 logeventf(ssh, "Initialised %.200s server->client encryption",
6106 ssh->sccipher->text_name);
6107 logeventf(ssh, "Initialised %.200s server->client MAC algorithm",
6108 ssh->scmac->text_name);
6109 if (ssh->sccomp->text_name)
6110 logeventf(ssh, "Initialised %s decompression",
6111 ssh->sccomp->text_name);
6114 * Free shared secret.
6119 * Key exchange is over. Loop straight back round if we have a
6120 * deferred rekey reason.
6122 if (ssh->deferred_rekey_reason) {
6123 logevent(ssh->deferred_rekey_reason);
6125 ssh->deferred_rekey_reason = NULL;
6126 goto begin_key_exchange;
6130 * Otherwise, schedule a timer for our next rekey.
6132 ssh->kex_in_progress = FALSE;
6133 ssh->last_rekey = GETTICKCOUNT();
6134 if (ssh->cfg.ssh_rekey_time != 0)
6135 ssh->next_rekey = schedule_timer(ssh->cfg.ssh_rekey_time*60*TICKSPERSEC,
6139 * If this is the first key exchange phase, we must pass the
6140 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
6141 * wants to see it but because it will need time to initialise
6142 * itself before it sees an actual packet. In subsequent key
6143 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
6144 * it would only confuse the layer above.
6146 if (s->activated_authconn) {
6149 s->activated_authconn = TRUE;
6152 * Now we're encrypting. Begin returning 1 to the protocol main
6153 * function so that other things can run on top of the
6154 * transport. If we ever see a KEXINIT, we must go back to the
6157 * We _also_ go back to the start if we see pktin==NULL and
6158 * inlen==-1, because this is a special signal meaning
6159 * `initiate client-driven rekey', and `in' contains a message
6160 * giving the reason for the rekey.
6162 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
6163 (!pktin && inlen == -1))) {
6168 logevent("Server initiated key re-exchange");
6171 * Special case: if the server bug is set that doesn't
6172 * allow rekeying, we give a different log message and
6173 * continue waiting. (If such a server _initiates_ a rekey,
6174 * we process it anyway!)
6176 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
6177 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
6179 /* Reset the counters, so that at least this message doesn't
6180 * hit the event log _too_ often. */
6181 ssh->outgoing_data_size = 0;
6182 ssh->incoming_data_size = 0;
6183 if (ssh->cfg.ssh_rekey_time != 0) {
6185 schedule_timer(ssh->cfg.ssh_rekey_time*60*TICKSPERSEC,
6188 goto wait_for_rekey; /* this is utterly horrid */
6190 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
6193 goto begin_key_exchange;
6199 * Add data to an SSH-2 channel output buffer.
6201 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
6204 bufchain_add(&c->v.v2.outbuffer, buf, len);
6208 * Attempt to send data on an SSH-2 channel.
6210 static int ssh2_try_send(struct ssh_channel *c)
6213 struct Packet *pktout;
6215 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
6218 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
6219 if ((unsigned)len > c->v.v2.remwindow)
6220 len = c->v.v2.remwindow;
6221 if ((unsigned)len > c->v.v2.remmaxpkt)
6222 len = c->v.v2.remmaxpkt;
6223 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
6224 ssh2_pkt_adduint32(pktout, c->remoteid);
6225 ssh2_pkt_addstring_start(pktout);
6226 dont_log_data(ssh, pktout, PKTLOG_OMIT);
6227 ssh2_pkt_addstring_data(pktout, data, len);
6228 end_log_omission(ssh, pktout);
6229 ssh2_pkt_send(ssh, pktout);
6230 bufchain_consume(&c->v.v2.outbuffer, len);
6231 c->v.v2.remwindow -= len;
6235 * After having sent as much data as we can, return the amount
6238 return bufchain_size(&c->v.v2.outbuffer);
6241 static void ssh2_try_send_and_unthrottle(struct ssh_channel *c)
6245 return; /* don't send on closing channels */
6246 bufsize = ssh2_try_send(c);
6249 case CHAN_MAINSESSION:
6250 /* stdin need not receive an unthrottle
6251 * notification since it will be polled */
6254 x11_unthrottle(c->u.x11.s);
6257 /* agent sockets are request/response and need no
6258 * buffer management */
6261 pfd_unthrottle(c->u.pfd.s);
6268 * Set up most of a new ssh_channel for SSH-2.
6270 static void ssh2_channel_init(struct ssh_channel *c)
6273 c->localid = alloc_channel_id(ssh);
6275 c->throttling_conn = FALSE;
6276 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
6277 ssh->cfg.ssh_simple ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
6278 c->v.v2.winadj_head = c->v.v2.winadj_tail = NULL;
6279 c->v.v2.throttle_state = UNTHROTTLED;
6280 bufchain_init(&c->v.v2.outbuffer);
6284 * Potentially enlarge the window on an SSH-2 channel.
6286 static void ssh2_set_window(struct ssh_channel *c, int newwin)
6291 * Never send WINDOW_ADJUST for a channel that the remote side
6292 * already thinks it's closed; there's no point, since it won't
6293 * be sending any more data anyway.
6299 * If the remote end has a habit of ignoring maxpkt, limit the
6300 * window so that it has no choice (assuming it doesn't ignore the
6303 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
6304 newwin = OUR_V2_MAXPKT;
6308 * Only send a WINDOW_ADJUST if there's significantly more window
6309 * available than the other end thinks there is. This saves us
6310 * sending a WINDOW_ADJUST for every character in a shell session.
6312 * "Significant" is arbitrarily defined as half the window size.
6314 if (newwin / 2 >= c->v.v2.locwindow) {
6315 struct Packet *pktout;
6319 * In order to keep track of how much window the client
6320 * actually has available, we'd like it to acknowledge each
6321 * WINDOW_ADJUST. We can't do that directly, so we accompany
6322 * it with a CHANNEL_REQUEST that has to be acknowledged.
6324 * This is only necessary if we're opening the window wide.
6325 * If we're not, then throughput is being constrained by
6326 * something other than the maximum window size anyway.
6328 * We also only send this if the main channel has finished its
6329 * initial CHANNEL_REQUESTs and installed the default
6330 * CHANNEL_FAILURE handler, so as not to risk giving it
6331 * unexpected CHANNEL_FAILUREs.
6333 if (newwin == c->v.v2.locmaxwin &&
6334 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE]) {
6335 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6336 ssh2_pkt_adduint32(pktout, c->remoteid);
6337 ssh2_pkt_addstring(pktout, "winadj@putty.projects.tartarus.org");
6338 ssh2_pkt_addbool(pktout, TRUE);
6339 ssh2_pkt_send(ssh, pktout);
6342 * CHANNEL_FAILURE doesn't come with any indication of
6343 * what message caused it, so we have to keep track of the
6344 * outstanding CHANNEL_REQUESTs ourselves.
6346 wa = snew(struct winadj);
6347 wa->size = newwin - c->v.v2.locwindow;
6349 if (!c->v.v2.winadj_head)
6350 c->v.v2.winadj_head = wa;
6352 c->v.v2.winadj_tail->next = wa;
6353 c->v.v2.winadj_tail = wa;
6354 if (c->v.v2.throttle_state != UNTHROTTLED)
6355 c->v.v2.throttle_state = UNTHROTTLING;
6357 /* Pretend the WINDOW_ADJUST was acked immediately. */
6358 c->v.v2.remlocwin = newwin;
6359 c->v.v2.throttle_state = THROTTLED;
6361 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
6362 ssh2_pkt_adduint32(pktout, c->remoteid);
6363 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
6364 ssh2_pkt_send(ssh, pktout);
6365 c->v.v2.locwindow = newwin;
6370 * Find the channel associated with a message. If there's no channel,
6371 * or it's not properly open, make a noise about it and return NULL.
6373 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
6375 unsigned localid = ssh_pkt_getuint32(pktin);
6376 struct ssh_channel *c;
6378 c = find234(ssh->channels, &localid, ssh_channelfind);
6380 (c->halfopen && pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
6381 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
6382 char *buf = dupprintf("Received %s for %s channel %u",
6383 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
6385 c ? "half-open" : "nonexistent", localid);
6386 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6393 static void ssh2_msg_channel_success(Ssh ssh, struct Packet *pktin)
6396 * This should never get called. All channel requests are either
6397 * sent with want_reply false or are sent before this handler gets
6400 struct ssh_channel *c;
6403 c = ssh2_channel_msg(ssh, pktin);
6406 wa = c->v.v2.winadj_head;
6408 ssh_disconnect(ssh, NULL, "Received SSH_MSG_CHANNEL_SUCCESS for "
6409 "\"winadj@putty.projects.tartarus.org\"",
6410 SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6412 ssh_disconnect(ssh, NULL,
6413 "Received unsolicited SSH_MSG_CHANNEL_SUCCESS",
6414 SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6417 static void ssh2_msg_channel_failure(Ssh ssh, struct Packet *pktin)
6420 * The only time this should get called is for "winadj@putty"
6421 * messages sent above. All other channel requests are either
6422 * sent with want_reply false or are sent before this handler gets
6425 struct ssh_channel *c;
6428 c = ssh2_channel_msg(ssh, pktin);
6431 wa = c->v.v2.winadj_head;
6433 ssh_disconnect(ssh, NULL,
6434 "Received unsolicited SSH_MSG_CHANNEL_FAILURE",
6435 SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6438 c->v.v2.winadj_head = wa->next;
6439 c->v.v2.remlocwin += wa->size;
6442 * winadj messages are only sent when the window is fully open, so
6443 * if we get an ack of one, we know any pending unthrottle is
6446 if (c->v.v2.throttle_state == UNTHROTTLING)
6447 c->v.v2.throttle_state = UNTHROTTLED;
6450 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
6452 struct ssh_channel *c;
6453 c = ssh2_channel_msg(ssh, pktin);
6457 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
6458 ssh2_try_send_and_unthrottle(c);
6462 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
6466 struct ssh_channel *c;
6467 c = ssh2_channel_msg(ssh, pktin);
6470 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
6471 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
6472 return; /* extended but not stderr */
6473 ssh_pkt_getstring(pktin, &data, &length);
6476 c->v.v2.locwindow -= length;
6477 c->v.v2.remlocwin -= length;
6479 case CHAN_MAINSESSION:
6481 from_backend(ssh->frontend, pktin->type ==
6482 SSH2_MSG_CHANNEL_EXTENDED_DATA,
6486 bufsize = x11_send(c->u.x11.s, data, length);
6489 bufsize = pfd_send(c->u.pfd.s, data, length);
6492 while (length > 0) {
6493 if (c->u.a.lensofar < 4) {
6494 unsigned int l = min(4 - c->u.a.lensofar,
6496 memcpy(c->u.a.msglen + c->u.a.lensofar,
6500 c->u.a.lensofar += l;
6502 if (c->u.a.lensofar == 4) {
6504 4 + GET_32BIT(c->u.a.msglen);
6505 c->u.a.message = snewn(c->u.a.totallen,
6507 memcpy(c->u.a.message, c->u.a.msglen, 4);
6509 if (c->u.a.lensofar >= 4 && length > 0) {
6511 min(c->u.a.totallen - c->u.a.lensofar,
6513 memcpy(c->u.a.message + c->u.a.lensofar,
6517 c->u.a.lensofar += l;
6519 if (c->u.a.lensofar == c->u.a.totallen) {
6522 if (agent_query(c->u.a.message,
6525 ssh_agentf_callback, c))
6526 ssh_agentf_callback(c, reply, replylen);
6527 sfree(c->u.a.message);
6528 c->u.a.lensofar = 0;
6535 * If it looks like the remote end hit the end of its window,
6536 * and we didn't want it to do that, think about using a
6539 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
6540 c->v.v2.locmaxwin < 0x40000000)
6541 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
6543 * If we are not buffering too much data,
6544 * enlarge the window again at the remote side.
6545 * If we are buffering too much, we may still
6546 * need to adjust the window if the server's
6549 ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
6550 c->v.v2.locmaxwin - bufsize : 0);
6552 * If we're either buffering way too much data, or if we're
6553 * buffering anything at all and we're in "simple" mode,
6554 * throttle the whole channel.
6556 if ((bufsize > c->v.v2.locmaxwin ||
6557 (ssh->cfg.ssh_simple && bufsize > 0)) &&
6558 !c->throttling_conn) {
6559 c->throttling_conn = 1;
6560 ssh_throttle_conn(ssh, +1);
6565 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
6567 struct ssh_channel *c;
6569 c = ssh2_channel_msg(ssh, pktin);
6573 if (c->type == CHAN_X11) {
6575 * Remote EOF on an X11 channel means we should
6576 * wrap up and close the channel ourselves.
6578 x11_close(c->u.x11.s);
6580 } else if (c->type == CHAN_AGENT) {
6582 } else if (c->type == CHAN_SOCKDATA) {
6583 pfd_close(c->u.pfd.s);
6588 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
6590 struct ssh_channel *c;
6591 struct Packet *pktout;
6593 c = ssh2_channel_msg(ssh, pktin);
6596 /* Do pre-close processing on the channel. */
6598 case CHAN_MAINSESSION:
6599 ssh->mainchan = NULL;
6600 update_specials_menu(ssh->frontend);
6603 if (c->u.x11.s != NULL)
6604 x11_close(c->u.x11.s);
6611 if (c->u.pfd.s != NULL)
6612 pfd_close(c->u.pfd.s);
6616 if (c->closes == 0) {
6617 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
6618 ssh2_pkt_adduint32(pktout, c->remoteid);
6619 ssh2_pkt_send(ssh, pktout);
6621 del234(ssh->channels, c);
6622 bufchain_clear(&c->v.v2.outbuffer);
6626 * See if that was the last channel left open.
6627 * (This is only our termination condition if we're
6628 * not running in -N mode.)
6630 if (!ssh->cfg.ssh_no_shell && count234(ssh->channels) == 0) {
6632 * We used to send SSH_MSG_DISCONNECT here,
6633 * because I'd believed that _every_ conforming
6634 * SSH-2 connection had to end with a disconnect
6635 * being sent by at least one side; apparently
6636 * I was wrong and it's perfectly OK to
6637 * unceremoniously slam the connection shut
6638 * when you're done, and indeed OpenSSH feels
6639 * this is more polite than sending a
6640 * DISCONNECT. So now we don't.
6642 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
6646 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
6648 struct ssh_channel *c;
6649 struct Packet *pktout;
6651 c = ssh2_channel_msg(ssh, pktin);
6654 if (c->type != CHAN_SOCKDATA_DORMANT)
6655 return; /* dunno why they're confirming this */
6656 c->remoteid = ssh_pkt_getuint32(pktin);
6657 c->halfopen = FALSE;
6658 c->type = CHAN_SOCKDATA;
6659 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
6660 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
6662 pfd_confirm(c->u.pfd.s);
6665 * We have a pending close on this channel,
6666 * which we decided on before the server acked
6667 * the channel open. So now we know the
6668 * remoteid, we can close it again.
6670 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
6671 ssh2_pkt_adduint32(pktout, c->remoteid);
6672 ssh2_pkt_send(ssh, pktout);
6676 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
6678 static const char *const reasons[] = {
6679 "<unknown reason code>",
6680 "Administratively prohibited",
6682 "Unknown channel type",
6683 "Resource shortage",
6685 unsigned reason_code;
6686 char *reason_string;
6688 struct ssh_channel *c;
6689 c = ssh2_channel_msg(ssh, pktin);
6692 if (c->type != CHAN_SOCKDATA_DORMANT)
6693 return; /* dunno why they're failing this */
6695 reason_code = ssh_pkt_getuint32(pktin);
6696 if (reason_code >= lenof(reasons))
6697 reason_code = 0; /* ensure reasons[reason_code] in range */
6698 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
6699 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
6700 reasons[reason_code], reason_length, reason_string);
6702 pfd_close(c->u.pfd.s);
6704 del234(ssh->channels, c);
6708 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
6711 int typelen, want_reply;
6712 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
6713 struct ssh_channel *c;
6714 struct Packet *pktout;
6716 c = ssh2_channel_msg(ssh, pktin);
6719 ssh_pkt_getstring(pktin, &type, &typelen);
6720 want_reply = ssh2_pkt_getbool(pktin);
6723 * Having got the channel number, we now look at
6724 * the request type string to see if it's something
6727 if (c == ssh->mainchan) {
6729 * We recognise "exit-status" and "exit-signal" on
6730 * the primary channel.
6732 if (typelen == 11 &&
6733 !memcmp(type, "exit-status", 11)) {
6735 ssh->exitcode = ssh_pkt_getuint32(pktin);
6736 logeventf(ssh, "Server sent command exit status %d",
6738 reply = SSH2_MSG_CHANNEL_SUCCESS;
6740 } else if (typelen == 11 &&
6741 !memcmp(type, "exit-signal", 11)) {
6743 int is_plausible = TRUE, is_int = FALSE;
6744 char *fmt_sig = "", *fmt_msg = "";
6746 int msglen = 0, core = FALSE;
6747 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
6748 * provide an `int' for the signal, despite its
6749 * having been a `string' in the drafts of RFC 4254 since at
6750 * least 2001. (Fixed in session.c 1.147.) Try to
6751 * infer which we can safely parse it as. */
6753 unsigned char *p = pktin->body +
6755 long len = pktin->length - pktin->savedpos;
6756 unsigned long num = GET_32BIT(p); /* what is it? */
6757 /* If it's 0, it hardly matters; assume string */
6761 int maybe_int = FALSE, maybe_str = FALSE;
6762 #define CHECK_HYPOTHESIS(offset, result) \
6765 if (q >= 0 && q+4 <= len) { \
6766 q = q + 4 + GET_32BIT(p+q); \
6767 if (q >= 0 && q+4 <= len && \
6768 ((q = q + 4 + GET_32BIT(p+q))!= 0) && q == len) \
6772 CHECK_HYPOTHESIS(4+1, maybe_int);
6773 CHECK_HYPOTHESIS(4+num+1, maybe_str);
6774 #undef CHECK_HYPOTHESIS
6775 if (maybe_int && !maybe_str)
6777 else if (!maybe_int && maybe_str)
6780 /* Crikey. Either or neither. Panic. */
6781 is_plausible = FALSE;
6784 ssh->exitcode = 128; /* means `unknown signal' */
6787 /* Old non-standard OpenSSH. */
6788 int signum = ssh_pkt_getuint32(pktin);
6789 fmt_sig = dupprintf(" %d", signum);
6790 ssh->exitcode = 128 + signum;
6792 /* As per RFC 4254. */
6795 ssh_pkt_getstring(pktin, &sig, &siglen);
6796 /* Signal name isn't supposed to be blank, but
6797 * let's cope gracefully if it is. */
6799 fmt_sig = dupprintf(" \"%.*s\"",
6804 * Really hideous method of translating the
6805 * signal description back into a locally
6806 * meaningful number.
6811 #define TRANSLATE_SIGNAL(s) \
6812 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
6813 ssh->exitcode = 128 + SIG ## s
6815 TRANSLATE_SIGNAL(ABRT);
6818 TRANSLATE_SIGNAL(ALRM);
6821 TRANSLATE_SIGNAL(FPE);
6824 TRANSLATE_SIGNAL(HUP);
6827 TRANSLATE_SIGNAL(ILL);
6830 TRANSLATE_SIGNAL(INT);
6833 TRANSLATE_SIGNAL(KILL);
6836 TRANSLATE_SIGNAL(PIPE);
6839 TRANSLATE_SIGNAL(QUIT);
6842 TRANSLATE_SIGNAL(SEGV);
6845 TRANSLATE_SIGNAL(TERM);
6848 TRANSLATE_SIGNAL(USR1);
6851 TRANSLATE_SIGNAL(USR2);
6853 #undef TRANSLATE_SIGNAL
6855 ssh->exitcode = 128;
6857 core = ssh2_pkt_getbool(pktin);
6858 ssh_pkt_getstring(pktin, &msg, &msglen);
6860 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
6862 /* ignore lang tag */
6863 } /* else don't attempt to parse */
6864 logeventf(ssh, "Server exited on signal%s%s%s",
6865 fmt_sig, core ? " (core dumped)" : "",
6867 if (*fmt_sig) sfree(fmt_sig);
6868 if (*fmt_msg) sfree(fmt_msg);
6869 reply = SSH2_MSG_CHANNEL_SUCCESS;
6874 * This is a channel request we don't know
6875 * about, so we now either ignore the request
6876 * or respond with CHANNEL_FAILURE, depending
6879 reply = SSH2_MSG_CHANNEL_FAILURE;
6882 pktout = ssh2_pkt_init(reply);
6883 ssh2_pkt_adduint32(pktout, c->remoteid);
6884 ssh2_pkt_send(ssh, pktout);
6888 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
6891 int typelen, want_reply;
6892 struct Packet *pktout;
6894 ssh_pkt_getstring(pktin, &type, &typelen);
6895 want_reply = ssh2_pkt_getbool(pktin);
6898 * We currently don't support any global requests
6899 * at all, so we either ignore the request or
6900 * respond with REQUEST_FAILURE, depending on
6904 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
6905 ssh2_pkt_send(ssh, pktout);
6909 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
6917 struct ssh_channel *c;
6918 unsigned remid, winsize, pktsize;
6919 struct Packet *pktout;
6921 ssh_pkt_getstring(pktin, &type, &typelen);
6922 c = snew(struct ssh_channel);
6925 remid = ssh_pkt_getuint32(pktin);
6926 winsize = ssh_pkt_getuint32(pktin);
6927 pktsize = ssh_pkt_getuint32(pktin);
6929 if (typelen == 3 && !memcmp(type, "x11", 3)) {
6932 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
6933 addrstr = snewn(peeraddrlen+1, char);
6934 memcpy(addrstr, peeraddr, peeraddrlen);
6935 addrstr[peeraddrlen] = '\0';
6936 peerport = ssh_pkt_getuint32(pktin);
6938 logeventf(ssh, "Received X11 connect request from %s:%d",
6941 if (!ssh->X11_fwd_enabled)
6942 error = "X11 forwarding is not enabled";
6943 else if (x11_init(&c->u.x11.s, ssh->x11disp, c,
6944 addrstr, peerport, &ssh->cfg) != NULL) {
6945 error = "Unable to open an X11 connection";
6947 logevent("Opening X11 forward connection succeeded");
6952 } else if (typelen == 15 &&
6953 !memcmp(type, "forwarded-tcpip", 15)) {
6954 struct ssh_rportfwd pf, *realpf;
6957 ssh_pkt_getstring(pktin, &dummy, &dummylen);/* skip address */
6958 pf.sport = ssh_pkt_getuint32(pktin);
6959 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
6960 peerport = ssh_pkt_getuint32(pktin);
6961 realpf = find234(ssh->rportfwds, &pf, NULL);
6962 logeventf(ssh, "Received remote port %d open request "
6963 "from %s:%d", pf.sport, peeraddr, peerport);
6964 if (realpf == NULL) {
6965 error = "Remote port is not recognised";
6967 const char *e = pfd_newconnect(&c->u.pfd.s,
6971 realpf->pfrec->addressfamily);
6972 logeventf(ssh, "Attempting to forward remote port to "
6973 "%s:%d", realpf->dhost, realpf->dport);
6975 logeventf(ssh, "Port open failed: %s", e);
6976 error = "Port open failed";
6978 logevent("Forwarded port opened successfully");
6979 c->type = CHAN_SOCKDATA;
6982 } else if (typelen == 22 &&
6983 !memcmp(type, "auth-agent@openssh.com", 22)) {
6984 if (!ssh->agentfwd_enabled)
6985 error = "Agent forwarding is not enabled";
6987 c->type = CHAN_AGENT; /* identify channel type */
6988 c->u.a.lensofar = 0;
6991 error = "Unsupported channel type requested";
6994 c->remoteid = remid;
6995 c->halfopen = FALSE;
6997 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
6998 ssh2_pkt_adduint32(pktout, c->remoteid);
6999 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
7000 ssh2_pkt_addstring(pktout, error);
7001 ssh2_pkt_addstring(pktout, "en"); /* language tag */
7002 ssh2_pkt_send(ssh, pktout);
7003 logeventf(ssh, "Rejected channel open: %s", error);
7006 ssh2_channel_init(c);
7007 c->v.v2.remwindow = winsize;
7008 c->v.v2.remmaxpkt = pktsize;
7009 add234(ssh->channels, c);
7010 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
7011 ssh2_pkt_adduint32(pktout, c->remoteid);
7012 ssh2_pkt_adduint32(pktout, c->localid);
7013 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
7014 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7015 ssh2_pkt_send(ssh, pktout);
7020 * Buffer banner messages for later display at some convenient point.
7022 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
7024 /* Arbitrary limit to prevent unbounded inflation of buffer */
7025 if (bufchain_size(&ssh->banner) <= 131072) {
7026 char *banner = NULL;
7028 ssh_pkt_getstring(pktin, &banner, &size);
7030 bufchain_add(&ssh->banner, banner, size);
7034 /* Helper function to deal with sending tty modes for "pty-req" */
7035 static void ssh2_send_ttymode(void *data, char *mode, char *val)
7037 struct Packet *pktout = (struct Packet *)data;
7039 unsigned int arg = 0;
7040 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
7041 if (i == lenof(ssh_ttymodes)) return;
7042 switch (ssh_ttymodes[i].type) {
7044 arg = ssh_tty_parse_specchar(val);
7047 arg = ssh_tty_parse_boolean(val);
7050 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
7051 ssh2_pkt_adduint32(pktout, arg);
7055 * Handle the SSH-2 userauth and connection layers.
7057 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
7058 struct Packet *pktin)
7060 struct do_ssh2_authconn_state {
7063 AUTH_TYPE_PUBLICKEY,
7064 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
7065 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
7068 AUTH_TYPE_KEYBOARD_INTERACTIVE,
7069 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
7071 int done_service_req;
7072 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
7073 int tried_pubkey_config, done_agent;
7076 int kbd_inter_refused;
7078 prompts_t *cur_prompt;
7083 void *publickey_blob;
7084 int publickey_bloblen;
7085 int publickey_encrypted;
7086 char *publickey_algorithm;
7087 char *publickey_comment;
7088 unsigned char agent_request[5], *agent_response, *agentp;
7089 int agent_responselen;
7090 unsigned char *pkblob_in_agent;
7092 char *pkblob, *alg, *commentp;
7093 int pklen, alglen, commentlen;
7094 int siglen, retlen, len;
7095 char *q, *agentreq, *ret;
7097 int num_env, env_left, env_ok;
7098 struct Packet *pktout;
7099 Ssh_gss_ctx gss_ctx;
7100 Ssh_gss_buf gss_buf;
7101 Ssh_gss_buf gss_rcvtok, gss_sndtok;
7102 Ssh_gss_name gss_srv_name;
7103 Ssh_gss_stat gss_stat;
7105 crState(do_ssh2_authconn_state);
7107 crBegin(ssh->do_ssh2_authconn_crstate);
7109 s->done_service_req = FALSE;
7110 s->we_are_in = FALSE;
7111 s->tried_gssapi = FALSE;
7113 if (!ssh->cfg.ssh_no_userauth) {
7115 * Request userauth protocol, and await a response to it.
7117 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7118 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
7119 ssh2_pkt_send(ssh, s->pktout);
7120 crWaitUntilV(pktin);
7121 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
7122 s->done_service_req = TRUE;
7124 if (!s->done_service_req) {
7126 * Request connection protocol directly, without authentication.
7128 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7129 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7130 ssh2_pkt_send(ssh, s->pktout);
7131 crWaitUntilV(pktin);
7132 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
7133 s->we_are_in = TRUE; /* no auth required */
7135 bombout(("Server refused service request"));
7140 /* Arrange to be able to deal with any BANNERs that come in.
7141 * (We do this now as packets may come in during the next bit.) */
7142 bufchain_init(&ssh->banner);
7143 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
7144 ssh2_msg_userauth_banner;
7147 * Misc one-time setup for authentication.
7149 s->publickey_blob = NULL;
7150 if (!s->we_are_in) {
7153 * Load the public half of any configured public key file
7156 if (!filename_is_null(ssh->cfg.keyfile)) {
7158 logeventf(ssh, "Reading private key file \"%.150s\"",
7159 filename_to_str(&ssh->cfg.keyfile));
7160 keytype = key_type(&ssh->cfg.keyfile);
7161 if (keytype == SSH_KEYTYPE_SSH2) {
7164 ssh2_userkey_loadpub(&ssh->cfg.keyfile,
7165 &s->publickey_algorithm,
7166 &s->publickey_bloblen,
7167 &s->publickey_comment, &error);
7168 if (s->publickey_blob) {
7169 s->publickey_encrypted =
7170 ssh2_userkey_encrypted(&ssh->cfg.keyfile, NULL);
7173 logeventf(ssh, "Unable to load private key (%s)",
7175 msgbuf = dupprintf("Unable to load private key file "
7176 "\"%.150s\" (%s)\r\n",
7177 filename_to_str(&ssh->cfg.keyfile),
7179 c_write_str(ssh, msgbuf);
7184 logeventf(ssh, "Unable to use this key file (%s)",
7185 key_type_to_str(keytype));
7186 msgbuf = dupprintf("Unable to use key file \"%.150s\""
7188 filename_to_str(&ssh->cfg.keyfile),
7189 key_type_to_str(keytype));
7190 c_write_str(ssh, msgbuf);
7192 s->publickey_blob = NULL;
7197 * Find out about any keys Pageant has (but if there's a
7198 * public key configured, filter out all others).
7201 s->agent_response = NULL;
7202 s->pkblob_in_agent = NULL;
7203 if (ssh->cfg.tryagent && agent_exists()) {
7207 logevent("Pageant is running. Requesting keys.");
7209 /* Request the keys held by the agent. */
7210 PUT_32BIT(s->agent_request, 1);
7211 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
7212 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
7213 ssh_agent_callback, ssh)) {
7217 bombout(("Unexpected data from server while"
7218 " waiting for agent response"));
7221 } while (pktin || inlen > 0);
7222 r = ssh->agent_response;
7223 s->agent_responselen = ssh->agent_response_len;
7225 s->agent_response = (unsigned char *) r;
7226 if (s->agent_response && s->agent_responselen >= 5 &&
7227 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
7230 p = s->agent_response + 5;
7231 s->nkeys = GET_32BIT(p);
7233 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
7234 if (s->publickey_blob) {
7235 /* See if configured key is in agent. */
7236 for (keyi = 0; keyi < s->nkeys; keyi++) {
7237 s->pklen = GET_32BIT(p);
7238 if (s->pklen == s->publickey_bloblen &&
7239 !memcmp(p+4, s->publickey_blob,
7240 s->publickey_bloblen)) {
7241 logeventf(ssh, "Pageant key #%d matches "
7242 "configured key file", keyi);
7244 s->pkblob_in_agent = p;
7248 p += GET_32BIT(p) + 4; /* comment */
7250 if (!s->pkblob_in_agent) {
7251 logevent("Configured key file not in Pageant");
7261 * We repeat this whole loop, including the username prompt,
7262 * until we manage a successful authentication. If the user
7263 * types the wrong _password_, they can be sent back to the
7264 * beginning to try another username, if this is configured on.
7265 * (If they specify a username in the config, they are never
7266 * asked, even if they do give a wrong password.)
7268 * I think this best serves the needs of
7270 * - the people who have no configuration, no keys, and just
7271 * want to try repeated (username,password) pairs until they
7272 * type both correctly
7274 * - people who have keys and configuration but occasionally
7275 * need to fall back to passwords
7277 * - people with a key held in Pageant, who might not have
7278 * logged in to a particular machine before; so they want to
7279 * type a username, and then _either_ their key will be
7280 * accepted, _or_ they will type a password. If they mistype
7281 * the username they will want to be able to get back and
7284 s->username[0] = '\0';
7285 s->got_username = FALSE;
7286 while (!s->we_are_in) {
7290 if (s->got_username && !ssh->cfg.change_username) {
7292 * We got a username last time round this loop, and
7293 * with change_username turned off we don't try to get
7296 } else if (!get_remote_username(&ssh->cfg, s->username,
7297 sizeof(s->username))) {
7298 int ret; /* need not be kept over crReturn */
7299 s->cur_prompt = new_prompts(ssh->frontend);
7300 s->cur_prompt->to_server = TRUE;
7301 s->cur_prompt->name = dupstr("SSH login name");
7302 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE,
7303 lenof(s->username));
7304 ret = get_userpass_input(s->cur_prompt, NULL, 0);
7307 crWaitUntilV(!pktin);
7308 ret = get_userpass_input(s->cur_prompt, in, inlen);
7313 * get_userpass_input() failed to get a username.
7316 free_prompts(s->cur_prompt);
7317 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
7320 memcpy(s->username, s->cur_prompt->prompts[0]->result,
7321 lenof(s->username));
7322 free_prompts(s->cur_prompt);
7325 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
7326 stuff = dupprintf("Using username \"%s\".\r\n", s->username);
7327 c_write_str(ssh, stuff);
7331 s->got_username = TRUE;
7334 * Send an authentication request using method "none": (a)
7335 * just in case it succeeds, and (b) so that we know what
7336 * authentication methods we can usefully try next.
7338 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
7340 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7341 ssh2_pkt_addstring(s->pktout, s->username);
7342 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
7343 ssh2_pkt_addstring(s->pktout, "none"); /* method */
7344 ssh2_pkt_send(ssh, s->pktout);
7345 s->type = AUTH_TYPE_NONE;
7347 s->we_are_in = FALSE;
7349 s->tried_pubkey_config = FALSE;
7350 s->kbd_inter_refused = FALSE;
7352 /* Reset agent request state. */
7353 s->done_agent = FALSE;
7354 if (s->agent_response) {
7355 if (s->pkblob_in_agent) {
7356 s->agentp = s->pkblob_in_agent;
7358 s->agentp = s->agent_response + 5 + 4;
7365 * Wait for the result of the last authentication request.
7368 crWaitUntilV(pktin);
7370 * Now is a convenient point to spew any banner material
7371 * that we've accumulated. (This should ensure that when
7372 * we exit the auth loop, we haven't any left to deal
7376 int size = bufchain_size(&ssh->banner);
7378 * Don't show the banner if we're operating in
7379 * non-verbose non-interactive mode. (It's probably
7380 * a script, which means nobody will read the
7381 * banner _anyway_, and moreover the printing of
7382 * the banner will screw up processing on the
7383 * output of (say) plink.)
7385 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
7386 char *banner = snewn(size, char);
7387 bufchain_fetch(&ssh->banner, banner, size);
7388 c_write_untrusted(ssh, banner, size);
7391 bufchain_clear(&ssh->banner);
7393 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
7394 logevent("Access granted");
7395 s->we_are_in = TRUE;
7399 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
7400 bombout(("Strange packet received during authentication: "
7401 "type %d", pktin->type));
7408 * OK, we're now sitting on a USERAUTH_FAILURE message, so
7409 * we can look at the string in it and know what we can
7410 * helpfully try next.
7412 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
7415 ssh_pkt_getstring(pktin, &methods, &methlen);
7416 if (!ssh2_pkt_getbool(pktin)) {
7418 * We have received an unequivocal Access
7419 * Denied. This can translate to a variety of
7422 * - if we'd just tried "none" authentication,
7423 * it's not worth printing anything at all
7425 * - if we'd just tried a public key _offer_,
7426 * the message should be "Server refused our
7427 * key" (or no message at all if the key
7428 * came from Pageant)
7430 * - if we'd just tried anything else, the
7431 * message really should be "Access denied".
7433 * Additionally, if we'd just tried password
7434 * authentication, we should break out of this
7435 * whole loop so as to go back to the username
7436 * prompt (iff we're configured to allow
7437 * username change attempts).
7439 if (s->type == AUTH_TYPE_NONE) {
7441 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
7442 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
7443 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
7444 c_write_str(ssh, "Server refused our key\r\n");
7445 logevent("Server refused public key");
7446 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
7447 /* server declined keyboard-interactive; ignore */
7449 c_write_str(ssh, "Access denied\r\n");
7450 logevent("Access denied");
7451 if (s->type == AUTH_TYPE_PASSWORD &&
7452 ssh->cfg.change_username) {
7453 /* XXX perhaps we should allow
7454 * keyboard-interactive to do this too? */
7455 s->we_are_in = FALSE;
7460 c_write_str(ssh, "Further authentication required\r\n");
7461 logevent("Further authentication required");
7465 in_commasep_string("publickey", methods, methlen);
7467 in_commasep_string("password", methods, methlen);
7468 s->can_keyb_inter = ssh->cfg.try_ki_auth &&
7469 in_commasep_string("keyboard-interactive", methods, methlen);
7471 s->can_gssapi = ssh->cfg.try_gssapi_auth &&
7472 in_commasep_string("gssapi-with-mic", methods, methlen) &&
7477 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
7479 if (s->can_pubkey && !s->done_agent && s->nkeys) {
7482 * Attempt public-key authentication using a key from Pageant.
7485 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
7487 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
7489 /* Unpack key from agent response */
7490 s->pklen = GET_32BIT(s->agentp);
7492 s->pkblob = (char *)s->agentp;
7493 s->agentp += s->pklen;
7494 s->alglen = GET_32BIT(s->pkblob);
7495 s->alg = s->pkblob + 4;
7496 s->commentlen = GET_32BIT(s->agentp);
7498 s->commentp = (char *)s->agentp;
7499 s->agentp += s->commentlen;
7500 /* s->agentp now points at next key, if any */
7502 /* See if server will accept it */
7503 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7504 ssh2_pkt_addstring(s->pktout, s->username);
7505 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7506 /* service requested */
7507 ssh2_pkt_addstring(s->pktout, "publickey");
7509 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
7510 ssh2_pkt_addstring_start(s->pktout);
7511 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
7512 ssh2_pkt_addstring_start(s->pktout);
7513 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
7514 ssh2_pkt_send(ssh, s->pktout);
7515 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
7517 crWaitUntilV(pktin);
7518 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
7520 /* Offer of key refused. */
7527 if (flags & FLAG_VERBOSE) {
7528 c_write_str(ssh, "Authenticating with "
7530 c_write(ssh, s->commentp, s->commentlen);
7531 c_write_str(ssh, "\" from agent\r\n");
7535 * Server is willing to accept the key.
7536 * Construct a SIGN_REQUEST.
7538 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7539 ssh2_pkt_addstring(s->pktout, s->username);
7540 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7541 /* service requested */
7542 ssh2_pkt_addstring(s->pktout, "publickey");
7544 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
7545 ssh2_pkt_addstring_start(s->pktout);
7546 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
7547 ssh2_pkt_addstring_start(s->pktout);
7548 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
7550 /* Ask agent for signature. */
7551 s->siglen = s->pktout->length - 5 + 4 +
7552 ssh->v2_session_id_len;
7553 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
7555 s->len = 1; /* message type */
7556 s->len += 4 + s->pklen; /* key blob */
7557 s->len += 4 + s->siglen; /* data to sign */
7558 s->len += 4; /* flags */
7559 s->agentreq = snewn(4 + s->len, char);
7560 PUT_32BIT(s->agentreq, s->len);
7561 s->q = s->agentreq + 4;
7562 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
7563 PUT_32BIT(s->q, s->pklen);
7565 memcpy(s->q, s->pkblob, s->pklen);
7567 PUT_32BIT(s->q, s->siglen);
7569 /* Now the data to be signed... */
7570 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
7571 PUT_32BIT(s->q, ssh->v2_session_id_len);
7574 memcpy(s->q, ssh->v2_session_id,
7575 ssh->v2_session_id_len);
7576 s->q += ssh->v2_session_id_len;
7577 memcpy(s->q, s->pktout->data + 5,
7578 s->pktout->length - 5);
7579 s->q += s->pktout->length - 5;
7580 /* And finally the (zero) flags word. */
7582 if (!agent_query(s->agentreq, s->len + 4,
7584 ssh_agent_callback, ssh)) {
7588 bombout(("Unexpected data from server"
7589 " while waiting for agent"
7593 } while (pktin || inlen > 0);
7594 vret = ssh->agent_response;
7595 s->retlen = ssh->agent_response_len;
7600 if (s->ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
7601 logevent("Sending Pageant's response");
7602 ssh2_add_sigblob(ssh, s->pktout,
7603 s->pkblob, s->pklen,
7605 GET_32BIT(s->ret + 5));
7606 ssh2_pkt_send(ssh, s->pktout);
7607 s->type = AUTH_TYPE_PUBLICKEY;
7609 /* FIXME: less drastic response */
7610 bombout(("Pageant failed to answer challenge"));
7616 /* Do we have any keys left to try? */
7617 if (s->pkblob_in_agent) {
7618 s->done_agent = TRUE;
7619 s->tried_pubkey_config = TRUE;
7622 if (s->keyi >= s->nkeys)
7623 s->done_agent = TRUE;
7626 } else if (s->can_pubkey && s->publickey_blob &&
7627 !s->tried_pubkey_config) {
7629 struct ssh2_userkey *key; /* not live over crReturn */
7630 char *passphrase; /* not live over crReturn */
7632 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
7634 s->tried_pubkey_config = TRUE;
7637 * Try the public key supplied in the configuration.
7639 * First, offer the public blob to see if the server is
7640 * willing to accept it.
7642 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7643 ssh2_pkt_addstring(s->pktout, s->username);
7644 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7645 /* service requested */
7646 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
7647 ssh2_pkt_addbool(s->pktout, FALSE);
7648 /* no signature included */
7649 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
7650 ssh2_pkt_addstring_start(s->pktout);
7651 ssh2_pkt_addstring_data(s->pktout,
7652 (char *)s->publickey_blob,
7653 s->publickey_bloblen);
7654 ssh2_pkt_send(ssh, s->pktout);
7655 logevent("Offered public key");
7657 crWaitUntilV(pktin);
7658 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
7659 /* Key refused. Give up. */
7660 s->gotit = TRUE; /* reconsider message next loop */
7661 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
7662 continue; /* process this new message */
7664 logevent("Offer of public key accepted");
7667 * Actually attempt a serious authentication using
7670 if (flags & FLAG_VERBOSE) {
7671 c_write_str(ssh, "Authenticating with public key \"");
7672 c_write_str(ssh, s->publickey_comment);
7673 c_write_str(ssh, "\"\r\n");
7677 const char *error; /* not live over crReturn */
7678 if (s->publickey_encrypted) {
7680 * Get a passphrase from the user.
7682 int ret; /* need not be kept over crReturn */
7683 s->cur_prompt = new_prompts(ssh->frontend);
7684 s->cur_prompt->to_server = FALSE;
7685 s->cur_prompt->name = dupstr("SSH key passphrase");
7686 add_prompt(s->cur_prompt,
7687 dupprintf("Passphrase for key \"%.100s\": ",
7688 s->publickey_comment),
7689 FALSE, SSH_MAX_PASSWORD_LEN);
7690 ret = get_userpass_input(s->cur_prompt, NULL, 0);
7693 crWaitUntilV(!pktin);
7694 ret = get_userpass_input(s->cur_prompt,
7699 /* Failed to get a passphrase. Terminate. */
7700 free_prompts(s->cur_prompt);
7701 ssh_disconnect(ssh, NULL,
7702 "Unable to authenticate",
7703 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
7708 dupstr(s->cur_prompt->prompts[0]->result);
7709 free_prompts(s->cur_prompt);
7711 passphrase = NULL; /* no passphrase needed */
7715 * Try decrypting the key.
7717 key = ssh2_load_userkey(&ssh->cfg.keyfile, passphrase,
7720 /* burn the evidence */
7721 memset(passphrase, 0, strlen(passphrase));
7724 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
7726 (key == SSH2_WRONG_PASSPHRASE)) {
7727 c_write_str(ssh, "Wrong passphrase\r\n");
7729 /* and loop again */
7731 c_write_str(ssh, "Unable to load private key (");
7732 c_write_str(ssh, error);
7733 c_write_str(ssh, ")\r\n");
7735 break; /* try something else */
7741 unsigned char *pkblob, *sigblob, *sigdata;
7742 int pkblob_len, sigblob_len, sigdata_len;
7746 * We have loaded the private key and the server
7747 * has announced that it's willing to accept it.
7748 * Hallelujah. Generate a signature and send it.
7750 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7751 ssh2_pkt_addstring(s->pktout, s->username);
7752 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7753 /* service requested */
7754 ssh2_pkt_addstring(s->pktout, "publickey");
7756 ssh2_pkt_addbool(s->pktout, TRUE);
7757 /* signature follows */
7758 ssh2_pkt_addstring(s->pktout, key->alg->name);
7759 pkblob = key->alg->public_blob(key->data,
7761 ssh2_pkt_addstring_start(s->pktout);
7762 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
7766 * The data to be signed is:
7770 * followed by everything so far placed in the
7773 sigdata_len = s->pktout->length - 5 + 4 +
7774 ssh->v2_session_id_len;
7775 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
7777 sigdata = snewn(sigdata_len, unsigned char);
7779 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
7780 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
7783 memcpy(sigdata+p, ssh->v2_session_id,
7784 ssh->v2_session_id_len);
7785 p += ssh->v2_session_id_len;
7786 memcpy(sigdata+p, s->pktout->data + 5,
7787 s->pktout->length - 5);
7788 p += s->pktout->length - 5;
7789 assert(p == sigdata_len);
7790 sigblob = key->alg->sign(key->data, (char *)sigdata,
7791 sigdata_len, &sigblob_len);
7792 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
7793 sigblob, sigblob_len);
7798 ssh2_pkt_send(ssh, s->pktout);
7799 s->type = AUTH_TYPE_PUBLICKEY;
7800 key->alg->freekey(key->data);
7804 } else if (s->can_gssapi && !s->tried_gssapi) {
7806 /* GSSAPI Authentication */
7811 s->type = AUTH_TYPE_GSSAPI;
7812 s->tried_gssapi = TRUE;
7814 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
7816 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
7817 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7818 ssh2_pkt_addstring(s->pktout, s->username);
7819 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7820 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
7822 /* add mechanism info */
7823 ssh_gss_indicate_mech(&s->gss_buf);
7825 /* number of GSSAPI mechanisms */
7826 ssh2_pkt_adduint32(s->pktout,1);
7828 /* length of OID + 2 */
7829 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
7830 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
7833 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
7835 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
7837 ssh2_pkt_send(ssh, s->pktout);
7838 crWaitUntilV(pktin);
7839 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
7840 logevent("GSSAPI authentication request refused");
7844 /* check returned packet ... */
7846 ssh_pkt_getstring(pktin, &data, &len);
7847 s->gss_rcvtok.value = data;
7848 s->gss_rcvtok.length = len;
7849 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
7850 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
7851 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
7852 memcmp((char *)s->gss_rcvtok.value + 2,
7853 s->gss_buf.value,s->gss_buf.length) ) {
7854 logevent("GSSAPI authentication - wrong response from server");
7858 /* now start running */
7859 s->gss_stat = ssh_gss_import_name(ssh->fullhostname,
7861 if (s->gss_stat != SSH_GSS_OK) {
7862 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
7863 logevent("GSSAPI import name failed - Bad service name");
7865 logevent("GSSAPI import name failed");
7869 /* fetch TGT into GSS engine */
7870 s->gss_stat = ssh_gss_acquire_cred(&s->gss_ctx);
7872 if (s->gss_stat != SSH_GSS_OK) {
7873 logevent("GSSAPI authentication failed to get credentials");
7874 ssh_gss_release_name(&s->gss_srv_name);
7878 /* initial tokens are empty */
7879 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
7881 /* now enter the loop */
7883 s->gss_stat = ssh_gss_init_sec_context(&s->gss_ctx,
7889 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
7890 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
7891 logevent("GSSAPI authentication initialisation failed");
7893 if (ssh_gss_display_status(s->gss_ctx,&s->gss_buf) == SSH_GSS_OK) {
7894 logevent(s->gss_buf.value);
7895 sfree(s->gss_buf.value);
7900 logevent("GSSAPI authentication initialised");
7902 /* Client and server now exchange tokens until GSSAPI
7903 * no longer says CONTINUE_NEEDED */
7905 if (s->gss_sndtok.length != 0) {
7906 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
7907 ssh_pkt_addstring_start(s->pktout);
7908 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
7909 ssh2_pkt_send(ssh, s->pktout);
7910 ssh_gss_free_tok(&s->gss_sndtok);
7913 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
7914 crWaitUntilV(pktin);
7915 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
7916 logevent("GSSAPI authentication - bad server response");
7917 s->gss_stat = SSH_GSS_FAILURE;
7920 ssh_pkt_getstring(pktin, &data, &len);
7921 s->gss_rcvtok.value = data;
7922 s->gss_rcvtok.length = len;
7924 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
7926 if (s->gss_stat != SSH_GSS_OK) {
7927 ssh_gss_release_name(&s->gss_srv_name);
7928 ssh_gss_release_cred(&s->gss_ctx);
7931 logevent("GSSAPI authentication loop finished OK");
7933 /* Now send the MIC */
7935 s->pktout = ssh2_pkt_init(0);
7936 micoffset = s->pktout->length;
7937 ssh_pkt_addstring_start(s->pktout);
7938 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
7939 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
7940 ssh_pkt_addstring(s->pktout, s->username);
7941 ssh_pkt_addstring(s->pktout, "ssh-connection");
7942 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
7944 s->gss_buf.value = (char *)s->pktout->data + micoffset;
7945 s->gss_buf.length = s->pktout->length - micoffset;
7947 ssh_gss_get_mic(s->gss_ctx, &s->gss_buf, &mic);
7948 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
7949 ssh_pkt_addstring_start(s->pktout);
7950 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
7951 ssh2_pkt_send(ssh, s->pktout);
7952 ssh_gss_free_mic(&mic);
7956 ssh_gss_release_name(&s->gss_srv_name);
7957 ssh_gss_release_cred(&s->gss_ctx);
7960 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
7963 * Keyboard-interactive authentication.
7966 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
7968 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
7970 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7971 ssh2_pkt_addstring(s->pktout, s->username);
7972 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7973 /* service requested */
7974 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
7976 ssh2_pkt_addstring(s->pktout, ""); /* lang */
7977 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
7978 ssh2_pkt_send(ssh, s->pktout);
7980 crWaitUntilV(pktin);
7981 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
7982 /* Server is not willing to do keyboard-interactive
7983 * at all (or, bizarrely but legally, accepts the
7984 * user without actually issuing any prompts).
7985 * Give up on it entirely. */
7987 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE)
7988 logevent("Keyboard-interactive authentication refused");
7989 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
7990 s->kbd_inter_refused = TRUE; /* don't try it again */
7995 * Loop while the server continues to send INFO_REQUESTs.
7997 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
7999 char *name, *inst, *lang;
8000 int name_len, inst_len, lang_len;
8004 * We've got a fresh USERAUTH_INFO_REQUEST.
8005 * Get the preamble and start building a prompt.
8007 ssh_pkt_getstring(pktin, &name, &name_len);
8008 ssh_pkt_getstring(pktin, &inst, &inst_len);
8009 ssh_pkt_getstring(pktin, &lang, &lang_len);
8010 s->cur_prompt = new_prompts(ssh->frontend);
8011 s->cur_prompt->to_server = TRUE;
8013 /* FIXME: better prefix to distinguish from
8015 s->cur_prompt->name =
8016 dupprintf("SSH server: %.*s", name_len, name);
8017 s->cur_prompt->name_reqd = TRUE;
8019 s->cur_prompt->name =
8020 dupstr("SSH server authentication");
8021 s->cur_prompt->name_reqd = FALSE;
8023 /* FIXME: ugly to print "Using..." in prompt _every_
8024 * time round. Can this be done more subtly? */
8025 s->cur_prompt->instruction =
8026 dupprintf("Using keyboard-interactive authentication.%s%.*s",
8027 inst_len ? "\n" : "", inst_len, inst);
8028 s->cur_prompt->instr_reqd = TRUE;
8031 * Get any prompt(s) from the packet.
8033 s->num_prompts = ssh_pkt_getuint32(pktin);
8034 for (i = 0; i < s->num_prompts; i++) {
8038 static char noprompt[] =
8039 "<server failed to send prompt>: ";
8041 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
8042 echo = ssh2_pkt_getbool(pktin);
8045 prompt_len = lenof(noprompt)-1;
8047 add_prompt(s->cur_prompt,
8048 dupprintf("%.*s", prompt_len, prompt),
8049 echo, SSH_MAX_PASSWORD_LEN);
8053 * Display any instructions, and get the user's
8057 int ret; /* not live over crReturn */
8058 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8061 crWaitUntilV(!pktin);
8062 ret = get_userpass_input(s->cur_prompt, in, inlen);
8067 * Failed to get responses. Terminate.
8069 free_prompts(s->cur_prompt);
8070 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8071 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8078 * Send the response(s) to the server.
8080 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
8081 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
8082 for (i=0; i < s->num_prompts; i++) {
8083 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8084 ssh2_pkt_addstring(s->pktout,
8085 s->cur_prompt->prompts[i]->result);
8086 end_log_omission(ssh, s->pktout);
8088 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8091 * Get the next packet in case it's another
8094 crWaitUntilV(pktin);
8099 * We should have SUCCESS or FAILURE now.
8103 } else if (s->can_passwd) {
8106 * Plain old password authentication.
8108 int ret; /* not live over crReturn */
8109 int changereq_first_time; /* not live over crReturn */
8111 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
8113 s->cur_prompt = new_prompts(ssh->frontend);
8114 s->cur_prompt->to_server = TRUE;
8115 s->cur_prompt->name = dupstr("SSH password");
8116 add_prompt(s->cur_prompt, dupprintf("%.90s@%.90s's password: ",
8119 FALSE, SSH_MAX_PASSWORD_LEN);
8121 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8124 crWaitUntilV(!pktin);
8125 ret = get_userpass_input(s->cur_prompt, in, inlen);
8130 * Failed to get responses. Terminate.
8132 free_prompts(s->cur_prompt);
8133 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8134 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8139 * Squirrel away the password. (We may need it later if
8140 * asked to change it.)
8142 s->password = dupstr(s->cur_prompt->prompts[0]->result);
8143 free_prompts(s->cur_prompt);
8146 * Send the password packet.
8148 * We pad out the password packet to 256 bytes to make
8149 * it harder for an attacker to find the length of the
8152 * Anyone using a password longer than 256 bytes
8153 * probably doesn't have much to worry about from
8154 * people who find out how long their password is!
8156 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8157 ssh2_pkt_addstring(s->pktout, s->username);
8158 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8159 /* service requested */
8160 ssh2_pkt_addstring(s->pktout, "password");
8161 ssh2_pkt_addbool(s->pktout, FALSE);
8162 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8163 ssh2_pkt_addstring(s->pktout, s->password);
8164 end_log_omission(ssh, s->pktout);
8165 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8166 logevent("Sent password");
8167 s->type = AUTH_TYPE_PASSWORD;
8170 * Wait for next packet, in case it's a password change
8173 crWaitUntilV(pktin);
8174 changereq_first_time = TRUE;
8176 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
8179 * We're being asked for a new password
8180 * (perhaps not for the first time).
8181 * Loop until the server accepts it.
8184 int got_new = FALSE; /* not live over crReturn */
8185 char *prompt; /* not live over crReturn */
8186 int prompt_len; /* not live over crReturn */
8190 if (changereq_first_time)
8191 msg = "Server requested password change";
8193 msg = "Server rejected new password";
8195 c_write_str(ssh, msg);
8196 c_write_str(ssh, "\r\n");
8199 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
8201 s->cur_prompt = new_prompts(ssh->frontend);
8202 s->cur_prompt->to_server = TRUE;
8203 s->cur_prompt->name = dupstr("New SSH password");
8204 s->cur_prompt->instruction =
8205 dupprintf("%.*s", prompt_len, prompt);
8206 s->cur_prompt->instr_reqd = TRUE;
8208 * There's no explicit requirement in the protocol
8209 * for the "old" passwords in the original and
8210 * password-change messages to be the same, and
8211 * apparently some Cisco kit supports password change
8212 * by the user entering a blank password originally
8213 * and the real password subsequently, so,
8214 * reluctantly, we prompt for the old password again.
8216 * (On the other hand, some servers don't even bother
8217 * to check this field.)
8219 add_prompt(s->cur_prompt,
8220 dupstr("Current password (blank for previously entered password): "),
8221 FALSE, SSH_MAX_PASSWORD_LEN);
8222 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
8223 FALSE, SSH_MAX_PASSWORD_LEN);
8224 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
8225 FALSE, SSH_MAX_PASSWORD_LEN);
8228 * Loop until the user manages to enter the same
8233 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8236 crWaitUntilV(!pktin);
8237 ret = get_userpass_input(s->cur_prompt, in, inlen);
8242 * Failed to get responses. Terminate.
8244 /* burn the evidence */
8245 free_prompts(s->cur_prompt);
8246 memset(s->password, 0, strlen(s->password));
8248 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8249 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8255 * If the user specified a new original password
8256 * (IYSWIM), overwrite any previously specified
8258 * (A side effect is that the user doesn't have to
8259 * re-enter it if they louse up the new password.)
8261 if (s->cur_prompt->prompts[0]->result[0]) {
8262 memset(s->password, 0, strlen(s->password));
8263 /* burn the evidence */
8266 dupstr(s->cur_prompt->prompts[0]->result);
8270 * Check the two new passwords match.
8272 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
8273 s->cur_prompt->prompts[2]->result)
8276 /* They don't. Silly user. */
8277 c_write_str(ssh, "Passwords do not match\r\n");
8282 * Send the new password (along with the old one).
8283 * (see above for padding rationale)
8285 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8286 ssh2_pkt_addstring(s->pktout, s->username);
8287 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8288 /* service requested */
8289 ssh2_pkt_addstring(s->pktout, "password");
8290 ssh2_pkt_addbool(s->pktout, TRUE);
8291 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8292 ssh2_pkt_addstring(s->pktout, s->password);
8293 ssh2_pkt_addstring(s->pktout,
8294 s->cur_prompt->prompts[1]->result);
8295 free_prompts(s->cur_prompt);
8296 end_log_omission(ssh, s->pktout);
8297 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
8298 logevent("Sent new password");
8301 * Now see what the server has to say about it.
8302 * (If it's CHANGEREQ again, it's not happy with the
8305 crWaitUntilV(pktin);
8306 changereq_first_time = FALSE;
8311 * We need to reexamine the current pktin at the top
8312 * of the loop. Either:
8313 * - we weren't asked to change password at all, in
8314 * which case it's a SUCCESS or FAILURE with the
8316 * - we sent a new password, and the server was
8317 * either OK with it (SUCCESS or FAILURE w/partial
8318 * success) or unhappy with the _old_ password
8319 * (FAILURE w/o partial success)
8320 * In any of these cases, we go back to the top of
8321 * the loop and start again.
8326 * We don't need the old password any more, in any
8327 * case. Burn the evidence.
8329 memset(s->password, 0, strlen(s->password));
8334 ssh_disconnect(ssh, NULL,
8335 "No supported authentication methods available",
8336 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
8344 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
8346 /* Clear up various bits and pieces from authentication. */
8347 if (s->publickey_blob) {
8348 sfree(s->publickey_blob);
8349 sfree(s->publickey_comment);
8351 if (s->agent_response)
8352 sfree(s->agent_response);
8355 * Now the connection protocol has started, one way or another.
8358 ssh->channels = newtree234(ssh_channelcmp);
8361 * Set up handlers for some connection protocol messages, so we
8362 * don't have to handle them repeatedly in this coroutine.
8364 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
8365 ssh2_msg_channel_window_adjust;
8366 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
8367 ssh2_msg_global_request;
8370 * Create the main session channel.
8372 if (ssh->cfg.ssh_no_shell) {
8373 ssh->mainchan = NULL;
8374 } else if (*ssh->cfg.ssh_nc_host) {
8376 * Just start a direct-tcpip channel and use it as the main
8379 ssh->mainchan = snew(struct ssh_channel);
8380 ssh->mainchan->ssh = ssh;
8381 ssh2_channel_init(ssh->mainchan);
8383 "Opening direct-tcpip channel to %s:%d in place of session",
8384 ssh->cfg.ssh_nc_host, ssh->cfg.ssh_nc_port);
8385 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
8386 ssh2_pkt_addstring(s->pktout, "direct-tcpip");
8387 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
8388 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
8389 ssh2_pkt_adduint32(s->pktout, OUR_V2_MAXPKT); /* our max pkt size */
8390 ssh2_pkt_addstring(s->pktout, ssh->cfg.ssh_nc_host);
8391 ssh2_pkt_adduint32(s->pktout, ssh->cfg.ssh_nc_port);
8393 * There's nothing meaningful to put in the originator
8394 * fields, but some servers insist on syntactically correct
8397 ssh2_pkt_addstring(s->pktout, "0.0.0.0");
8398 ssh2_pkt_adduint32(s->pktout, 0);
8399 ssh2_pkt_send(ssh, s->pktout);
8401 crWaitUntilV(pktin);
8402 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
8403 bombout(("Server refused to open a direct-tcpip channel"));
8405 /* FIXME: error data comes back in FAILURE packet */
8407 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
8408 bombout(("Server's channel confirmation cited wrong channel"));
8411 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
8412 ssh->mainchan->halfopen = FALSE;
8413 ssh->mainchan->type = CHAN_MAINSESSION;
8414 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8415 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8416 add234(ssh->channels, ssh->mainchan);
8417 update_specials_menu(ssh->frontend);
8418 logevent("Opened direct-tcpip channel");
8421 ssh->mainchan = snew(struct ssh_channel);
8422 ssh->mainchan->ssh = ssh;
8423 ssh2_channel_init(ssh->mainchan);
8424 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
8425 ssh2_pkt_addstring(s->pktout, "session");
8426 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
8427 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
8428 ssh2_pkt_adduint32(s->pktout, OUR_V2_MAXPKT); /* our max pkt size */
8429 ssh2_pkt_send(ssh, s->pktout);
8430 crWaitUntilV(pktin);
8431 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
8432 bombout(("Server refused to open a session"));
8434 /* FIXME: error data comes back in FAILURE packet */
8436 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
8437 bombout(("Server's channel confirmation cited wrong channel"));
8440 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
8441 ssh->mainchan->halfopen = FALSE;
8442 ssh->mainchan->type = CHAN_MAINSESSION;
8443 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8444 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8445 add234(ssh->channels, ssh->mainchan);
8446 update_specials_menu(ssh->frontend);
8447 logevent("Opened channel for session");
8448 ssh->ncmode = FALSE;
8452 * Now we have a channel, make dispatch table entries for
8453 * general channel-based messages.
8455 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
8456 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
8457 ssh2_msg_channel_data;
8458 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
8459 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
8460 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
8461 ssh2_msg_channel_open_confirmation;
8462 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
8463 ssh2_msg_channel_open_failure;
8464 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
8465 ssh2_msg_channel_request;
8466 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
8467 ssh2_msg_channel_open;
8469 if (ssh->cfg.ssh_simple) {
8471 * This message indicates to the server that we promise
8472 * not to try to run any other channel in parallel with
8473 * this one, so it's safe for it to advertise a very large
8474 * window and leave the flow control to TCP.
8476 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8477 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8478 ssh2_pkt_addstring(s->pktout, "simple@putty.projects.tartarus.org");
8479 ssh2_pkt_addbool(s->pktout, 0); /* no reply */
8480 ssh2_pkt_send(ssh, s->pktout);
8484 * Potentially enable X11 forwarding.
8486 if (ssh->mainchan && !ssh->ncmode && ssh->cfg.x11_forward) {
8487 logevent("Requesting X11 forwarding");
8488 ssh->x11disp = x11_setup_display(ssh->cfg.x11_display,
8489 ssh->cfg.x11_auth, &ssh->cfg);
8490 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8491 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8492 ssh2_pkt_addstring(s->pktout, "x11-req");
8493 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8494 ssh2_pkt_addbool(s->pktout, 0); /* many connections */
8495 ssh2_pkt_addstring(s->pktout, ssh->x11disp->remoteauthprotoname);
8497 * Note that while we blank the X authentication data here, we don't
8498 * take any special action to blank the start of an X11 channel,
8499 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
8500 * without having session blanking enabled is likely to leak your
8501 * cookie into the log.
8503 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8504 ssh2_pkt_addstring(s->pktout, ssh->x11disp->remoteauthdatastring);
8505 end_log_omission(ssh, s->pktout);
8506 ssh2_pkt_adduint32(s->pktout, ssh->x11disp->screennum);
8507 ssh2_pkt_send(ssh, s->pktout);
8509 crWaitUntilV(pktin);
8511 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8512 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8513 bombout(("Unexpected response to X11 forwarding request:"
8514 " packet type %d", pktin->type));
8517 logevent("X11 forwarding refused");
8519 logevent("X11 forwarding enabled");
8520 ssh->X11_fwd_enabled = TRUE;
8525 * Enable port forwardings.
8527 ssh_setup_portfwd(ssh, &ssh->cfg);
8530 * Potentially enable agent forwarding.
8532 if (ssh->mainchan && !ssh->ncmode && ssh->cfg.agentfwd && agent_exists()) {
8533 logevent("Requesting OpenSSH-style agent forwarding");
8534 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8535 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8536 ssh2_pkt_addstring(s->pktout, "auth-agent-req@openssh.com");
8537 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8538 ssh2_pkt_send(ssh, s->pktout);
8540 crWaitUntilV(pktin);
8542 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8543 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8544 bombout(("Unexpected response to agent forwarding request:"
8545 " packet type %d", pktin->type));
8548 logevent("Agent forwarding refused");
8550 logevent("Agent forwarding enabled");
8551 ssh->agentfwd_enabled = TRUE;
8556 * Now allocate a pty for the session.
8558 if (ssh->mainchan && !ssh->ncmode && !ssh->cfg.nopty) {
8559 /* Unpick the terminal-speed string. */
8560 /* XXX perhaps we should allow no speeds to be sent. */
8561 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
8562 sscanf(ssh->cfg.termspeed, "%d,%d", &ssh->ospeed, &ssh->ispeed);
8563 /* Build the pty request. */
8564 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8565 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
8566 ssh2_pkt_addstring(s->pktout, "pty-req");
8567 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8568 ssh2_pkt_addstring(s->pktout, ssh->cfg.termtype);
8569 ssh2_pkt_adduint32(s->pktout, ssh->term_width);
8570 ssh2_pkt_adduint32(s->pktout, ssh->term_height);
8571 ssh2_pkt_adduint32(s->pktout, 0); /* pixel width */
8572 ssh2_pkt_adduint32(s->pktout, 0); /* pixel height */
8573 ssh2_pkt_addstring_start(s->pktout);
8574 parse_ttymodes(ssh, ssh->cfg.ttymodes,
8575 ssh2_send_ttymode, (void *)s->pktout);
8576 ssh2_pkt_addbyte(s->pktout, SSH2_TTY_OP_ISPEED);
8577 ssh2_pkt_adduint32(s->pktout, ssh->ispeed);
8578 ssh2_pkt_addbyte(s->pktout, SSH2_TTY_OP_OSPEED);
8579 ssh2_pkt_adduint32(s->pktout, ssh->ospeed);
8580 ssh2_pkt_addstring_data(s->pktout, "\0", 1); /* TTY_OP_END */
8581 ssh2_pkt_send(ssh, s->pktout);
8582 ssh->state = SSH_STATE_INTERMED;
8584 crWaitUntilV(pktin);
8586 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8587 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8588 bombout(("Unexpected response to pty request:"
8589 " packet type %d", pktin->type));
8592 c_write_str(ssh, "Server refused to allocate pty\r\n");
8593 ssh->editing = ssh->echoing = 1;
8595 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
8596 ssh->ospeed, ssh->ispeed);
8599 ssh->editing = ssh->echoing = 1;
8603 * Send environment variables.
8605 * Simplest thing here is to send all the requests at once, and
8606 * then wait for a whole bunch of successes or failures.
8608 if (ssh->mainchan && !ssh->ncmode && *ssh->cfg.environmt) {
8609 char *e = ssh->cfg.environmt;
8610 char *var, *varend, *val;
8616 while (*e && *e != '\t') e++;
8618 if (*e == '\t') e++;
8623 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8624 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8625 ssh2_pkt_addstring(s->pktout, "env");
8626 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8627 ssh2_pkt_addstring_start(s->pktout);
8628 ssh2_pkt_addstring_data(s->pktout, var, varend-var);
8629 ssh2_pkt_addstring(s->pktout, val);
8630 ssh2_pkt_send(ssh, s->pktout);
8635 logeventf(ssh, "Sent %d environment variables", s->num_env);
8638 s->env_left = s->num_env;
8640 while (s->env_left > 0) {
8641 crWaitUntilV(pktin);
8643 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8644 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8645 bombout(("Unexpected response to environment request:"
8646 " packet type %d", pktin->type));
8656 if (s->env_ok == s->num_env) {
8657 logevent("All environment variables successfully set");
8658 } else if (s->env_ok == 0) {
8659 logevent("All environment variables refused");
8660 c_write_str(ssh, "Server refused to set environment variables\r\n");
8662 logeventf(ssh, "%d environment variables refused",
8663 s->num_env - s->env_ok);
8664 c_write_str(ssh, "Server refused to set all environment variables\r\n");
8669 * Start a shell or a remote command. We may have to attempt
8670 * this twice if the config data has provided a second choice
8673 if (ssh->mainchan && !ssh->ncmode) while (1) {
8677 if (ssh->fallback_cmd) {
8678 subsys = ssh->cfg.ssh_subsys2;
8679 cmd = ssh->cfg.remote_cmd_ptr2;
8681 subsys = ssh->cfg.ssh_subsys;
8682 cmd = ssh->cfg.remote_cmd_ptr;
8683 if (!cmd) cmd = ssh->cfg.remote_cmd;
8686 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8687 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
8689 ssh2_pkt_addstring(s->pktout, "subsystem");
8690 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8691 ssh2_pkt_addstring(s->pktout, cmd);
8693 ssh2_pkt_addstring(s->pktout, "exec");
8694 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8695 ssh2_pkt_addstring(s->pktout, cmd);
8697 ssh2_pkt_addstring(s->pktout, "shell");
8698 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
8700 ssh2_pkt_send(ssh, s->pktout);
8702 crWaitUntilV(pktin);
8704 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
8705 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
8706 bombout(("Unexpected response to shell/command request:"
8707 " packet type %d", pktin->type));
8711 * We failed to start the command. If this is the
8712 * fallback command, we really are finished; if it's
8713 * not, and if the fallback command exists, try falling
8714 * back to it before complaining.
8716 if (!ssh->fallback_cmd && ssh->cfg.remote_cmd_ptr2 != NULL) {
8717 logevent("Primary command failed; attempting fallback");
8718 ssh->fallback_cmd = TRUE;
8721 bombout(("Server refused to start a shell/command"));
8724 logevent("Started a shell/command");
8729 ssh->state = SSH_STATE_SESSION;
8730 if (ssh->size_needed)
8731 ssh_size(ssh, ssh->term_width, ssh->term_height);
8732 if (ssh->eof_needed)
8733 ssh_special(ssh, TS_EOF);
8736 * All the initial channel requests are done, so install the default
8739 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_success;
8740 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_failure;
8746 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
8751 s->try_send = FALSE;
8755 * _All_ the connection-layer packets we expect to
8756 * receive are now handled by the dispatch table.
8757 * Anything that reaches here must be bogus.
8760 bombout(("Strange packet received: type %d", pktin->type));
8762 } else if (ssh->mainchan) {
8764 * We have spare data. Add it to the channel buffer.
8766 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
8771 struct ssh_channel *c;
8773 * Try to send data on all channels if we can.
8775 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
8776 ssh2_try_send_and_unthrottle(c);
8784 * Handlers for SSH-2 messages that might arrive at any moment.
8786 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
8788 /* log reason code in disconnect message */
8792 reason = ssh_pkt_getuint32(pktin);
8793 ssh_pkt_getstring(pktin, &msg, &msglen);
8795 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
8796 buf = dupprintf("Received disconnect message (%s)",
8797 ssh2_disconnect_reasons[reason]);
8799 buf = dupprintf("Received disconnect message (unknown"
8800 " type %d)", reason);
8804 buf = dupprintf("Disconnection message text: %.*s",
8807 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
8809 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
8810 ssh2_disconnect_reasons[reason] : "unknown",
8815 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
8817 /* log the debug message */
8822 /* XXX maybe we should actually take notice of this */
8823 always_display = ssh2_pkt_getbool(pktin);
8824 ssh_pkt_getstring(pktin, &msg, &msglen);
8826 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
8829 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
8831 struct Packet *pktout;
8832 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
8833 ssh2_pkt_adduint32(pktout, pktin->sequence);
8835 * UNIMPLEMENTED messages MUST appear in the same order as the
8836 * messages they respond to. Hence, never queue them.
8838 ssh2_pkt_send_noqueue(ssh, pktout);
8842 * Handle the top-level SSH-2 protocol.
8844 static void ssh2_protocol_setup(Ssh ssh)
8849 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
8851 for (i = 0; i < 256; i++)
8852 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
8855 * Any message we actually understand, we set to NULL so that
8856 * the coroutines will get it.
8858 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = NULL;
8859 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = NULL;
8860 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = NULL;
8861 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = NULL;
8862 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = NULL;
8863 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = NULL;
8864 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = NULL;
8865 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = NULL; duplicate case value */
8866 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = NULL; duplicate case value */
8867 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = NULL;
8868 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = NULL;
8869 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = NULL;
8870 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = NULL;
8871 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = NULL;
8872 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
8873 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = NULL;
8874 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = NULL; duplicate case value */
8875 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = NULL; duplicate case value */
8876 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = NULL;
8877 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = NULL;
8878 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = NULL;
8879 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = NULL;
8880 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = NULL;
8881 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = NULL;
8882 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = NULL;
8883 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = NULL;
8884 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = NULL;
8885 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = NULL;
8886 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = NULL;
8887 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = NULL;
8888 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = NULL;
8889 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = NULL;
8890 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = NULL;
8893 * These special message types we install handlers for.
8895 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
8896 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
8897 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
8900 static void ssh2_timer(void *ctx, long now)
8904 if (ssh->state == SSH_STATE_CLOSED)
8907 if (!ssh->kex_in_progress && ssh->cfg.ssh_rekey_time != 0 &&
8908 now - ssh->next_rekey >= 0) {
8909 do_ssh2_transport(ssh, "timeout", -1, NULL);
8913 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
8914 struct Packet *pktin)
8916 unsigned char *in = (unsigned char *)vin;
8917 if (ssh->state == SSH_STATE_CLOSED)
8921 ssh->incoming_data_size += pktin->encrypted_len;
8922 if (!ssh->kex_in_progress &&
8923 ssh->max_data_size != 0 &&
8924 ssh->incoming_data_size > ssh->max_data_size)
8925 do_ssh2_transport(ssh, "too much data received", -1, NULL);
8928 if (pktin && ssh->packet_dispatch[pktin->type]) {
8929 ssh->packet_dispatch[pktin->type](ssh, pktin);
8933 if (!ssh->protocol_initial_phase_done ||
8934 (pktin && pktin->type >= 20 && pktin->type < 50)) {
8935 if (do_ssh2_transport(ssh, in, inlen, pktin) &&
8936 !ssh->protocol_initial_phase_done) {
8937 ssh->protocol_initial_phase_done = TRUE;
8939 * Allow authconn to initialise itself.
8941 do_ssh2_authconn(ssh, NULL, 0, NULL);
8944 do_ssh2_authconn(ssh, in, inlen, pktin);
8949 * Called to set up the connection.
8951 * Returns an error message, or NULL on success.
8953 static const char *ssh_init(void *frontend_handle, void **backend_handle,
8955 char *host, int port, char **realhost, int nodelay,
8961 ssh = snew(struct ssh_tag);
8962 ssh->cfg = *cfg; /* STRUCTURE COPY */
8963 ssh->version = 0; /* when not ready yet */
8966 ssh->v1_cipher_ctx = NULL;
8967 ssh->crcda_ctx = NULL;
8968 ssh->cscipher = NULL;
8969 ssh->cs_cipher_ctx = NULL;
8970 ssh->sccipher = NULL;
8971 ssh->sc_cipher_ctx = NULL;
8973 ssh->cs_mac_ctx = NULL;
8975 ssh->sc_mac_ctx = NULL;
8977 ssh->cs_comp_ctx = NULL;
8979 ssh->sc_comp_ctx = NULL;
8981 ssh->kex_ctx = NULL;
8982 ssh->hostkey = NULL;
8984 ssh->close_expected = FALSE;
8985 ssh->clean_exit = FALSE;
8986 ssh->state = SSH_STATE_PREPACKET;
8987 ssh->size_needed = FALSE;
8988 ssh->eof_needed = FALSE;
8991 ssh->deferred_send_data = NULL;
8992 ssh->deferred_len = 0;
8993 ssh->deferred_size = 0;
8994 ssh->fallback_cmd = 0;
8995 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
8996 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
8997 ssh->x11disp = NULL;
8998 ssh->v1_compressing = FALSE;
8999 ssh->v2_outgoing_sequence = 0;
9000 ssh->ssh1_rdpkt_crstate = 0;
9001 ssh->ssh2_rdpkt_crstate = 0;
9002 ssh->do_ssh_init_crstate = 0;
9003 ssh->ssh_gotdata_crstate = 0;
9004 ssh->do_ssh1_connection_crstate = 0;
9005 ssh->do_ssh1_login_crstate = 0;
9006 ssh->do_ssh2_transport_crstate = 0;
9007 ssh->do_ssh2_authconn_crstate = 0;
9008 ssh->do_ssh_init_state = NULL;
9009 ssh->do_ssh1_login_state = NULL;
9010 ssh->do_ssh2_transport_state = NULL;
9011 ssh->do_ssh2_authconn_state = NULL;
9014 ssh->mainchan = NULL;
9015 ssh->throttled_all = 0;
9016 ssh->v1_stdout_throttling = 0;
9018 ssh->queuelen = ssh->queuesize = 0;
9019 ssh->queueing = FALSE;
9020 ssh->qhead = ssh->qtail = NULL;
9021 ssh->deferred_rekey_reason = NULL;
9022 bufchain_init(&ssh->queued_incoming_data);
9023 ssh->frozen = FALSE;
9025 *backend_handle = ssh;
9028 if (crypto_startup() == 0)
9029 return "Microsoft high encryption pack not installed!";
9032 ssh->frontend = frontend_handle;
9033 ssh->term_width = ssh->cfg.width;
9034 ssh->term_height = ssh->cfg.height;
9036 ssh->channels = NULL;
9037 ssh->rportfwds = NULL;
9038 ssh->portfwds = NULL;
9043 ssh->conn_throttle_count = 0;
9044 ssh->overall_bufsize = 0;
9045 ssh->fallback_cmd = 0;
9047 ssh->protocol = NULL;
9049 ssh->protocol_initial_phase_done = FALSE;
9053 ssh->incoming_data_size = ssh->outgoing_data_size =
9054 ssh->deferred_data_size = 0L;
9055 ssh->max_data_size = parse_blocksize(ssh->cfg.ssh_rekey_data);
9056 ssh->kex_in_progress = FALSE;
9058 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
9067 static void ssh_free(void *handle)
9069 Ssh ssh = (Ssh) handle;
9070 struct ssh_channel *c;
9071 struct ssh_rportfwd *pf;
9073 if (ssh->v1_cipher_ctx)
9074 ssh->cipher->free_context(ssh->v1_cipher_ctx);
9075 if (ssh->cs_cipher_ctx)
9076 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
9077 if (ssh->sc_cipher_ctx)
9078 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
9079 if (ssh->cs_mac_ctx)
9080 ssh->csmac->free_context(ssh->cs_mac_ctx);
9081 if (ssh->sc_mac_ctx)
9082 ssh->scmac->free_context(ssh->sc_mac_ctx);
9083 if (ssh->cs_comp_ctx) {
9085 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
9087 zlib_compress_cleanup(ssh->cs_comp_ctx);
9089 if (ssh->sc_comp_ctx) {
9091 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
9093 zlib_decompress_cleanup(ssh->sc_comp_ctx);
9096 dh_cleanup(ssh->kex_ctx);
9097 sfree(ssh->savedhost);
9099 while (ssh->queuelen-- > 0)
9100 ssh_free_packet(ssh->queue[ssh->queuelen]);
9103 while (ssh->qhead) {
9104 struct queued_handler *qh = ssh->qhead;
9105 ssh->qhead = qh->next;
9108 ssh->qhead = ssh->qtail = NULL;
9110 if (ssh->channels) {
9111 while ((c = delpos234(ssh->channels, 0)) != NULL) {
9114 if (c->u.x11.s != NULL)
9115 x11_close(c->u.x11.s);
9118 if (c->u.pfd.s != NULL)
9119 pfd_close(c->u.pfd.s);
9124 freetree234(ssh->channels);
9125 ssh->channels = NULL;
9128 if (ssh->rportfwds) {
9129 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
9131 freetree234(ssh->rportfwds);
9132 ssh->rportfwds = NULL;
9134 sfree(ssh->deferred_send_data);
9136 x11_free_display(ssh->x11disp);
9137 sfree(ssh->do_ssh_init_state);
9138 sfree(ssh->do_ssh1_login_state);
9139 sfree(ssh->do_ssh2_transport_state);
9140 sfree(ssh->do_ssh2_authconn_state);
9143 sfree(ssh->fullhostname);
9144 if (ssh->crcda_ctx) {
9145 crcda_free_context(ssh->crcda_ctx);
9146 ssh->crcda_ctx = NULL;
9149 ssh_do_close(ssh, TRUE);
9150 expire_timer_context(ssh);
9152 pinger_free(ssh->pinger);
9153 bufchain_clear(&ssh->queued_incoming_data);
9160 * Reconfigure the SSH backend.
9162 static void ssh_reconfig(void *handle, Config *cfg)
9164 Ssh ssh = (Ssh) handle;
9165 char *rekeying = NULL, rekey_mandatory = FALSE;
9166 unsigned long old_max_data_size;
9168 pinger_reconfig(ssh->pinger, &ssh->cfg, cfg);
9170 ssh_setup_portfwd(ssh, cfg);
9172 if (ssh->cfg.ssh_rekey_time != cfg->ssh_rekey_time &&
9173 cfg->ssh_rekey_time != 0) {
9174 long new_next = ssh->last_rekey + cfg->ssh_rekey_time*60*TICKSPERSEC;
9175 long now = GETTICKCOUNT();
9177 if (new_next - now < 0) {
9178 rekeying = "timeout shortened";
9180 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
9184 old_max_data_size = ssh->max_data_size;
9185 ssh->max_data_size = parse_blocksize(cfg->ssh_rekey_data);
9186 if (old_max_data_size != ssh->max_data_size &&
9187 ssh->max_data_size != 0) {
9188 if (ssh->outgoing_data_size > ssh->max_data_size ||
9189 ssh->incoming_data_size > ssh->max_data_size)
9190 rekeying = "data limit lowered";
9193 if (ssh->cfg.compression != cfg->compression) {
9194 rekeying = "compression setting changed";
9195 rekey_mandatory = TRUE;
9198 if (ssh->cfg.ssh2_des_cbc != cfg->ssh2_des_cbc ||
9199 memcmp(ssh->cfg.ssh_cipherlist, cfg->ssh_cipherlist,
9200 sizeof(ssh->cfg.ssh_cipherlist))) {
9201 rekeying = "cipher settings changed";
9202 rekey_mandatory = TRUE;
9205 ssh->cfg = *cfg; /* STRUCTURE COPY */
9208 if (!ssh->kex_in_progress) {
9209 do_ssh2_transport(ssh, rekeying, -1, NULL);
9210 } else if (rekey_mandatory) {
9211 ssh->deferred_rekey_reason = rekeying;
9217 * Called to send data down the SSH connection.
9219 static int ssh_send(void *handle, char *buf, int len)
9221 Ssh ssh = (Ssh) handle;
9223 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
9226 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
9228 return ssh_sendbuffer(ssh);
9232 * Called to query the current amount of buffered stdin data.
9234 static int ssh_sendbuffer(void *handle)
9236 Ssh ssh = (Ssh) handle;
9239 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
9243 * If the SSH socket itself has backed up, add the total backup
9244 * size on that to any individual buffer on the stdin channel.
9247 if (ssh->throttled_all)
9248 override_value = ssh->overall_bufsize;
9250 if (ssh->version == 1) {
9251 return override_value;
9252 } else if (ssh->version == 2) {
9253 if (!ssh->mainchan || ssh->mainchan->closes > 0)
9254 return override_value;
9256 return (override_value +
9257 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
9264 * Called to set the size of the window from SSH's POV.
9266 static void ssh_size(void *handle, int width, int height)
9268 Ssh ssh = (Ssh) handle;
9269 struct Packet *pktout;
9271 ssh->term_width = width;
9272 ssh->term_height = height;
9274 switch (ssh->state) {
9275 case SSH_STATE_BEFORE_SIZE:
9276 case SSH_STATE_PREPACKET:
9277 case SSH_STATE_CLOSED:
9278 break; /* do nothing */
9279 case SSH_STATE_INTERMED:
9280 ssh->size_needed = TRUE; /* buffer for later */
9282 case SSH_STATE_SESSION:
9283 if (!ssh->cfg.nopty) {
9284 if (ssh->version == 1) {
9285 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
9286 PKT_INT, ssh->term_height,
9287 PKT_INT, ssh->term_width,
9288 PKT_INT, 0, PKT_INT, 0, PKT_END);
9289 } else if (ssh->mainchan) {
9290 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9291 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9292 ssh2_pkt_addstring(pktout, "window-change");
9293 ssh2_pkt_addbool(pktout, 0);
9294 ssh2_pkt_adduint32(pktout, ssh->term_width);
9295 ssh2_pkt_adduint32(pktout, ssh->term_height);
9296 ssh2_pkt_adduint32(pktout, 0);
9297 ssh2_pkt_adduint32(pktout, 0);
9298 ssh2_pkt_send(ssh, pktout);
9306 * Return a list of the special codes that make sense in this
9309 static const struct telnet_special *ssh_get_specials(void *handle)
9311 static const struct telnet_special ssh1_ignore_special[] = {
9312 {"IGNORE message", TS_NOP}
9314 static const struct telnet_special ssh2_transport_specials[] = {
9315 {"IGNORE message", TS_NOP},
9316 {"Repeat key exchange", TS_REKEY},
9318 static const struct telnet_special ssh2_session_specials[] = {
9321 /* These are the signal names defined by RFC 4254.
9322 * They include all the ISO C signals, but are a subset of the POSIX
9323 * required signals. */
9324 {"SIGINT (Interrupt)", TS_SIGINT},
9325 {"SIGTERM (Terminate)", TS_SIGTERM},
9326 {"SIGKILL (Kill)", TS_SIGKILL},
9327 {"SIGQUIT (Quit)", TS_SIGQUIT},
9328 {"SIGHUP (Hangup)", TS_SIGHUP},
9329 {"More signals", TS_SUBMENU},
9330 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
9331 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
9332 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
9333 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
9336 static const struct telnet_special specials_end[] = {
9339 /* XXX review this length for any changes: */
9340 static struct telnet_special ssh_specials[lenof(ssh2_transport_specials) +
9341 lenof(ssh2_session_specials) +
9342 lenof(specials_end)];
9343 Ssh ssh = (Ssh) handle;
9345 #define ADD_SPECIALS(name) \
9347 assert((i + lenof(name)) <= lenof(ssh_specials)); \
9348 memcpy(&ssh_specials[i], name, sizeof name); \
9352 if (ssh->version == 1) {
9353 /* Don't bother offering IGNORE if we've decided the remote
9354 * won't cope with it, since we wouldn't bother sending it if
9356 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
9357 ADD_SPECIALS(ssh1_ignore_special);
9358 } else if (ssh->version == 2) {
9359 ADD_SPECIALS(ssh2_transport_specials);
9361 ADD_SPECIALS(ssh2_session_specials);
9362 } /* else we're not ready yet */
9365 ADD_SPECIALS(specials_end);
9366 return ssh_specials;
9374 * Send special codes. TS_EOF is useful for `plink', so you
9375 * can send an EOF and collect resulting output (e.g. `plink
9378 static void ssh_special(void *handle, Telnet_Special code)
9380 Ssh ssh = (Ssh) handle;
9381 struct Packet *pktout;
9383 if (code == TS_EOF) {
9384 if (ssh->state != SSH_STATE_SESSION) {
9386 * Buffer the EOF in case we are pre-SESSION, so we can
9387 * send it as soon as we reach SESSION.
9390 ssh->eof_needed = TRUE;
9393 if (ssh->version == 1) {
9394 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
9395 } else if (ssh->mainchan) {
9396 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
9397 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9398 ssh2_pkt_send(ssh, pktout);
9399 ssh->send_ok = 0; /* now stop trying to read from stdin */
9401 logevent("Sent EOF message");
9402 } else if (code == TS_PING || code == TS_NOP) {
9403 if (ssh->state == SSH_STATE_CLOSED
9404 || ssh->state == SSH_STATE_PREPACKET) return;
9405 if (ssh->version == 1) {
9406 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
9407 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
9409 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
9410 ssh2_pkt_addstring_start(pktout);
9411 ssh2_pkt_send_noqueue(ssh, pktout);
9413 } else if (code == TS_REKEY) {
9414 if (!ssh->kex_in_progress && ssh->version == 2) {
9415 do_ssh2_transport(ssh, "at user request", -1, NULL);
9417 } else if (code == TS_BRK) {
9418 if (ssh->state == SSH_STATE_CLOSED
9419 || ssh->state == SSH_STATE_PREPACKET) return;
9420 if (ssh->version == 1) {
9421 logevent("Unable to send BREAK signal in SSH-1");
9422 } else if (ssh->mainchan) {
9423 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9424 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9425 ssh2_pkt_addstring(pktout, "break");
9426 ssh2_pkt_addbool(pktout, 0);
9427 ssh2_pkt_adduint32(pktout, 0); /* default break length */
9428 ssh2_pkt_send(ssh, pktout);
9431 /* Is is a POSIX signal? */
9432 char *signame = NULL;
9433 if (code == TS_SIGABRT) signame = "ABRT";
9434 if (code == TS_SIGALRM) signame = "ALRM";
9435 if (code == TS_SIGFPE) signame = "FPE";
9436 if (code == TS_SIGHUP) signame = "HUP";
9437 if (code == TS_SIGILL) signame = "ILL";
9438 if (code == TS_SIGINT) signame = "INT";
9439 if (code == TS_SIGKILL) signame = "KILL";
9440 if (code == TS_SIGPIPE) signame = "PIPE";
9441 if (code == TS_SIGQUIT) signame = "QUIT";
9442 if (code == TS_SIGSEGV) signame = "SEGV";
9443 if (code == TS_SIGTERM) signame = "TERM";
9444 if (code == TS_SIGUSR1) signame = "USR1";
9445 if (code == TS_SIGUSR2) signame = "USR2";
9446 /* The SSH-2 protocol does in principle support arbitrary named
9447 * signals, including signame@domain, but we don't support those. */
9449 /* It's a signal. */
9450 if (ssh->version == 2 && ssh->mainchan) {
9451 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9452 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9453 ssh2_pkt_addstring(pktout, "signal");
9454 ssh2_pkt_addbool(pktout, 0);
9455 ssh2_pkt_addstring(pktout, signame);
9456 ssh2_pkt_send(ssh, pktout);
9457 logeventf(ssh, "Sent signal SIG%s", signame);
9460 /* Never heard of it. Do nothing */
9465 void *new_sock_channel(void *handle, Socket s)
9467 Ssh ssh = (Ssh) handle;
9468 struct ssh_channel *c;
9469 c = snew(struct ssh_channel);
9472 ssh2_channel_init(c);
9474 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
9476 add234(ssh->channels, c);
9481 * This is called when stdout/stderr (the entity to which
9482 * from_backend sends data) manages to clear some backlog.
9484 static void ssh_unthrottle(void *handle, int bufsize)
9486 Ssh ssh = (Ssh) handle;
9489 if (ssh->version == 1) {
9490 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
9491 ssh->v1_stdout_throttling = 0;
9492 ssh_throttle_conn(ssh, -1);
9495 if (ssh->mainchan) {
9496 ssh2_set_window(ssh->mainchan,
9497 bufsize < ssh->mainchan->v.v2.locmaxwin ?
9498 ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
9499 if (ssh->cfg.ssh_simple)
9502 buflimit = ssh->mainchan->v.v2.locmaxwin;
9503 if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
9504 ssh->mainchan->throttling_conn = 0;
9505 ssh_throttle_conn(ssh, -1);
9511 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
9513 struct ssh_channel *c = (struct ssh_channel *)channel;
9515 struct Packet *pktout;
9517 logeventf(ssh, "Opening forwarded connection to %s:%d", hostname, port);
9519 if (ssh->version == 1) {
9520 send_packet(ssh, SSH1_MSG_PORT_OPEN,
9521 PKT_INT, c->localid,
9524 /* PKT_STR, <org:orgport>, */
9527 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
9528 ssh2_pkt_addstring(pktout, "direct-tcpip");
9529 ssh2_pkt_adduint32(pktout, c->localid);
9530 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
9531 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
9532 ssh2_pkt_addstring(pktout, hostname);
9533 ssh2_pkt_adduint32(pktout, port);
9535 * We make up values for the originator data; partly it's
9536 * too much hassle to keep track, and partly I'm not
9537 * convinced the server should be told details like that
9538 * about my local network configuration.
9539 * The "originator IP address" is syntactically a numeric
9540 * IP address, and some servers (e.g., Tectia) get upset
9541 * if it doesn't match this syntax.
9543 ssh2_pkt_addstring(pktout, "0.0.0.0");
9544 ssh2_pkt_adduint32(pktout, 0);
9545 ssh2_pkt_send(ssh, pktout);
9549 static int ssh_connected(void *handle)
9551 Ssh ssh = (Ssh) handle;
9552 return ssh->s != NULL;
9555 static int ssh_sendok(void *handle)
9557 Ssh ssh = (Ssh) handle;
9558 return ssh->send_ok;
9561 static int ssh_ldisc(void *handle, int option)
9563 Ssh ssh = (Ssh) handle;
9564 if (option == LD_ECHO)
9565 return ssh->echoing;
9566 if (option == LD_EDIT)
9567 return ssh->editing;
9571 static void ssh_provide_ldisc(void *handle, void *ldisc)
9573 Ssh ssh = (Ssh) handle;
9577 static void ssh_provide_logctx(void *handle, void *logctx)
9579 Ssh ssh = (Ssh) handle;
9580 ssh->logctx = logctx;
9583 static int ssh_return_exitcode(void *handle)
9585 Ssh ssh = (Ssh) handle;
9589 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
9593 * cfg_info for SSH is the currently running version of the
9594 * protocol. (1 for 1; 2 for 2; 0 for not-decided-yet.)
9596 static int ssh_cfg_info(void *handle)
9598 Ssh ssh = (Ssh) handle;
9599 return ssh->version;
9603 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
9604 * that fails. This variable is the means by which scp.c can reach
9605 * into the SSH code and find out which one it got.
9607 extern int ssh_fallback_cmd(void *handle)
9609 Ssh ssh = (Ssh) handle;
9610 return ssh->fallback_cmd;
9613 Backend ssh_backend = {
9623 ssh_return_exitcode,